content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
app = Flask(__name__) api = Api(app) index = RetrievalIndex() class BuildIndex(Resource): def post(self): request_body = json.loads(request.data) user_id = request_body["user_id"] image_hashes = request_body["image_hashes"] image_embeddings = request_body["image_embeddings"] index.build_index_for_user(user_id, image_hashes, image_embeddings) return jsonify({"status": True, "index_size": index.indices[user_id].ntotal}) class SearchIndex(Resource): def post(self): try: request_body = json.loads(request.data) user_id = request_body["user_id"] image_embedding = request_body["image_embedding"] if "n" in request_body.keys(): n = int(request_body["n"]) else: n = 100 res = index.search_similar(user_id, image_embedding, n) return jsonify({"status": True, "result": res}) except BaseException as e: logger.error(str(e)) return jsonify({"status": False, "result": []}, status=500) api.add_resource(BuildIndex, "/build/") api.add_resource(SearchIndex, "/search/") if __name__ == "__main__": logger.info("starting server") server = WSGIServer(("0.0.0.0", 8002), app) server_thread = gevent.spawn(server.serve_forever) gevent.joinall([server_thread])
app = flask(__name__) api = api(app) index = retrieval_index() class Buildindex(Resource): def post(self): request_body = json.loads(request.data) user_id = request_body['user_id'] image_hashes = request_body['image_hashes'] image_embeddings = request_body['image_embeddings'] index.build_index_for_user(user_id, image_hashes, image_embeddings) return jsonify({'status': True, 'index_size': index.indices[user_id].ntotal}) class Searchindex(Resource): def post(self): try: request_body = json.loads(request.data) user_id = request_body['user_id'] image_embedding = request_body['image_embedding'] if 'n' in request_body.keys(): n = int(request_body['n']) else: n = 100 res = index.search_similar(user_id, image_embedding, n) return jsonify({'status': True, 'result': res}) except BaseException as e: logger.error(str(e)) return jsonify({'status': False, 'result': []}, status=500) api.add_resource(BuildIndex, '/build/') api.add_resource(SearchIndex, '/search/') if __name__ == '__main__': logger.info('starting server') server = wsgi_server(('0.0.0.0', 8002), app) server_thread = gevent.spawn(server.serve_forever) gevent.joinall([server_thread])
# ########################################################### # ## 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.vars.app or request.args: _t = request.vars.app or 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 os.path.exists('applications/examples'): response.menu.append( (T('Help'), False, URL('examples', 'default', 'documentation'))) else: response.menu.append((T('Help'), False, 'http://web2py.com/examples/default/documentation')) if not session.authorized: response.menu = [(T('Login'), True, URL('site'))] else: response.menu.append((T('Logout'), False, URL(_a, 'default', f='logout'))) response.menu.append((T('Debug'), False, URL(_a, 'debug', 'interact')))
_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.vars.app or request.args: _t = request.vars.app or 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 os.path.exists('applications/examples'): response.menu.append((t('Help'), False, url('examples', 'default', 'documentation'))) else: response.menu.append((t('Help'), False, 'http://web2py.com/examples/default/documentation')) if not session.authorized: response.menu = [(t('Login'), True, url('site'))] else: response.menu.append((t('Logout'), False, url(_a, 'default', f='logout'))) response.menu.append((t('Debug'), False, url(_a, 'debug', 'interact')))
class ReverseProxied(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): print(environ) script_name = environ.get('HTTP_X_SCRIPT_NAME', '') if script_name: environ['SCRIPT_NAME'] = script_name path_info = environ['PATH_INFO'] if path_info.startswith(script_name): environ['PATH_INFO'] = path_info[len(script_name):] scheme = environ.get('HTTP_X_SCHEME', '') if scheme: environ['wsgi.url_scheme'] = scheme return self.app(environ, start_response)
class Reverseproxied(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): print(environ) script_name = environ.get('HTTP_X_SCRIPT_NAME', '') if script_name: environ['SCRIPT_NAME'] = script_name path_info = environ['PATH_INFO'] if path_info.startswith(script_name): environ['PATH_INFO'] = path_info[len(script_name):] scheme = environ.get('HTTP_X_SCHEME', '') if scheme: environ['wsgi.url_scheme'] = scheme return self.app(environ, start_response)
print("first string" + ", " + "second string") print(str(1) + "2" + "3" + "4") print("spam" * 3) print(4 * "2") print("Love" * 0) print("7" * 3) # 1 + "2" + 3 -- TypeError # "4" * "2" -- TypeError # "Python is fun" * 7.0 -- TypeError
print('first string' + ', ' + 'second string') print(str(1) + '2' + '3' + '4') print('spam' * 3) print(4 * '2') print('Love' * 0) print('7' * 3)
f = open("all.txt") s = f.readlines(); f.close() fout = open("allout1.txt", 'w') o = [] outPath = 'S:\\BACKUP!!!\\WD\\L\\Canon\\All\\' quote = "\"" for x in s: #x.replace('\\', '\\\\') #print(x) #if x.rfind('MVI') > -1: ix = x.rindex('MVI'); x = x.strip(); if x.rfind('MVI') > -1: ix = x.rindex('MVI'); else: ix = -1 if x.rfind('THM') > -1: ix = -1 fn = x[ix:] #if ix != None: fn = x[ix:] #else: fn = "NONE" #if (x.rfind("avi")): o = o + ["VirtualDub.Open(" + x + "); " + "VirtualDub.SaveAVI(" + outPath + fn + ");\n" ] if ix != -1: #if (x.rfind("avi")): so = "VirtualDub.Open(\"" + x + "\"" + "); VirtualDub.SaveAVI(" + quote + outPath + fn + quote + ");" if (x.rfind("avi")): so = "VirtualDub.Open(" + quote + x + quote + "); VirtualDub.SaveAVI(" + quote + outPath + fn + quote + ");" + "\r\n"; print(so) fout.write(so) fout.close(); #print(o)
f = open('all.txt') s = f.readlines() f.close() fout = open('allout1.txt', 'w') o = [] out_path = 'S:\\BACKUP!!!\\WD\\L\\Canon\\All\\' quote = '"' for x in s: x = x.strip() if x.rfind('MVI') > -1: ix = x.rindex('MVI') else: ix = -1 if x.rfind('THM') > -1: ix = -1 fn = x[ix:] if ix != -1: if x.rfind('avi'): so = 'VirtualDub.Open(' + quote + x + quote + '); VirtualDub.SaveAVI(' + quote + outPath + fn + quote + ');' + '\r\n' print(so) fout.write(so) fout.close()
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"ROOT_DIR": "00_core.ipynb", "DOWNLOAD_DIR_BASE": "00_core.ipynb", "PROCESSED_DIR_BASE": "00_core.ipynb", "DATASET_DIR": "00_core.ipynb", "create_country_dirs": "00_core.ipynb", "gen_weekdates": "00_core.ipynb", "STANDARD_WEEK": "00_core.ipynb", "STANDARD_WEEK.columns": "00_core.ipynb", "LAST_MODIFIED": "020_Netherlands.ipynb", "COUNTRIES": "03_collect.ipynb", "SUMMARY": "03_collect.ipynb"} modules = ["core.py", "countries/uk.py", "countries/netherlands.py", "collect.py"] doc_url = "https://kk1694.github.io/weekly_mort/" git_url = "https://github.com/kk1694/weekly_mort/tree/master/" def custom_doc_links(name): return None
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'ROOT_DIR': '00_core.ipynb', 'DOWNLOAD_DIR_BASE': '00_core.ipynb', 'PROCESSED_DIR_BASE': '00_core.ipynb', 'DATASET_DIR': '00_core.ipynb', 'create_country_dirs': '00_core.ipynb', 'gen_weekdates': '00_core.ipynb', 'STANDARD_WEEK': '00_core.ipynb', 'STANDARD_WEEK.columns': '00_core.ipynb', 'LAST_MODIFIED': '020_Netherlands.ipynb', 'COUNTRIES': '03_collect.ipynb', 'SUMMARY': '03_collect.ipynb'} modules = ['core.py', 'countries/uk.py', 'countries/netherlands.py', 'collect.py'] doc_url = 'https://kk1694.github.io/weekly_mort/' git_url = 'https://github.com/kk1694/weekly_mort/tree/master/' def custom_doc_links(name): return None
server='tcp:mkgsupport.database.windows.net' database='mkgsupport' username='mkguser' password='Usersqlmkg123!' driver='/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.6.so.1.1'
server = 'tcp:mkgsupport.database.windows.net' database = 'mkgsupport' username = 'mkguser' password = 'Usersqlmkg123!' driver = '/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.6.so.1.1'
a = 1 b = 0 c = 128 d = 0 f = 836 + c #964 if a == 1: c = 10550400 f = f + c #10551364 a = 0 for b in range(1, f+1): if (f % b) == 0: a += b print(a)
a = 1 b = 0 c = 128 d = 0 f = 836 + c if a == 1: c = 10550400 f = f + c a = 0 for b in range(1, f + 1): if f % b == 0: a += b print(a)
class GoodreadsClientException(Exception): pass class NetworkError(GoodreadsClientException): pass
class Goodreadsclientexception(Exception): pass class Networkerror(GoodreadsClientException): pass
def show_words(**kwargs): print(kwargs['pies'], kwargs['kot']) for key, value in kwargs.items(): print(key + "->" + value) show_words(pies="Dog", kot="Cat", sowa="Owl", mysz="Mouse")
def show_words(**kwargs): print(kwargs['pies'], kwargs['kot']) for (key, value) in kwargs.items(): print(key + '->' + value) show_words(pies='Dog', kot='Cat', sowa='Owl', mysz='Mouse')
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Shashi Bhushan (sbhushan1 @ outlook dot com)' class GameObject(object): pass
__author__ = 'Shashi Bhushan (sbhushan1 @ outlook dot com)' class Gameobject(object): pass
debian_os = ['debian', 'ubuntu'] rhel_os = ['redhat', 'centos'] def test_distribution(host): assert host.system_info.distribution.lower() in debian_os + rhel_os def test_conf_dir(host): f = host.file('/etc/pgbouncer_exporter') assert f.exists assert f.is_directory def test_log_dir(host): f = host.file('/var/log/pgbouncer_exporter') assert f.exists assert f.is_directory def test_service(host): s = host.service('pgbouncer_exporter') assert s.is_enabled assert s.is_running def test_user(host): u = host.user('postgres') assert u.exists def test_group(host): g = host.group('postgres') assert g.exists def test_socket(host): s = host.socket("tcp://127.0.0.1:9127") assert s.is_listening def test_version(host): g = host.pip_package.get_packages(pip_path='pip3') for k, v in g.items(): if k == "prometheus-pgbouncer-exporter": version = v['version'] break assert version == "2.0.1"
debian_os = ['debian', 'ubuntu'] rhel_os = ['redhat', 'centos'] def test_distribution(host): assert host.system_info.distribution.lower() in debian_os + rhel_os def test_conf_dir(host): f = host.file('/etc/pgbouncer_exporter') assert f.exists assert f.is_directory def test_log_dir(host): f = host.file('/var/log/pgbouncer_exporter') assert f.exists assert f.is_directory def test_service(host): s = host.service('pgbouncer_exporter') assert s.is_enabled assert s.is_running def test_user(host): u = host.user('postgres') assert u.exists def test_group(host): g = host.group('postgres') assert g.exists def test_socket(host): s = host.socket('tcp://127.0.0.1:9127') assert s.is_listening def test_version(host): g = host.pip_package.get_packages(pip_path='pip3') for (k, v) in g.items(): if k == 'prometheus-pgbouncer-exporter': version = v['version'] break assert version == '2.0.1'
a = 1 b = 2 c = 3 d = 4 e = 5 f = 6
a = 1 b = 2 c = 3 d = 4 e = 5 f = 6
# --- Day 15: Rambunctious Recitation --- # You catch the airport shuttle and try to book a new flight to your vacation island. Due to the storm, all direct flights have been cancelled, but a route is available to get around the storm. You take it. # While you wait for your flight, you decide to check in with the Elves back at the North Pole. They're playing a memory game and are ever so excited to explain the rules! # In this game, the players take turns saying numbers. They begin by taking turns reading from a list of starting numbers (your puzzle input). Then, each turn consists of considering the most recently spoken number: # If that was the first time the number has been spoken, the current player says 0. # Otherwise, the number had been spoken before; the current player announces how many turns apart the number is from when it was previously spoken. # So, after the starting numbers, each turn results in that player speaking aloud either 0 (if the last number is new) or an age (if the last number is a repeat). # For example, suppose the starting numbers are 0,3,6: # Turn 1: The 1st number spoken is a starting number, 0. # Turn 2: The 2nd number spoken is a starting number, 3. # Turn 3: The 3rd number spoken is a starting number, 6. # Turn 4: Now, consider the last number spoken, 6. Since that was the first time the number had been spoken, the 4th number spoken is 0. # Turn 5: Next, again consider the last number spoken, 0. Since it had been spoken before, the next number to speak is the difference between the turn number when it was last spoken (the previous turn, 4) and the turn number of the time it was most recently spoken before then (turn 1). Thus, the 5th number spoken is 4 - 1, 3. # Turn 6: The last number spoken, 3 had also been spoken before, most recently on turns 5 and 2. So, the 6th number spoken is 5 - 2, 3. # Turn 7: Since 3 was just spoken twice in a row, and the last two turns are 1 turn apart, the 7th number spoken is 1. # Turn 8: Since 1 is new, the 8th number spoken is 0. # Turn 9: 0 was last spoken on turns 8 and 4, so the 9th number spoken is the difference between them, 4. # Turn 10: 4 is new, so the 10th number spoken is 0. # (The game ends when the Elves get sick of playing or dinner is ready, whichever comes first.) # Their question for you is: what will be the 2020th number spoken? In the example above, the 2020th number spoken will be 436. # Here are a few more examples: # Given the starting numbers 1,3,2, the 2020th number spoken is 1. # Given the starting numbers 2,1,3, the 2020th number spoken is 10. # Given the starting numbers 1,2,3, the 2020th number spoken is 27. # Given the starting numbers 2,3,1, the 2020th number spoken is 78. # Given the starting numbers 3,2,1, the 2020th number spoken is 438. # Given the starting numbers 3,1,2, the 2020th number spoken is 1836. # Given your starting numbers, what will be the 2020th number spoken? def fileInput(): f = open(inputFile, 'r') with open(inputFile) as f: read_data = f.read().split(',') f.close() return read_data def dictTransform(data): turn_count = 0 dict_data = {} for num in data: turn_count += 1 #turn starts on count 1, so do it before and add extra count at the end dict_data.update({int(num):[0,turn_count]}) prev_num = num dict_data.update({int(prev_num):[turn_count]}) return dict_data,turn_count def memGameTurn(dict_data,prev_num,turn_count): # print('-----------') # print('#',turn_count,prev_num, '->',dict_data,end=" ") if dict_data.get(prev_num) is None: dict_data.update({prev_num:[turn_count]}) prev_num = 0 elif len(dict_data.get(prev_num)) == 1: dict_data.update({prev_num:[dict_data.get(prev_num)[0],turn_count]}) prev_num = dict_data.get(prev_num)[1]-dict_data.get(prev_num)[0] else: dict_data.update({prev_num:[dict_data.get(prev_num)[1],turn_count]}) prev_num = dict_data.get(prev_num)[1]-dict_data.get(prev_num)[0] return dict_data,prev_num def memGame(data): turn_end = 2020 prev_num = 0 #first turn after data is always new number dict_data,turn_start = dictTransform(data) for i in range(turn_start+1,turn_end): dict_data,prev_num = memGameTurn(dict_data,prev_num,i) return prev_num #/////////////////////////////////////////////////// inputFile = 'day15-input.txt' if __name__ == "__main__": data = fileInput() print(memGame(data))
def file_input(): f = open(inputFile, 'r') with open(inputFile) as f: read_data = f.read().split(',') f.close() return read_data def dict_transform(data): turn_count = 0 dict_data = {} for num in data: turn_count += 1 dict_data.update({int(num): [0, turn_count]}) prev_num = num dict_data.update({int(prev_num): [turn_count]}) return (dict_data, turn_count) def mem_game_turn(dict_data, prev_num, turn_count): if dict_data.get(prev_num) is None: dict_data.update({prev_num: [turn_count]}) prev_num = 0 elif len(dict_data.get(prev_num)) == 1: dict_data.update({prev_num: [dict_data.get(prev_num)[0], turn_count]}) prev_num = dict_data.get(prev_num)[1] - dict_data.get(prev_num)[0] else: dict_data.update({prev_num: [dict_data.get(prev_num)[1], turn_count]}) prev_num = dict_data.get(prev_num)[1] - dict_data.get(prev_num)[0] return (dict_data, prev_num) def mem_game(data): turn_end = 2020 prev_num = 0 (dict_data, turn_start) = dict_transform(data) for i in range(turn_start + 1, turn_end): (dict_data, prev_num) = mem_game_turn(dict_data, prev_num, i) return prev_num input_file = 'day15-input.txt' if __name__ == '__main__': data = file_input() print(mem_game(data))
# -*- coding: utf-8 -*- # in VTK, the header file is the same as the classname def get_include_file(classname,filename): incfile = '#include "{0}"'.format(filename) #print "including class {0} from file {1}".format(classname,incfile) if classname.startswith("itk::DefaultConvertPixelTraits"): incfile = '#include "itkMatrix.h"\n'+incfile if classname.startswith("std::set"): incfile = '#include <set>\n'+incfile return incfile #return "{0}.h".format(classname) def get_var_filter(): return "(itk::|vnl_|itkAmi|gdcm::|std::).*" def wrap_public_fields(classname): return False def deleter_includefile(): return "" def implement_deleter(classname): # no deleter for the moment unless for smart pointers? # or only in case of protected deleter? return ", smartpointer_nodeleter<{0} >()".format(classname)
def get_include_file(classname, filename): incfile = '#include "{0}"'.format(filename) if classname.startswith('itk::DefaultConvertPixelTraits'): incfile = '#include "itkMatrix.h"\n' + incfile if classname.startswith('std::set'): incfile = '#include <set>\n' + incfile return incfile def get_var_filter(): return '(itk::|vnl_|itkAmi|gdcm::|std::).*' def wrap_public_fields(classname): return False def deleter_includefile(): return '' def implement_deleter(classname): return ', smartpointer_nodeleter<{0} >()'.format(classname)
class Calculadora: def soma(self, valor_a, valor_b): return valor_a + valor_b def subtracao(self, valor_a, valor_b): return valor_a - valor_b def multiplacacao(self, valor_a, valor_b): return valor_a * valor_b def divisao(self, valor_a, valor_b): return valor_a / valor_b calculadora = Calculadora() print(calculadora.soma(10, 2)) print(calculadora.subtracao(5, 3)) print(calculadora.divisao(100, 2)) print(calculadora.multiplacacao(10, 5))
class Calculadora: def soma(self, valor_a, valor_b): return valor_a + valor_b def subtracao(self, valor_a, valor_b): return valor_a - valor_b def multiplacacao(self, valor_a, valor_b): return valor_a * valor_b def divisao(self, valor_a, valor_b): return valor_a / valor_b calculadora = calculadora() print(calculadora.soma(10, 2)) print(calculadora.subtracao(5, 3)) print(calculadora.divisao(100, 2)) print(calculadora.multiplacacao(10, 5))
#!/usr/bin/python #Excercise 1 from Chapter 4 spam = ['apples','bananas','tofu','cats'] def structlist(lists): sstring = "" for i in range(len(lists)): if i == len(lists)-1: sstring +="and "+lists[i] print(sstring) break else: sstring += lists[i]+", " structlist(spam) spam.append("lions") #This should prove that the size of the list wont matter. structlist(spam)
spam = ['apples', 'bananas', 'tofu', 'cats'] def structlist(lists): sstring = '' for i in range(len(lists)): if i == len(lists) - 1: sstring += 'and ' + lists[i] print(sstring) break else: sstring += lists[i] + ', ' structlist(spam) spam.append('lions') structlist(spam)
# Configuration file for ipcontroller. c = get_config() #------------------------------------------------------------------------------ # IPControllerApp configuration #------------------------------------------------------------------------------ # IPControllerApp will inherit config from: BaseParallelApplication, # BaseIPythonApplication, Application # Use threads instead of processes for the schedulers # c.IPControllerApp.use_threads = False # Create a massive crash report when IPython encounters what may be an internal # error. The default is to append a short message to the usual traceback # c.IPControllerApp.verbose_crash = False # JSON filename where client connection info will be stored. # c.IPControllerApp.client_json_file = 'ipcontroller-client.json' # String id to add to runtime files, to prevent name collisions when using # multiple clusters with a single profile simultaneously. # # When set, files will be named like: 'ipcontroller-<cluster_id>-engine.json' # # Since this is text inserted into filenames, typical recommendations apply: # Simple character strings are ideal, and spaces are not recommended (but should # generally work). # c.IPControllerApp.cluster_id = '' # The date format used by logging formatters for %(asctime)s # c.IPControllerApp.log_datefmt = '%Y-%m-%d %H:%M:%S' # Whether to overwrite existing config files when copying # c.IPControllerApp.overwrite = False # Set the log level by value or name. # c.IPControllerApp.log_level = 30 # Set the working dir for the process. # c.IPControllerApp.work_dir = u'/fusion/gpfs/home/scollis' # ssh url for engines to use when connecting to the Controller processes. It # should be of the form: [user@]server[:port]. The Controller's listening # addresses must be accessible from the ssh server # c.IPControllerApp.engine_ssh_server = u'' # Path to an extra config file to load. # # If specified, load this config file in addition to any other IPython config. # c.IPControllerApp.extra_config_file = u'' # Whether to create profile dir if it doesn't exist. # c.IPControllerApp.auto_create = True # The external IP or domain name of the Controller, used for disambiguating # engine and client connections. # c.IPControllerApp.location = u'' # ssh url for clients to use when connecting to the Controller processes. It # should be of the form: [user@]server[:port]. The Controller's listening # addresses must be accessible from the ssh server # c.IPControllerApp.ssh_server = u'' # The IPython profile to use. # c.IPControllerApp.profile = u'default' # The ZMQ URL of the iplogger to aggregate logging. # c.IPControllerApp.log_url = '' # whether to log to a file # c.IPControllerApp.log_to_file = False # The name of the IPython directory. This directory is used for logging # configuration (through profiles), history storage, etc. The default is usually # $HOME/.ipython. This option can also be specified through the environment # variable IPYTHONDIR. # c.IPControllerApp.ipython_dir = u'' # Whether to install the default config files into the profile dir. If a new # profile is being created, and IPython contains config files for that profile, # then they will be staged into the new directory. Otherwise, default config # files will be automatically generated. # c.IPControllerApp.copy_config_files = False # import statements to be run at startup. Necessary in some environments # c.IPControllerApp.import_statements = [] # Whether to reuse existing json connection files. If False, connection files # will be removed on a clean exit. # c.IPControllerApp.reuse_files = False # Reload engine state from JSON file # c.IPControllerApp.restore_engines = False # JSON filename where engine connection info will be stored. # c.IPControllerApp.engine_json_file = 'ipcontroller-engine.json' # whether to cleanup old logfiles before starting # c.IPControllerApp.clean_logs = False # The Logging format template # c.IPControllerApp.log_format = '[%(name)s]%(highlevel)s %(message)s' #------------------------------------------------------------------------------ # ProfileDir configuration #------------------------------------------------------------------------------ # An object to manage the profile directory and its resources. # # The profile directory is used by all IPython applications, to manage # configuration, logging and security. # # This object knows how to find, create and manage these directories. This # should be used by any code that wants to handle profiles. # Set the profile location directly. This overrides the logic used by the # `profile` option. # c.ProfileDir.location = u'' #------------------------------------------------------------------------------ # Session configuration #------------------------------------------------------------------------------ # Object for handling serialization and sending of messages. # # The Session object handles building messages and sending them with ZMQ sockets # or ZMQStream objects. Objects can communicate with each other over the # network via Session objects, and only need to work with the dict-based IPython # message spec. The Session will handle serialization/deserialization, security, # and metadata. # # Sessions support configurable serialization via packer/unpacker traits, and # signing with HMAC digests via the key/keyfile traits. # # Parameters ---------- # # debug : bool # whether to trigger extra debugging statements # packer/unpacker : str : 'json', 'pickle' or import_string # importstrings for methods to serialize message parts. If just # 'json' or 'pickle', predefined JSON and pickle packers will be used. # Otherwise, the entire importstring must be used. # # The functions must accept at least valid JSON input, and output *bytes*. # # For example, to use msgpack: # packer = 'msgpack.packb', unpacker='msgpack.unpackb' # pack/unpack : callables # You can also set the pack/unpack callables for serialization directly. # session : bytes # the ID of this Session object. The default is to generate a new UUID. # username : unicode # username added to message headers. The default is to ask the OS. # key : bytes # The key used to initialize an HMAC signature. If unset, messages # will not be signed or checked. # keyfile : filepath # The file containing a key. If this is set, `key` will be initialized # to the contents of the file. # Username for the Session. Default is your system username. # c.Session.username = u'scollis' # The name of the unpacker for unserializing messages. Only used with custom # functions for `packer`. # c.Session.unpacker = 'json' # Threshold (in bytes) beyond which a buffer should be sent without copying. # c.Session.copy_threshold = 65536 # The name of the packer for serializing messages. Should be one of 'json', # 'pickle', or an import name for a custom callable serializer. # c.Session.packer = 'json' # The maximum number of digests to remember. # # The digest history will be culled when it exceeds this value. # c.Session.digest_history_size = 65536 # The UUID identifying this session. # c.Session.session = u'' # The digest scheme used to construct the message signatures. Must have the form # 'hmac-HASH'. # c.Session.signature_scheme = 'hmac-sha256' # execution key, for signing messages. # c.Session.key = '' # Debug output in the Session # c.Session.debug = False # The maximum number of items for a container to be introspected for custom # serialization. Containers larger than this are pickled outright. # c.Session.item_threshold = 64 # path to file containing execution key. # c.Session.keyfile = '' # Threshold (in bytes) beyond which an object's buffer should be extracted to # avoid pickling. # c.Session.buffer_threshold = 1024 # Metadata dictionary, which serves as the default top-level metadata dict for # each message. # c.Session.metadata = {} #------------------------------------------------------------------------------ # HubFactory configuration #------------------------------------------------------------------------------ # The Configurable for setting up a Hub. # HubFactory will inherit config from: RegistrationFactory # Client/Engine Port pair for Control queue # c.HubFactory.control = None # 0MQ transport for monitor messages. [default : tcp] # c.HubFactory.monitor_transport = 'tcp' # IP on which to listen for client connections. [default: loopback] # c.HubFactory.client_ip = u'' # Client/Engine Port pair for Task queue # c.HubFactory.task = None # 0MQ transport for engine connections. [default: tcp] # c.HubFactory.engine_transport = 'tcp' # 0MQ transport for client connections. [default : tcp] # c.HubFactory.client_transport = 'tcp' # Monitor (SUB) port for queue traffic # c.HubFactory.mon_port = 0 # The IP address for registration. This is generally either '127.0.0.1' for # loopback only or '*' for all interfaces. c.HubFactory.ip = '*' # Engine registration timeout in seconds [default: # max(30,10*heartmonitor.period)] # c.HubFactory.registration_timeout = 0 # Client/Engine Port pair for MUX queue # c.HubFactory.mux = None # PUB port for sending engine status notifications # c.HubFactory.notifier_port = 0 # The port on which the Hub listens for registration. # c.HubFactory.regport = 0 # The 0MQ url used for registration. This sets transport, ip, and port in one # variable. For example: url='tcp://127.0.0.1:12345' or url='epgm://*:90210' # c.HubFactory.url = '' # IP on which to listen for engine connections. [default: loopback] # c.HubFactory.engine_ip = u'' # Client/Engine Port pair for IOPub relay # c.HubFactory.iopub = None # PUB/ROUTER Port pair for Engine heartbeats # c.HubFactory.hb = None # The class to use for the DB backend # # Options include: # # SQLiteDB: SQLite MongoDB : use MongoDB DictDB : in-memory storage (fastest, # but be mindful of memory growth of the Hub) NoDB : disable database # altogether (default) # c.HubFactory.db_class = 'NoDB' # IP on which to listen for monitor messages. [default: loopback] # c.HubFactory.monitor_ip = u'' # The 0MQ transport for communications. This will likely be the default of # 'tcp', but other values include 'ipc', 'epgm', 'inproc'. # c.HubFactory.transport = 'tcp' #------------------------------------------------------------------------------ # TaskScheduler configuration #------------------------------------------------------------------------------ # Python TaskScheduler object. # # This is the simplest object that supports msg_id based DAG dependencies. # *Only* task msg_ids are checked, not msg_ids of jobs submitted via the MUX # queue. # select the task scheduler scheme [default: Python LRU] Options are: 'pure', # 'lru', 'plainrandom', 'weighted', 'twobin','leastload' # c.TaskScheduler.scheme_name = 'leastload' # specify the High Water Mark (HWM) for the downstream socket in the Task # scheduler. This is the maximum number of allowed outstanding tasks on each # engine. # # The default (1) means that only one task can be outstanding on each engine. # Setting TaskScheduler.hwm=0 means there is no limit, and the engines continue # to be assigned tasks while they are working, effectively hiding network # latency behind computation, but can result in an imbalance of work when # submitting many heterogenous tasks all at once. Any positive value greater # than one is a compromise between the two. # c.TaskScheduler.hwm = 1 #------------------------------------------------------------------------------ # HeartMonitor configuration #------------------------------------------------------------------------------ # A basic HeartMonitor class pingstream: a PUB stream pongstream: an ROUTER # stream period: the period of the heartbeat in milliseconds # Whether to include every heartbeat in debugging output. # # Has to be set explicitly, because there will be *a lot* of output. # c.HeartMonitor.debug = False # The frequency at which the Hub pings the engines for heartbeats (in ms) # c.HeartMonitor.period = 3000 # Allowed consecutive missed pings from controller Hub to engine before # unregistering. # c.HeartMonitor.max_heartmonitor_misses = 10 #------------------------------------------------------------------------------ # DictDB configuration #------------------------------------------------------------------------------ # Basic in-memory dict-based object for saving Task Records. # # This is the first object to present the DB interface for logging tasks out of # memory. # # The interface is based on MongoDB, so adding a MongoDB backend should be # straightforward. # The fraction by which the db should culled when one of the limits is exceeded # # In general, the db size will spend most of its time with a size in the range: # # [limit * (1-cull_fraction), limit] # # for each of size_limit and record_limit. # c.DictDB.cull_fraction = 0.1 # The maximum total size (in bytes) of the buffers stored in the db # # When the db exceeds this size, the oldest records will be culled until the # total size is under size_limit * (1-cull_fraction). default: 1 GB # c.DictDB.size_limit = 1073741824 # The maximum number of records in the db # # When the history exceeds this size, the first record_limit * cull_fraction # records will be culled. # c.DictDB.record_limit = 1024 #------------------------------------------------------------------------------ # SQLiteDB configuration #------------------------------------------------------------------------------ # SQLite3 TaskRecord backend. # The SQLite Table to use for storing tasks for this session. If unspecified, a # new table will be created with the Hub's IDENT. Specifying the table will # result in tasks from previous sessions being available via Clients' db_query # and get_result methods. # c.SQLiteDB.table = 'ipython-tasks' # The directory containing the sqlite task database. The default is to use the # cluster_dir location. # c.SQLiteDB.location = '' # The filename of the sqlite task database. [default: 'tasks.db'] # c.SQLiteDB.filename = 'tasks.db'
c = get_config() c.HubFactory.ip = '*'
# Package Constants # Meraki dashboard API key, set either at instantiation or as an environment variable API_KEY_ENVIRONMENT_VARIABLE = 'MERAKI_DASHBOARD_API_KEY' # Base URL preceding all endpoint resources DEFAULT_BASE_URL = 'https://api.meraki.com/api/v1' # Maximum number of seconds for each API call SINGLE_REQUEST_TIMEOUT = 60 # Path for TLS/SSL certificate verification if behind local proxy CERTIFICATE_PATH = '' # Proxy server and port, if needed, for HTTPS REQUESTS_PROXY = '' # Retry if 429 rate limit error encountered? WAIT_ON_RATE_LIMIT = True # Nginx 429 retry wait time NGINX_429_RETRY_WAIT_TIME = 60 # Action batch concurrency error retry wait time ACTION_BATCH_RETRY_WAIT_TIME = 60 # Retry if encountering other 4XX error (besides 429)? RETRY_4XX_ERROR = False # Other 4XX error retry wait time RETRY_4XX_ERROR_WAIT_TIME = 60 # Retry up to this many times when encountering 429s or other server-side errors MAXIMUM_RETRIES = 2 # Create an output log file? OUTPUT_LOG = True # Path to output log; by default, working directory of script if not specified LOG_PATH = '' # Log file name appended with date and timestamp LOG_FILE_PREFIX = 'meraki_api_' # Print output logging to console? PRINT_TO_CONSOLE = True # Disable all logging? You're on your own then! SUPPRESS_LOGGING = False # Simulate POST/PUT/DELETE calls to prevent changes? SIMULATE_API_CALLS = False # Number of concurrent API requests for asynchronous class AIO_MAXIMUM_CONCURRENT_REQUESTS = 8 # Optional partner identifier for API usage tracking; can also be set as an environment variable BE_GEO_ID BE_GEO_ID = '' # Optional identifier for API usage tracking; can also be set as an environment variable MERAKI_PYTHON_SDK_CALLER MERAKI_PYTHON_SDK_CALLER = ''
api_key_environment_variable = 'MERAKI_DASHBOARD_API_KEY' default_base_url = 'https://api.meraki.com/api/v1' single_request_timeout = 60 certificate_path = '' requests_proxy = '' wait_on_rate_limit = True nginx_429_retry_wait_time = 60 action_batch_retry_wait_time = 60 retry_4_xx_error = False retry_4_xx_error_wait_time = 60 maximum_retries = 2 output_log = True log_path = '' log_file_prefix = 'meraki_api_' print_to_console = True suppress_logging = False simulate_api_calls = False aio_maximum_concurrent_requests = 8 be_geo_id = '' meraki_python_sdk_caller = ''
class Solution: # @param word1 & word2: Two string. # @return: The minimum number of steps. def minDistance(self, word1, word2): # write your code here dp = [] for i in range(len(word1) + 1): dp.append([]) for j in range(len(word2) + 1): if (i == 0): dp[i].append(j) elif (j == 0): dp[i].append(i) else: a = dp[i - 1][j] + 1 b = dp[i][j - 1] + 1 c = dp[i - 1][j - 1] if word1[i - 1] == word2[j - 1] else dp[i - 1][j - 1] + 1 dp[i].append(min(a, b, c)) return dp[-1][-1]
class Solution: def min_distance(self, word1, word2): dp = [] for i in range(len(word1) + 1): dp.append([]) for j in range(len(word2) + 1): if i == 0: dp[i].append(j) elif j == 0: dp[i].append(i) else: a = dp[i - 1][j] + 1 b = dp[i][j - 1] + 1 c = dp[i - 1][j - 1] if word1[i - 1] == word2[j - 1] else dp[i - 1][j - 1] + 1 dp[i].append(min(a, b, c)) return dp[-1][-1]
fp = open("assets/virus2.csv", "r", encoding="utf-8") lines = fp.readlines() fp.close() n = len(lines) if lines[n-1][0:10] == lines[n-2][0:10]: lines.pop(n-2) pass with open("assets/virus2.csv", "w", encoding="utf-8") as fp: start = 10 stop = 26 id = 0 for line in lines: if id !=0: fp.write(line[0: 10:] + line[26::]) else: fp.write(line) id += 1 print("finished!")
fp = open('assets/virus2.csv', 'r', encoding='utf-8') lines = fp.readlines() fp.close() n = len(lines) if lines[n - 1][0:10] == lines[n - 2][0:10]: lines.pop(n - 2) pass with open('assets/virus2.csv', 'w', encoding='utf-8') as fp: start = 10 stop = 26 id = 0 for line in lines: if id != 0: fp.write(line[0:10] + line[26:]) else: fp.write(line) id += 1 print('finished!')
# # PySNMP MIB module ZHONE-COM-IP-FILTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-COM-IP-FILTER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:40:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibIdentifier, ObjectIdentity, NotificationType, Unsigned32, Counter32, Integer32, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Bits, TimeTicks, Gauge32, Counter64, iso = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "ObjectIdentity", "NotificationType", "Unsigned32", "Counter32", "Integer32", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Bits", "TimeTicks", "Gauge32", "Counter64", "iso") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") zhoneModules, zhoneIp = mibBuilder.importSymbols("Zhone", "zhoneModules", "zhoneIp") ZhoneRowStatus, ZhoneAdminString = mibBuilder.importSymbols("Zhone-TC", "ZhoneRowStatus", "ZhoneAdminString") comIpFilter = ModuleIdentity((1, 3, 6, 1, 4, 1, 5504, 6, 58)) comIpFilter.setRevisions(('2005-01-10 10:16', '2005-01-03 09:24', '2004-12-21 09:25', '2004-08-30 11:00', '2004-04-06 00:17', '2001-01-17 08:48', '2000-09-11 16:22',)) if mibBuilder.loadTexts: comIpFilter.setLastUpdated('200501100015Z') if mibBuilder.loadTexts: comIpFilter.setOrganization('Zhone Technologies, Inc.') filter = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8)) if mibBuilder.loadTexts: filter.setStatus('current') filterGlobal = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1)) if mibBuilder.loadTexts: filterGlobal.setStatus('current') fltGlobalIndexNext = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: fltGlobalIndexNext.setStatus('current') fltGlobalTimeout = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setUnits('seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: fltGlobalTimeout.setStatus('current') filterSpecTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2), ) if mibBuilder.loadTexts: filterSpecTable.setStatus('current') filterSpecEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1), ).setIndexNames((0, "ZHONE-COM-IP-FILTER-MIB", "fltSpecIndex")) if mibBuilder.loadTexts: filterSpecEntry.setStatus('current') fltSpecIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: fltSpecIndex.setStatus('current') fltSpecName = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 2), ZhoneAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltSpecName.setStatus('current') fltSpecDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 3), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltSpecDesc.setStatus('current') fltSpecVersion1 = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 4), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltSpecVersion1.setStatus('current') fltSpecVersion2 = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 5), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltSpecVersion2.setStatus('current') fltSpecLanguageVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 6), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltSpecLanguageVersion.setStatus('current') fltSpecRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 7), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltSpecRowStatus.setStatus('current') filterStatementTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3), ) if mibBuilder.loadTexts: filterStatementTable.setStatus('current') filterStatementEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1), ).setIndexNames((0, "ZHONE-COM-IP-FILTER-MIB", "fltSpecIndex"), (0, "ZHONE-COM-IP-FILTER-MIB", "fltStmtIndex")) if mibBuilder.loadTexts: filterStatementEntry.setStatus('current') fltStmtIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: fltStmtIndex.setStatus('current') fltStmtIpSrcAddrLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 2), IpAddress().clone(hexValue="00000000")).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtIpSrcAddrLow.setStatus('current') fltStmtIpSrcAddrHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 3), IpAddress().clone(hexValue="00000000")).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtIpSrcAddrHigh.setStatus('current') fltStmtSrcPortLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtSrcPortLow.setStatus('current') fltStmtSrcPortHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtSrcPortHigh.setStatus('current') fltStmtIpDstAddrLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 6), IpAddress().clone(hexValue="00000000")).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtIpDstAddrLow.setStatus('current') fltStmtIpDstAddrHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 7), IpAddress().clone(hexValue="00000000")).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtIpDstAddrHigh.setStatus('current') fltStmtDstPortLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtDstPortLow.setStatus('current') fltStmtDstPortHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtDstPortHigh.setStatus('current') fltStmtIpProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("any", 1), ("ip", 2), ("tcp", 3), ("udp", 4), ("icmp", 5))).clone('any')).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtIpProtocol.setStatus('current') fltStmtArbValueBase = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("none", 1), ("ip", 2), ("udp", 3), ("tcp", 4), ("icmp", 5), ("ipOptions", 6), ("tcpOptions", 7))).clone('none')).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtArbValueBase.setStatus('current') fltStmtArbOffset = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtArbOffset.setStatus('current') fltStmtArbMask = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 13), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtArbMask.setStatus('current') fltStmtArbValueLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 14), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtArbValueLow.setStatus('current') fltStmtArbValueHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 15), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtArbValueHigh.setStatus('current') fltStmtModifier = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 16), Bits().clone(namedValues=NamedValues(("notIpSrc", 0), ("notSrcPort", 1), ("notDstIp", 2), ("notPortDst", 3), ("notProtocol", 4), ("notArbitrary", 5), ("notStatement", 6)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtModifier.setStatus('current') fltStmtAction = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 17), Bits().clone(namedValues=NamedValues(("reset", 0), ("permit", 1), ("deny", 2), ("forward", 3), ("reject", 4), ("log", 5))).clone(namedValues=NamedValues(("deny", 2)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtAction.setStatus('current') fltStmtActionArg = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 18), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtActionArg.setStatus('current') fltStmtRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 19), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtRowStatus.setStatus('current') filterStmtRenumTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4), ) if mibBuilder.loadTexts: filterStmtRenumTable.setStatus('current') filterStmtRenumEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4, 1), ) filterStatementEntry.registerAugmentions(("ZHONE-COM-IP-FILTER-MIB", "filterStmtRenumEntry")) filterStmtRenumEntry.setIndexNames(*filterStatementEntry.getIndexNames()) if mibBuilder.loadTexts: filterStmtRenumEntry.setStatus('current') fltStmtIndexNew = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readwrite") if mibBuilder.loadTexts: fltStmtIndexNew.setStatus('current') filterStatsTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5), ) if mibBuilder.loadTexts: filterStatsTable.setStatus('current') filterStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "ZHONE-COM-IP-FILTER-MIB", "fltStatDirection")) if mibBuilder.loadTexts: filterStatsEntry.setStatus('current') fltStatDirection = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ingress", 1), ("egress", 2)))) if mibBuilder.loadTexts: fltStatDirection.setStatus('current') fltStatResetPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 2), Counter32()).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatResetPkts.setStatus('current') fltStatPermitPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 3), Counter32()).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatPermitPkts.setStatus('current') fltStatDenyPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 4), Counter32()).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatDenyPkts.setStatus('current') fltStatForwardPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 5), Counter32()).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatForwardPkts.setStatus('current') fltStatRejectPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 6), Counter32()).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatRejectPkts.setStatus('current') fltStatLogPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 7), Counter32()).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatLogPkts.setStatus('current') fltStatDefaultPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatDefaultPkts.setStatus('current') fltStatSpecVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 9), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatSpecVersion.setStatus('current') fltStatSpecIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatSpecIndex.setStatus('current') mcastControl = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6)) if mibBuilder.loadTexts: mcastControl.setStatus('current') mcastControlListTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1), ) if mibBuilder.loadTexts: mcastControlListTable.setStatus('current') mcastControlListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1), ).setIndexNames((0, "ZHONE-COM-IP-FILTER-MIB", "mcastControlListControlId"), (0, "ZHONE-COM-IP-FILTER-MIB", "mcastControlListControlPrecedence")) if mibBuilder.loadTexts: mcastControlListEntry.setStatus('current') mcastControlListControlId = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: mcastControlListControlId.setStatus('current') mcastControlListControlPrecedence = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: mcastControlListControlPrecedence.setStatus('current') mcastControlListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 3), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mcastControlListRowStatus.setStatus('current') mcastControlListIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 4), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mcastControlListIpAddress.setStatus('current') mcastControlListType = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("normal", 1), ("always-on", 2), ("periodic", 3))).clone('normal')).setMaxAccess("readcreate") if mibBuilder.loadTexts: mcastControlListType.setStatus('current') portAccessControl = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7)) if mibBuilder.loadTexts: portAccessControl.setStatus('current') portAccessNextIndex = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: portAccessNextIndex.setStatus('current') portAccessTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2), ) if mibBuilder.loadTexts: portAccessTable.setStatus('current') portAccessEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1), ).setIndexNames((0, "ZHONE-COM-IP-FILTER-MIB", "portAccessIndex")) if mibBuilder.loadTexts: portAccessEntry.setStatus('current') portAccessIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100))) if mibBuilder.loadTexts: portAccessIndex.setStatus('current') portAccessRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 2), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: portAccessRowStatus.setStatus('current') portAccessNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1023))).setMaxAccess("readcreate") if mibBuilder.loadTexts: portAccessNumber.setStatus('current') portAccessSrcAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 4), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: portAccessSrcAddr.setStatus('current') portAccessNetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 5), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: portAccessNetMask.setStatus('current') mibBuilder.exportSymbols("ZHONE-COM-IP-FILTER-MIB", fltStmtSrcPortHigh=fltStmtSrcPortHigh, fltStmtArbMask=fltStmtArbMask, mcastControlListIpAddress=mcastControlListIpAddress, fltSpecDesc=fltSpecDesc, fltSpecName=fltSpecName, fltStmtIpSrcAddrLow=fltStmtIpSrcAddrLow, mcastControlListRowStatus=mcastControlListRowStatus, fltStmtArbOffset=fltStmtArbOffset, fltStatPermitPkts=fltStatPermitPkts, fltStmtRowStatus=fltStmtRowStatus, mcastControlListTable=mcastControlListTable, fltStatDenyPkts=fltStatDenyPkts, filterStatementTable=filterStatementTable, filterGlobal=filterGlobal, PYSNMP_MODULE_ID=comIpFilter, fltStmtIpDstAddrLow=fltStmtIpDstAddrLow, fltStmtDstPortHigh=fltStmtDstPortHigh, fltStmtActionArg=fltStmtActionArg, portAccessNextIndex=portAccessNextIndex, fltSpecVersion1=fltSpecVersion1, filterSpecEntry=filterSpecEntry, filterStmtRenumTable=filterStmtRenumTable, portAccessEntry=portAccessEntry, mcastControlListControlPrecedence=mcastControlListControlPrecedence, portAccessSrcAddr=portAccessSrcAddr, portAccessControl=portAccessControl, mcastControlListControlId=mcastControlListControlId, fltSpecLanguageVersion=fltSpecLanguageVersion, fltStmtIpSrcAddrHigh=fltStmtIpSrcAddrHigh, fltStatDirection=fltStatDirection, mcastControl=mcastControl, fltStatSpecIndex=fltStatSpecIndex, fltStmtArbValueBase=fltStmtArbValueBase, fltStmtArbValueHigh=fltStmtArbValueHigh, fltStmtSrcPortLow=fltStmtSrcPortLow, fltStmtIpProtocol=fltStmtIpProtocol, fltSpecIndex=fltSpecIndex, fltStmtArbValueLow=fltStmtArbValueLow, fltGlobalTimeout=fltGlobalTimeout, fltStmtModifier=fltStmtModifier, fltStatForwardPkts=fltStatForwardPkts, filterSpecTable=filterSpecTable, fltStmtDstPortLow=fltStmtDstPortLow, filterStatsEntry=filterStatsEntry, fltStatDefaultPkts=fltStatDefaultPkts, portAccessRowStatus=portAccessRowStatus, fltStmtAction=fltStmtAction, fltStmtIpDstAddrHigh=fltStmtIpDstAddrHigh, portAccessNetMask=portAccessNetMask, portAccessTable=portAccessTable, filterStatementEntry=filterStatementEntry, filter=filter, fltSpecVersion2=fltSpecVersion2, fltStmtIndexNew=fltStmtIndexNew, filterStmtRenumEntry=filterStmtRenumEntry, fltSpecRowStatus=fltSpecRowStatus, filterStatsTable=filterStatsTable, portAccessIndex=portAccessIndex, fltStatSpecVersion=fltStatSpecVersion, portAccessNumber=portAccessNumber, fltGlobalIndexNext=fltGlobalIndexNext, mcastControlListEntry=mcastControlListEntry, mcastControlListType=mcastControlListType, fltStmtIndex=fltStmtIndex, fltStatRejectPkts=fltStatRejectPkts, comIpFilter=comIpFilter, fltStatLogPkts=fltStatLogPkts, fltStatResetPkts=fltStatResetPkts)
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_union, constraints_intersection, single_value_constraint, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueRangeConstraint') (if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex') (snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (mib_identifier, object_identity, notification_type, unsigned32, counter32, integer32, module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, bits, time_ticks, gauge32, counter64, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'ObjectIdentity', 'NotificationType', 'Unsigned32', 'Counter32', 'Integer32', 'ModuleIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'Bits', 'TimeTicks', 'Gauge32', 'Counter64', 'iso') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') (zhone_modules, zhone_ip) = mibBuilder.importSymbols('Zhone', 'zhoneModules', 'zhoneIp') (zhone_row_status, zhone_admin_string) = mibBuilder.importSymbols('Zhone-TC', 'ZhoneRowStatus', 'ZhoneAdminString') com_ip_filter = module_identity((1, 3, 6, 1, 4, 1, 5504, 6, 58)) comIpFilter.setRevisions(('2005-01-10 10:16', '2005-01-03 09:24', '2004-12-21 09:25', '2004-08-30 11:00', '2004-04-06 00:17', '2001-01-17 08:48', '2000-09-11 16:22')) if mibBuilder.loadTexts: comIpFilter.setLastUpdated('200501100015Z') if mibBuilder.loadTexts: comIpFilter.setOrganization('Zhone Technologies, Inc.') filter = object_identity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8)) if mibBuilder.loadTexts: filter.setStatus('current') filter_global = object_identity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1)) if mibBuilder.loadTexts: filterGlobal.setStatus('current') flt_global_index_next = mib_scalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setMaxAccess('readonly') if mibBuilder.loadTexts: fltGlobalIndexNext.setStatus('current') flt_global_timeout = mib_scalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setUnits('seconds').setMaxAccess('readwrite') if mibBuilder.loadTexts: fltGlobalTimeout.setStatus('current') filter_spec_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2)) if mibBuilder.loadTexts: filterSpecTable.setStatus('current') filter_spec_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1)).setIndexNames((0, 'ZHONE-COM-IP-FILTER-MIB', 'fltSpecIndex')) if mibBuilder.loadTexts: filterSpecEntry.setStatus('current') flt_spec_index = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))) if mibBuilder.loadTexts: fltSpecIndex.setStatus('current') flt_spec_name = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 2), zhone_admin_string()).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltSpecName.setStatus('current') flt_spec_desc = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 3), snmp_admin_string()).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltSpecDesc.setStatus('current') flt_spec_version1 = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 4), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltSpecVersion1.setStatus('current') flt_spec_version2 = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 5), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltSpecVersion2.setStatus('current') flt_spec_language_version = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 6), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltSpecLanguageVersion.setStatus('current') flt_spec_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 7), zhone_row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltSpecRowStatus.setStatus('current') filter_statement_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3)) if mibBuilder.loadTexts: filterStatementTable.setStatus('current') filter_statement_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1)).setIndexNames((0, 'ZHONE-COM-IP-FILTER-MIB', 'fltSpecIndex'), (0, 'ZHONE-COM-IP-FILTER-MIB', 'fltStmtIndex')) if mibBuilder.loadTexts: filterStatementEntry.setStatus('current') flt_stmt_index = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))) if mibBuilder.loadTexts: fltStmtIndex.setStatus('current') flt_stmt_ip_src_addr_low = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 2), ip_address().clone(hexValue='00000000')).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtIpSrcAddrLow.setStatus('current') flt_stmt_ip_src_addr_high = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 3), ip_address().clone(hexValue='00000000')).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtIpSrcAddrHigh.setStatus('current') flt_stmt_src_port_low = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtSrcPortLow.setStatus('current') flt_stmt_src_port_high = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtSrcPortHigh.setStatus('current') flt_stmt_ip_dst_addr_low = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 6), ip_address().clone(hexValue='00000000')).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtIpDstAddrLow.setStatus('current') flt_stmt_ip_dst_addr_high = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 7), ip_address().clone(hexValue='00000000')).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtIpDstAddrHigh.setStatus('current') flt_stmt_dst_port_low = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 8), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtDstPortLow.setStatus('current') flt_stmt_dst_port_high = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 9), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtDstPortHigh.setStatus('current') flt_stmt_ip_protocol = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('any', 1), ('ip', 2), ('tcp', 3), ('udp', 4), ('icmp', 5))).clone('any')).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtIpProtocol.setStatus('current') flt_stmt_arb_value_base = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 11), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=named_values(('none', 1), ('ip', 2), ('udp', 3), ('tcp', 4), ('icmp', 5), ('ipOptions', 6), ('tcpOptions', 7))).clone('none')).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtArbValueBase.setStatus('current') flt_stmt_arb_offset = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 12), integer32().subtype(subtypeSpec=value_range_constraint(0, 64))).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtArbOffset.setStatus('current') flt_stmt_arb_mask = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 13), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtArbMask.setStatus('current') flt_stmt_arb_value_low = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 14), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtArbValueLow.setStatus('current') flt_stmt_arb_value_high = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 15), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtArbValueHigh.setStatus('current') flt_stmt_modifier = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 16), bits().clone(namedValues=named_values(('notIpSrc', 0), ('notSrcPort', 1), ('notDstIp', 2), ('notPortDst', 3), ('notProtocol', 4), ('notArbitrary', 5), ('notStatement', 6)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtModifier.setStatus('current') flt_stmt_action = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 17), bits().clone(namedValues=named_values(('reset', 0), ('permit', 1), ('deny', 2), ('forward', 3), ('reject', 4), ('log', 5))).clone(namedValues=named_values(('deny', 2)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtAction.setStatus('current') flt_stmt_action_arg = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 18), integer32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtActionArg.setStatus('current') flt_stmt_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 19), zhone_row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: fltStmtRowStatus.setStatus('current') filter_stmt_renum_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4)) if mibBuilder.loadTexts: filterStmtRenumTable.setStatus('current') filter_stmt_renum_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4, 1)) filterStatementEntry.registerAugmentions(('ZHONE-COM-IP-FILTER-MIB', 'filterStmtRenumEntry')) filterStmtRenumEntry.setIndexNames(*filterStatementEntry.getIndexNames()) if mibBuilder.loadTexts: filterStmtRenumEntry.setStatus('current') flt_stmt_index_new = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setMaxAccess('readwrite') if mibBuilder.loadTexts: fltStmtIndexNew.setStatus('current') filter_stats_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5)) if mibBuilder.loadTexts: filterStatsTable.setStatus('current') filter_stats_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'), (0, 'ZHONE-COM-IP-FILTER-MIB', 'fltStatDirection')) if mibBuilder.loadTexts: filterStatsEntry.setStatus('current') flt_stat_direction = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('ingress', 1), ('egress', 2)))) if mibBuilder.loadTexts: fltStatDirection.setStatus('current') flt_stat_reset_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 2), counter32()).setUnits('packets').setMaxAccess('readonly') if mibBuilder.loadTexts: fltStatResetPkts.setStatus('current') flt_stat_permit_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 3), counter32()).setUnits('packets').setMaxAccess('readonly') if mibBuilder.loadTexts: fltStatPermitPkts.setStatus('current') flt_stat_deny_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 4), counter32()).setUnits('packets').setMaxAccess('readonly') if mibBuilder.loadTexts: fltStatDenyPkts.setStatus('current') flt_stat_forward_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 5), counter32()).setUnits('packets').setMaxAccess('readonly') if mibBuilder.loadTexts: fltStatForwardPkts.setStatus('current') flt_stat_reject_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 6), counter32()).setUnits('packets').setMaxAccess('readonly') if mibBuilder.loadTexts: fltStatRejectPkts.setStatus('current') flt_stat_log_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 7), counter32()).setUnits('packets').setMaxAccess('readonly') if mibBuilder.loadTexts: fltStatLogPkts.setStatus('current') flt_stat_default_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 8), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: fltStatDefaultPkts.setStatus('current') flt_stat_spec_version = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 9), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: fltStatSpecVersion.setStatus('current') flt_stat_spec_index = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 10), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setMaxAccess('readonly') if mibBuilder.loadTexts: fltStatSpecIndex.setStatus('current') mcast_control = object_identity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6)) if mibBuilder.loadTexts: mcastControl.setStatus('current') mcast_control_list_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1)) if mibBuilder.loadTexts: mcastControlListTable.setStatus('current') mcast_control_list_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1)).setIndexNames((0, 'ZHONE-COM-IP-FILTER-MIB', 'mcastControlListControlId'), (0, 'ZHONE-COM-IP-FILTER-MIB', 'mcastControlListControlPrecedence')) if mibBuilder.loadTexts: mcastControlListEntry.setStatus('current') mcast_control_list_control_id = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))) if mibBuilder.loadTexts: mcastControlListControlId.setStatus('current') mcast_control_list_control_precedence = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))) if mibBuilder.loadTexts: mcastControlListControlPrecedence.setStatus('current') mcast_control_list_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 3), zhone_row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: mcastControlListRowStatus.setStatus('current') mcast_control_list_ip_address = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 4), ip_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: mcastControlListIpAddress.setStatus('current') mcast_control_list_type = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('normal', 1), ('always-on', 2), ('periodic', 3))).clone('normal')).setMaxAccess('readcreate') if mibBuilder.loadTexts: mcastControlListType.setStatus('current') port_access_control = object_identity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7)) if mibBuilder.loadTexts: portAccessControl.setStatus('current') port_access_next_index = mib_scalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: portAccessNextIndex.setStatus('current') port_access_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2)) if mibBuilder.loadTexts: portAccessTable.setStatus('current') port_access_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1)).setIndexNames((0, 'ZHONE-COM-IP-FILTER-MIB', 'portAccessIndex')) if mibBuilder.loadTexts: portAccessEntry.setStatus('current') port_access_index = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 100))) if mibBuilder.loadTexts: portAccessIndex.setStatus('current') port_access_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 2), zhone_row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: portAccessRowStatus.setStatus('current') port_access_number = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(1, 1023))).setMaxAccess('readcreate') if mibBuilder.loadTexts: portAccessNumber.setStatus('current') port_access_src_addr = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 4), ip_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: portAccessSrcAddr.setStatus('current') port_access_net_mask = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 5), ip_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: portAccessNetMask.setStatus('current') mibBuilder.exportSymbols('ZHONE-COM-IP-FILTER-MIB', fltStmtSrcPortHigh=fltStmtSrcPortHigh, fltStmtArbMask=fltStmtArbMask, mcastControlListIpAddress=mcastControlListIpAddress, fltSpecDesc=fltSpecDesc, fltSpecName=fltSpecName, fltStmtIpSrcAddrLow=fltStmtIpSrcAddrLow, mcastControlListRowStatus=mcastControlListRowStatus, fltStmtArbOffset=fltStmtArbOffset, fltStatPermitPkts=fltStatPermitPkts, fltStmtRowStatus=fltStmtRowStatus, mcastControlListTable=mcastControlListTable, fltStatDenyPkts=fltStatDenyPkts, filterStatementTable=filterStatementTable, filterGlobal=filterGlobal, PYSNMP_MODULE_ID=comIpFilter, fltStmtIpDstAddrLow=fltStmtIpDstAddrLow, fltStmtDstPortHigh=fltStmtDstPortHigh, fltStmtActionArg=fltStmtActionArg, portAccessNextIndex=portAccessNextIndex, fltSpecVersion1=fltSpecVersion1, filterSpecEntry=filterSpecEntry, filterStmtRenumTable=filterStmtRenumTable, portAccessEntry=portAccessEntry, mcastControlListControlPrecedence=mcastControlListControlPrecedence, portAccessSrcAddr=portAccessSrcAddr, portAccessControl=portAccessControl, mcastControlListControlId=mcastControlListControlId, fltSpecLanguageVersion=fltSpecLanguageVersion, fltStmtIpSrcAddrHigh=fltStmtIpSrcAddrHigh, fltStatDirection=fltStatDirection, mcastControl=mcastControl, fltStatSpecIndex=fltStatSpecIndex, fltStmtArbValueBase=fltStmtArbValueBase, fltStmtArbValueHigh=fltStmtArbValueHigh, fltStmtSrcPortLow=fltStmtSrcPortLow, fltStmtIpProtocol=fltStmtIpProtocol, fltSpecIndex=fltSpecIndex, fltStmtArbValueLow=fltStmtArbValueLow, fltGlobalTimeout=fltGlobalTimeout, fltStmtModifier=fltStmtModifier, fltStatForwardPkts=fltStatForwardPkts, filterSpecTable=filterSpecTable, fltStmtDstPortLow=fltStmtDstPortLow, filterStatsEntry=filterStatsEntry, fltStatDefaultPkts=fltStatDefaultPkts, portAccessRowStatus=portAccessRowStatus, fltStmtAction=fltStmtAction, fltStmtIpDstAddrHigh=fltStmtIpDstAddrHigh, portAccessNetMask=portAccessNetMask, portAccessTable=portAccessTable, filterStatementEntry=filterStatementEntry, filter=filter, fltSpecVersion2=fltSpecVersion2, fltStmtIndexNew=fltStmtIndexNew, filterStmtRenumEntry=filterStmtRenumEntry, fltSpecRowStatus=fltSpecRowStatus, filterStatsTable=filterStatsTable, portAccessIndex=portAccessIndex, fltStatSpecVersion=fltStatSpecVersion, portAccessNumber=portAccessNumber, fltGlobalIndexNext=fltGlobalIndexNext, mcastControlListEntry=mcastControlListEntry, mcastControlListType=mcastControlListType, fltStmtIndex=fltStmtIndex, fltStatRejectPkts=fltStatRejectPkts, comIpFilter=comIpFilter, fltStatLogPkts=fltStatLogPkts, fltStatResetPkts=fltStatResetPkts)
user = "" password = "" host = "127.0.0.1" database = "" raise_on_warnings = True config = { "user": user, "password": password, "host": host, "database": database, "raise_on_warnings": raise_on_warnings, } def set_configs(user=None, password=None, database=None): config["user"] = user config["password"] = password config["database"] = database
user = '' password = '' host = '127.0.0.1' database = '' raise_on_warnings = True config = {'user': user, 'password': password, 'host': host, 'database': database, 'raise_on_warnings': raise_on_warnings} def set_configs(user=None, password=None, database=None): config['user'] = user config['password'] = password config['database'] = database
dic = { 'color':'red', 'typw':'car', 'price': 1250 }
dic = {'color': 'red', 'typw': 'car', 'price': 1250}
# Store the RSS feed IDs for each of the topics in the CNBC client. cnbc_rss_feeds_id = { 'top_news': 100003114, 'world_news': 100727362, 'us_news': 15837362, 'asia_news': 19832390, 'europe_news': 19794221, 'business': 10001147, 'earnings': 15839135, 'commentary': 100370673, 'economy': 20910258, 'finance': 10000664, 'technology': 19854910, 'politics': 10000113, 'health_care': 10000108, 'real_estate': 10000115, 'wealth': 10001054, 'autos': 10000101, 'energy': 19836768, 'media': 10000110, 'retail': 10000116, 'travel': 10000739, 'small_business': 44877279, 'investing': 15839069, 'financial_advisors': 100646281, 'personal_finance': 21324812, 'charting_asia': 23103686, 'funny_business': 17646093, 'market_insider': 20409666, 'netnet': 38818154, 'trader_talk': 20398120, 'buffett_watch': 19206666, 'top_video': 15839263, 'digital_workshop': 100616801, 'latest_video': 100004038, 'ceo_interviews': 100004032, 'analyst_interviews': 100004033, 'must_watch': 101014894, 'squawk_box': 15838368, 'squawk_on_the_street': 15838381, 'power_lunch': 15838342, 'street_signs': 15838408, 'options_action': 28282083, 'closing_bell': 15838421, 'fast_money': 15838499, 'mad_money': 15838459, 'kudlow_report': 15838446, 'futures_now': 48227449, 'suze_orman': 15838523, 'capital_connection': 17501773, 'squawk_box_europe': 15838652, 'worldwide_exchange': 15838355, 'squawk_box_asia': 15838831, 'the_call': 37447855, }
cnbc_rss_feeds_id = {'top_news': 100003114, 'world_news': 100727362, 'us_news': 15837362, 'asia_news': 19832390, 'europe_news': 19794221, 'business': 10001147, 'earnings': 15839135, 'commentary': 100370673, 'economy': 20910258, 'finance': 10000664, 'technology': 19854910, 'politics': 10000113, 'health_care': 10000108, 'real_estate': 10000115, 'wealth': 10001054, 'autos': 10000101, 'energy': 19836768, 'media': 10000110, 'retail': 10000116, 'travel': 10000739, 'small_business': 44877279, 'investing': 15839069, 'financial_advisors': 100646281, 'personal_finance': 21324812, 'charting_asia': 23103686, 'funny_business': 17646093, 'market_insider': 20409666, 'netnet': 38818154, 'trader_talk': 20398120, 'buffett_watch': 19206666, 'top_video': 15839263, 'digital_workshop': 100616801, 'latest_video': 100004038, 'ceo_interviews': 100004032, 'analyst_interviews': 100004033, 'must_watch': 101014894, 'squawk_box': 15838368, 'squawk_on_the_street': 15838381, 'power_lunch': 15838342, 'street_signs': 15838408, 'options_action': 28282083, 'closing_bell': 15838421, 'fast_money': 15838499, 'mad_money': 15838459, 'kudlow_report': 15838446, 'futures_now': 48227449, 'suze_orman': 15838523, 'capital_connection': 17501773, 'squawk_box_europe': 15838652, 'worldwide_exchange': 15838355, 'squawk_box_asia': 15838831, 'the_call': 37447855}
class BasicCalculator: def __init__(self): return def sum(self, num1, num2): return num1 + num2 def sub(self, num1, num2): return num1 - num2 def mul(self, num1, num2): return num1 * num2 def div(self, num1, num2): return num1 / num2 class AdvancedCalculator(BasicCalculator): def __init__(self): return def pow(self, num, power): foo = num while power > 0: print(power) num *= foo power -= 1 return num def square(self, num): return pow(self, num, 2) def cube(self, num): return pow(self, num, 3) class ScientificCalculator(AdvancedCalculator): def __init__(self): return def average(self, *nums): sum = 0 count = 0 for num in nums: count += 1 sum += num return int(sum / count)
class Basiccalculator: def __init__(self): return def sum(self, num1, num2): return num1 + num2 def sub(self, num1, num2): return num1 - num2 def mul(self, num1, num2): return num1 * num2 def div(self, num1, num2): return num1 / num2 class Advancedcalculator(BasicCalculator): def __init__(self): return def pow(self, num, power): foo = num while power > 0: print(power) num *= foo power -= 1 return num def square(self, num): return pow(self, num, 2) def cube(self, num): return pow(self, num, 3) class Scientificcalculator(AdvancedCalculator): def __init__(self): return def average(self, *nums): sum = 0 count = 0 for num in nums: count += 1 sum += num return int(sum / count)
#!/usr/bin/env python3 def harmasosztas(szam): if szam in range(0, 10): return "00" + str(szam) elif szam in range(10, 100): return "0" + str(szam) elif szam in range(100, 1000): return szam else: return str(harmasosztas(szam // 1000)) + " " + str(harmasosztas(szam % 1000)) def main(): print(harmasosztas(1000222)) main()
def harmasosztas(szam): if szam in range(0, 10): return '00' + str(szam) elif szam in range(10, 100): return '0' + str(szam) elif szam in range(100, 1000): return szam else: return str(harmasosztas(szam // 1000)) + ' ' + str(harmasosztas(szam % 1000)) def main(): print(harmasosztas(1000222)) main()
keywords = ["asm","else","new","this","auto","enum","operator","throw","bool","explicit","private","true","break","export","protected","try","case","extern","public","typedef","catch","false","register","typeid","char","float","reinterpret_cast","typename","class","for","return","union","const","friend","short","unsigned","const_cast","goto","signed", "using","continue","if","sizeof","virtual","default","inline","static","void","delete", "int","static_cast","volatile","do","long","struct","wchar_t","double","mutable","switch","while",'dynamic_cast',"namespace","template"] operator = ["+", "-", "*", "/", "%", "="] punc_marks = ["<", ">", "#", "}", "{", "(", ")", ":", ";", ","] key_count = [0]*len(keywords) op_count = [0]*len(operator) pun_count = [0]*len(punc_marks) with open('1.cpp', 'r') as f: sample = f.read() words = [] lines = sample.split("\n") for i in lines: for j in range(0, len(i)): if i[j] == "/" and i[j+1] == "/": lines.remove(i) for word in lines: words.append(word.split(" ")) if word.split("(") not in words: words.append(word.split("(")) else: if word.split(")") not in words: words.append(word.split(")")) else: if word.split(")") not in words: words.append(word.split(")")) else: if word.split("#") not in words: words.append(word.split(";")) else: if word.split("#") not in words: words.append(word.split("#")) else: if word.split("<") not in words: words.append(word.split("<")) else: if word.split(">") not in words: words.append(word.split(">")) else: if word.split(":") not in words: words.append(word.split(":")) for line in sample: for ch in line: for i in range(0, len(operator)): if ch == operator[i]: op_count[i] += 1 for i in range(0, len(punc_marks)): if ch == punc_marks[i]: pun_count[i] += 1 q = [] for i in words: for j in i: q.append(j) for i in range(0, len(q)): if q[i] in keywords: ind = keywords.index(q[i]) key_count[ind] += 1 if q[i] in operator: ind = operator.index(q[i]) op_count[ind] += 1 if q[i] in punc_marks: ind = punc_marks.index(q[i]) pun_count[ind] += 1 print("Keywords :") for i in range(0, len(keywords)): if key_count[i] > 0: print(keywords[i], ": ", key_count[i]) print("\nOperators :") for i in range(0, len(operator)): if op_count[i] > 0: print(operator[i], ": ", op_count[i]) print("\nPunctuation Marks :") for i in range(0, len(punc_marks)): if pun_count[i] > 0: print(punc_marks[i], ": ", pun_count[i])
keywords = ['asm', 'else', 'new', 'this', 'auto', 'enum', 'operator', 'throw', 'bool', 'explicit', 'private', 'true', 'break', 'export', 'protected', 'try', 'case', 'extern', 'public', 'typedef', 'catch', 'false', 'register', 'typeid', 'char', 'float', 'reinterpret_cast', 'typename', 'class', 'for', 'return', 'union', 'const', 'friend', 'short', 'unsigned', 'const_cast', 'goto', 'signed', 'using', 'continue', 'if', 'sizeof', 'virtual', 'default', 'inline', 'static', 'void', 'delete', 'int', 'static_cast', 'volatile', 'do', 'long', 'struct', 'wchar_t', 'double', 'mutable', 'switch', 'while', 'dynamic_cast', 'namespace', 'template'] operator = ['+', '-', '*', '/', '%', '='] punc_marks = ['<', '>', '#', '}', '{', '(', ')', ':', ';', ','] key_count = [0] * len(keywords) op_count = [0] * len(operator) pun_count = [0] * len(punc_marks) with open('1.cpp', 'r') as f: sample = f.read() words = [] lines = sample.split('\n') for i in lines: for j in range(0, len(i)): if i[j] == '/' and i[j + 1] == '/': lines.remove(i) for word in lines: words.append(word.split(' ')) if word.split('(') not in words: words.append(word.split('(')) elif word.split(')') not in words: words.append(word.split(')')) elif word.split(')') not in words: words.append(word.split(')')) elif word.split('#') not in words: words.append(word.split(';')) elif word.split('#') not in words: words.append(word.split('#')) elif word.split('<') not in words: words.append(word.split('<')) elif word.split('>') not in words: words.append(word.split('>')) elif word.split(':') not in words: words.append(word.split(':')) for line in sample: for ch in line: for i in range(0, len(operator)): if ch == operator[i]: op_count[i] += 1 for i in range(0, len(punc_marks)): if ch == punc_marks[i]: pun_count[i] += 1 q = [] for i in words: for j in i: q.append(j) for i in range(0, len(q)): if q[i] in keywords: ind = keywords.index(q[i]) key_count[ind] += 1 if q[i] in operator: ind = operator.index(q[i]) op_count[ind] += 1 if q[i] in punc_marks: ind = punc_marks.index(q[i]) pun_count[ind] += 1 print('Keywords :') for i in range(0, len(keywords)): if key_count[i] > 0: print(keywords[i], ': ', key_count[i]) print('\nOperators :') for i in range(0, len(operator)): if op_count[i] > 0: print(operator[i], ': ', op_count[i]) print('\nPunctuation Marks :') for i in range(0, len(punc_marks)): if pun_count[i] > 0: print(punc_marks[i], ': ', pun_count[i])
EventRandomDialogue = 1 EventRandomEffects = 2 EventEstateGravity = 3 EventGlobalGravity = 4 EventSirMaxBirthday = 5 RandomCheesyList = [ 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 11, 11] RandomCheesyMinTime = 3 RandomCheesyMaxTime = 60
event_random_dialogue = 1 event_random_effects = 2 event_estate_gravity = 3 event_global_gravity = 4 event_sir_max_birthday = 5 random_cheesy_list = [1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 11, 11] random_cheesy_min_time = 3 random_cheesy_max_time = 60
mylist = [[1,2,3],[4,5,6],[4,3,8]] print("Multi-Dimensional List",mylist) mylist[1].reverse() mylist[0].reverse() print("Multi-Dimensional After Sublist-List",mylist)
mylist = [[1, 2, 3], [4, 5, 6], [4, 3, 8]] print('Multi-Dimensional List', mylist) mylist[1].reverse() mylist[0].reverse() print('Multi-Dimensional After Sublist-List', mylist)
def print_metrics(counter, metrics, summary_writer=None, prefix=None, model_name=""): if 'cls_report' in metrics.keys(): metrics = metrics.copy() del metrics['cls_report'] # print(prefix + "\t" + "\t".join([f"{key}:{value:.5f}" for key, value in metrics.items()])) if summary_writer is not None: assert prefix is not None for key, value in metrics.items(): summary_writer.add_scalar(f'{model_name}_{prefix}_{key}', value, counter)
def print_metrics(counter, metrics, summary_writer=None, prefix=None, model_name=''): if 'cls_report' in metrics.keys(): metrics = metrics.copy() del metrics['cls_report'] if summary_writer is not None: assert prefix is not None for (key, value) in metrics.items(): summary_writer.add_scalar(f'{model_name}_{prefix}_{key}', value, counter)
# Argument that are used to create simulation objects. # # They are resolved as follows: # # 1. Numeric values are inlined. # 2. List and Tuples are iterated over, creating a # separate simulation object for each value. # 3. Strings are evaluated as previous keys of ARGS. # If it fails to find a key, the value is inlined. # # Example # ARGS = { # 'x': 10, # Evaluates to "x 10" # 'y': [10, 20, 30], # Create one simulation for # # each value of y # 'logfile': '~/mylog.txt' # As there is no previous entry with # # the key `logfile`, the string # # '~/mylog.txt' is inlined. # # It evaluates to "logfile ~/mylog.txt" # 'other_x': 'x', # Because `x` is a previous key, # # 'other_x' will have the same value # # of x. # # It evaluates to "other_x 10" # } ARGS = dict() # Sequencial arguments to be passed to the executable. # To set keyword arguments, use `ARGS` # Example: # SEQ_ARGS = [ '-one', '-two' ] SEQ_ARGS = list() # Executable EXECUTABLE = None # Redirect standard input STDIN = None # Redirect standard output STDOUT = None # Redirect standard error STDERR = None # Number of parallel instaces used on the simulation. # Internally, the implementation uses subprocesses to # spawn instances. Avoid using more than the number of # cpus available PARALLEL_INSTANCES = 1 # If True, pysim will capture all SIGINT interruptions and # send them to pysim.core.signals.keyboard_interrupt. CAPTURE_SIGINT = False
args = dict() seq_args = list() executable = None stdin = None stdout = None stderr = None parallel_instances = 1 capture_sigint = False
def entrada(): p,n = map(int,input().split()) x = input().split() for i in range(len(x)): x[i] = int(x[i]) return p,n,x def verifica(a,b,p): if abs(a-b) > p: return True else: return False def main(): p,n,x = entrada() a = False for i in range(n-1): a = verifica(x[i],x[i+1],p) if a == True: print('GAME OVER') break if a == False: print('YOU WIN') main()
def entrada(): (p, n) = map(int, input().split()) x = input().split() for i in range(len(x)): x[i] = int(x[i]) return (p, n, x) def verifica(a, b, p): if abs(a - b) > p: return True else: return False def main(): (p, n, x) = entrada() a = False for i in range(n - 1): a = verifica(x[i], x[i + 1], p) if a == True: print('GAME OVER') break if a == False: print('YOU WIN') main()
''' *** A program for the cryptanalysis of Caesar cipher and identify the plaintext *** ''' #All albhabet Frequencies in Known and meaningful English words al_freq = [0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074] chi_square = [0] * 25 #Decryption of ciphertext with relative decryption key def decrypt(ciphertext, s): pltext = "" for i in range(len(ciphertext)): char = ciphertext[i] if (char.isupper()): pltext += chr((ord(char) - s - 65) % 26 + 65) else: pltext += chr((ord(char) - s - 97) % 26 + 97) return pltext #Finding the key by applying Chi - Square method def find_key(ciphertext, k): l = len(ciphertext) cipher_freq = [0] * 26 ci = [0] * 26 ei = [0] * 26 #ci and ei are Current value of letter and Expected value of letter. for i in range(65, 91): j = i-65 cipher_freq[j] = ciphertext.count(chr(i)) ci[j] = cipher_freq[j] ei[j] = al_freq[j] * l #Calculating Chi - Square value for every plain text with relative decryption key div = 0 for m in range(0, l): num = (ci[int(ord(ciphertext[m]) - 65) % 26] - ei[int(ord(ciphertext[m]) - 65) % 26]) ** 2 den = ei[int(ord(ciphertext[m]) - 65) % 26] div = num / den chi_square[k-1] += div for n in range(0, 26): if ci[n] == 0: chi_square[k-1] += ei[n] #cipher = "aoljhlzhyjpwolypzvulvmaollhysplzaruvduhukzptwslzajpwolyzpapzhafwlvmzbizapabapvujpwolypudopjolhjoslaalypuaolwshpualeapzzopmalkhjlyahpuubtilyvmwshjlzkvduaolhswohila" #cipher = "YMJHFJXFWHNUMJWNXTSJTKYMJJFWQNJXYPSTBSFSIXNRUQJXYHNUMJWX" print("\nEnter the cipher text : ", end="") cipher = str(input()) #Calculating 25 Decrypted(Plain) text with key value 1 to 25 for k in range(1, 26): ciphertext = decrypt(cipher, k) #print(ciphertext + str(k)) ciphertext = ciphertext.upper() find_key(ciphertext, k) #Getting the index of minimum chi - square value which is our Decryption key. index = min(range(25), key = chi_square.__getitem__) index += 1 index = int(index) print("\nFound Decryption Key : " + str(index)) print("\nThe Decrypted Text (Plain Text) : ", end="") print(decrypt(cipher, index)) print("\n")
""" *** A program for the cryptanalysis of Caesar cipher and identify the plaintext *** """ al_freq = [0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.0236, 0.0015, 0.01974, 0.00074] chi_square = [0] * 25 def decrypt(ciphertext, s): pltext = '' for i in range(len(ciphertext)): char = ciphertext[i] if char.isupper(): pltext += chr((ord(char) - s - 65) % 26 + 65) else: pltext += chr((ord(char) - s - 97) % 26 + 97) return pltext def find_key(ciphertext, k): l = len(ciphertext) cipher_freq = [0] * 26 ci = [0] * 26 ei = [0] * 26 for i in range(65, 91): j = i - 65 cipher_freq[j] = ciphertext.count(chr(i)) ci[j] = cipher_freq[j] ei[j] = al_freq[j] * l div = 0 for m in range(0, l): num = (ci[int(ord(ciphertext[m]) - 65) % 26] - ei[int(ord(ciphertext[m]) - 65) % 26]) ** 2 den = ei[int(ord(ciphertext[m]) - 65) % 26] div = num / den chi_square[k - 1] += div for n in range(0, 26): if ci[n] == 0: chi_square[k - 1] += ei[n] print('\nEnter the cipher text : ', end='') cipher = str(input()) for k in range(1, 26): ciphertext = decrypt(cipher, k) ciphertext = ciphertext.upper() find_key(ciphertext, k) index = min(range(25), key=chi_square.__getitem__) index += 1 index = int(index) print('\nFound Decryption Key : ' + str(index)) print('\nThe Decrypted Text (Plain Text) : ', end='') print(decrypt(cipher, index)) print('\n')
def main(): usernameStr = input("Enter username:") passwordStr = input("Enter password:") browser = webdriver.Chrome() browser.get(('http://192.168.100.100:8090/')) # fill in username and hit the next button username = browser.find_element_by_id('username') username.send_keys(usernameStr) nextButton = browser.find_element_by_id('password') nextButton.click() # wait for transition then continue to fill items password = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.NAME, "password"))) password.send_keys(passwordStr) signInButton = browser.find_element_by_id('loginbutton') signInButton.click()
def main(): username_str = input('Enter username:') password_str = input('Enter password:') browser = webdriver.Chrome() browser.get('http://192.168.100.100:8090/') username = browser.find_element_by_id('username') username.send_keys(usernameStr) next_button = browser.find_element_by_id('password') nextButton.click() password = web_driver_wait(browser, 10).until(EC.presence_of_element_located((By.NAME, 'password'))) password.send_keys(passwordStr) sign_in_button = browser.find_element_by_id('loginbutton') signInButton.click()
class DkuApplication(object): def __init__(self, name, label, source, model_func, preprocessing, weights, input_shape=None): self.name = name self.label = label self.source = source self.model_func = model_func self.preprocessing = preprocessing self.input_shape = input_shape self.weights = weights self.model = None def is_keras_application(self): return self.source == "keras" def get_weights_url(self, trained_on): assert trained_on in self.weights, "You provided a wrong field 'trained_on'. Avilable are {}.".format( str(self.weights.keys()) ) return self.weights.get(trained_on) def jsonify(self): return self.name.value
class Dkuapplication(object): def __init__(self, name, label, source, model_func, preprocessing, weights, input_shape=None): self.name = name self.label = label self.source = source self.model_func = model_func self.preprocessing = preprocessing self.input_shape = input_shape self.weights = weights self.model = None def is_keras_application(self): return self.source == 'keras' def get_weights_url(self, trained_on): assert trained_on in self.weights, "You provided a wrong field 'trained_on'. Avilable are {}.".format(str(self.weights.keys())) return self.weights.get(trained_on) def jsonify(self): return self.name.value
# Use for, .split(), and if to create a Statement that will print out words that start with 's': print("Challenge 1 : ") st = 'Print only the words that start with s in this sentence' for word in st.split(): if word[0]=='s' or word[0]=='S': print(word) # Use range() to print all the even numbers from 0 to 10. l1= list(range(0,11,2)) print(l1) for num in range(0,11,2): print(num) # Use a List Comprehension to create a list of all numbers between 1 and 50 that are divisible by 3. print("Challenge 3 : ") list1 =[i for i in range(1,51) if i%3==0] print(list1) # Go through the string below and if the length of a word is even print "even!" st1 = 'Print every word in this sentence that has an even number of letters' print("Challenge 4 : ") for i in st1.split(): if len(i) %2==0: print(f"{i}: even") # Write a program that prints the integers from 1 to 100. But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". for n in range(1,101): if n % 3==0 and n % 5== 0: print("FizzBuzz") elif n % 3 ==0: print("Fizz") elif n % 5 ==0: print("Buzz") else: print(n) # Use List Comprehension to create a list of the first letters of every word in the string below: st2 = 'Create a list of the first letters of every word in this string' list1 =[ i[0] for i in st2.split()] print(list1)
print('Challenge 1 : ') st = 'Print only the words that start with s in this sentence' for word in st.split(): if word[0] == 's' or word[0] == 'S': print(word) l1 = list(range(0, 11, 2)) print(l1) for num in range(0, 11, 2): print(num) print('Challenge 3 : ') list1 = [i for i in range(1, 51) if i % 3 == 0] print(list1) st1 = 'Print every word in this sentence that has an even number of letters' print('Challenge 4 : ') for i in st1.split(): if len(i) % 2 == 0: print(f'{i}: even') for n in range(1, 101): if n % 3 == 0 and n % 5 == 0: print('FizzBuzz') elif n % 3 == 0: print('Fizz') elif n % 5 == 0: print('Buzz') else: print(n) st2 = 'Create a list of the first letters of every word in this string' list1 = [i[0] for i in st2.split()] print(list1)
eUnit = { 0: "Academy, Disabled", 1: "Gator, disabled", 3: "Archer, D", 4: "Archer", 5: "Hand Cannoneer", 6: "Elite Skirmisher", 7: "Skirmisher", 8: "Longbowman", 9: "Arrow", 10: "Archery Range 3", 11: "Mangudai", 12: "Barracks", 13: "Fishing Ship", 14: "Archery Range 4", 15: "Junk", 16: "Bombard Cannon, D", 17: "Trade Cog", 18: "Blacksmith 3", 19: "Blacksmith 4", 20: "Barracks 4", 21: "War Galley", 22: "Berserk, D", 23: "Battering Ram, D", 24: "Crossbowman", 25: "Teutonic Knight", 26: "Crossbowman, D", 27: "Cataphract, D", 28: "Cho-Ko-Nu, D", 29: "Trading Cog, D", 30: "Monastery 2", 31: "Monastery 3", 32: "Monastery 4", 33: "Castle 4", 34: "Cavalry Archer, D", 35: "Battering Ram", 36: "Bombard Cannon", 37: "LANCE", 38: "Knight", 39: "Cavalry Archer", 40: "Cataphract", 41: "Huskarl", 42: "Trebuchet (Unpacked)", 43: "Deer, D", 44: "Mameluke, D", 45: "Dock", 46: "Janissary", 47: "Dock 3", 48: "Boar", 49: "Siege Workshop", 50: "Farm", 51: "Dock 4", 52: "Fish 1, Disabled", 53: "Fish (Perch)", 54: "Proj, VOL", 55: "Fishing Ship, D", 56: "Fisher, M", 57: "Fisher, F", 58: "Fisher, M D", 59: "Forage Bush", 60: "Fisher, F D", 61: "Galley, D (Canoe?)", 62: "Huskarl (E?), D", 63: "Gate, AA3", 64: "Gate, AA2", 65: "Deer", 66: "Gold Mine", 67: "Gate, AB3", 68: "Mill", 69: "Fish, Shore", 70: "House", 71: "Town Center 2", 72: "Wall, Palisade", 73: "Chu Ko Nu", 74: "Militia", 75: "Man At Arms", 76: "Heavy Swordsman", 77: "Long Swordsman", 78: "Gate, AB2", 79: "Watch Tower", 80: "Gate, AC3", 81: "Gate, AC2", 82: "Castle", 83: "Villager, M", 84: "Market", 85: "Gate, BA3", 86: "Stable 3", 87: "Archery Range", 88: "Gate, BA2", 89: "Dire Wolf", 90: "Gate, BB3", 91: "Gate, BB2", 92: "Gate, BC3", 93: "Spearman", 94: "Berserk 2", 95: "Gate, BC2", 96: "Hawk", 97: "Arrow 1", 98: "Hand Cannoneer, D", 99: "Heavy Swordsman, D", 100: "Elite Skirmisher, D", 101: "Stable", 102: "Stone Mine", 103: "Blacksmith", 104: "Monastery", 105: "Blacksmith 2", 106: "Infiltrator, D", 107: "Janissary, D", 108: "Junk, D", 109: "Town Center", 110: "Trade Workshop", 111: "Knight, D", 112: "Flare", 113: "Lance, D", 114: "Longboat, D", 115: "Longbowman, D", 116: "Market 3", 117: "Wall, Stone", 118: "Builder, M", 119: "Fisherman, disabled", 120: "Forager, M", 121: "Mangonel, D", 122: "Hunter, M", 123: "Lumberjack, M", 124: "Stone Miner, M", 125: "Monk", 126: "Wolf", 127: "Explorer, Old", 128: "Trade Cart, Empty", 129: "Mill 2", 130: "Mill 3", 131: "Mill 4", 132: "Barracks 3", 133: "Dock 2", 134: "Monk, D", 135: "Mangudai, D", 136: "War Elephant, D", 137: "Market 4", 138: "OUTLW, D", 139: "Paladin, D", 140: "Spearman, D", 141: "Town Center 3", 142: "Town Center 4", 143: "Rubble 1 X 1", 144: "Rubble 2 X 2", 145: "Rubble 3 X 3", 146: "Rubble 4 X 4", 147: "Rubble 6", 148: "Rubble 5 X 5", 149: "Scorpion, D", 150: "Siege Workshop 4", 151: "Samurai, D", 152: "Militia, D", 153: "Stable 4", 154: "Man-At-Arms, D", 155: "Wall, Fortified", 156: "Repairer, M", 157: "Throwing Axeman, D", 158: "OUTLW", 159: "Relic Cart", 160: "Richard The Lionharted", 161: "The Black Prince", 162: "FLAGX", 163: "Friar Tuck", 164: "Sherrif Of Notingham", 165: "Charlemagne", 166: "Roland", 167: "Belisarius", 168: "Theodoric The Goth", 169: "Aethelfirth", 170: "Siegfried", 171: "Erik The Red", 172: "Tamerlane", 173: "King Arthur", 174: "Lancelot", 175: "Gawain", 176: "Mordred", 177: "Archbishop", 178: "Trade Cart, D", 179: "Trade Workshop 4", 180: "Long Swordsman, D", 181: "Teutonic Knight, D", 182: "TMISA", 183: "TMISB", 184: "TMISC", 185: "TMISD", 186: "TMISE", 187: "TMISF", 188: "TMISG", 189: "TMISH", 190: "TMISI", 191: "TMISJ", 192: "TMISK", 193: "TMISL", 194: "Trebuchet, D", 195: "Kitabatake", 196: "Minamoto", 197: "Alexander Nevski", 198: "El Cid", 199: "Fish Trap", 200: "Robin Hood", 201: "FLR_R", 202: "Rabid Wolf", 203: "Rabid Wolf, D", 204: "Trade Cart, Full", 205: "Trade Cart, Full D", 206: "VMDL", 207: "VMDL, D", 208: "TWAL", 209: "University", 210: "University 4", 211: "Villager, F D", 212: "Builder, F", 213: "Builder, F D", 214: "Farmer, F", 215: "Farmer, F D", 216: "Hunter, F", 217: "Hunter, F D", 218: "Lumberjack, F", 219: "Lumberjack, F D", 220: "Stone Miner, F", 221: "Stone Miner, F D", 222: "Repairer, F", 223: "Repairer, F D", 224: "Villager, M D", 225: "Builder, M D", 226: "Farmer, M D", 227: "Hunter, M D", 228: "Lumberjack, M D", 229: "Stone Miner, M D", 230: "Repairer, M D", 232: "Woad Raider", 233: "Woad Raider, D", 234: "Guard Tower", 235: "Keep", 236: "Bombard Tower", 237: "Wolf, D", 238: "Skirmisher, D", 239: "War Elephant", 240: "TERRC", 241: "Cracks", 242: "Stone, Catapult", 243: "DOPL", 244: "Stone, Catapult F", 245: "Bolt (Scorpion Proj.)", 246: "Bolt, F", 247: "Smoke", 248: "Pile Of Stone", 249: "POREX", 250: "Longboat", 251: "Goldminer, Disabled", 252: "Pile Of Gold", 253: "Pile Of Wood", 254: "PILE1", 255: "PILE2", 256: "PILE3", 257: "PILE4", 258: "PILE6", 259: "Farmer, M", 260: "Fish3, Disabled", 261: "PILE8", 262: "Pile Of Food", 263: "Fish4, Disabled", 264: "Cliff 1", 265: "Cliff 2", 266: "Cliff 3", 267: "Cliff 4", 268: "Cliff 5", 269: "Cliff 6", 270: "Cliff 7", 271: "Cliff 8", 272: "Cliff 9", 273: "Cliff 10", 274: "Flare 2", 276: "Wonder", 278: "Fishtrap, D", 279: "Scorpion", 280: "Mangonel", 281: "Throwing Axeman", 282: "Mameluke", 283: "Cavalier", 284: "Tree TD", 285: "Relic", 286: "Monk With Relic", 287: "British Relic", 288: "Byzantine Relic", 289: "Chinese Relic", 290: "Frankish Relic", 291: "Samurai", 292: "Gothic Relic", 293: "Villager, F", 294: "Japanese Relic", 295: "Persian Relic", 296: "Saracen Relic", 297: "Teutonic Relic", 298: "Turkish Relic", 299: "Infiltrator", 300: "Monk With British Relic", 301: "Monk With Byzantine Relic", 302: "Monk With Chinese Relic", 303: "Monk With Frankish Relic", 304: "Monk With Gothic Relic", 305: "Monk With Japanese Relic", 306: "Monk With Persian Relic", 307: "Monk With Saracen Relic", 308: "Monk With Teutonic Relic", 309: "Monk With Turkish Relic", 310: "Mountain 1", 311: "Mountain 2", 312: "Arrow 2", 313: "Stone, Treb", 314: "Stone, Mangonel", 315: "Arrow 3", 316: "Arrow 4", 317: "Arrow 5", 318: "Arrow 6", 319: "Arrow 7", 320: "Arrow 8", 321: "Arrow 9", 322: "Arrow 10", 323: "Stone, Catapult 1", 324: "Stone, Catapult 2", 325: "Stone, Catapult 3", 326: "Stone, Catapult 4", 327: "Stone, Catapult 5", 328: "Arrow, F", 329: "Camel", 330: "Heavy Camel", 331: "Trebuchet, P", 332: "Flare 3", 333: "Deer, Nomeat", 334: "Flowers 1", 335: "Flowers 2", 336: "Flowers 3", 337: "Flowers 4", 338: "Path 4", 339: "Path 1", 340: "Path 2", 341: "Path 3", 342: "TERRU", 343: "TERRV", 344: "TERRW", 345: "Ruins", 346: "TERRY", 347: "TERRZ", 348: "Forest, Bamboo", 349: "Forest, Oak", 350: "Forest, Pine", 351: "Forest, Palm", 352: "OREMN", 353: "Forager, M D", 354: "Forager, F", 355: "Forager, F D", 356: "Board, D", 357: "Farm, D Crash", 358: "Pikeman", 359: "Halberdier", 360: "Arrow 2, F", 363: "Proj, Archer", 364: "Proj, Crossbowman", 365: "Proj, Skirmisher", 366: "Proj, Elite Skirmisher", 367: "Proj, Scorpion", 368: "Proj, Bombard Cannon", 369: "Proj, Mangonel", 370: "Fish 2, Disabled", 371: "Proj, Trebuchet", 372: "Proj, Galleon", 373: "Proj, War Galley", 374: "Proj, Cannon Galleon", 375: "Proj, Crossbowman F", 376: "Proj, Skirmisher F", 377: "Proj, Elite Skirmisher F", 378: "Proj, Scorpion F", 380: "Proj, H Cannoneer", 381: "Bolt, F", 385: "Bolt 1, F", 389: "Sea Rocks 1", 390: "TERRB", 391: "TERRD", 392: "TERRE", 393: "TERRF", 394: "TERRH", 395: "TERRI", 396: "Sea Rocks 2", 397: "TERRK", 398: "TERRL", 399: "Tree A", 400: "Tree B", 401: "Tree C", 402: "Tree D", 403: "Tree E", 404: "Tree F", 405: "Tree G", 406: "Tree H", 407: "Tree I", 408: "Tree J", 409: "Tree K", 410: "Tree L", 411: "Forest Tree", 413: "Snow Pine Tree", 414: "Jungle Tree", 415: "Stump", 416: "Debris", 417: "Dust C", 418: "TROCK", 419: "Debris B", 420: "Cannon Galleon", 421: "Cannon Galleon, D", 422: "Capped Ram", 423: "Capped Ram, D", 424: "Charles Martel", 425: "Charles Martel, D", 426: "Harald Hardraade", 427: "Harald Hardraade, D", 428: "Hrolf The Ganger", 429: "Hrolf The Ganger, D", 430: "Joan The Maid", 431: "Joan The Maid, D", 432: "William Wallace", 433: "William Wallace, D", 434: "King", 435: "King, D", 436: "OMTBO", 437: "OMTBO, D", 438: "STRBO", 439: "STRRBO, D", 440: "Petard", 441: "Hussar", 442: "Galleon", 443: "Galleon, Dead", 444: "PTWC", 445: "Church 4", 446: "Port", 447: "Purple Spots", 448: "Scout Cavalry", 449: "Scout Cavalry, D", 450: "Marlin 1", 451: "Marlin 2", 452: "DOLP3", 453: "DOLP4", 454: "DOLP5", 455: "Fish, Dorado", 456: "Fish, Salmon", 457: "Fish, Tuna", 458: "Fish, Snapper", 459: "FISH5", 460: "WHAL1", 461: "WHAL2", 462: "Proj, Mangonel F2", 463: "House 2", 464: "House 3", 465: "House 4", 466: "Proj, Archer F", 468: "Projectile, Mangonel F", 469: "Projectile, Treb F", 470: "Proj, Galleon F", 471: "Proj, War Galley F", 473: "Two Handed Swordsman", 474: "Heavy Cavalry Archer", 475: "Proj, HAR F", 476: "Proj, Harold Haraade F", 477: "Proj, HAR", 478: "Proj, Harold Haraade", 479: "PMANG", 480: "Hussar, D", 481: "Town Center 3A", 482: "Town Center 3B", 483: "Town Center 3C", 484: "Town Center 3X", 485: "Arrow, Town Center", 487: "Gate, AX2", 488: "Gate, AX3", 490: "Gate, BX2", 491: "Gate, BX3", 492: "Arbalest", 493: "Adv Heavy Crossbowman", 494: "Camel, D", 495: "Heavy Camel, D", 496: "Arbalest, D", 497: "AH Crossbowman, D", 498: "Barracks 2", 499: "Torch", 500: "Two-Handed Swordsman, D", 501: "Pikeman, D", 502: "Halberdier, D", 503: "Proj, Watch Tower", 504: "Proj, Guard Tower", 505: "Proj, Keep", 506: "Proj, Bombard Tower", 507: "Proj, Arbalest", 508: "Proj, AH Crossbowman", 509: "Proj, Villager", 510: "Proj, Cho Ko Nu", 511: "Proj, Longbowman", 512: "Proj, Longboat", 513: "Proj, MSU", 514: "Proj, MPC", 515: "Proj, Axeman", 516: "Proj, Watch Tower F", 517: "Proj, Guard Tower F", 518: "Proj, Keep F", 519: "Proj, Arbalest F", 520: "Proj, AH Crossbowman F", 521: "Proj, Villager F", 522: "Proj, Cho Ko Nu F", 523: "Proj, Longbowman F", 524: "Proj, Longboat F", 525: "Proj, MPC F", 526: "Proj, MSU F", 527: "Demolition Ship", 528: "Heavy Demolition Ship", 529: "Fire Ship", 530: "Elite Longbowman", 531: "Elite Throwing Axeman", 532: "Fast Fire Ship", 533: "Elite Longboat", 534: "Elite Woad Raider", 535: "BDGAL", 536: "ABGAL", 537: "Proj, FRG", 538: "Proj, HFG", 539: "Galley", 540: "Proj, Galley", 541: "Proj, Galley F", 542: "Heavy Scorpion", 543: "Heavy Scorpion, D", 544: "FLDOG", 545: "Transport Ship", 546: "Light Cavalry", 547: "Light Cavalry, D", 548: "Siege Ram", 549: "Siege Ram, D", 550: "Onager", 551: "Proj, Onager", 552: "Proj, Onager F", 553: "Elite Cataphract", 554: "Elite Teutonic Knight", 555: "Elite Huskarl", 556: "Elite Mameluke", 557: "Elite Janissary", 558: "Elite War Elephant", 559: "Elite Chu Ko Nu", 560: "Elite Samurai", 561: "Elite Mangudai", 562: "Lumber Camp", 563: "Lumber Camp 2", 564: "Lumber Camp 3", 565: "Lumber Camp 4", 566: "WCTWR", 567: "Champion", 568: "Champion, Dead", 569: "Paladin", 570: "Paladin, D", 571: "RFARC", 572: "RFARC, D", 573: "RFSWD", 574: "RFSWD, D", 575: "RCSWD", 576: "RCSWD, D", 577: "RCARC", 578: "RCARC, D", 579: "Gold Miner, M", 580: "Gold Miner, M D", 581: "Gold Miner, F", 582: "Gold Miner, F D", 583: "Genitour", 584: "Mining Camp", 585: "Mining Camp 2", 586: "Mining Camp 3", 587: "Mining Camp 4", 588: "Siege Onager", 589: "Siege Onager, D", 590: "Shepherd, F", 591: "Shepherd, F D", 592: "Shepherd, M", 593: "Shepherd, M D", 594: "Sheep", 595: "Sheep, D", 596: "Elite Genitour", 597: "Town Center 4X", 598: "Outpost", 599: "Cathedral", 600: "Flag A", 601: "Flag B", 602: "Flag C", 603: "Flag D", 604: "Flag E", 605: "Bridge A Top", 606: "Bridge A Middle", 607: "Bridge A Bottom", 608: "Bridge B Top", 609: "Bridge B Middle", 610: "Bridge B Bottom", 611: "Town Center 4A", 612: "Town Center 4B", 613: "Town Center 4C", 614: "Town Center 2A", 615: "Town Center 2B", 616: "Town Center 2C", 617: "Town Center 2X", 618: "Town Center 1A", 619: "Town Center 1B", 620: "Town Center 1C", 621: "Town Center 1X", 622: "D Iron Boar", 623: "Rock", 624: "Pavilion 1", 625: "Pavilion 3", 626: "Pavilion 2", 627: "Proj, Heavy Scorpion", 628: "Proj, Heavy Scorpion F", 629: "Joan Of Arc", 630: "Joan Of Arc, D", 631: "Subotai, D", 632: "Frankish Paladin", 633: "Frankish Paladin, D", 634: "Sieur De Metz", 635: "Sieur De Metz, D", 636: "Sieur Bertrand", 637: "Sieur Bertrand, D", 638: "Duke D'Alencon", 639: "Duke D'Alencon, D", 640: "La Hire", 641: "La Hire, D", 642: "Lord De Graville", 643: "Lord De Graville, D", 644: "Jean De Lorrain", 645: "Jean De Lorrain, D", 646: "Constable Richemont", 647: "Constable Richemont, D", 648: "Guy Josselyne", 649: "Guy Josselyne, D", 650: "Jean Bureau", 651: "Jean Bureau, D", 652: "Sir John Fastolf", 653: "Sir John Fastolf, D", 654: "S_SMOKE", 655: "Mosque", 656: "Proj, MNB", 657: "Proj, GP1", 658: "Proj, MNB F", 659: "Gate, CA2", 660: "Gate, CA3", 661: "Gate, CB2", 662: "Gate, CB3", 663: "Gate, CC2", 664: "Gate, CC3", 665: "Gate, CX2", 666: "Gate, CX3", 667: "Gate, DA2", 668: "Gate, DA3", 669: "Gate, DB2", 670: "Gate, DB3", 671: "Gate, DC2", 672: "Gate, DC3", 673: "Gate, DX2", 674: "Gate, DX3", 675: "Onager, D", 676: "Proj, FFG F", 677: "S_Fire", 678: "Reynald De Chatillon", 679: "Reynald De Chatillon, D", 680: "Master Of The Templar", 681: "Master Of The Templar, D", 682: "Bad Neighbor", 683: "Gods Own Sling", 684: "The Accursed Tower", 685: "The Tower Of Flies", 686: "Archer Of The Eyes", 687: "Archer Of The Eyes, D", 688: "Piece Of The True Cross", 689: "Pyramid", 690: "Dome Of The Rock", 691: "Elite Cannon Galleon", 692: "Berserk", 693: "Berserk, D", 694: "Elite Berserk", 695: "Elite Berserk, D", 696: "Great Pyramid", 697: "Flare 4", 698: "Subotai", 699: "Subotai, D", 700: "Hunting Wolf", 701: "Hunting Wolf, D", 702: "Kushluk", 703: "Kushluk, D", 704: "Shah", 705: "Shah, D", 706: "Saboteur", 707: "Ornlu The Wolf", 708: "Ornlu The Wolf, D", 709: "Cactus", 710: "Skeleton", 711: "Rugs", 712: "Yurt", 713: "Yurt 2", 714: "Yurt 3", 715: "Yurt 4", 716: "Yurt 5", 717: "Yurt 6", 718: "Yurt 7", 719: "Yurt 8", 720: "Nine Bands", 721: "Shipwreck", 722: "Shipwreck 2", 723: "Crater", 724: "Genitour, Dead", 725: "Jaguar Warrior", 726: "Elite Jaguar Warrior", 728: "Ice Spots", 729: "Gods Own Sling, Packed", 730: "Bad Neighbor, Packed", 731: "Genghis Khan", 732: "Genghis Khan, D", 733: "Emperor In A Barrel", 734: "Emperor In A Barrel, D", 735: "Trebuchet, Packed D", 736: "Proj, Mameluke", 737: "Stump B", 738: "Bridge A Middle Broken", 739: "Bridge A Middle Broken 2", 740: "Bridge A Middle Broken 3", 741: "Bridge B Middle Broken", 742: "Bridge B Middle Broken 2", 743: "Bridge B Middle Broken 3", 744: "Mountain 3", 745: "Mountain 4", 746: "Proj, Castle", 747: "Proj, Castle Flaming", 748: "Cobra Car", 749: "Cobra, D", 750: "Jaguar Warrior, D", 751: "Eagle Warrior", 752: "Elite Eagle Warrior", 754: "Eagle Warrior, D", 755: "Tarkan", 756: "Tarkan, D", 757: "Elite Tarkan", 759: "Huskarl", 760: "Huskarl, Dead", 761: "Elite Huskarl", 762: "Elite Huskarl, Dead", 763: "Plumed Archer", 764: "Plumed Archer, D", 765: "Elite Plumed Archer", 766: "Elite Plumed Archer, D", 767: "Proj, Elite Cannon Galleon", 771: "Conquistador", 772: "Conquistador, D", 773: "Elite Conquistador", 774: "Elite Conquistador, D", 775: "Missionary", 776: "Missionary, D", 777: "Attila The Hun", 778: "Atilla The Hun, D", 779: "Bleda The Hun", 780: "Bleda The Hun, D", 781: "Pope Leo I", 782: "Pope Leo I, D", 783: "Scythian Wild Woman", 784: "Scythian Wild Woman, D", 785: "Sea Tower", 786: "Proj, Sea Tower", 787: "Proj, Sea Tower Flaming", 788: "Sea Wall", 789: "Sea Gate, AA", 790: "Sea Gate, AB", 791: "Sea Gate, AC", 792: "Sea Gate, AX", 793: "Sea Gate, BA", 794: "Sea Gate, BB", 795: "Sea Gate, BC", 796: "Sea Gate, BX", 797: "Sea Gate, CA", 798: "Sea Gate, CB", 799: "Sea Gate, CC", 800: "Sea Gate, CX", 801: "Sea Gate, DA", 802: "Sea Gate, DB", 803: "Sea Gate, DC", 804: "Sea Gate, DX", 805: "S Dock", 806: "S Dock 2", 807: "S Dock 3", 808: "S Dock 4", 809: "Stump 2", 810: "Iron Boar", 811: "Iron Boar, D", 812: "Jaguar", 813: "Jaguar, D", 814: "Horse", 815: "Horse, D", 816: "Macaw", 817: "Statue", 818: "Plants", 819: "Sign", 820: "Grave", 821: "Head", 822: "Javelina", 823: "Javelina, D", 824: "El Cid Campeador", 825: "El Cid Campeador, D", 826: "Monument (KotH)", 827: "War Wagon", 828: "War Wagon, D", 829: "Elite War Wagon", 830: "Elite War Wagon, D", 831: "Turtle Ship", 832: "Elite Turtle Ship", 833: "Turkey", 834: "Turkey, Dead", 835: "Wild Horse", 836: "Wild Horse, D", 837: "Map Revealer", 838: "King Sancho", 839: "King Sancho, D", 840: "King Alfonso", 841: "King Alfonso, D", 842: "Imam", 843: "Imam, D", 844: "Admiral Yi Sun Shin", 845: "Nobunaga", 846: "Nobunaga, D", 847: "Henry V", 848: "Henry V, D", 849: "William The Conqueror", 850: "William The Conqueror, D", 851: "Flag, ES", 852: "Scythian Scout", 853: "Scythian Scout, D", 854: "Torch 2", 855: "Old Stone Head", 856: "Roman Ruins", 857: "Hay Stack", 858: "Broken Cart", 859: "Flower Bed", 860: "Furious The Monkey Boy", 861: "Furious The Monkey Boy, D", 862: "Stormy Dog", 863: "Rubble 1 X 1", 864: "Rubble 2 X 2", 865: "Rubble 3 X 3" }
e_unit = {0: 'Academy, Disabled', 1: 'Gator, disabled', 3: 'Archer, D', 4: 'Archer', 5: 'Hand Cannoneer', 6: 'Elite Skirmisher', 7: 'Skirmisher', 8: 'Longbowman', 9: 'Arrow', 10: 'Archery Range 3', 11: 'Mangudai', 12: 'Barracks', 13: 'Fishing Ship', 14: 'Archery Range 4', 15: 'Junk', 16: 'Bombard Cannon, D', 17: 'Trade Cog', 18: 'Blacksmith 3', 19: 'Blacksmith 4', 20: 'Barracks 4', 21: 'War Galley', 22: 'Berserk, D', 23: 'Battering Ram, D', 24: 'Crossbowman', 25: 'Teutonic Knight', 26: 'Crossbowman, D', 27: 'Cataphract, D', 28: 'Cho-Ko-Nu, D', 29: 'Trading Cog, D', 30: 'Monastery 2', 31: 'Monastery 3', 32: 'Monastery 4', 33: 'Castle 4', 34: 'Cavalry Archer, D', 35: 'Battering Ram', 36: 'Bombard Cannon', 37: 'LANCE', 38: 'Knight', 39: 'Cavalry Archer', 40: 'Cataphract', 41: 'Huskarl', 42: 'Trebuchet (Unpacked)', 43: 'Deer, D', 44: 'Mameluke, D', 45: 'Dock', 46: 'Janissary', 47: 'Dock 3', 48: 'Boar', 49: 'Siege Workshop', 50: 'Farm', 51: 'Dock 4', 52: 'Fish 1, Disabled', 53: 'Fish (Perch)', 54: 'Proj, VOL', 55: 'Fishing Ship, D', 56: 'Fisher, M', 57: 'Fisher, F', 58: 'Fisher, M D', 59: 'Forage Bush', 60: 'Fisher, F D', 61: 'Galley, D (Canoe?)', 62: 'Huskarl (E?), D', 63: 'Gate, AA3', 64: 'Gate, AA2', 65: 'Deer', 66: 'Gold Mine', 67: 'Gate, AB3', 68: 'Mill', 69: 'Fish, Shore', 70: 'House', 71: 'Town Center 2', 72: 'Wall, Palisade', 73: 'Chu Ko Nu', 74: 'Militia', 75: 'Man At Arms', 76: 'Heavy Swordsman', 77: 'Long Swordsman', 78: 'Gate, AB2', 79: 'Watch Tower', 80: 'Gate, AC3', 81: 'Gate, AC2', 82: 'Castle', 83: 'Villager, M', 84: 'Market', 85: 'Gate, BA3', 86: 'Stable 3', 87: 'Archery Range', 88: 'Gate, BA2', 89: 'Dire Wolf', 90: 'Gate, BB3', 91: 'Gate, BB2', 92: 'Gate, BC3', 93: 'Spearman', 94: 'Berserk 2', 95: 'Gate, BC2', 96: 'Hawk', 97: 'Arrow 1', 98: 'Hand Cannoneer, D', 99: 'Heavy Swordsman, D', 100: 'Elite Skirmisher, D', 101: 'Stable', 102: 'Stone Mine', 103: 'Blacksmith', 104: 'Monastery', 105: 'Blacksmith 2', 106: 'Infiltrator, D', 107: 'Janissary, D', 108: 'Junk, D', 109: 'Town Center', 110: 'Trade Workshop', 111: 'Knight, D', 112: 'Flare', 113: 'Lance, D', 114: 'Longboat, D', 115: 'Longbowman, D', 116: 'Market 3', 117: 'Wall, Stone', 118: 'Builder, M', 119: 'Fisherman, disabled', 120: 'Forager, M', 121: 'Mangonel, D', 122: 'Hunter, M', 123: 'Lumberjack, M', 124: 'Stone Miner, M', 125: 'Monk', 126: 'Wolf', 127: 'Explorer, Old', 128: 'Trade Cart, Empty', 129: 'Mill 2', 130: 'Mill 3', 131: 'Mill 4', 132: 'Barracks 3', 133: 'Dock 2', 134: 'Monk, D', 135: 'Mangudai, D', 136: 'War Elephant, D', 137: 'Market 4', 138: 'OUTLW, D', 139: 'Paladin, D', 140: 'Spearman, D', 141: 'Town Center 3', 142: 'Town Center 4', 143: 'Rubble 1 X 1', 144: 'Rubble 2 X 2', 145: 'Rubble 3 X 3', 146: 'Rubble 4 X 4', 147: 'Rubble 6', 148: 'Rubble 5 X 5', 149: 'Scorpion, D', 150: 'Siege Workshop 4', 151: 'Samurai, D', 152: 'Militia, D', 153: 'Stable 4', 154: 'Man-At-Arms, D', 155: 'Wall, Fortified', 156: 'Repairer, M', 157: 'Throwing Axeman, D', 158: 'OUTLW', 159: 'Relic Cart', 160: 'Richard The Lionharted', 161: 'The Black Prince', 162: 'FLAGX', 163: 'Friar Tuck', 164: 'Sherrif Of Notingham', 165: 'Charlemagne', 166: 'Roland', 167: 'Belisarius', 168: 'Theodoric The Goth', 169: 'Aethelfirth', 170: 'Siegfried', 171: 'Erik The Red', 172: 'Tamerlane', 173: 'King Arthur', 174: 'Lancelot', 175: 'Gawain', 176: 'Mordred', 177: 'Archbishop', 178: 'Trade Cart, D', 179: 'Trade Workshop 4', 180: 'Long Swordsman, D', 181: 'Teutonic Knight, D', 182: 'TMISA', 183: 'TMISB', 184: 'TMISC', 185: 'TMISD', 186: 'TMISE', 187: 'TMISF', 188: 'TMISG', 189: 'TMISH', 190: 'TMISI', 191: 'TMISJ', 192: 'TMISK', 193: 'TMISL', 194: 'Trebuchet, D', 195: 'Kitabatake', 196: 'Minamoto', 197: 'Alexander Nevski', 198: 'El Cid', 199: 'Fish Trap', 200: 'Robin Hood', 201: 'FLR_R', 202: 'Rabid Wolf', 203: 'Rabid Wolf, D', 204: 'Trade Cart, Full', 205: 'Trade Cart, Full D', 206: 'VMDL', 207: 'VMDL, D', 208: 'TWAL', 209: 'University', 210: 'University 4', 211: 'Villager, F D', 212: 'Builder, F', 213: 'Builder, F D', 214: 'Farmer, F', 215: 'Farmer, F D', 216: 'Hunter, F', 217: 'Hunter, F D', 218: 'Lumberjack, F', 219: 'Lumberjack, F D', 220: 'Stone Miner, F', 221: 'Stone Miner, F D', 222: 'Repairer, F', 223: 'Repairer, F D', 224: 'Villager, M D', 225: 'Builder, M D', 226: 'Farmer, M D', 227: 'Hunter, M D', 228: 'Lumberjack, M D', 229: 'Stone Miner, M D', 230: 'Repairer, M D', 232: 'Woad Raider', 233: 'Woad Raider, D', 234: 'Guard Tower', 235: 'Keep', 236: 'Bombard Tower', 237: 'Wolf, D', 238: 'Skirmisher, D', 239: 'War Elephant', 240: 'TERRC', 241: 'Cracks', 242: 'Stone, Catapult', 243: 'DOPL', 244: 'Stone, Catapult F', 245: 'Bolt (Scorpion Proj.)', 246: 'Bolt, F', 247: 'Smoke', 248: 'Pile Of Stone', 249: 'POREX', 250: 'Longboat', 251: 'Goldminer, Disabled', 252: 'Pile Of Gold', 253: 'Pile Of Wood', 254: 'PILE1', 255: 'PILE2', 256: 'PILE3', 257: 'PILE4', 258: 'PILE6', 259: 'Farmer, M', 260: 'Fish3, Disabled', 261: 'PILE8', 262: 'Pile Of Food', 263: 'Fish4, Disabled', 264: 'Cliff 1', 265: 'Cliff 2', 266: 'Cliff 3', 267: 'Cliff 4', 268: 'Cliff 5', 269: 'Cliff 6', 270: 'Cliff 7', 271: 'Cliff 8', 272: 'Cliff 9', 273: 'Cliff 10', 274: 'Flare 2', 276: 'Wonder', 278: 'Fishtrap, D', 279: 'Scorpion', 280: 'Mangonel', 281: 'Throwing Axeman', 282: 'Mameluke', 283: 'Cavalier', 284: 'Tree TD', 285: 'Relic', 286: 'Monk With Relic', 287: 'British Relic', 288: 'Byzantine Relic', 289: 'Chinese Relic', 290: 'Frankish Relic', 291: 'Samurai', 292: 'Gothic Relic', 293: 'Villager, F', 294: 'Japanese Relic', 295: 'Persian Relic', 296: 'Saracen Relic', 297: 'Teutonic Relic', 298: 'Turkish Relic', 299: 'Infiltrator', 300: 'Monk With British Relic', 301: 'Monk With Byzantine Relic', 302: 'Monk With Chinese Relic', 303: 'Monk With Frankish Relic', 304: 'Monk With Gothic Relic', 305: 'Monk With Japanese Relic', 306: 'Monk With Persian Relic', 307: 'Monk With Saracen Relic', 308: 'Monk With Teutonic Relic', 309: 'Monk With Turkish Relic', 310: 'Mountain 1', 311: 'Mountain 2', 312: 'Arrow 2', 313: 'Stone, Treb', 314: 'Stone, Mangonel', 315: 'Arrow 3', 316: 'Arrow 4', 317: 'Arrow 5', 318: 'Arrow 6', 319: 'Arrow 7', 320: 'Arrow 8', 321: 'Arrow 9', 322: 'Arrow 10', 323: 'Stone, Catapult 1', 324: 'Stone, Catapult 2', 325: 'Stone, Catapult 3', 326: 'Stone, Catapult 4', 327: 'Stone, Catapult 5', 328: 'Arrow, F', 329: 'Camel', 330: 'Heavy Camel', 331: 'Trebuchet, P', 332: 'Flare 3', 333: 'Deer, Nomeat', 334: 'Flowers 1', 335: 'Flowers 2', 336: 'Flowers 3', 337: 'Flowers 4', 338: 'Path 4', 339: 'Path 1', 340: 'Path 2', 341: 'Path 3', 342: 'TERRU', 343: 'TERRV', 344: 'TERRW', 345: 'Ruins', 346: 'TERRY', 347: 'TERRZ', 348: 'Forest, Bamboo', 349: 'Forest, Oak', 350: 'Forest, Pine', 351: 'Forest, Palm', 352: 'OREMN', 353: 'Forager, M D', 354: 'Forager, F', 355: 'Forager, F D', 356: 'Board, D', 357: 'Farm, D Crash', 358: 'Pikeman', 359: 'Halberdier', 360: 'Arrow 2, F', 363: 'Proj, Archer', 364: 'Proj, Crossbowman', 365: 'Proj, Skirmisher', 366: 'Proj, Elite Skirmisher', 367: 'Proj, Scorpion', 368: 'Proj, Bombard Cannon', 369: 'Proj, Mangonel', 370: 'Fish 2, Disabled', 371: 'Proj, Trebuchet', 372: 'Proj, Galleon', 373: 'Proj, War Galley', 374: 'Proj, Cannon Galleon', 375: 'Proj, Crossbowman F', 376: 'Proj, Skirmisher F', 377: 'Proj, Elite Skirmisher F', 378: 'Proj, Scorpion F', 380: 'Proj, H Cannoneer', 381: 'Bolt, F', 385: 'Bolt 1, F', 389: 'Sea Rocks 1', 390: 'TERRB', 391: 'TERRD', 392: 'TERRE', 393: 'TERRF', 394: 'TERRH', 395: 'TERRI', 396: 'Sea Rocks 2', 397: 'TERRK', 398: 'TERRL', 399: 'Tree A', 400: 'Tree B', 401: 'Tree C', 402: 'Tree D', 403: 'Tree E', 404: 'Tree F', 405: 'Tree G', 406: 'Tree H', 407: 'Tree I', 408: 'Tree J', 409: 'Tree K', 410: 'Tree L', 411: 'Forest Tree', 413: 'Snow Pine Tree', 414: 'Jungle Tree', 415: 'Stump', 416: 'Debris', 417: 'Dust C', 418: 'TROCK', 419: 'Debris B', 420: 'Cannon Galleon', 421: 'Cannon Galleon, D', 422: 'Capped Ram', 423: 'Capped Ram, D', 424: 'Charles Martel', 425: 'Charles Martel, D', 426: 'Harald Hardraade', 427: 'Harald Hardraade, D', 428: 'Hrolf The Ganger', 429: 'Hrolf The Ganger, D', 430: 'Joan The Maid', 431: 'Joan The Maid, D', 432: 'William Wallace', 433: 'William Wallace, D', 434: 'King', 435: 'King, D', 436: 'OMTBO', 437: 'OMTBO, D', 438: 'STRBO', 439: 'STRRBO, D', 440: 'Petard', 441: 'Hussar', 442: 'Galleon', 443: 'Galleon, Dead', 444: 'PTWC', 445: 'Church 4', 446: 'Port', 447: 'Purple Spots', 448: 'Scout Cavalry', 449: 'Scout Cavalry, D', 450: 'Marlin 1', 451: 'Marlin 2', 452: 'DOLP3', 453: 'DOLP4', 454: 'DOLP5', 455: 'Fish, Dorado', 456: 'Fish, Salmon', 457: 'Fish, Tuna', 458: 'Fish, Snapper', 459: 'FISH5', 460: 'WHAL1', 461: 'WHAL2', 462: 'Proj, Mangonel F2', 463: 'House 2', 464: 'House 3', 465: 'House 4', 466: 'Proj, Archer F', 468: 'Projectile, Mangonel F', 469: 'Projectile, Treb F', 470: 'Proj, Galleon F', 471: 'Proj, War Galley F', 473: 'Two Handed Swordsman', 474: 'Heavy Cavalry Archer', 475: 'Proj, HAR F', 476: 'Proj, Harold Haraade F', 477: 'Proj, HAR', 478: 'Proj, Harold Haraade', 479: 'PMANG', 480: 'Hussar, D', 481: 'Town Center 3A', 482: 'Town Center 3B', 483: 'Town Center 3C', 484: 'Town Center 3X', 485: 'Arrow, Town Center', 487: 'Gate, AX2', 488: 'Gate, AX3', 490: 'Gate, BX2', 491: 'Gate, BX3', 492: 'Arbalest', 493: 'Adv Heavy Crossbowman', 494: 'Camel, D', 495: 'Heavy Camel, D', 496: 'Arbalest, D', 497: 'AH Crossbowman, D', 498: 'Barracks 2', 499: 'Torch', 500: 'Two-Handed Swordsman, D', 501: 'Pikeman, D', 502: 'Halberdier, D', 503: 'Proj, Watch Tower', 504: 'Proj, Guard Tower', 505: 'Proj, Keep', 506: 'Proj, Bombard Tower', 507: 'Proj, Arbalest', 508: 'Proj, AH Crossbowman', 509: 'Proj, Villager', 510: 'Proj, Cho Ko Nu', 511: 'Proj, Longbowman', 512: 'Proj, Longboat', 513: 'Proj, MSU', 514: 'Proj, MPC', 515: 'Proj, Axeman', 516: 'Proj, Watch Tower F', 517: 'Proj, Guard Tower F', 518: 'Proj, Keep F', 519: 'Proj, Arbalest F', 520: 'Proj, AH Crossbowman F', 521: 'Proj, Villager F', 522: 'Proj, Cho Ko Nu F', 523: 'Proj, Longbowman F', 524: 'Proj, Longboat F', 525: 'Proj, MPC F', 526: 'Proj, MSU F', 527: 'Demolition Ship', 528: 'Heavy Demolition Ship', 529: 'Fire Ship', 530: 'Elite Longbowman', 531: 'Elite Throwing Axeman', 532: 'Fast Fire Ship', 533: 'Elite Longboat', 534: 'Elite Woad Raider', 535: 'BDGAL', 536: 'ABGAL', 537: 'Proj, FRG', 538: 'Proj, HFG', 539: 'Galley', 540: 'Proj, Galley', 541: 'Proj, Galley F', 542: 'Heavy Scorpion', 543: 'Heavy Scorpion, D', 544: 'FLDOG', 545: 'Transport Ship', 546: 'Light Cavalry', 547: 'Light Cavalry, D', 548: 'Siege Ram', 549: 'Siege Ram, D', 550: 'Onager', 551: 'Proj, Onager', 552: 'Proj, Onager F', 553: 'Elite Cataphract', 554: 'Elite Teutonic Knight', 555: 'Elite Huskarl', 556: 'Elite Mameluke', 557: 'Elite Janissary', 558: 'Elite War Elephant', 559: 'Elite Chu Ko Nu', 560: 'Elite Samurai', 561: 'Elite Mangudai', 562: 'Lumber Camp', 563: 'Lumber Camp 2', 564: 'Lumber Camp 3', 565: 'Lumber Camp 4', 566: 'WCTWR', 567: 'Champion', 568: 'Champion, Dead', 569: 'Paladin', 570: 'Paladin, D', 571: 'RFARC', 572: 'RFARC, D', 573: 'RFSWD', 574: 'RFSWD, D', 575: 'RCSWD', 576: 'RCSWD, D', 577: 'RCARC', 578: 'RCARC, D', 579: 'Gold Miner, M', 580: 'Gold Miner, M D', 581: 'Gold Miner, F', 582: 'Gold Miner, F D', 583: 'Genitour', 584: 'Mining Camp', 585: 'Mining Camp 2', 586: 'Mining Camp 3', 587: 'Mining Camp 4', 588: 'Siege Onager', 589: 'Siege Onager, D', 590: 'Shepherd, F', 591: 'Shepherd, F D', 592: 'Shepherd, M', 593: 'Shepherd, M D', 594: 'Sheep', 595: 'Sheep, D', 596: 'Elite Genitour', 597: 'Town Center 4X', 598: 'Outpost', 599: 'Cathedral', 600: 'Flag A', 601: 'Flag B', 602: 'Flag C', 603: 'Flag D', 604: 'Flag E', 605: 'Bridge A Top', 606: 'Bridge A Middle', 607: 'Bridge A Bottom', 608: 'Bridge B Top', 609: 'Bridge B Middle', 610: 'Bridge B Bottom', 611: 'Town Center 4A', 612: 'Town Center 4B', 613: 'Town Center 4C', 614: 'Town Center 2A', 615: 'Town Center 2B', 616: 'Town Center 2C', 617: 'Town Center 2X', 618: 'Town Center 1A', 619: 'Town Center 1B', 620: 'Town Center 1C', 621: 'Town Center 1X', 622: 'D Iron Boar', 623: 'Rock', 624: 'Pavilion 1', 625: 'Pavilion 3', 626: 'Pavilion 2', 627: 'Proj, Heavy Scorpion', 628: 'Proj, Heavy Scorpion F', 629: 'Joan Of Arc', 630: 'Joan Of Arc, D', 631: 'Subotai, D', 632: 'Frankish Paladin', 633: 'Frankish Paladin, D', 634: 'Sieur De Metz', 635: 'Sieur De Metz, D', 636: 'Sieur Bertrand', 637: 'Sieur Bertrand, D', 638: "Duke D'Alencon", 639: "Duke D'Alencon, D", 640: 'La Hire', 641: 'La Hire, D', 642: 'Lord De Graville', 643: 'Lord De Graville, D', 644: 'Jean De Lorrain', 645: 'Jean De Lorrain, D', 646: 'Constable Richemont', 647: 'Constable Richemont, D', 648: 'Guy Josselyne', 649: 'Guy Josselyne, D', 650: 'Jean Bureau', 651: 'Jean Bureau, D', 652: 'Sir John Fastolf', 653: 'Sir John Fastolf, D', 654: 'S_SMOKE', 655: 'Mosque', 656: 'Proj, MNB', 657: 'Proj, GP1', 658: 'Proj, MNB F', 659: 'Gate, CA2', 660: 'Gate, CA3', 661: 'Gate, CB2', 662: 'Gate, CB3', 663: 'Gate, CC2', 664: 'Gate, CC3', 665: 'Gate, CX2', 666: 'Gate, CX3', 667: 'Gate, DA2', 668: 'Gate, DA3', 669: 'Gate, DB2', 670: 'Gate, DB3', 671: 'Gate, DC2', 672: 'Gate, DC3', 673: 'Gate, DX2', 674: 'Gate, DX3', 675: 'Onager, D', 676: 'Proj, FFG F', 677: 'S_Fire', 678: 'Reynald De Chatillon', 679: 'Reynald De Chatillon, D', 680: 'Master Of The Templar', 681: 'Master Of The Templar, D', 682: 'Bad Neighbor', 683: 'Gods Own Sling', 684: 'The Accursed Tower', 685: 'The Tower Of Flies', 686: 'Archer Of The Eyes', 687: 'Archer Of The Eyes, D', 688: 'Piece Of The True Cross', 689: 'Pyramid', 690: 'Dome Of The Rock', 691: 'Elite Cannon Galleon', 692: 'Berserk', 693: 'Berserk, D', 694: 'Elite Berserk', 695: 'Elite Berserk, D', 696: 'Great Pyramid', 697: 'Flare 4', 698: 'Subotai', 699: 'Subotai, D', 700: 'Hunting Wolf', 701: 'Hunting Wolf, D', 702: 'Kushluk', 703: 'Kushluk, D', 704: 'Shah', 705: 'Shah, D', 706: 'Saboteur', 707: 'Ornlu The Wolf', 708: 'Ornlu The Wolf, D', 709: 'Cactus', 710: 'Skeleton', 711: 'Rugs', 712: 'Yurt', 713: 'Yurt 2', 714: 'Yurt 3', 715: 'Yurt 4', 716: 'Yurt 5', 717: 'Yurt 6', 718: 'Yurt 7', 719: 'Yurt 8', 720: 'Nine Bands', 721: 'Shipwreck', 722: 'Shipwreck 2', 723: 'Crater', 724: 'Genitour, Dead', 725: 'Jaguar Warrior', 726: 'Elite Jaguar Warrior', 728: 'Ice Spots', 729: 'Gods Own Sling, Packed', 730: 'Bad Neighbor, Packed', 731: 'Genghis Khan', 732: 'Genghis Khan, D', 733: 'Emperor In A Barrel', 734: 'Emperor In A Barrel, D', 735: 'Trebuchet, Packed D', 736: 'Proj, Mameluke', 737: 'Stump B', 738: 'Bridge A Middle Broken', 739: 'Bridge A Middle Broken 2', 740: 'Bridge A Middle Broken 3', 741: 'Bridge B Middle Broken', 742: 'Bridge B Middle Broken 2', 743: 'Bridge B Middle Broken 3', 744: 'Mountain 3', 745: 'Mountain 4', 746: 'Proj, Castle', 747: 'Proj, Castle Flaming', 748: 'Cobra Car', 749: 'Cobra, D', 750: 'Jaguar Warrior, D', 751: 'Eagle Warrior', 752: 'Elite Eagle Warrior', 754: 'Eagle Warrior, D', 755: 'Tarkan', 756: 'Tarkan, D', 757: 'Elite Tarkan', 759: 'Huskarl', 760: 'Huskarl, Dead', 761: 'Elite Huskarl', 762: 'Elite Huskarl, Dead', 763: 'Plumed Archer', 764: 'Plumed Archer, D', 765: 'Elite Plumed Archer', 766: 'Elite Plumed Archer, D', 767: 'Proj, Elite Cannon Galleon', 771: 'Conquistador', 772: 'Conquistador, D', 773: 'Elite Conquistador', 774: 'Elite Conquistador, D', 775: 'Missionary', 776: 'Missionary, D', 777: 'Attila The Hun', 778: 'Atilla The Hun, D', 779: 'Bleda The Hun', 780: 'Bleda The Hun, D', 781: 'Pope Leo I', 782: 'Pope Leo I, D', 783: 'Scythian Wild Woman', 784: 'Scythian Wild Woman, D', 785: 'Sea Tower', 786: 'Proj, Sea Tower', 787: 'Proj, Sea Tower Flaming', 788: 'Sea Wall', 789: 'Sea Gate, AA', 790: 'Sea Gate, AB', 791: 'Sea Gate, AC', 792: 'Sea Gate, AX', 793: 'Sea Gate, BA', 794: 'Sea Gate, BB', 795: 'Sea Gate, BC', 796: 'Sea Gate, BX', 797: 'Sea Gate, CA', 798: 'Sea Gate, CB', 799: 'Sea Gate, CC', 800: 'Sea Gate, CX', 801: 'Sea Gate, DA', 802: 'Sea Gate, DB', 803: 'Sea Gate, DC', 804: 'Sea Gate, DX', 805: 'S Dock', 806: 'S Dock 2', 807: 'S Dock 3', 808: 'S Dock 4', 809: 'Stump 2', 810: 'Iron Boar', 811: 'Iron Boar, D', 812: 'Jaguar', 813: 'Jaguar, D', 814: 'Horse', 815: 'Horse, D', 816: 'Macaw', 817: 'Statue', 818: 'Plants', 819: 'Sign', 820: 'Grave', 821: 'Head', 822: 'Javelina', 823: 'Javelina, D', 824: 'El Cid Campeador', 825: 'El Cid Campeador, D', 826: 'Monument (KotH)', 827: 'War Wagon', 828: 'War Wagon, D', 829: 'Elite War Wagon', 830: 'Elite War Wagon, D', 831: 'Turtle Ship', 832: 'Elite Turtle Ship', 833: 'Turkey', 834: 'Turkey, Dead', 835: 'Wild Horse', 836: 'Wild Horse, D', 837: 'Map Revealer', 838: 'King Sancho', 839: 'King Sancho, D', 840: 'King Alfonso', 841: 'King Alfonso, D', 842: 'Imam', 843: 'Imam, D', 844: 'Admiral Yi Sun Shin', 845: 'Nobunaga', 846: 'Nobunaga, D', 847: 'Henry V', 848: 'Henry V, D', 849: 'William The Conqueror', 850: 'William The Conqueror, D', 851: 'Flag, ES', 852: 'Scythian Scout', 853: 'Scythian Scout, D', 854: 'Torch 2', 855: 'Old Stone Head', 856: 'Roman Ruins', 857: 'Hay Stack', 858: 'Broken Cart', 859: 'Flower Bed', 860: 'Furious The Monkey Boy', 861: 'Furious The Monkey Boy, D', 862: 'Stormy Dog', 863: 'Rubble 1 X 1', 864: 'Rubble 2 X 2', 865: 'Rubble 3 X 3'}
#Return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters. def get_middle(s): if len(s) % 2 == 0: return s[int(len(s) / 2) - 1] + s[int((len(s) / 2))] else: return s[int(len(s) / 2)] #Alternate Solution def get_middle(s): index, odd = divmod(len(s), 2) return s[index] if odd else s[index - 1:index + 1]
def get_middle(s): if len(s) % 2 == 0: return s[int(len(s) / 2) - 1] + s[int(len(s) / 2)] else: return s[int(len(s) / 2)] def get_middle(s): (index, odd) = divmod(len(s), 2) return s[index] if odd else s[index - 1:index + 1]
# codeforces round 600 div 2 - A # solved in time # https://codeforces.com/contest/1253/problem/A?locale=en t = int(input()) for i in range(t): n = int(input()) a_list = input().split(' ') b_list = input().split(' ') prev_diff = 0 current_diff = 0 diff_found = 0 result = '' if n == 1: if b_list[0] >= a_list[0]: result = 'YES' else: result = 'NO' else: for j in range(n): current_diff = int(b_list[j]) - int(a_list[j]) if current_diff < 0: result = 'NO' else: if diff_found == 0: if current_diff != 0: prev_diff = current_diff diff_found = 1 else: if current_diff == 0: prev_diff = current_diff else: if prev_diff == 0: result = 'NO' if prev_diff != 0 and prev_diff != current_diff: result = 'NO' if result == '': result = 'YES' print(result) #1 #3 #1 2 3 #2 2 4
t = int(input()) for i in range(t): n = int(input()) a_list = input().split(' ') b_list = input().split(' ') prev_diff = 0 current_diff = 0 diff_found = 0 result = '' if n == 1: if b_list[0] >= a_list[0]: result = 'YES' else: result = 'NO' else: for j in range(n): current_diff = int(b_list[j]) - int(a_list[j]) if current_diff < 0: result = 'NO' elif diff_found == 0: if current_diff != 0: prev_diff = current_diff diff_found = 1 elif current_diff == 0: prev_diff = current_diff else: if prev_diff == 0: result = 'NO' if prev_diff != 0 and prev_diff != current_diff: result = 'NO' if result == '': result = 'YES' print(result)
# SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'HOST': '', 'NAME': '', 'USER': '', 'PASSWORD': '', } }
secret_key = '' databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'HOST': '', 'NAME': '', 'USER': '', 'PASSWORD': ''}}
def add_native_methods(clazz): def __java_init______(a0): raise NotImplementedError() def selectAlternatives__com_sun_xml_internal_ws_policy_EffectivePolicyModifier__com_sun_xml_internal_ws_policy_AssertionValidationProcessor__(a0, a1): raise NotImplementedError() clazz.__java_init______ = __java_init______ clazz.selectAlternatives__com_sun_xml_internal_ws_policy_EffectivePolicyModifier__com_sun_xml_internal_ws_policy_AssertionValidationProcessor__ = staticmethod(selectAlternatives__com_sun_xml_internal_ws_policy_EffectivePolicyModifier__com_sun_xml_internal_ws_policy_AssertionValidationProcessor__)
def add_native_methods(clazz): def __java_init______(a0): raise not_implemented_error() def select_alternatives__com_sun_xml_internal_ws_policy__effective_policy_modifier__com_sun_xml_internal_ws_policy__assertion_validation_processor__(a0, a1): raise not_implemented_error() clazz.__java_init______ = __java_init______ clazz.selectAlternatives__com_sun_xml_internal_ws_policy_EffectivePolicyModifier__com_sun_xml_internal_ws_policy_AssertionValidationProcessor__ = staticmethod(selectAlternatives__com_sun_xml_internal_ws_policy_EffectivePolicyModifier__com_sun_xml_internal_ws_policy_AssertionValidationProcessor__)
############### Configuration file for Bayesian ############### n_epochs = 10000 lr_start = 0.0001 num_workers = 16 valid_size = 0.1 batch_size = 1024 train_ens = 1 valid_ens = 1 record_mean_var = True recording_freq_per_epoch = 8 record_layers = ['fc5'] # Cross-module global variables mean_var_dir = None record_now = False curr_epoch_no = None curr_batch_no = None
n_epochs = 10000 lr_start = 0.0001 num_workers = 16 valid_size = 0.1 batch_size = 1024 train_ens = 1 valid_ens = 1 record_mean_var = True recording_freq_per_epoch = 8 record_layers = ['fc5'] mean_var_dir = None record_now = False curr_epoch_no = None curr_batch_no = None
''' Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M). More formally check if there exists two indices i and j such that : i != j 0 <= i, j < arr.length arr[i] == 2 * arr[j] Example 1: Input: arr = [10,2,5,3] Output: true Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5. Example 2: Input: arr = [7,1,14,11] Output: true Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7. Example 3: Input: arr = [3,1,7,11] Output: false Explanation: In this case does not exist N and M, such that N = 2 * M. ''' class Solution: def checkIfExist(self, arr: List[int]) -> bool: # step 1: deal with exceptions if arr==None: return False if len(arr)<=1: return False # step 2: traverse the list tb = set() for num in arr: if (2*num in tb)|(num/2 in tb): return True if num not in tb: tb.add(num) return False
""" Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M). More formally check if there exists two indices i and j such that : i != j 0 <= i, j < arr.length arr[i] == 2 * arr[j] Example 1: Input: arr = [10,2,5,3] Output: true Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5. Example 2: Input: arr = [7,1,14,11] Output: true Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7. Example 3: Input: arr = [3,1,7,11] Output: false Explanation: In this case does not exist N and M, such that N = 2 * M. """ class Solution: def check_if_exist(self, arr: List[int]) -> bool: if arr == None: return False if len(arr) <= 1: return False tb = set() for num in arr: if (2 * num in tb) | (num / 2 in tb): return True if num not in tb: tb.add(num) return False
# Author: btjanaka (Bryon Tjanaka) # Problem: (HackerRank) summing-the-n-series # Title: Summing the N series # Link: https://www.hackerrank.com/challenges/summing-the-n-series/problem # Idea: The terms cancel out such that the sum is just n^2. # Difficulty: easy # Tags: math t = int(input()) MOD = 10**9 + 7 for i in range(t): n = int(input()) % MOD print((n * n) % MOD)
t = int(input()) mod = 10 ** 9 + 7 for i in range(t): n = int(input()) % MOD print(n * n % MOD)
def classify(entries): for entry in entries: entry['category_id'] = 1 entry['event_id'] = 1 return entries
def classify(entries): for entry in entries: entry['category_id'] = 1 entry['event_id'] = 1 return entries
# Given list of values. We play a game against the opponent and we always grab # one value from either left or right side of our list of values. Our opponent # does the same move. What is the maximum value we can grab if our opponent # plays optimally, just like us. def optimal_values(V): T = [[0]*(len(V)+1) for _ in range(len(V)+1)] for i in range(1, len(V)+1): T[0][i] = i for i in range(1, len(V)+1): T[i][0] = i for i in range(1, len(T)): T[i][i] = (V[i-1], 0) for value in range(2, len(V)+1): for i in range(1, len(T)-value+1): j = i+value-1 for k in range(i, j): first = max(T[i][j-1][1] + V[j-1], T[i+1][j][1]+V[i-1]) second = min(T[i][j-1][0], T[i+1][j][0]) T[i][j] = (first, second) return T[1][-1][0] V = [3, 8, 4, 5, 1, 7, 6] print(optimal_values(V))
def optimal_values(V): t = [[0] * (len(V) + 1) for _ in range(len(V) + 1)] for i in range(1, len(V) + 1): T[0][i] = i for i in range(1, len(V) + 1): T[i][0] = i for i in range(1, len(T)): T[i][i] = (V[i - 1], 0) for value in range(2, len(V) + 1): for i in range(1, len(T) - value + 1): j = i + value - 1 for k in range(i, j): first = max(T[i][j - 1][1] + V[j - 1], T[i + 1][j][1] + V[i - 1]) second = min(T[i][j - 1][0], T[i + 1][j][0]) T[i][j] = (first, second) return T[1][-1][0] v = [3, 8, 4, 5, 1, 7, 6] print(optimal_values(V))
stars = "" for i in range(0, 5, 1): for j in range(0, i, 1): stars += "*" print(stars)
stars = '' for i in range(0, 5, 1): for j in range(0, i, 1): stars += '*' print(stars)
''' Configuration for the style, size, and elements of the GUI will be configured here ''' class window: scale_height = 0.5 scale_width = 0.5
""" Configuration for the style, size, and elements of the GUI will be configured here """ class Window: scale_height = 0.5 scale_width = 0.5
linestyles = {'wind_speed': '-', 'wind_gust': '--', 'pressure': '-'} fig, axes = plt.subplots(1, len(plot_variables), sharex=True, figsize=(18, 6)) for ax, var_names in zip(axes, plot_variables): for var_name in var_names: # Grab the color from our dictionary and pass it to plot() color = colors[var_name] linestyle = linestyles[var_name] ax.plot(df.time, df[var_name], color, linestyle=linestyle) ax.set_ylabel(var_name) ax.set_title('Buoy {}'.format(var_name)) ax.grid(True) ax.set_xlabel('Time') ax.xaxis.set_major_formatter(DateFormatter('%m/%d')) ax.xaxis.set_major_locator(DayLocator())
linestyles = {'wind_speed': '-', 'wind_gust': '--', 'pressure': '-'} (fig, axes) = plt.subplots(1, len(plot_variables), sharex=True, figsize=(18, 6)) for (ax, var_names) in zip(axes, plot_variables): for var_name in var_names: color = colors[var_name] linestyle = linestyles[var_name] ax.plot(df.time, df[var_name], color, linestyle=linestyle) ax.set_ylabel(var_name) ax.set_title('Buoy {}'.format(var_name)) ax.grid(True) ax.set_xlabel('Time') ax.xaxis.set_major_formatter(date_formatter('%m/%d')) ax.xaxis.set_major_locator(day_locator())
#! /usr/bin/env python3 REQUEST = 'Request' PRE_PREPARE = 'PrePrepare' PREPARE = 'Prepare' COMMIT = 'Commit' RESULT = 'Result' VIEW_CHANGE = 'ViewChange' NEW_VIEW = 'NewView' # Decouple actual message from preprepare message is highly recommended for optimization (etc. choice of protocol for small and big sized messages) # Message is only in Preprepare for educational reasons! class PBFTPreprepareMessage: ''' Pre-prepare message ''' def __init__(self, phase, viewNum, seqNum, digest, signature, message): self.phase = phase self.viewNum = viewNum self.seqNum = seqNum self.digest = digest self.signature = signature # Better use a separate message for the actual request self.message = message def __str__(self): return f''' ( "self.phase" = {self.phase} "self.viewNum" = {self.viewNum} "self.seqNum" = {self.seqNum} "self.digest" = {self.digest} "self.signature" = {self.signature} "self.message" = {self.message} ) ''' class PBFTMessage: ''' Message object for Prepare and Commit ''' def __init__(self, phase, viewNum, seqNum, digest, signature, fromNode): self.phase = phase self.viewNum = viewNum self.seqNum = seqNum self.digest = digest self.signature = signature self.fromNode = fromNode def __str__(self): return f''' ( "self.phase" = {self.phase} "self.viewNum" = {self.viewNum} "self.seqNum" = {self.seqNum} "self.digest" = {self.digest} "self.signature" = {self.signature} "self.fromNode" = {self.fromNode} ) ''' class PBFTResultMessage: ''' Message object for result ''' def __init__(self, viewNum, timestamp, toClientHost, toClientPort, fromNode, result, signature): self.phase = RESULT self.viewNum = viewNum self.timestamp = timestamp self.toClientHost = toClientHost self.toClientPort = toClientPort self.fromNode = fromNode self.result = result self.signature = signature def __str__(self): return f''' ( "self.phase" = {self.phase} "self.viewNum" = {self.viewNum} "self.timestamp" = {self.timestamp} "self.fromNode" = {self.fromNode} "self.result" = {self.result} "self.signature" = {self.signature} ) '''
request = 'Request' pre_prepare = 'PrePrepare' prepare = 'Prepare' commit = 'Commit' result = 'Result' view_change = 'ViewChange' new_view = 'NewView' class Pbftprepreparemessage: """ Pre-prepare message """ def __init__(self, phase, viewNum, seqNum, digest, signature, message): self.phase = phase self.viewNum = viewNum self.seqNum = seqNum self.digest = digest self.signature = signature self.message = message def __str__(self): return f'\n (\n "self.phase" = {self.phase}\n "self.viewNum" = {self.viewNum}\n "self.seqNum" = {self.seqNum}\n "self.digest" = {self.digest}\n "self.signature" = {self.signature}\n "self.message" = {self.message}\n )\n ' class Pbftmessage: """ Message object for Prepare and Commit """ def __init__(self, phase, viewNum, seqNum, digest, signature, fromNode): self.phase = phase self.viewNum = viewNum self.seqNum = seqNum self.digest = digest self.signature = signature self.fromNode = fromNode def __str__(self): return f'\n (\n "self.phase" = {self.phase}\n "self.viewNum" = {self.viewNum}\n "self.seqNum" = {self.seqNum}\n "self.digest" = {self.digest}\n "self.signature" = {self.signature}\n "self.fromNode" = {self.fromNode}\n )\n ' class Pbftresultmessage: """ Message object for result """ def __init__(self, viewNum, timestamp, toClientHost, toClientPort, fromNode, result, signature): self.phase = RESULT self.viewNum = viewNum self.timestamp = timestamp self.toClientHost = toClientHost self.toClientPort = toClientPort self.fromNode = fromNode self.result = result self.signature = signature def __str__(self): return f'\n (\n "self.phase" = {self.phase}\n "self.viewNum" = {self.viewNum}\n "self.timestamp" = {self.timestamp}\n "self.fromNode" = {self.fromNode}\n "self.result" = {self.result}\n "self.signature" = {self.signature}\n )\n '
{ "targets": [{ "target_name": "picosat", "include_dirs": [ "<!(node -e \"require('napi-macros')\")" ], "sources": [ "index.c", "lib/picosat.c" ] }] }
{'targets': [{'target_name': 'picosat', 'include_dirs': ['<!(node -e "require(\'napi-macros\')")'], 'sources': ['index.c', 'lib/picosat.c']}]}
################################# FINAL SETTING! # model settings voxel_size = [0.05, 0.05, 0.1] point_cloud_range = [0, -40, -3, 70.4, 40, 1] # MOCO Model model = dict( # type='Inter_Intro_moco', type='Inter_Intro_moco_better', img_backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, # norm_cfg=dict(type='BN'), # for debug norm_cfg=dict(type='SyncBN', eps=1e-3, momentum=0.01), norm_eval=False, style='pytorch'), # With MOCO pts_backbone=dict( type='PointNet2SAMSG', in_channels=4, num_points=(4096, 1024, (512, 512)), radii=((0.2, 0.4, 0.8), (0.4, 0.8, 1.6), (1.6, 3.2, 4.8)), num_samples=((32, 32, 64), (32, 32, 64), (16, 16, 16)), sa_channels=(((32, 32, 64), (32, 32, 64), (64, 64, 128)), ((64, 64, 128), (64, 64, 128), (128, 128, 256)), ((128, 128, 256), (128, 128, 256), (256, 256, 512))), aggregation_channels=(128, 256, 1024), fps_mods=(('D-FPS'), ('FS'), ('F-FPS', 'D-FPS')), fps_sample_range_lists=((-1), (-1), (512, -1)), norm_cfg=dict(type='BN2d', eps=1e-3, momentum=0.1), sa_cfg=dict( type='PointSAModuleMSG', pool_mod='max', # use_xyz=True, use_xyz=False, normalize_xyz=False)), # model training and testing settings train_cfg=dict( cl_strategy = dict( pts_intro_hidden_dim=1024, pts_intro_out_dim=128, img_inter_hidden_dim=2048, img_inter_out_dim=128, pts_inter_hidden_dim=1024, pts_inter_out_dim=128, pts_feat_dim=1024, img_feat_dim=2048, K=8192*4, m=0.999, T=0.07, points_center=[35.2, 0, -1], cross_factor=1, moco=False, simsiam=False, ############################################ img_moco=False, point_intro=True, # intro-loss point_branch=True # if pts backbone ))) # dataset settings dataset_type = 'KittiDataset' data_root = 'data/kitti/' class_names = ['Pedestrian', 'Cyclist', 'Car'] img_norm_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False) input_modality = dict(use_lidar=True, use_camera=True) # db_sampler = dict( # data_root=data_root, # info_path=data_root + 'kitti_dbinfos_train.pkl', # rate=1.0, # prepare=dict(filter_by_difficulty=[-1], filter_by_min_points=dict(Car=5)), # classes=class_names, # sample_groups=dict(Car=15)) file_client_args = dict(backend='disk') # Uncomment the following if use ceph or other file clients. # See https://mmcv.readthedocs.io/en/latest/api.html#mmcv.fileio.FileClient # for more details. # file_client_args = dict( # backend='petrel', path_mapping=dict(data='s3://kitti_data/')) train_pipeline = [ dict(type='LoadPointsFromFile', coord_type='LIDAR', load_dim=4, use_dim=4), dict(type='LoadImageFromFile'), dict(type='PointsRangeFilter', point_cloud_range=point_cloud_range), # filter range dict(type='IndoorPointSample', num_points=16384), # sample here only for pretrain! dict(type='LoadAnnotations3D', with_bbox_3d=True, with_label_3d=True), ############################## dict( type='Resize', # img_scale=[(640, 192), (2560, 768)], img_scale=[(640, 192), (2400, 720)], multiscale_mode='range', keep_ratio=True), ############################## dict( type='GlobalRotScaleTrans', # rot_range=[-0.78539816, 0.78539816], # scale_ratio_range=[0.95, 1.05], rot_range=[-1.5707963, 1.5707963], scale_ratio_range=[0.75, 1.25], translation_std=[0, 0, 0], points_center=[35.2, 0, -1]), dict(type='RandomFlip3D', flip_ratio_bev_horizontal=0.5), # dict(type='ObjectRangeFilter', point_cloud_range=point_cloud_range), dict(type='PointShuffle'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle3D', class_names=class_names), dict( type='Collect3D', keys=['points', 'img', 'gt_bboxes_3d', 'gt_labels_3d', 'points_ori']), ] test_pipeline = [] # No need to test # for dataset pretraining=True cross=True # for cross pretrain data = dict( samples_per_gpu=4, workers_per_gpu=4, # samples_per_gpu=3, # workers_per_gpu=3, train=dict( type='RepeatDataset', times=1, dataset=dict( type=dataset_type, data_root=data_root, ann_file=data_root + 'kitti_infos_train.pkl', split='training', pts_prefix='velodyne_reduced', pipeline=train_pipeline, modality=input_modality, classes=class_names, test_mode=False, pretraining=True, cross=True, # we use box_type_3d='LiDAR' in kitti and nuscenes dataset # and box_type_3d='Depth' in sunrgbd and scannet dataset. box_type_3d='LiDAR')), # actually there is no val val=dict( type=dataset_type, data_root=data_root, ann_file=data_root + 'kitti_infos_val.pkl', split='training', pts_prefix='velodyne_reduced', pipeline=test_pipeline, modality=input_modality, classes=class_names, test_mode=True, pretraining=True, box_type_3d='LiDAR')) # Not be used in pretrain evaluation = dict(start=9999, interval=1) # No use # optimizer optimizer = dict( constructor='HybridOptimizerConstructor', pts=dict( type='AdamW', # lr=0.002, lr=0.001, betas=(0.95, 0.99), weight_decay=0.01, step_interval=1), img=dict( type='SGD', # lr=0.03, lr=0.03, momentum=0.9, weight_decay=0.0001, step_interval=1), mlp=dict( type='SGD', # lr=0.03, lr=0.03, momentum=0.9, weight_decay=0.0001, step_interval=1)) # optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) optimizer_config = dict(grad_clip=None) # lr_config = dict(policy='CosineAnnealing', min_lr=0, warmup='linear', warmup_iters=10, warmup_ratio=0.001, warmup_by_epoch=True) lr_config = dict(policy='Exp', gamma=0.99) # runtime settings checkpoint_config = dict(interval=5) # yapf:disable log_config = dict( interval=30, hooks=[ dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook') ]) # yapf:enable dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = None load_from = None resume_from = None workflow = [('train', 1)] total_epochs = 100 runner = dict(type='EpochBasedRunner', max_epochs=total_epochs) find_unused_parameters=True # I cannot find it
voxel_size = [0.05, 0.05, 0.1] point_cloud_range = [0, -40, -3, 70.4, 40, 1] model = dict(type='Inter_Intro_moco_better', img_backbone=dict(type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_cfg=dict(type='SyncBN', eps=0.001, momentum=0.01), norm_eval=False, style='pytorch'), pts_backbone=dict(type='PointNet2SAMSG', in_channels=4, num_points=(4096, 1024, (512, 512)), radii=((0.2, 0.4, 0.8), (0.4, 0.8, 1.6), (1.6, 3.2, 4.8)), num_samples=((32, 32, 64), (32, 32, 64), (16, 16, 16)), sa_channels=(((32, 32, 64), (32, 32, 64), (64, 64, 128)), ((64, 64, 128), (64, 64, 128), (128, 128, 256)), ((128, 128, 256), (128, 128, 256), (256, 256, 512))), aggregation_channels=(128, 256, 1024), fps_mods=('D-FPS', 'FS', ('F-FPS', 'D-FPS')), fps_sample_range_lists=(-1, -1, (512, -1)), norm_cfg=dict(type='BN2d', eps=0.001, momentum=0.1), sa_cfg=dict(type='PointSAModuleMSG', pool_mod='max', use_xyz=False, normalize_xyz=False)), train_cfg=dict(cl_strategy=dict(pts_intro_hidden_dim=1024, pts_intro_out_dim=128, img_inter_hidden_dim=2048, img_inter_out_dim=128, pts_inter_hidden_dim=1024, pts_inter_out_dim=128, pts_feat_dim=1024, img_feat_dim=2048, K=8192 * 4, m=0.999, T=0.07, points_center=[35.2, 0, -1], cross_factor=1, moco=False, simsiam=False, img_moco=False, point_intro=True, point_branch=True))) dataset_type = 'KittiDataset' data_root = 'data/kitti/' class_names = ['Pedestrian', 'Cyclist', 'Car'] img_norm_cfg = dict(mean=[103.53, 116.28, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False) input_modality = dict(use_lidar=True, use_camera=True) file_client_args = dict(backend='disk') train_pipeline = [dict(type='LoadPointsFromFile', coord_type='LIDAR', load_dim=4, use_dim=4), dict(type='LoadImageFromFile'), dict(type='PointsRangeFilter', point_cloud_range=point_cloud_range), dict(type='IndoorPointSample', num_points=16384), dict(type='LoadAnnotations3D', with_bbox_3d=True, with_label_3d=True), dict(type='Resize', img_scale=[(640, 192), (2400, 720)], multiscale_mode='range', keep_ratio=True), dict(type='GlobalRotScaleTrans', rot_range=[-1.5707963, 1.5707963], scale_ratio_range=[0.75, 1.25], translation_std=[0, 0, 0], points_center=[35.2, 0, -1]), dict(type='RandomFlip3D', flip_ratio_bev_horizontal=0.5), dict(type='PointShuffle'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle3D', class_names=class_names), dict(type='Collect3D', keys=['points', 'img', 'gt_bboxes_3d', 'gt_labels_3d', 'points_ori'])] test_pipeline = [] pretraining = True cross = True data = dict(samples_per_gpu=4, workers_per_gpu=4, train=dict(type='RepeatDataset', times=1, dataset=dict(type=dataset_type, data_root=data_root, ann_file=data_root + 'kitti_infos_train.pkl', split='training', pts_prefix='velodyne_reduced', pipeline=train_pipeline, modality=input_modality, classes=class_names, test_mode=False, pretraining=True, cross=True, box_type_3d='LiDAR')), val=dict(type=dataset_type, data_root=data_root, ann_file=data_root + 'kitti_infos_val.pkl', split='training', pts_prefix='velodyne_reduced', pipeline=test_pipeline, modality=input_modality, classes=class_names, test_mode=True, pretraining=True, box_type_3d='LiDAR')) evaluation = dict(start=9999, interval=1) optimizer = dict(constructor='HybridOptimizerConstructor', pts=dict(type='AdamW', lr=0.001, betas=(0.95, 0.99), weight_decay=0.01, step_interval=1), img=dict(type='SGD', lr=0.03, momentum=0.9, weight_decay=0.0001, step_interval=1), mlp=dict(type='SGD', lr=0.03, momentum=0.9, weight_decay=0.0001, step_interval=1)) optimizer_config = dict(grad_clip=None) lr_config = dict(policy='Exp', gamma=0.99) checkpoint_config = dict(interval=5) log_config = dict(interval=30, hooks=[dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook')]) dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = None load_from = None resume_from = None workflow = [('train', 1)] total_epochs = 100 runner = dict(type='EpochBasedRunner', max_epochs=total_epochs) find_unused_parameters = True
class ScoreCard: def __init__(self, score_text: str): score_texts = score_text.split('|') self.normal_turns = [score_texts[i] for i in range(10)] if len(score_texts) == 12: self.additional_turns = [score_texts[11]] self.all_turns = self.normal_turns + self.additional_turns def to_score(self): sum = 0 for i in range(len(self.normal_turns)): sum = sum + self.get_score_by_turn(i) return sum def get_score_by_turn(self, turn: int)->int: score = self.text_to_score(self.normal_turns[turn]) if self.__is_strike(self.normal_turns[turn]) or self.__is_spare(self.normal_turns[turn]): return score + self.__get_bonus_score(turn) else: return score def __get_bonus_score(self, turn:int)->int: if turn + 1 == len(self.normal_turns): return self.text_to_score(self.additional_turns[0]) next_2_balls = str(self.all_turns[turn + 1] + self.all_turns[turn + 2])[0:2] return self.text_to_score(next_2_balls) def text_to_score(self, score_text:str)->int: if score_text.find('/') == 1: return 10 score = 0 for i in range(len(score_text)): score = score + self.__char_to_score(score_text[i]) return score def __char_to_score(self, score_text:str)->int: if self.__is_strike(score_text): return 10 elif score_text == '-': return 0 else: return int(score_text) def __is_strike(self, score_text: str)->bool: return True if score_text.upper() == 'X' else False def __is_spare(self, score_text: str)->bool: return True if score_text.find('/') == 1 else False
class Scorecard: def __init__(self, score_text: str): score_texts = score_text.split('|') self.normal_turns = [score_texts[i] for i in range(10)] if len(score_texts) == 12: self.additional_turns = [score_texts[11]] self.all_turns = self.normal_turns + self.additional_turns def to_score(self): sum = 0 for i in range(len(self.normal_turns)): sum = sum + self.get_score_by_turn(i) return sum def get_score_by_turn(self, turn: int) -> int: score = self.text_to_score(self.normal_turns[turn]) if self.__is_strike(self.normal_turns[turn]) or self.__is_spare(self.normal_turns[turn]): return score + self.__get_bonus_score(turn) else: return score def __get_bonus_score(self, turn: int) -> int: if turn + 1 == len(self.normal_turns): return self.text_to_score(self.additional_turns[0]) next_2_balls = str(self.all_turns[turn + 1] + self.all_turns[turn + 2])[0:2] return self.text_to_score(next_2_balls) def text_to_score(self, score_text: str) -> int: if score_text.find('/') == 1: return 10 score = 0 for i in range(len(score_text)): score = score + self.__char_to_score(score_text[i]) return score def __char_to_score(self, score_text: str) -> int: if self.__is_strike(score_text): return 10 elif score_text == '-': return 0 else: return int(score_text) def __is_strike(self, score_text: str) -> bool: return True if score_text.upper() == 'X' else False def __is_spare(self, score_text: str) -> bool: return True if score_text.find('/') == 1 else False
## Copyright 2018 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. ProtocolCompatibilityInfo = provider() def _check_protocol_compatibility_impl(ctx): stamp = ctx.actions.declare_file("{}.stamp".format(ctx.attr.name)) ctx.actions.run( outputs = [stamp], inputs = [ctx.file.protocol], arguments = [ "--stamp", stamp.path, ctx.file.protocol.path, ], executable = ctx.executable._check_protocol_compatibility, ) return [ ProtocolCompatibilityInfo( stamp = stamp, ), ] check_protocol_compatibility = rule( implementation = _check_protocol_compatibility_impl, attrs = { "protocol": attr.label( mandatory = True, allow_single_file = [".json"], ), "_check_protocol_compatibility": attr.label( default = Label("//third_party/inspector_protocol:CheckProtocolCompatibility"), executable = True, cfg = "host", ), }, )
protocol_compatibility_info = provider() def _check_protocol_compatibility_impl(ctx): stamp = ctx.actions.declare_file('{}.stamp'.format(ctx.attr.name)) ctx.actions.run(outputs=[stamp], inputs=[ctx.file.protocol], arguments=['--stamp', stamp.path, ctx.file.protocol.path], executable=ctx.executable._check_protocol_compatibility) return [protocol_compatibility_info(stamp=stamp)] check_protocol_compatibility = rule(implementation=_check_protocol_compatibility_impl, attrs={'protocol': attr.label(mandatory=True, allow_single_file=['.json']), '_check_protocol_compatibility': attr.label(default=label('//third_party/inspector_protocol:CheckProtocolCompatibility'), executable=True, cfg='host')})
bot_token = "" users = [ ] website_links =[ "https://www.google.com", ]
bot_token = '' users = [] website_links = ['https://www.google.com']
test = { 'name': 'q3_b', 'points': 5, 'suites': [ { 'cases': [ { 'code': '>>> no_match in ' "list(['professor', 'engineer', " "'scientist', 'cat'])\n" 'True', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
test = {'name': 'q3_b', 'points': 5, 'suites': [{'cases': [{'code': ">>> no_match in list(['professor', 'engineer', 'scientist', 'cat'])\nTrue", 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
#I, Andy Le, student number 000805099, certify that all code submitted is my own work; # that i have not copied it from any other source. I also certify that I have not allowed my work to be copied by others. color = input("What is your favourite color? ") print("You said " + color) #This is a comment, Python will ignore it.
color = input('What is your favourite color? ') print('You said ' + color)
# variables 2 x = 5 y = "John" print(x) print(y) # variables in py dont need to be specified as a boolean int char string etc
x = 5 y = 'John' print(x) print(y)
def format_timestamp(timestamp): localtime = timestamp.timetuple() result = unicode(int(time.strftime(u'%I', localtime))) result += time.strftime(u':%M %p, %A %B ', localtime) result += unicode(int(time.strftime(u'%d', localtime))) result += time.strftime(u', %Y') return result
def format_timestamp(timestamp): localtime = timestamp.timetuple() result = unicode(int(time.strftime(u'%I', localtime))) result += time.strftime(u':%M %p, %A %B ', localtime) result += unicode(int(time.strftime(u'%d', localtime))) result += time.strftime(u', %Y') return result
#!/usr/bin/python3 def safe_print_list(my_list=[], x=0): idx = 0 while my_list and idx < x: try: print("{:d}".format(my_list[idx]), end="") idx += 1 except IndexError: break print() return idx
def safe_print_list(my_list=[], x=0): idx = 0 while my_list and idx < x: try: print('{:d}'.format(my_list[idx]), end='') idx += 1 except IndexError: break print() return idx
#9TH PROGRAM # THIS PROGRAM WILL HELP IN ACCESSING DICTIONARY ITEMS AND PERFROM CERTAIN OPERATIONS WITH DICTIONARY ages = {} #EMPTY DICTIONARY ages["Micky"] = 24 ages["Lucky"] = 25 print(ages) keys = ages.keys # .keys prints all the keys avaialble in Dictionary print(keys) values = ages.values # .values prints all the values avaialble in Dictionary print(values) print(sorted(ages)) # NOTE Unable to sort print(sorted(ages.values)) print(ages.values) # Prints the values # NOTE has_key() has been replaced by "in" in Python 3 , You can access like below. # Syntax : "Values" in "dict" if("Micky" in ages): print("Micky is there") else: print("Micky is not there") print(len(ages)) # Print the length of the dictionary #Adding new item # New initialization ages = {"Snehasis" : "24" , "Sradhasis" : 25} print(ages) # New members ages["LKP"] = 45 # Here value is saved as int if("LKP" in ages): updatedValue = ages.get("LKP") + 10 print("Updated Value = " , updatedValue) print(ages) ages["JYOTI"] = "38" # Here value is saved as string if("JYOTI" in ages): updatedValue = ages.get("JYOTI") + " New Age" print("Updated Value = " , updatedValue) print(ages)
ages = {} ages['Micky'] = 24 ages['Lucky'] = 25 print(ages) keys = ages.keys print(keys) values = ages.values print(values) print(sorted(ages)) print(ages.values) if 'Micky' in ages: print('Micky is there') else: print('Micky is not there') print(len(ages)) ages = {'Snehasis': '24', 'Sradhasis': 25} print(ages) ages['LKP'] = 45 if 'LKP' in ages: updated_value = ages.get('LKP') + 10 print('Updated Value = ', updatedValue) print(ages) ages['JYOTI'] = '38' if 'JYOTI' in ages: updated_value = ages.get('JYOTI') + ' New Age' print('Updated Value = ', updatedValue) print(ages)
# # PySNMP MIB module A3COM-HUAWEI-LswIGSP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-LswIGSP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 16:51:01 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) # lswCommon, = mibBuilder.importSymbols("A3COM-HUAWEI-OID-MIB", "lswCommon") ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion") InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") IpAddress, Unsigned32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, iso, TimeTicks, NotificationType, Counter32, Integer32, ObjectIdentity, Gauge32, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Unsigned32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "iso", "TimeTicks", "NotificationType", "Counter32", "Integer32", "ObjectIdentity", "Gauge32", "Bits") RowStatus, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TextualConvention", "DisplayString") hwLswIgmpsnoopingMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7)) hwLswIgmpsnoopingMib.setRevisions(('2001-06-29 00:00',)) if mibBuilder.loadTexts: hwLswIgmpsnoopingMib.setLastUpdated('200106290000Z') if mibBuilder.loadTexts: hwLswIgmpsnoopingMib.setOrganization('') class EnabledStatus(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("enabled", 1), ("disabled", 2)) hwLswIgmpsnoopingMibObject = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1)) hwIgmpSnoopingStatus = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 1), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingStatus.setStatus('current') hwIgmpSnoopingRouterPortAge = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000)).clone(105)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingRouterPortAge.setStatus('current') hwIgmpSnoopingResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 25)).clone(10)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingResponseTime.setStatus('current') hwIgmpSnoopingHostTime = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(200, 1000)).clone(260)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingHostTime.setStatus('current') hwIgmpSnoopingGroupLimitTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5), ) if mibBuilder.loadTexts: hwIgmpSnoopingGroupLimitTable.setStatus('current') hwIgmpSnoopingGroupLimitEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5, 1), ).setIndexNames((0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingGroupIfIndex")) if mibBuilder.loadTexts: hwIgmpSnoopingGroupLimitEntry.setStatus('current') hwIgmpSnoopingGroupIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: hwIgmpSnoopingGroupIfIndex.setStatus('current') hwIgmpSnoopingGroupLimitNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5, 1, 2), Unsigned32().clone(4294967295)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingGroupLimitNumber.setStatus('current') hwIgmpSnoopingFastLeaveTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6), ) if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveTable.setStatus('current') hwIgmpSnoopingFastLeaveEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6, 1), ).setIndexNames((0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingFastLeaveIfIndex")) if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveEntry.setStatus('current') hwIgmpSnoopingFastLeaveIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveIfIndex.setStatus('current') hwIgmpSnoopingFastLeaveStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6, 1, 2), EnabledStatus().clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveStatus.setStatus('current') hwIgmpSnoopingGroupPolicyTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7), ) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyTable.setStatus('current') hwIgmpSnoopingGroupPolicyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1), ).setIndexNames((0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingGroupPolicyIfIndex"), (0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingGroupPolicyVlanID")) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyEntry.setStatus('current') hwIgmpSnoopingGroupPolicyIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyIfIndex.setStatus('current') hwIgmpSnoopingGroupPolicyVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyVlanID.setStatus('current') hwIgmpSnoopingGroupPolicyParameter = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2000, 2999))).setMaxAccess("readcreate") if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyParameter.setStatus('current') hwIgmpSnoopingGroupPolicyStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyStatus.setStatus('current') hwIgmpSnoopingNonFloodingStatus = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 8), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingNonFloodingStatus.setStatus('current') hwIgmpSnoopingVlanStatusTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9), ) if mibBuilder.loadTexts: hwIgmpSnoopingVlanStatusTable.setStatus('current') hwIgmpSnoopingVlanStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9, 1), ).setIndexNames((0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingVlanID")) if mibBuilder.loadTexts: hwIgmpSnoopingVlanStatusEntry.setStatus('current') hwIgmpSnoopingVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))) if mibBuilder.loadTexts: hwIgmpSnoopingVlanID.setStatus('current') hwIgmpSnoopingVlanEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9, 1, 2), EnabledStatus().clone('disabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingVlanEnabled.setStatus('current') hwIgmpSnoopingStatsObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10)) hwRecvIGMPGQueryNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPGQueryNum.setStatus('current') hwRecvIGMPSQueryNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPSQueryNum.setStatus('current') hwRecvIGMPV1ReportNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPV1ReportNum.setStatus('current') hwRecvIGMPV2ReportNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPV2ReportNum.setStatus('current') hwRecvIGMPLeaveNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPLeaveNum.setStatus('current') hwRecvErrorIGMPPacketNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvErrorIGMPPacketNum.setStatus('current') hwSentIGMPSQueryNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwSentIGMPSQueryNum.setStatus('current') hwIgmpSnoopingClearStats = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("clear", 1), ("counting", 2))).clone('counting')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingClearStats.setStatus('current') mibBuilder.exportSymbols("A3COM-HUAWEI-LswIGSP-MIB", hwIgmpSnoopingStatus=hwIgmpSnoopingStatus, hwIgmpSnoopingResponseTime=hwIgmpSnoopingResponseTime, hwIgmpSnoopingGroupPolicyParameter=hwIgmpSnoopingGroupPolicyParameter, hwIgmpSnoopingRouterPortAge=hwIgmpSnoopingRouterPortAge, hwIgmpSnoopingHostTime=hwIgmpSnoopingHostTime, hwRecvIGMPV2ReportNum=hwRecvIGMPV2ReportNum, hwIgmpSnoopingGroupPolicyEntry=hwIgmpSnoopingGroupPolicyEntry, hwIgmpSnoopingGroupPolicyVlanID=hwIgmpSnoopingGroupPolicyVlanID, hwIgmpSnoopingGroupLimitEntry=hwIgmpSnoopingGroupLimitEntry, hwSentIGMPSQueryNum=hwSentIGMPSQueryNum, hwIgmpSnoopingGroupPolicyStatus=hwIgmpSnoopingGroupPolicyStatus, hwLswIgmpsnoopingMibObject=hwLswIgmpsnoopingMibObject, hwRecvIGMPSQueryNum=hwRecvIGMPSQueryNum, hwIgmpSnoopingGroupIfIndex=hwIgmpSnoopingGroupIfIndex, hwLswIgmpsnoopingMib=hwLswIgmpsnoopingMib, hwIgmpSnoopingVlanEnabled=hwIgmpSnoopingVlanEnabled, hwIgmpSnoopingClearStats=hwIgmpSnoopingClearStats, hwIgmpSnoopingStatsObjects=hwIgmpSnoopingStatsObjects, hwRecvErrorIGMPPacketNum=hwRecvErrorIGMPPacketNum, PYSNMP_MODULE_ID=hwLswIgmpsnoopingMib, hwIgmpSnoopingFastLeaveIfIndex=hwIgmpSnoopingFastLeaveIfIndex, hwRecvIGMPLeaveNum=hwRecvIGMPLeaveNum, hwIgmpSnoopingGroupLimitNumber=hwIgmpSnoopingGroupLimitNumber, hwIgmpSnoopingNonFloodingStatus=hwIgmpSnoopingNonFloodingStatus, hwIgmpSnoopingGroupLimitTable=hwIgmpSnoopingGroupLimitTable, hwIgmpSnoopingFastLeaveTable=hwIgmpSnoopingFastLeaveTable, hwRecvIGMPGQueryNum=hwRecvIGMPGQueryNum, EnabledStatus=EnabledStatus, hwIgmpSnoopingVlanStatusEntry=hwIgmpSnoopingVlanStatusEntry, hwIgmpSnoopingGroupPolicyIfIndex=hwIgmpSnoopingGroupPolicyIfIndex, hwIgmpSnoopingFastLeaveStatus=hwIgmpSnoopingFastLeaveStatus, hwIgmpSnoopingVlanID=hwIgmpSnoopingVlanID, hwIgmpSnoopingGroupPolicyTable=hwIgmpSnoopingGroupPolicyTable, hwIgmpSnoopingVlanStatusTable=hwIgmpSnoopingVlanStatusTable, hwIgmpSnoopingFastLeaveEntry=hwIgmpSnoopingFastLeaveEntry, hwRecvIGMPV1ReportNum=hwRecvIGMPV1ReportNum)
(lsw_common,) = mibBuilder.importSymbols('A3COM-HUAWEI-OID-MIB', 'lswCommon') (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ConstraintsUnion') (interface_index,) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndex') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (ip_address, unsigned32, module_identity, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, counter64, iso, time_ticks, notification_type, counter32, integer32, object_identity, gauge32, bits) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'Unsigned32', 'ModuleIdentity', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter64', 'iso', 'TimeTicks', 'NotificationType', 'Counter32', 'Integer32', 'ObjectIdentity', 'Gauge32', 'Bits') (row_status, textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'TextualConvention', 'DisplayString') hw_lsw_igmpsnooping_mib = module_identity((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7)) hwLswIgmpsnoopingMib.setRevisions(('2001-06-29 00:00',)) if mibBuilder.loadTexts: hwLswIgmpsnoopingMib.setLastUpdated('200106290000Z') if mibBuilder.loadTexts: hwLswIgmpsnoopingMib.setOrganization('') class Enabledstatus(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2)) named_values = named_values(('enabled', 1), ('disabled', 2)) hw_lsw_igmpsnooping_mib_object = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1)) hw_igmp_snooping_status = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 1), enabled_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: hwIgmpSnoopingStatus.setStatus('current') hw_igmp_snooping_router_port_age = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 1000)).clone(105)).setMaxAccess('readwrite') if mibBuilder.loadTexts: hwIgmpSnoopingRouterPortAge.setStatus('current') hw_igmp_snooping_response_time = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(1, 25)).clone(10)).setMaxAccess('readwrite') if mibBuilder.loadTexts: hwIgmpSnoopingResponseTime.setStatus('current') hw_igmp_snooping_host_time = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(200, 1000)).clone(260)).setMaxAccess('readwrite') if mibBuilder.loadTexts: hwIgmpSnoopingHostTime.setStatus('current') hw_igmp_snooping_group_limit_table = mib_table((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5)) if mibBuilder.loadTexts: hwIgmpSnoopingGroupLimitTable.setStatus('current') hw_igmp_snooping_group_limit_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5, 1)).setIndexNames((0, 'A3COM-HUAWEI-LswIGSP-MIB', 'hwIgmpSnoopingGroupIfIndex')) if mibBuilder.loadTexts: hwIgmpSnoopingGroupLimitEntry.setStatus('current') hw_igmp_snooping_group_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5, 1, 1), interface_index()) if mibBuilder.loadTexts: hwIgmpSnoopingGroupIfIndex.setStatus('current') hw_igmp_snooping_group_limit_number = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5, 1, 2), unsigned32().clone(4294967295)).setMaxAccess('readwrite') if mibBuilder.loadTexts: hwIgmpSnoopingGroupLimitNumber.setStatus('current') hw_igmp_snooping_fast_leave_table = mib_table((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6)) if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveTable.setStatus('current') hw_igmp_snooping_fast_leave_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6, 1)).setIndexNames((0, 'A3COM-HUAWEI-LswIGSP-MIB', 'hwIgmpSnoopingFastLeaveIfIndex')) if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveEntry.setStatus('current') hw_igmp_snooping_fast_leave_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6, 1, 1), interface_index()) if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveIfIndex.setStatus('current') hw_igmp_snooping_fast_leave_status = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6, 1, 2), enabled_status().clone(2)).setMaxAccess('readwrite') if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveStatus.setStatus('current') hw_igmp_snooping_group_policy_table = mib_table((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7)) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyTable.setStatus('current') hw_igmp_snooping_group_policy_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1)).setIndexNames((0, 'A3COM-HUAWEI-LswIGSP-MIB', 'hwIgmpSnoopingGroupPolicyIfIndex'), (0, 'A3COM-HUAWEI-LswIGSP-MIB', 'hwIgmpSnoopingGroupPolicyVlanID')) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyEntry.setStatus('current') hw_igmp_snooping_group_policy_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 1), interface_index()) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyIfIndex.setStatus('current') hw_igmp_snooping_group_policy_vlan_id = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 4094))) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyVlanID.setStatus('current') hw_igmp_snooping_group_policy_parameter = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(2000, 2999))).setMaxAccess('readcreate') if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyParameter.setStatus('current') hw_igmp_snooping_group_policy_status = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 4), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyStatus.setStatus('current') hw_igmp_snooping_non_flooding_status = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 8), enabled_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: hwIgmpSnoopingNonFloodingStatus.setStatus('current') hw_igmp_snooping_vlan_status_table = mib_table((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9)) if mibBuilder.loadTexts: hwIgmpSnoopingVlanStatusTable.setStatus('current') hw_igmp_snooping_vlan_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9, 1)).setIndexNames((0, 'A3COM-HUAWEI-LswIGSP-MIB', 'hwIgmpSnoopingVlanID')) if mibBuilder.loadTexts: hwIgmpSnoopingVlanStatusEntry.setStatus('current') hw_igmp_snooping_vlan_id = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 4094))) if mibBuilder.loadTexts: hwIgmpSnoopingVlanID.setStatus('current') hw_igmp_snooping_vlan_enabled = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9, 1, 2), enabled_status().clone('disabled')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hwIgmpSnoopingVlanEnabled.setStatus('current') hw_igmp_snooping_stats_objects = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10)) hw_recv_igmpg_query_num = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 1), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hwRecvIGMPGQueryNum.setStatus('current') hw_recv_igmps_query_num = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 2), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hwRecvIGMPSQueryNum.setStatus('current') hw_recv_igmpv1_report_num = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 3), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hwRecvIGMPV1ReportNum.setStatus('current') hw_recv_igmpv2_report_num = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 4), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hwRecvIGMPV2ReportNum.setStatus('current') hw_recv_igmp_leave_num = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 5), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hwRecvIGMPLeaveNum.setStatus('current') hw_recv_error_igmp_packet_num = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 6), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hwRecvErrorIGMPPacketNum.setStatus('current') hw_sent_igmps_query_num = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 7), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hwSentIGMPSQueryNum.setStatus('current') hw_igmp_snooping_clear_stats = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('clear', 1), ('counting', 2))).clone('counting')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hwIgmpSnoopingClearStats.setStatus('current') mibBuilder.exportSymbols('A3COM-HUAWEI-LswIGSP-MIB', hwIgmpSnoopingStatus=hwIgmpSnoopingStatus, hwIgmpSnoopingResponseTime=hwIgmpSnoopingResponseTime, hwIgmpSnoopingGroupPolicyParameter=hwIgmpSnoopingGroupPolicyParameter, hwIgmpSnoopingRouterPortAge=hwIgmpSnoopingRouterPortAge, hwIgmpSnoopingHostTime=hwIgmpSnoopingHostTime, hwRecvIGMPV2ReportNum=hwRecvIGMPV2ReportNum, hwIgmpSnoopingGroupPolicyEntry=hwIgmpSnoopingGroupPolicyEntry, hwIgmpSnoopingGroupPolicyVlanID=hwIgmpSnoopingGroupPolicyVlanID, hwIgmpSnoopingGroupLimitEntry=hwIgmpSnoopingGroupLimitEntry, hwSentIGMPSQueryNum=hwSentIGMPSQueryNum, hwIgmpSnoopingGroupPolicyStatus=hwIgmpSnoopingGroupPolicyStatus, hwLswIgmpsnoopingMibObject=hwLswIgmpsnoopingMibObject, hwRecvIGMPSQueryNum=hwRecvIGMPSQueryNum, hwIgmpSnoopingGroupIfIndex=hwIgmpSnoopingGroupIfIndex, hwLswIgmpsnoopingMib=hwLswIgmpsnoopingMib, hwIgmpSnoopingVlanEnabled=hwIgmpSnoopingVlanEnabled, hwIgmpSnoopingClearStats=hwIgmpSnoopingClearStats, hwIgmpSnoopingStatsObjects=hwIgmpSnoopingStatsObjects, hwRecvErrorIGMPPacketNum=hwRecvErrorIGMPPacketNum, PYSNMP_MODULE_ID=hwLswIgmpsnoopingMib, hwIgmpSnoopingFastLeaveIfIndex=hwIgmpSnoopingFastLeaveIfIndex, hwRecvIGMPLeaveNum=hwRecvIGMPLeaveNum, hwIgmpSnoopingGroupLimitNumber=hwIgmpSnoopingGroupLimitNumber, hwIgmpSnoopingNonFloodingStatus=hwIgmpSnoopingNonFloodingStatus, hwIgmpSnoopingGroupLimitTable=hwIgmpSnoopingGroupLimitTable, hwIgmpSnoopingFastLeaveTable=hwIgmpSnoopingFastLeaveTable, hwRecvIGMPGQueryNum=hwRecvIGMPGQueryNum, EnabledStatus=EnabledStatus, hwIgmpSnoopingVlanStatusEntry=hwIgmpSnoopingVlanStatusEntry, hwIgmpSnoopingGroupPolicyIfIndex=hwIgmpSnoopingGroupPolicyIfIndex, hwIgmpSnoopingFastLeaveStatus=hwIgmpSnoopingFastLeaveStatus, hwIgmpSnoopingVlanID=hwIgmpSnoopingVlanID, hwIgmpSnoopingGroupPolicyTable=hwIgmpSnoopingGroupPolicyTable, hwIgmpSnoopingVlanStatusTable=hwIgmpSnoopingVlanStatusTable, hwIgmpSnoopingFastLeaveEntry=hwIgmpSnoopingFastLeaveEntry, hwRecvIGMPV1ReportNum=hwRecvIGMPV1ReportNum)
T = input() hh, mm = map(int, T.split(':')) mm += 5 if mm > 59: hh += 1 mm %= 60 if hh > 23: hh %= 24 print('%02d:%02d' % (hh, mm))
t = input() (hh, mm) = map(int, T.split(':')) mm += 5 if mm > 59: hh += 1 mm %= 60 if hh > 23: hh %= 24 print('%02d:%02d' % (hh, mm))
class NodeSocketInterfaceIntUnsigned: default_value = None max_value = None min_value = None
class Nodesocketinterfaceintunsigned: default_value = None max_value = None min_value = None
''' # TASK 5 - Write a function that takes a string and a shift integer and returns the string with each letter shifted - you can iterate over the letters in a string - for letter in str: ''' def get_shifted_string(string, shift): ''' return the input string with each letter shifted shift steps ''' raise NotImplementedError
""" # TASK 5 - Write a function that takes a string and a shift integer and returns the string with each letter shifted - you can iterate over the letters in a string - for letter in str: """ def get_shifted_string(string, shift): """ return the input string with each letter shifted shift steps """ raise NotImplementedError
mytuple = (9,8,7,5,4,1,2,3) num = len(mytuple) print("# of element:", num) min_value = min(mytuple) max_value = max(mytuple) print("Min value:", min_value) print("Max value:", max_value)
mytuple = (9, 8, 7, 5, 4, 1, 2, 3) num = len(mytuple) print('# of element:', num) min_value = min(mytuple) max_value = max(mytuple) print('Min value:', min_value) print('Max value:', max_value)
class CalcController: def __init__(self, model, view): self.model = model self.model.OnResult = self.OnResult self.model.OnError = self.OnError self.view = view self.model.AllClear() # interface for view def command(self, command): if command in ['0','1','2','3','4','5','6','7','8','9']: self.model.EnterDigit(command) elif command == 'DOT': self.model.EnterDot() elif command == 'SIGN': self.model.Sign() elif command == 'CLEAR': self.model.Clear() elif command == 'ALL_CLEAR': self.model.AllClear() elif command == 'ADDITION': self.model.Addition() elif command == 'SUBSTRACTION': self.model.Substraction() elif command == 'MULTIPLICATION': self.model.Multiplication() elif command == 'DIVISION': self.model.Division() elif command == 'SQRT': self.model.CalcSqrt() elif command == 'CALCULATE': self.model.CalcResult() def OnResult(self, result): self.view.ShowResult(result) def OnError(self): self.view.ShowResult('ERROR')
class Calccontroller: def __init__(self, model, view): self.model = model self.model.OnResult = self.OnResult self.model.OnError = self.OnError self.view = view self.model.AllClear() def command(self, command): if command in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: self.model.EnterDigit(command) elif command == 'DOT': self.model.EnterDot() elif command == 'SIGN': self.model.Sign() elif command == 'CLEAR': self.model.Clear() elif command == 'ALL_CLEAR': self.model.AllClear() elif command == 'ADDITION': self.model.Addition() elif command == 'SUBSTRACTION': self.model.Substraction() elif command == 'MULTIPLICATION': self.model.Multiplication() elif command == 'DIVISION': self.model.Division() elif command == 'SQRT': self.model.CalcSqrt() elif command == 'CALCULATE': self.model.CalcResult() def on_result(self, result): self.view.ShowResult(result) def on_error(self): self.view.ShowResult('ERROR')
# Delete all keys that start with 'foo'. for k in hiera.keys(): if k.startswith('foo'): hiera.pop(k)
for k in hiera.keys(): if k.startswith('foo'): hiera.pop(k)
length = float(input()) width = float(input()) height = float(input()) perc_full = float(input()) aquarium_volume = length*width*height total_liters = aquarium_volume*0.001 perc = perc_full*0.01 needed_liters = total_liters*(1-perc) print(needed_liters)
length = float(input()) width = float(input()) height = float(input()) perc_full = float(input()) aquarium_volume = length * width * height total_liters = aquarium_volume * 0.001 perc = perc_full * 0.01 needed_liters = total_liters * (1 - perc) print(needed_liters)
def maximum_subarray(nums): current_sum = max_sum = nums[0] for num in nums[1:]: current_sum = max(num, current_sum + num) max_sum = max(max_sum, current_sum) return max_sum if __name__ == '__main__': print(maximum_subarray([-2,1,-3,4,-1,2,1,-5,4]))
def maximum_subarray(nums): current_sum = max_sum = nums[0] for num in nums[1:]: current_sum = max(num, current_sum + num) max_sum = max(max_sum, current_sum) return max_sum if __name__ == '__main__': print(maximum_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
class MocNode: def __init__(self): self.name = '' self.parent = '' self.refmoc = [] def setName(self, name): self.name = name def setParent(self, parent): self.parent = parent def setRefmoc(self, refmoc): self.refmoc = refmoc
class Mocnode: def __init__(self): self.name = '' self.parent = '' self.refmoc = [] def set_name(self, name): self.name = name def set_parent(self, parent): self.parent = parent def set_refmoc(self, refmoc): self.refmoc = refmoc
print("| U0 | U1 | U2 | Element |") print("|--|--|--|--------|") stack = [] for a in (0, 1, 2): for b in (0, 1, 2): for c in (0, 1, 2): stack.append(str(a) if a != 0 else '') stack.append(((str(b) if b > 1 else '') + 'x') if b != 0 else '') stack.append(((str(c) if c > 1 else '') + 'x^2') if c != 0 else '') while stack and stack[-1] == '': stack.pop() element = stack.pop() if stack else '' while stack: element = stack[-1] + ' + ' + element if stack[-1] != '' else element stack.pop() print("|" + str(a) + "|" + str(b) + "|" + str(c) + "|" + (element if element != '' else '0') + "|") # Galios field multiplicative inverse # SPN w = int() def permute(w, P): new = 0 for i in range(len(P)): new |= ((w & (1 << (15 - i))) >> (15 - i)) << (16 - P[i]) return new permute()
print('| U0 | U1 | U2 | Element |') print('|--|--|--|--------|') stack = [] for a in (0, 1, 2): for b in (0, 1, 2): for c in (0, 1, 2): stack.append(str(a) if a != 0 else '') stack.append((str(b) if b > 1 else '') + 'x' if b != 0 else '') stack.append((str(c) if c > 1 else '') + 'x^2' if c != 0 else '') while stack and stack[-1] == '': stack.pop() element = stack.pop() if stack else '' while stack: element = stack[-1] + ' + ' + element if stack[-1] != '' else element stack.pop() print('|' + str(a) + '|' + str(b) + '|' + str(c) + '|' + (element if element != '' else '0') + '|') w = int() def permute(w, P): new = 0 for i in range(len(P)): new |= (w & 1 << 15 - i) >> 15 - i << 16 - P[i] return new permute()
print(" ADIN EGIAZTAKETA\n") adina=int(input("Sartu zure adina: ")) while adina<0: print(f"{adina} zenbaki negatibo bat da eta ezin dezu adin negatiborik eduki.") adina=int(input("Sartu zure adina: ")) while adina>130: print(f"{adina} adin haundiegi bat da, ez det sinisten adin hoi dezunik.") adina=int(input("Sartu zure adina: ")) if adina>=18: print("18 urte baino gehiago dituzu, beraz pasa zaitezke.") else: print("18 urte baino gutxiago dituzu, beraz ezin zea pasa.")
print(' ADIN EGIAZTAKETA\n') adina = int(input('Sartu zure adina: ')) while adina < 0: print(f'{adina} zenbaki negatibo bat da eta ezin dezu adin negatiborik eduki.') adina = int(input('Sartu zure adina: ')) while adina > 130: print(f'{adina} adin haundiegi bat da, ez det sinisten adin hoi dezunik.') adina = int(input('Sartu zure adina: ')) if adina >= 18: print('18 urte baino gehiago dituzu, beraz pasa zaitezke.') else: print('18 urte baino gutxiago dituzu, beraz ezin zea pasa.')
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"show_binmask": "00_core.ipynb", "BinaryMasksBlock": "00_core.ipynb", "TensorBinMasks": "00_core.ipynb", "TensorBinMasks2TensorMask": "00_core.ipynb", "CocoData": "01_datasets.ipynb", "ObjectDetectionDataLoaders": "02_dataloaders.ipynb", "ObjDetAdapter": "03_callbacks.ipynb", "get_fasterrcnn_model": "04a_models.fasterrcnn.ipynb", "get_fasterrcnn_model_swin": "04a_models.fasterrcnn.ipynb", "SwinTransformerFPN": "04a_models.fasterrcnn.ipynb", "fasterrcnn_resnet18": "04a_models.fasterrcnn.ipynb", "fasterrcnn_resnet34": "04a_models.fasterrcnn.ipynb", "fasterrcnn_resnet50": "04a_models.fasterrcnn.ipynb", "fasterrcnn_resnet101": "04a_models.fasterrcnn.ipynb", "fasterrcnn_resnet152": "04a_models.fasterrcnn.ipynb", "fasterrcnn_swinT": "04a_models.fasterrcnn.ipynb", "fasterrcnn_swinS": "04a_models.fasterrcnn.ipynb", "fasterrcnn_swinB": "04a_models.fasterrcnn.ipynb", "fasterrcnn_swinL": "04a_models.fasterrcnn.ipynb", "get_maskrcnn_model": "04b_models.maskrcnn.ipynb", "maskrcnn_resnet18": "04b_models.maskrcnn.ipynb", "maskrcnn_resnet34": "04b_models.maskrcnn.ipynb", "maskrcnn_resnet50": "04b_models.maskrcnn.ipynb", "maskrcnn_resnet101": "04b_models.maskrcnn.ipynb", "maskrcnn_resnet152": "04b_models.maskrcnn.ipynb", "EffDetModelWrapper": "04c_models.efficientdet.ipynb", "get_efficientdet_model": "04c_models.efficientdet.ipynb", "efficientdet_d0": "04c_models.efficientdet.ipynb", "efficientdet_d1": "04c_models.efficientdet.ipynb", "efficientdet_d2": "04c_models.efficientdet.ipynb", "efficientdet_d3": "04c_models.efficientdet.ipynb", "efficientdet_d4": "04c_models.efficientdet.ipynb", "efficientdet_d5": "04c_models.efficientdet.ipynb", "efficientdet_d6": "04c_models.efficientdet.ipynb", "efficientdet_d7": "04c_models.efficientdet.ipynb", "no_split": "05_learners.ipynb", "rcnn_split": "05_learners.ipynb", "effdet_split": "05_learners.ipynb", "ObjDetLearner": "05_learners.ipynb", "ObjDetLearner.get_preds": "05_learners.ipynb", "ObjDetLearner.show_results": "05_learners.ipynb", "InstSegLearner": "05_learners.ipynb", "InstSegLearner.get_preds": "05_learners.ipynb", "InstSegLearner.show_results": "05_learners.ipynb", "fasterrcnn_learner": "05_learners.ipynb", "maskrcnn_learner": "05_learners.ipynb", "efficientdet_learner": "05_learners.ipynb", "mAP_Metric": "06_metrics.ipynb", "create_mAP_metric": "06_metrics.ipynb", "mAP_at_IoU40": "06_metrics.ipynb", "mAP_at_IoU50": "06_metrics.ipynb", "mAP_at_IoU60": "06_metrics.ipynb", "mAP_at_IoU70": "06_metrics.ipynb", "mAP_at_IoU80": "06_metrics.ipynb", "mAP_at_IoU90": "06_metrics.ipynb", "mAP_at_IoU50_95": "06_metrics.ipynb", "mAP_Metric_np": "07_metrics_np.ipynb", "create_mAP_metric_np": "07_metrics_np.ipynb", "mAP_at_IoU40_np": "07_metrics_np.ipynb", "mAP_at_IoU50_np": "07_metrics_np.ipynb", "mAP_at_IoU60_np": "07_metrics_np.ipynb", "mAP_at_IoU70_np": "07_metrics_np.ipynb", "mAP_at_IoU80_np": "07_metrics_np.ipynb", "mAP_at_IoU90_np": "07_metrics_np.ipynb", "mAP_at_IoU50_95_np": "07_metrics_np.ipynb"} modules = ["core.py", "datasets.py", "dataloaders.py", "callbacks.py", "models/fasterrcnn.py", "models/maskrcnn.py", "models/efficientdet.py", "learners.py", "metrics.py", "metrics_np.py"] doc_url = "https://rbrtwlz.github.io/fastai_object_detection/" git_url = "https://github.com/rbrtwlz/fastai_object_detection/tree/master/" def custom_doc_links(name): return None
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'show_binmask': '00_core.ipynb', 'BinaryMasksBlock': '00_core.ipynb', 'TensorBinMasks': '00_core.ipynb', 'TensorBinMasks2TensorMask': '00_core.ipynb', 'CocoData': '01_datasets.ipynb', 'ObjectDetectionDataLoaders': '02_dataloaders.ipynb', 'ObjDetAdapter': '03_callbacks.ipynb', 'get_fasterrcnn_model': '04a_models.fasterrcnn.ipynb', 'get_fasterrcnn_model_swin': '04a_models.fasterrcnn.ipynb', 'SwinTransformerFPN': '04a_models.fasterrcnn.ipynb', 'fasterrcnn_resnet18': '04a_models.fasterrcnn.ipynb', 'fasterrcnn_resnet34': '04a_models.fasterrcnn.ipynb', 'fasterrcnn_resnet50': '04a_models.fasterrcnn.ipynb', 'fasterrcnn_resnet101': '04a_models.fasterrcnn.ipynb', 'fasterrcnn_resnet152': '04a_models.fasterrcnn.ipynb', 'fasterrcnn_swinT': '04a_models.fasterrcnn.ipynb', 'fasterrcnn_swinS': '04a_models.fasterrcnn.ipynb', 'fasterrcnn_swinB': '04a_models.fasterrcnn.ipynb', 'fasterrcnn_swinL': '04a_models.fasterrcnn.ipynb', 'get_maskrcnn_model': '04b_models.maskrcnn.ipynb', 'maskrcnn_resnet18': '04b_models.maskrcnn.ipynb', 'maskrcnn_resnet34': '04b_models.maskrcnn.ipynb', 'maskrcnn_resnet50': '04b_models.maskrcnn.ipynb', 'maskrcnn_resnet101': '04b_models.maskrcnn.ipynb', 'maskrcnn_resnet152': '04b_models.maskrcnn.ipynb', 'EffDetModelWrapper': '04c_models.efficientdet.ipynb', 'get_efficientdet_model': '04c_models.efficientdet.ipynb', 'efficientdet_d0': '04c_models.efficientdet.ipynb', 'efficientdet_d1': '04c_models.efficientdet.ipynb', 'efficientdet_d2': '04c_models.efficientdet.ipynb', 'efficientdet_d3': '04c_models.efficientdet.ipynb', 'efficientdet_d4': '04c_models.efficientdet.ipynb', 'efficientdet_d5': '04c_models.efficientdet.ipynb', 'efficientdet_d6': '04c_models.efficientdet.ipynb', 'efficientdet_d7': '04c_models.efficientdet.ipynb', 'no_split': '05_learners.ipynb', 'rcnn_split': '05_learners.ipynb', 'effdet_split': '05_learners.ipynb', 'ObjDetLearner': '05_learners.ipynb', 'ObjDetLearner.get_preds': '05_learners.ipynb', 'ObjDetLearner.show_results': '05_learners.ipynb', 'InstSegLearner': '05_learners.ipynb', 'InstSegLearner.get_preds': '05_learners.ipynb', 'InstSegLearner.show_results': '05_learners.ipynb', 'fasterrcnn_learner': '05_learners.ipynb', 'maskrcnn_learner': '05_learners.ipynb', 'efficientdet_learner': '05_learners.ipynb', 'mAP_Metric': '06_metrics.ipynb', 'create_mAP_metric': '06_metrics.ipynb', 'mAP_at_IoU40': '06_metrics.ipynb', 'mAP_at_IoU50': '06_metrics.ipynb', 'mAP_at_IoU60': '06_metrics.ipynb', 'mAP_at_IoU70': '06_metrics.ipynb', 'mAP_at_IoU80': '06_metrics.ipynb', 'mAP_at_IoU90': '06_metrics.ipynb', 'mAP_at_IoU50_95': '06_metrics.ipynb', 'mAP_Metric_np': '07_metrics_np.ipynb', 'create_mAP_metric_np': '07_metrics_np.ipynb', 'mAP_at_IoU40_np': '07_metrics_np.ipynb', 'mAP_at_IoU50_np': '07_metrics_np.ipynb', 'mAP_at_IoU60_np': '07_metrics_np.ipynb', 'mAP_at_IoU70_np': '07_metrics_np.ipynb', 'mAP_at_IoU80_np': '07_metrics_np.ipynb', 'mAP_at_IoU90_np': '07_metrics_np.ipynb', 'mAP_at_IoU50_95_np': '07_metrics_np.ipynb'} modules = ['core.py', 'datasets.py', 'dataloaders.py', 'callbacks.py', 'models/fasterrcnn.py', 'models/maskrcnn.py', 'models/efficientdet.py', 'learners.py', 'metrics.py', 'metrics_np.py'] doc_url = 'https://rbrtwlz.github.io/fastai_object_detection/' git_url = 'https://github.com/rbrtwlz/fastai_object_detection/tree/master/' def custom_doc_links(name): return None
DEFAULT_TIMEOUT = 120 def test_upgrade_simple(context, client): _run_upgrade(context, client, 1, 1, finalScale=2, intervalMillis=100) def test_upgrade_odd_numbers(context, client): _run_upgrade(context, client, 5, 2, batchSize=100, finalScale=3, intervalMillis=100) def test_upgrade_to_too_high(context, client): _run_upgrade(context, client, 1, 5, batchSize=2, finalScale=2, intervalMillis=100) def test_upgrade_relink(context, client): service, service2, env = _create_env_and_services(context, client) image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid} source = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config) lb = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config) source = client.wait_success(client.wait_success(source).activate()) assert source.state == "active" lb = client.wait_success(client.wait_success(lb).activate()) assert lb.state == "active" service_link = {"serviceId": service.id, "name": "link1"} source.setservicelinks(serviceLinks=[service_link]) lb.setservicelinks(serviceLinks=[service_link]) source = client.wait_success(source) assert source.state == "active" lb = client.wait_success(lb) assert lb.state == "active" assert len(source.consumedservices()) == 1 assert len(lb.consumedservices()) == 1 assert len(service.consumedbyservices()) == 2 assert len(service2.consumedbyservices()) == 0 strategy = {"finalScale": 1, "toServiceId": service2.id, "updateLinks": True, "intervalMillis": 100} service = service.upgrade_action(toServiceStrategy=strategy) service = client.wait_success(service, timeout=DEFAULT_TIMEOUT) assert service.state == "upgraded" assert len(source.consumedservices()) == 2 assert len(lb.consumedservices()) == 2 assert len(service.consumedbyservices()) == 2 assert len(service2.consumedbyservices()) == 2 links = client.list_service_consume_map(serviceId=lb.id) assert len(links) == 2 def test_in_service_upgrade_primary(context, client, super_client): env, svc, up_svc = _insvc_upgrade(context, client, super_client, True, launchConfig={"labels": {"foo": "bar"}}, startFirst=True) _validate_upgrade(super_client, svc, up_svc, primary="1", secondary1="0", secondary2="0") def test_in_service_upgrade_inactive(context, client, super_client): env, svc, up_svc = _insvc_upgrade(context, client, super_client, True, activate=False, launchConfig={"labels": {"foo": "bar"}}, startFirst=True) _validate_upgrade(super_client, svc, up_svc, primary="1", secondary1="0", secondary2="0") def test_in_service_upgrade_all(context, client, super_client): secondary = [{"name": "secondary1", "labels": {"foo": "bar"}}, {"name": "secondary2", "labels": {"foo": "bar"}}] env, svc, up_svc = _insvc_upgrade(context, client, super_client, True, launchConfig={"labels": {"foo": "bar"}}, secondaryLaunchConfigs=secondary, batchSize=3, intervalMillis=100) _validate_upgrade(super_client, svc, up_svc, primary="1", secondary1="1", secondary2="1") def test_in_service_upgrade_one_secondary(context, client, super_client): secondary = [{"name": "secondary1", "labels": {"foo": "bar"}}] env, svc, upgraded_svc = _insvc_upgrade(context, client, super_client, True, secondaryLaunchConfigs=secondary, batchSize=2, intervalMillis=100) _validate_upgrade(super_client, svc, upgraded_svc, primary="0", secondary1="1", secondary2="0") def test_in_service_upgrade_mix(context, client, super_client): secondary = [{"name": "secondary1", "labels": {"foo": "bar"}}] env, svc, up_svc = _insvc_upgrade(context, client, super_client, True, launchConfig={"labels": {"foo": "bar"}}, secondaryLaunchConfigs=secondary, batchSize=1) _validate_upgrade(super_client, svc, up_svc, primary="1", secondary1="1", secondary2="0") def test_big_scale(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) assert env.state == "active" image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid, "networkMode": None} svc = client.create_service(name=random_str(), environmentId=env.id, scale=10, launchConfig=launch_config, intervalMillis=100) svc = client.wait_success(svc) svc = client.wait_success(svc.activate(), DEFAULT_TIMEOUT) svc = _run_insvc_upgrade(svc, batchSize=1, launchConfig=launch_config) svc = client.wait_success(svc, DEFAULT_TIMEOUT) svc = client.wait_success(svc.finishupgrade()) svc = _run_insvc_upgrade(svc, batchSize=5, launchConfig=launch_config) svc = client.wait_success(svc, DEFAULT_TIMEOUT) client.wait_success(svc.finishupgrade()) def test_rollback_regular_upgrade(context, client, super_client): svc, service2, env = _create_env_and_services(context, client, 4, 4) svc = _run_tosvc_upgrade(svc, service2, toServiceId=service2.id, finalScale=4) time.sleep(1) svc = wait_state(client, svc.cancelupgrade(), "canceled-upgrade") svc = wait_state(client, svc.rollback(), "active") _wait_for_map_count(super_client, svc) def _create_and_schedule_inservice_upgrade(client, context, startFirst=False): env = client.create_environment(name=random_str()) env = client.wait_success(env) assert env.state == "active" image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid, "networkMode": None} svc = client.create_service(name=random_str(), environmentId=env.id, scale=4, launchConfig=launch_config, image=image_uuid) svc = client.wait_success(svc) svc = client.wait_success(svc.activate(), timeout=DEFAULT_TIMEOUT) svc = _run_insvc_upgrade(svc, batchSize=2, launchConfig=launch_config, startFirst=startFirst, intervalMillis=100) def upgrade_not_null(): return _validate_in_svc_upgrade(client, svc) svc = wait_for(upgrade_not_null, DEFAULT_TIMEOUT) return svc def test_rollback_inservice_upgrade(context, client, super_client): svc = _create_and_schedule_inservice_upgrade(client, context) time.sleep(1) svc = _cancel_upgrade(client, svc) _rollback(client, super_client, svc, 1, 0, 0) def test_cancelupgrade_remove(context, client): svc = _create_and_schedule_inservice_upgrade(client, context) svc = _cancel_upgrade(client, svc) svc.remove() def test_cancelupgrade_rollback(context, client): svc = _create_and_schedule_inservice_upgrade(client, context) svc = _cancel_upgrade(client, svc) svc = client.wait_success(svc.rollback()) svc.remove() def test_cancelupgrade_finish(context, client): svc = _create_and_schedule_inservice_upgrade(client, context) svc = _cancel_upgrade(client, svc) svc.continueupgrade() def test_upgrade_finish_cancel_rollback(context, client): svc = _create_and_schedule_inservice_upgrade(client, context) svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.state == "upgraded" svc = svc.finishupgrade() wait_for(lambda: client.reload(svc).state == "finishing-upgrade") svc = _cancel_upgrade(client, svc) assert svc.state == "canceled-upgrade" svc = client.wait_success(svc.rollback()) def test_state_transition_start_first(context, client): svc = _create_and_schedule_inservice_upgrade(client, context, startFirst=False) svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.state == "upgraded" svc = svc.rollback() svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.state == "active" return svc = _create_and_schedule_inservice_upgrade(client, context, startFirst=True) svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.state == "upgraded" svc = svc.rollback() svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.state == "active" svc = _create_and_schedule_inservice_upgrade(client, context, startFirst=False) svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.state == "upgraded" client.wait_success(svc.remove()) def test_in_service_upgrade_networks_from(context, client, super_client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid, "networkMode": "container", "networkLaunchConfig": "secondary1"} secondary1 = {"imageUuid": image_uuid, "name": "secondary1"} secondary2 = {"imageUuid": image_uuid, "name": "secondary2"} svc = client.create_service(name=random_str(), environmentId=env.id, scale=2, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) u_svc = _run_insvc_upgrade(svc, secondaryLaunchConfigs=[secondary1], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == "upgraded" u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) _validate_upgrade(super_client, svc, u_svc, primary="1", secondary1="1", secondary2="0") def test_in_service_upgrade_volumes_from(context, client, super_client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid} secondary1 = {"imageUuid": image_uuid, "name": "secondary1", "dataVolumesFromLaunchConfigs": ["secondary2"]} secondary2 = {"imageUuid": image_uuid, "name": "secondary2"} svc = client.create_service(name=random_str(), environmentId=env.id, scale=2, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) u_svc = _run_insvc_upgrade(svc, launchConfig=launch_config, secondaryLaunchConfigs=[secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == "upgraded" u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) _validate_upgrade(super_client, svc, u_svc, primary="1", secondary1="1", secondary2="1") def _create_stack(client): env = client.create_environment(name=random_str()) env = client.wait_success(env) return env def test_dns_service_upgrade(client): env = _create_stack(client) labels = {"foo": "bar"} launch_config = {"labels": labels} dns = client.create_dnsService(name=random_str(), environmentId=env.id, launchConfig=launch_config) dns = client.wait_success(dns) assert dns.launchConfig is not None assert dns.launchConfig.labels == labels dns = client.wait_success(dns.activate()) labels = {"bar": "foo"} launch_config = {"labels": labels} dns = _run_insvc_upgrade(dns, batchSize=1, launchConfig=launch_config) dns = client.wait_success(dns, DEFAULT_TIMEOUT) assert dns.launchConfig is not None assert dns.launchConfig.labels == labels def test_external_service_upgrade(client): env = _create_stack(client) labels = {"foo": "bar"} launch_config = {"labels": labels} ips = ["72.22.16.5", "192.168.0.10"] svc = client.create_externalService(name=random_str(), environmentId=env.id, externalIpAddresses=ips, launchConfig=launch_config) svc = client.wait_success(svc) assert svc.launchConfig is not None assert svc.launchConfig.labels == labels svc = client.wait_success(svc.activate()) labels = {"bar": "foo"} launch_config = {"labels": labels} svc = _run_insvc_upgrade(svc, batchSize=1, launchConfig=launch_config) svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.launchConfig is not None assert svc.launchConfig.labels == labels def test_service_upgrade_no_image_selector(client): env = _create_stack(client) launch_config = {"imageUuid": "rancher/none"} svc1 = client.create_service(name=random_str(), environmentId=env.id, launchConfig=launch_config, selectorContainer="foo=barbar") svc1 = client.wait_success(svc1) svc1 = client.wait_success(svc1.activate()) strategy = {"intervalMillis": 100, "launchConfig": {}} svc1.upgrade_action(launchConfig=launch_config, inServiceStrategy=strategy) def test_service_upgrade_mixed_selector(client, context): env = _create_stack(client) image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid} svc2 = client.create_service(name=random_str(), environmentId=env.id, launchConfig=launch_config, selectorContainer="foo=barbar") svc2 = client.wait_success(svc2) svc2 = client.wait_success(svc2.activate()) _run_insvc_upgrade(svc2, launchConfig=launch_config) def test_rollback_sidekicks(context, client, super_client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid} secondary1 = {"imageUuid": image_uuid, "name": "secondary1"} secondary2 = {"imageUuid": image_uuid, "name": "secondary2"} svc = client.create_service(name=random_str(), environmentId=env.id, scale=3, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) initial_maps = super_client.list_serviceExposeMap(serviceId=svc.id, state="active", upgrade=False) u_svc = _run_insvc_upgrade(svc, secondaryLaunchConfigs=[secondary1], batchSize=2) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == "upgraded" u_svc = client.wait_success(u_svc.rollback(), DEFAULT_TIMEOUT) assert u_svc.state == "active" final_maps = super_client.list_serviceExposeMap(serviceId=u_svc.id, state="active", upgrade=False) for initial_map in initial_maps: found = False for final_map in final_maps: if final_map.id == initial_map.id: found = True break assert found is True def test_upgrade_env(client): env = client.create_environment(name="env-" + random_str()) env = client.wait_success(env) assert env.state == "active" env = env.upgrade() assert env.state == "upgrading" env = client.wait_success(env) assert env.state == "upgraded" def test_upgrade_rollback_env(client): env = client.create_environment(name="env-" + random_str()) env = client.wait_success(env) assert env.state == "active" assert "upgrade" in env env = env.upgrade() assert env.state == "upgrading" env = client.wait_success(env) assert env.state == "upgraded" assert "rollback" in env env = env.rollback() assert env.state == "rolling-back" env = client.wait_success(env) assert env.state == "active" def _run_insvc_upgrade(svc, **kw): kw["intervalMillis"] = 100 svc = svc.upgrade_action(inServiceStrategy=kw) assert svc.state == "upgrading" return svc def _insvc_upgrade(context, client, super_client, finish_upgrade, activate=True, **kw): env, svc = _create_multi_lc_svc(super_client, client, context, activate) _run_insvc_upgrade(svc, **kw) def upgrade_not_null(): return _validate_in_svc_upgrade(client, svc) u_svc = wait_for(upgrade_not_null) u_svc = client.wait_success(u_svc, timeout=DEFAULT_TIMEOUT) assert u_svc.state == "upgraded" if finish_upgrade: u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) assert u_svc.state == "active" return env, svc, u_svc def _validate_in_svc_upgrade(client, svc): s = client.reload(svc) upgrade = s.upgrade if upgrade is not None: strategy = upgrade.inServiceStrategy c1 = strategy.previousLaunchConfig is not None c2 = strategy.previousSecondaryLaunchConfigs is not None if c1 or c2: return s def _wait_for_instance_start(super_client, id): wait_for(lambda: len(super_client.by_id("container", id)) > 0) return super_client.by_id("container", id) def _wait_for_map_count(super_client, service, launchConfig=None): def get_active_launch_config_instances(): match = [] instance_maps = super_client.list_serviceExposeMap(serviceId=service.id, state="active", upgrade=False) for instance_map in instance_maps: if launchConfig is not None: if instance_map.dnsPrefix == launchConfig: match.append(instance_map) else: if instance_map.dnsPrefix is None: match.append(instance_map) return match def active_len(): match = get_active_launch_config_instances() if len(match) == service.scale: return match wait_for(active_len) return get_active_launch_config_instances() def _validate_upgraded_instances_count(super_client, svc, primary=0, secondary1=0, secondary2=0): if primary == 1: lc = svc.launchConfig _validate_launch_config(super_client, lc, svc) if secondary1 == 1: lc = svc.secondaryLaunchConfigs[0] _validate_launch_config(super_client, lc, svc) if secondary2 == 1: lc = svc.secondaryLaunchConfigs[1] _validate_launch_config(super_client, lc, svc) def _validate_launch_config(super_client, launchConfig, svc): match = _get_upgraded_instances(super_client, launchConfig, svc) if len(match) == svc.scale: return match def _get_upgraded_instances(super_client, launchConfig, svc): c_name = svc.name if hasattr(launchConfig, "name"): c_name = svc.name + "-" + launchConfig.name match = [] instances = super_client.list_container(state="running", accountId=svc.accountId) for instance in instances: if instance.name is not None and c_name in instance.name and instance.version == launchConfig.version: labels = {"foo": "bar"} assert all(item in instance.labels for item in labels) is True match.append(instance) return match def _create_env_and_services(context, client, from_scale=1, to_scale=1): env = client.create_environment(name=random_str()) env = client.wait_success(env) assert env.state == "active" image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid, "networkMode": None} service = client.create_service(name=random_str(), environmentId=env.id, scale=from_scale, launchConfig=launch_config) service = client.wait_success(service) service = client.wait_success(service.activate(), timeout=DEFAULT_TIMEOUT) assert service.state == "active" assert service.upgrade is None service2 = client.create_service(name=random_str(), environmentId=env.id, scale=to_scale, launchConfig=launch_config) service2 = client.wait_success(service2) service2 = client.wait_success(service2.activate(), timeout=DEFAULT_TIMEOUT) assert service2.state == "active" assert service2.upgrade is None return service, service2, env def _run_tosvc_upgrade(service, service2, **kw): kw["toServiceId"] = service2.id service = service.upgrade_action(toServiceStrategy=kw) assert service.state == "upgrading" return service def _run_upgrade(context, client, from_scale, to_scale, **kw): service, service2, env = _create_env_and_services(context, client, from_scale, to_scale) _run_tosvc_upgrade(service, service2, **kw) def upgrade_not_null(): s = client.reload(service) if s.upgrade is not None: return s service = wait_for(upgrade_not_null) service = client.wait_success(service, timeout=DEFAULT_TIMEOUT) assert service.state == "upgraded" assert service.scale == 0 service2 = client.wait_success(service2) assert service2.state == "active" assert service2.scale == kw["finalScale"] service = client.wait_success(service.finishupgrade(), DEFAULT_TIMEOUT) assert service.state == "active" def _create_multi_lc_svc(super_client, client, context, activate=True): env = client.create_environment(name=random_str()) env = client.wait_success(env) assert env.state == "active" image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid, "networkMode": None} secondary_lc1 = {"imageUuid": image_uuid, "name": "secondary1", "dataVolumesFromLaunchConfigs": ["secondary2"]} secondary_lc2 = {"imageUuid": image_uuid, "name": "secondary2"} secondary = [secondary_lc1, secondary_lc2] svc = client.create_service(name=random_str(), environmentId=env.id, scale=2, launchConfig=launch_config, secondaryLaunchConfigs=secondary) svc = client.wait_success(svc) if activate: svc = client.wait_success(svc.activate(), timeout=DEFAULT_TIMEOUT) assert svc.state == "active" c11, c11_sec1, c11_sec2, c12, c12_sec1, c12_sec2 = _get_containers(super_client, svc) assert svc.launchConfig.version is not None assert svc.secondaryLaunchConfigs[0].version is not None assert svc.secondaryLaunchConfigs[1].version is not None assert c11.version == svc.launchConfig.version assert c12.version == svc.launchConfig.version assert c11_sec1.version == svc.secondaryLaunchConfigs[0].version assert c12_sec1.version == svc.secondaryLaunchConfigs[0].version assert c11_sec2.version == svc.secondaryLaunchConfigs[1].version assert c12_sec2.version == svc.secondaryLaunchConfigs[1].version return env, svc def _get_containers(super_client, service): i_maps = _wait_for_map_count(super_client, service) c11 = _wait_for_instance_start(super_client, i_maps[0].instanceId) c12 = _wait_for_instance_start(super_client, i_maps[1].instanceId) i_maps = _wait_for_map_count(super_client, service, "secondary1") c11_sec1 = _wait_for_instance_start(super_client, i_maps[0].instanceId) c12_sec1 = _wait_for_instance_start(super_client, i_maps[1].instanceId) i_maps = _wait_for_map_count(super_client, service, "secondary2") c11_sec2 = _wait_for_instance_start(super_client, i_maps[0].instanceId) c12_sec2 = _wait_for_instance_start(super_client, i_maps[1].instanceId) return c11, c11_sec1, c11_sec2, c12, c12_sec1, c12_sec2 def _validate_upgrade(super_client, svc, upgraded_svc, primary="0", secondary1="0", secondary2="0"): _validate_upgraded_instances_count(super_client, upgraded_svc, primary, secondary1, secondary2) primary_v = svc.launchConfig.version sec1_v = svc.secondaryLaunchConfigs[0].version sec2_v = svc.secondaryLaunchConfigs[1].version primary_upgraded_v = primary_v sec1_upgraded_v = sec1_v sec2_upgraded_v = sec2_v strategy = upgraded_svc.upgrade.inServiceStrategy if primary == "1": primary_upgraded_v = upgraded_svc.launchConfig.version primary_prev_v = strategy.previousLaunchConfig.version assert primary_v != primary_upgraded_v assert primary_prev_v == primary_v if secondary1 == "1": sec1_upgraded_v = upgraded_svc.secondaryLaunchConfigs[0].version sec1_prev_v = strategy.previousSecondaryLaunchConfigs[0].version assert sec1_v != sec1_upgraded_v assert sec1_prev_v == sec1_v if secondary2 == "1": sec2_upgraded_v = upgraded_svc.secondaryLaunchConfigs[1].version sec2_prev_v = strategy.previousSecondaryLaunchConfigs[1].version assert sec2_v != sec2_upgraded_v assert sec2_prev_v == sec2_v c21, c21_sec1, c21_sec2, c22, c22_sec1, c22_sec2 = _get_containers(super_client, upgraded_svc) assert upgraded_svc.launchConfig.version == primary_upgraded_v assert upgraded_svc.secondaryLaunchConfigs[0].version == sec1_upgraded_v assert upgraded_svc.secondaryLaunchConfigs[1].version == sec2_upgraded_v assert c21.version == upgraded_svc.launchConfig.version assert c22.version == upgraded_svc.launchConfig.version assert c21_sec1.version == upgraded_svc.secondaryLaunchConfigs[0].version assert c22_sec1.version == upgraded_svc.secondaryLaunchConfigs[0].version assert c21_sec2.version == upgraded_svc.secondaryLaunchConfigs[1].version assert c22_sec2.version == upgraded_svc.secondaryLaunchConfigs[1].version def _validate_rollback(super_client, svc, rolledback_svc, primary=0, secondary1=0, secondary2=0): _validate_upgraded_instances_count(super_client, svc, primary, secondary1, secondary2) strategy = svc.upgrade.inServiceStrategy if primary == 1: primary_v = rolledback_svc.launchConfig.version primary_prev_v = strategy.previousLaunchConfig.version assert primary_prev_v == primary_v maps = _wait_for_map_count(super_client, rolledback_svc) for map in maps: i = _wait_for_instance_start(super_client, map.instanceId) assert i.version == primary_v if secondary1 == 1: sec1_v = rolledback_svc.secondaryLaunchConfigs[0].version sec1_prev_v = strategy.previousSecondaryLaunchConfigs[0].version assert sec1_prev_v == sec1_v maps = _wait_for_map_count(super_client, rolledback_svc, "secondary1") for map in maps: i = _wait_for_instance_start(super_client, map.instanceId) assert i.version == sec1_v if secondary2 == 1: sec2_v = rolledback_svc.secondaryLaunchConfigs[1].version sec2_prev_v = strategy.previousSecondaryLaunchConfigs[1].version assert sec2_prev_v == sec2_v maps = _wait_for_map_count(super_client, rolledback_svc, "secondary2") for map in maps: i = _wait_for_instance_start(super_client, map.instanceId) assert i.version == sec2_v def _cancel_upgrade(client, svc): svc.cancelupgrade() wait_for(lambda: client.reload(svc).state == "canceled-upgrade") svc = client.reload(svc) strategy = svc.upgrade.inServiceStrategy assert strategy.previousLaunchConfig is not None assert strategy.previousSecondaryLaunchConfigs is not None return svc def _rollback(client, super_client, svc, primary=0, secondary1=0, secondary2=0): rolledback_svc = client.wait_success(svc.rollback(), DEFAULT_TIMEOUT) assert rolledback_svc.state == "active" roll_v = rolledback_svc.launchConfig.version strategy = svc.upgrade.inServiceStrategy assert roll_v == strategy.previousLaunchConfig.version _validate_rollback(super_client, svc, rolledback_svc, primary, secondary1, secondary2) def test_rollback_id(context, client, super_client): env = client.create_environment(name=random_str()) env = client.wait_success(env) assert env.state == "active" image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid, "networkMode": None} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config, image=image_uuid) svc = client.wait_success(svc) svc = client.wait_success(svc.activate(), timeout=DEFAULT_TIMEOUT) maps = _wait_for_map_count(super_client, svc) expose_map = maps[0] c1 = super_client.reload(expose_map.instance()) svc = _run_insvc_upgrade(svc, batchSize=2, launchConfig=launch_config, startFirst=False, intervalMillis=100) svc = client.wait_success(svc) svc = client.wait_success(svc.rollback(), DEFAULT_TIMEOUT) maps = _wait_for_map_count(super_client, svc) expose_map = maps[0] c2 = super_client.reload(expose_map.instance()) assert c1.uuid == c2.uuid def test_in_service_upgrade_port_mapping(context, client, super_client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid, "ports": ["80", "82/tcp"]} secondary1 = {"imageUuid": image_uuid, "name": "secondary1", "ports": ["90"]} secondary2 = {"imageUuid": image_uuid, "name": "secondary2", "ports": ["100"]} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) launch_config = {"imageUuid": image_uuid, "ports": ["80", "82/tcp", "8083:83/udp"]} u_svc = _run_insvc_upgrade(svc, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == "upgraded" u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) svc.launchConfig.ports.append(unicode("8083:83/udp")) assert u_svc.launchConfig.ports == svc.launchConfig.ports assert u_svc.secondaryLaunchConfigs[0].ports == svc.secondaryLaunchConfigs[0].ports assert u_svc.secondaryLaunchConfigs[1].ports == svc.secondaryLaunchConfigs[1].ports def test_sidekick_addition(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid} secondary1 = {"imageUuid": image_uuid, "name": "secondary1"} secondary2 = {"imageUuid": image_uuid, "name": "secondary2"} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) c2_pre = _validate_compose_instance_start(client, svc, env, "1", "secondary1") u_svc = _run_insvc_upgrade(svc, launchConfig=launch_config, secondaryLaunchConfigs=[secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == "upgraded" u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) _wait_until_active_map_count(u_svc, 3, client) c1 = _validate_compose_instance_start(client, svc, env, "1") assert c1.version != "0" c2 = _validate_compose_instance_start(client, svc, env, "1", "secondary1") assert c2.version == "0" assert c2.id == c2_pre.id c3 = _validate_compose_instance_start(client, svc, env, "1", "secondary2") assert c3.version != "0" def test_sidekick_addition_rollback(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid} secondary1 = {"imageUuid": image_uuid, "name": "secondary1"} secondary2 = {"imageUuid": image_uuid, "name": "secondary2"} svc = client.create_service(name=random_str(), environmentId=env.id, scale=2, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) c11_pre = _validate_compose_instance_start(client, svc, env, "1") c12_pre = _validate_compose_instance_start(client, svc, env, "2") c21_pre = _validate_compose_instance_start(client, svc, env, "1", "secondary1") c22_pre = _validate_compose_instance_start(client, svc, env, "2", "secondary1") u_svc = _run_insvc_upgrade(svc, launchConfig=launch_config, secondaryLaunchConfigs=[secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == "upgraded" u_svc = client.wait_success(u_svc.rollback(), DEFAULT_TIMEOUT) _wait_until_active_map_count(u_svc, 4, client) c11 = _validate_compose_instance_start(client, svc, env, "1") assert c11.version == "0" assert c11.id == c11_pre.id c12 = _validate_compose_instance_start(client, svc, env, "2") assert c12.version == "0" assert c12.id == c12_pre.id c21 = _validate_compose_instance_start(client, svc, env, "1", "secondary1") assert c21.version == "0" assert c21.id == c21_pre.id c22 = _validate_compose_instance_start(client, svc, env, "2", "secondary1") assert c22.version == "0" assert c22.id == c22_pre.id def test_sidekick_addition_wo_primary(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid} secondary1 = {"imageUuid": image_uuid, "name": "secondary1"} secondary2 = {"imageUuid": image_uuid, "name": "secondary2"} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) c1_pre = _validate_compose_instance_start(client, svc, env, "1") c2_pre = _validate_compose_instance_start(client, svc, env, "1", "secondary1") u_svc = _run_insvc_upgrade(svc, secondaryLaunchConfigs=[secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == "upgraded" u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) _wait_until_active_map_count(u_svc, 3, client) c1 = _validate_compose_instance_start(client, svc, env, "1") assert c1.version == "0" assert c1.id == c1_pre.id c2 = _validate_compose_instance_start(client, svc, env, "1", "secondary1") assert c2.version == "0" assert c2.id == c2_pre.id c3 = _validate_compose_instance_start(client, svc, env, "1", "secondary2") assert c3.version != "0" def test_sidekick_addition_two_sidekicks(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid} secondary1 = {"imageUuid": image_uuid, "name": "secondary1"} secondary2 = {"imageUuid": image_uuid, "name": "secondary2"} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) c1_pre = _validate_compose_instance_start(client, svc, env, "1") u_svc = _run_insvc_upgrade(svc, secondaryLaunchConfigs=[secondary1, secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == "upgraded" u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) _wait_until_active_map_count(u_svc, 3, client) c1 = _validate_compose_instance_start(client, svc, env, "1") assert c1.version == "0" assert c1.id == c1_pre.id c2 = _validate_compose_instance_start(client, svc, env, "1", "secondary1") assert c2.version != "0" c3 = _validate_compose_instance_start(client, svc, env, "1", "secondary2") assert c3.version != "0" def test_sidekick_removal(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid} secondary1 = {"imageUuid": image_uuid, "name": "secondary1"} secondary2 = {"imageUuid": image_uuid, "name": "secondary2"} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) c1_pre = _validate_compose_instance_start(client, svc, env, "1") secondary2 = {"imageUuid": image_uuid, "name": "secondary2", "imageUuid": "rancher/none"} u_svc = _run_insvc_upgrade(svc, secondaryLaunchConfigs=[secondary1, secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == "upgraded" u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) _wait_until_active_map_count(u_svc, 2, client) c1 = _validate_compose_instance_start(client, svc, env, "1") assert c1.version == "0" assert c1.id == c1_pre.id c2 = _validate_compose_instance_start(client, svc, env, "1", "secondary1") assert c2.version != "0" def test_sidekick_removal_rollback(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {"imageUuid": image_uuid} secondary1 = {"imageUuid": image_uuid, "name": "secondary1"} secondary2 = {"imageUuid": image_uuid, "name": "secondary2"} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) c1_pre = _validate_compose_instance_start(client, svc, env, "1") c2_pre = _validate_compose_instance_start(client, svc, env, "1", "secondary1") c3_pre = _validate_compose_instance_start(client, svc, env, "1", "secondary2") secondary2 = {"imageUuid": image_uuid, "name": "secondary2", "imageUuid": "rancher/none"} u_svc = _run_insvc_upgrade(svc, secondaryLaunchConfigs=[secondary1, secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == "upgraded" u_svc = client.wait_success(u_svc.rollback(), DEFAULT_TIMEOUT) _wait_until_active_map_count(u_svc, 3, client) c1 = _validate_compose_instance_start(client, svc, env, "1") assert c1.version == "0" assert c1.id == c1_pre.id c2 = _validate_compose_instance_start(client, svc, env, "1", "secondary1") assert c2.version == "0" assert c2.id == c2_pre.id c3 = _validate_compose_instance_start(client, svc, env, "1", "secondary2") assert c3.version == "0" assert c3.id == c3_pre.id def _wait_until_active_map_count(service, count, client): def wait_for_map_count(service): m = client.list_serviceExposeMap(serviceId=service.id, state="active") return len(m) == count wait_for(lambda: wait_for_condition(client, service, wait_for_map_count)) return client.list_serviceExposeMap(serviceId=service.id, state="active") def _validate_compose_instance_start(client, service, env, number, launch_config_name=None): cn = launch_config_name + "-" if launch_config_name is not None else "" name = env.name + "-" + service.name + "-" + cn + number def wait_for_map_count(service): instances = client.list_container(name=name, state="running") return len(instances) == 1 wait_for(lambda: wait_for_condition(client, service, wait_for_map_count)) instances = client.list_container(name=name, state="running") return instances[0] def test_upgrade_global_service(new_context): client = new_context.client host1 = new_context.host host2 = register_simulated_host(new_context) host3 = register_simulated_host(new_context) client.wait_success(host1) client.wait_success(host2) client.wait_success(host3) env = _create_stack(client) image_uuid = new_context.image_uuid launch_config = {"imageUuid": image_uuid, "labels": {"io.rancher.scheduler.global": "true"}} service = client.create_service(name=random_str(), environmentId=env.id, launchConfig=launch_config) service = client.wait_success(service) assert service.state == "inactive" service = client.wait_success(service.activate(), 120) assert service.state == "active" c = client.list_serviceExposeMap(serviceId=service.id, state="active") strategy = {"launchConfig": launch_config, "intervalMillis": 100} service.upgrade_action(inServiceStrategy=strategy) wait_for(lambda: client.reload(service).state == "upgraded") service = client.reload(service) service = client.wait_success(service.rollback()) _wait_until_active_map_count(service, len(c), client)
default_timeout = 120 def test_upgrade_simple(context, client): _run_upgrade(context, client, 1, 1, finalScale=2, intervalMillis=100) def test_upgrade_odd_numbers(context, client): _run_upgrade(context, client, 5, 2, batchSize=100, finalScale=3, intervalMillis=100) def test_upgrade_to_too_high(context, client): _run_upgrade(context, client, 1, 5, batchSize=2, finalScale=2, intervalMillis=100) def test_upgrade_relink(context, client): (service, service2, env) = _create_env_and_services(context, client) image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid} source = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config) lb = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config) source = client.wait_success(client.wait_success(source).activate()) assert source.state == 'active' lb = client.wait_success(client.wait_success(lb).activate()) assert lb.state == 'active' service_link = {'serviceId': service.id, 'name': 'link1'} source.setservicelinks(serviceLinks=[service_link]) lb.setservicelinks(serviceLinks=[service_link]) source = client.wait_success(source) assert source.state == 'active' lb = client.wait_success(lb) assert lb.state == 'active' assert len(source.consumedservices()) == 1 assert len(lb.consumedservices()) == 1 assert len(service.consumedbyservices()) == 2 assert len(service2.consumedbyservices()) == 0 strategy = {'finalScale': 1, 'toServiceId': service2.id, 'updateLinks': True, 'intervalMillis': 100} service = service.upgrade_action(toServiceStrategy=strategy) service = client.wait_success(service, timeout=DEFAULT_TIMEOUT) assert service.state == 'upgraded' assert len(source.consumedservices()) == 2 assert len(lb.consumedservices()) == 2 assert len(service.consumedbyservices()) == 2 assert len(service2.consumedbyservices()) == 2 links = client.list_service_consume_map(serviceId=lb.id) assert len(links) == 2 def test_in_service_upgrade_primary(context, client, super_client): (env, svc, up_svc) = _insvc_upgrade(context, client, super_client, True, launchConfig={'labels': {'foo': 'bar'}}, startFirst=True) _validate_upgrade(super_client, svc, up_svc, primary='1', secondary1='0', secondary2='0') def test_in_service_upgrade_inactive(context, client, super_client): (env, svc, up_svc) = _insvc_upgrade(context, client, super_client, True, activate=False, launchConfig={'labels': {'foo': 'bar'}}, startFirst=True) _validate_upgrade(super_client, svc, up_svc, primary='1', secondary1='0', secondary2='0') def test_in_service_upgrade_all(context, client, super_client): secondary = [{'name': 'secondary1', 'labels': {'foo': 'bar'}}, {'name': 'secondary2', 'labels': {'foo': 'bar'}}] (env, svc, up_svc) = _insvc_upgrade(context, client, super_client, True, launchConfig={'labels': {'foo': 'bar'}}, secondaryLaunchConfigs=secondary, batchSize=3, intervalMillis=100) _validate_upgrade(super_client, svc, up_svc, primary='1', secondary1='1', secondary2='1') def test_in_service_upgrade_one_secondary(context, client, super_client): secondary = [{'name': 'secondary1', 'labels': {'foo': 'bar'}}] (env, svc, upgraded_svc) = _insvc_upgrade(context, client, super_client, True, secondaryLaunchConfigs=secondary, batchSize=2, intervalMillis=100) _validate_upgrade(super_client, svc, upgraded_svc, primary='0', secondary1='1', secondary2='0') def test_in_service_upgrade_mix(context, client, super_client): secondary = [{'name': 'secondary1', 'labels': {'foo': 'bar'}}] (env, svc, up_svc) = _insvc_upgrade(context, client, super_client, True, launchConfig={'labels': {'foo': 'bar'}}, secondaryLaunchConfigs=secondary, batchSize=1) _validate_upgrade(super_client, svc, up_svc, primary='1', secondary1='1', secondary2='0') def test_big_scale(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) assert env.state == 'active' image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid, 'networkMode': None} svc = client.create_service(name=random_str(), environmentId=env.id, scale=10, launchConfig=launch_config, intervalMillis=100) svc = client.wait_success(svc) svc = client.wait_success(svc.activate(), DEFAULT_TIMEOUT) svc = _run_insvc_upgrade(svc, batchSize=1, launchConfig=launch_config) svc = client.wait_success(svc, DEFAULT_TIMEOUT) svc = client.wait_success(svc.finishupgrade()) svc = _run_insvc_upgrade(svc, batchSize=5, launchConfig=launch_config) svc = client.wait_success(svc, DEFAULT_TIMEOUT) client.wait_success(svc.finishupgrade()) def test_rollback_regular_upgrade(context, client, super_client): (svc, service2, env) = _create_env_and_services(context, client, 4, 4) svc = _run_tosvc_upgrade(svc, service2, toServiceId=service2.id, finalScale=4) time.sleep(1) svc = wait_state(client, svc.cancelupgrade(), 'canceled-upgrade') svc = wait_state(client, svc.rollback(), 'active') _wait_for_map_count(super_client, svc) def _create_and_schedule_inservice_upgrade(client, context, startFirst=False): env = client.create_environment(name=random_str()) env = client.wait_success(env) assert env.state == 'active' image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid, 'networkMode': None} svc = client.create_service(name=random_str(), environmentId=env.id, scale=4, launchConfig=launch_config, image=image_uuid) svc = client.wait_success(svc) svc = client.wait_success(svc.activate(), timeout=DEFAULT_TIMEOUT) svc = _run_insvc_upgrade(svc, batchSize=2, launchConfig=launch_config, startFirst=startFirst, intervalMillis=100) def upgrade_not_null(): return _validate_in_svc_upgrade(client, svc) svc = wait_for(upgrade_not_null, DEFAULT_TIMEOUT) return svc def test_rollback_inservice_upgrade(context, client, super_client): svc = _create_and_schedule_inservice_upgrade(client, context) time.sleep(1) svc = _cancel_upgrade(client, svc) _rollback(client, super_client, svc, 1, 0, 0) def test_cancelupgrade_remove(context, client): svc = _create_and_schedule_inservice_upgrade(client, context) svc = _cancel_upgrade(client, svc) svc.remove() def test_cancelupgrade_rollback(context, client): svc = _create_and_schedule_inservice_upgrade(client, context) svc = _cancel_upgrade(client, svc) svc = client.wait_success(svc.rollback()) svc.remove() def test_cancelupgrade_finish(context, client): svc = _create_and_schedule_inservice_upgrade(client, context) svc = _cancel_upgrade(client, svc) svc.continueupgrade() def test_upgrade_finish_cancel_rollback(context, client): svc = _create_and_schedule_inservice_upgrade(client, context) svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.state == 'upgraded' svc = svc.finishupgrade() wait_for(lambda : client.reload(svc).state == 'finishing-upgrade') svc = _cancel_upgrade(client, svc) assert svc.state == 'canceled-upgrade' svc = client.wait_success(svc.rollback()) def test_state_transition_start_first(context, client): svc = _create_and_schedule_inservice_upgrade(client, context, startFirst=False) svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.state == 'upgraded' svc = svc.rollback() svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.state == 'active' return svc = _create_and_schedule_inservice_upgrade(client, context, startFirst=True) svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.state == 'upgraded' svc = svc.rollback() svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.state == 'active' svc = _create_and_schedule_inservice_upgrade(client, context, startFirst=False) svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.state == 'upgraded' client.wait_success(svc.remove()) def test_in_service_upgrade_networks_from(context, client, super_client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid, 'networkMode': 'container', 'networkLaunchConfig': 'secondary1'} secondary1 = {'imageUuid': image_uuid, 'name': 'secondary1'} secondary2 = {'imageUuid': image_uuid, 'name': 'secondary2'} svc = client.create_service(name=random_str(), environmentId=env.id, scale=2, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) u_svc = _run_insvc_upgrade(svc, secondaryLaunchConfigs=[secondary1], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == 'upgraded' u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) _validate_upgrade(super_client, svc, u_svc, primary='1', secondary1='1', secondary2='0') def test_in_service_upgrade_volumes_from(context, client, super_client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid} secondary1 = {'imageUuid': image_uuid, 'name': 'secondary1', 'dataVolumesFromLaunchConfigs': ['secondary2']} secondary2 = {'imageUuid': image_uuid, 'name': 'secondary2'} svc = client.create_service(name=random_str(), environmentId=env.id, scale=2, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) u_svc = _run_insvc_upgrade(svc, launchConfig=launch_config, secondaryLaunchConfigs=[secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == 'upgraded' u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) _validate_upgrade(super_client, svc, u_svc, primary='1', secondary1='1', secondary2='1') def _create_stack(client): env = client.create_environment(name=random_str()) env = client.wait_success(env) return env def test_dns_service_upgrade(client): env = _create_stack(client) labels = {'foo': 'bar'} launch_config = {'labels': labels} dns = client.create_dnsService(name=random_str(), environmentId=env.id, launchConfig=launch_config) dns = client.wait_success(dns) assert dns.launchConfig is not None assert dns.launchConfig.labels == labels dns = client.wait_success(dns.activate()) labels = {'bar': 'foo'} launch_config = {'labels': labels} dns = _run_insvc_upgrade(dns, batchSize=1, launchConfig=launch_config) dns = client.wait_success(dns, DEFAULT_TIMEOUT) assert dns.launchConfig is not None assert dns.launchConfig.labels == labels def test_external_service_upgrade(client): env = _create_stack(client) labels = {'foo': 'bar'} launch_config = {'labels': labels} ips = ['72.22.16.5', '192.168.0.10'] svc = client.create_externalService(name=random_str(), environmentId=env.id, externalIpAddresses=ips, launchConfig=launch_config) svc = client.wait_success(svc) assert svc.launchConfig is not None assert svc.launchConfig.labels == labels svc = client.wait_success(svc.activate()) labels = {'bar': 'foo'} launch_config = {'labels': labels} svc = _run_insvc_upgrade(svc, batchSize=1, launchConfig=launch_config) svc = client.wait_success(svc, DEFAULT_TIMEOUT) assert svc.launchConfig is not None assert svc.launchConfig.labels == labels def test_service_upgrade_no_image_selector(client): env = _create_stack(client) launch_config = {'imageUuid': 'rancher/none'} svc1 = client.create_service(name=random_str(), environmentId=env.id, launchConfig=launch_config, selectorContainer='foo=barbar') svc1 = client.wait_success(svc1) svc1 = client.wait_success(svc1.activate()) strategy = {'intervalMillis': 100, 'launchConfig': {}} svc1.upgrade_action(launchConfig=launch_config, inServiceStrategy=strategy) def test_service_upgrade_mixed_selector(client, context): env = _create_stack(client) image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid} svc2 = client.create_service(name=random_str(), environmentId=env.id, launchConfig=launch_config, selectorContainer='foo=barbar') svc2 = client.wait_success(svc2) svc2 = client.wait_success(svc2.activate()) _run_insvc_upgrade(svc2, launchConfig=launch_config) def test_rollback_sidekicks(context, client, super_client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid} secondary1 = {'imageUuid': image_uuid, 'name': 'secondary1'} secondary2 = {'imageUuid': image_uuid, 'name': 'secondary2'} svc = client.create_service(name=random_str(), environmentId=env.id, scale=3, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) initial_maps = super_client.list_serviceExposeMap(serviceId=svc.id, state='active', upgrade=False) u_svc = _run_insvc_upgrade(svc, secondaryLaunchConfigs=[secondary1], batchSize=2) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == 'upgraded' u_svc = client.wait_success(u_svc.rollback(), DEFAULT_TIMEOUT) assert u_svc.state == 'active' final_maps = super_client.list_serviceExposeMap(serviceId=u_svc.id, state='active', upgrade=False) for initial_map in initial_maps: found = False for final_map in final_maps: if final_map.id == initial_map.id: found = True break assert found is True def test_upgrade_env(client): env = client.create_environment(name='env-' + random_str()) env = client.wait_success(env) assert env.state == 'active' env = env.upgrade() assert env.state == 'upgrading' env = client.wait_success(env) assert env.state == 'upgraded' def test_upgrade_rollback_env(client): env = client.create_environment(name='env-' + random_str()) env = client.wait_success(env) assert env.state == 'active' assert 'upgrade' in env env = env.upgrade() assert env.state == 'upgrading' env = client.wait_success(env) assert env.state == 'upgraded' assert 'rollback' in env env = env.rollback() assert env.state == 'rolling-back' env = client.wait_success(env) assert env.state == 'active' def _run_insvc_upgrade(svc, **kw): kw['intervalMillis'] = 100 svc = svc.upgrade_action(inServiceStrategy=kw) assert svc.state == 'upgrading' return svc def _insvc_upgrade(context, client, super_client, finish_upgrade, activate=True, **kw): (env, svc) = _create_multi_lc_svc(super_client, client, context, activate) _run_insvc_upgrade(svc, **kw) def upgrade_not_null(): return _validate_in_svc_upgrade(client, svc) u_svc = wait_for(upgrade_not_null) u_svc = client.wait_success(u_svc, timeout=DEFAULT_TIMEOUT) assert u_svc.state == 'upgraded' if finish_upgrade: u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) assert u_svc.state == 'active' return (env, svc, u_svc) def _validate_in_svc_upgrade(client, svc): s = client.reload(svc) upgrade = s.upgrade if upgrade is not None: strategy = upgrade.inServiceStrategy c1 = strategy.previousLaunchConfig is not None c2 = strategy.previousSecondaryLaunchConfigs is not None if c1 or c2: return s def _wait_for_instance_start(super_client, id): wait_for(lambda : len(super_client.by_id('container', id)) > 0) return super_client.by_id('container', id) def _wait_for_map_count(super_client, service, launchConfig=None): def get_active_launch_config_instances(): match = [] instance_maps = super_client.list_serviceExposeMap(serviceId=service.id, state='active', upgrade=False) for instance_map in instance_maps: if launchConfig is not None: if instance_map.dnsPrefix == launchConfig: match.append(instance_map) elif instance_map.dnsPrefix is None: match.append(instance_map) return match def active_len(): match = get_active_launch_config_instances() if len(match) == service.scale: return match wait_for(active_len) return get_active_launch_config_instances() def _validate_upgraded_instances_count(super_client, svc, primary=0, secondary1=0, secondary2=0): if primary == 1: lc = svc.launchConfig _validate_launch_config(super_client, lc, svc) if secondary1 == 1: lc = svc.secondaryLaunchConfigs[0] _validate_launch_config(super_client, lc, svc) if secondary2 == 1: lc = svc.secondaryLaunchConfigs[1] _validate_launch_config(super_client, lc, svc) def _validate_launch_config(super_client, launchConfig, svc): match = _get_upgraded_instances(super_client, launchConfig, svc) if len(match) == svc.scale: return match def _get_upgraded_instances(super_client, launchConfig, svc): c_name = svc.name if hasattr(launchConfig, 'name'): c_name = svc.name + '-' + launchConfig.name match = [] instances = super_client.list_container(state='running', accountId=svc.accountId) for instance in instances: if instance.name is not None and c_name in instance.name and (instance.version == launchConfig.version): labels = {'foo': 'bar'} assert all((item in instance.labels for item in labels)) is True match.append(instance) return match def _create_env_and_services(context, client, from_scale=1, to_scale=1): env = client.create_environment(name=random_str()) env = client.wait_success(env) assert env.state == 'active' image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid, 'networkMode': None} service = client.create_service(name=random_str(), environmentId=env.id, scale=from_scale, launchConfig=launch_config) service = client.wait_success(service) service = client.wait_success(service.activate(), timeout=DEFAULT_TIMEOUT) assert service.state == 'active' assert service.upgrade is None service2 = client.create_service(name=random_str(), environmentId=env.id, scale=to_scale, launchConfig=launch_config) service2 = client.wait_success(service2) service2 = client.wait_success(service2.activate(), timeout=DEFAULT_TIMEOUT) assert service2.state == 'active' assert service2.upgrade is None return (service, service2, env) def _run_tosvc_upgrade(service, service2, **kw): kw['toServiceId'] = service2.id service = service.upgrade_action(toServiceStrategy=kw) assert service.state == 'upgrading' return service def _run_upgrade(context, client, from_scale, to_scale, **kw): (service, service2, env) = _create_env_and_services(context, client, from_scale, to_scale) _run_tosvc_upgrade(service, service2, **kw) def upgrade_not_null(): s = client.reload(service) if s.upgrade is not None: return s service = wait_for(upgrade_not_null) service = client.wait_success(service, timeout=DEFAULT_TIMEOUT) assert service.state == 'upgraded' assert service.scale == 0 service2 = client.wait_success(service2) assert service2.state == 'active' assert service2.scale == kw['finalScale'] service = client.wait_success(service.finishupgrade(), DEFAULT_TIMEOUT) assert service.state == 'active' def _create_multi_lc_svc(super_client, client, context, activate=True): env = client.create_environment(name=random_str()) env = client.wait_success(env) assert env.state == 'active' image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid, 'networkMode': None} secondary_lc1 = {'imageUuid': image_uuid, 'name': 'secondary1', 'dataVolumesFromLaunchConfigs': ['secondary2']} secondary_lc2 = {'imageUuid': image_uuid, 'name': 'secondary2'} secondary = [secondary_lc1, secondary_lc2] svc = client.create_service(name=random_str(), environmentId=env.id, scale=2, launchConfig=launch_config, secondaryLaunchConfigs=secondary) svc = client.wait_success(svc) if activate: svc = client.wait_success(svc.activate(), timeout=DEFAULT_TIMEOUT) assert svc.state == 'active' (c11, c11_sec1, c11_sec2, c12, c12_sec1, c12_sec2) = _get_containers(super_client, svc) assert svc.launchConfig.version is not None assert svc.secondaryLaunchConfigs[0].version is not None assert svc.secondaryLaunchConfigs[1].version is not None assert c11.version == svc.launchConfig.version assert c12.version == svc.launchConfig.version assert c11_sec1.version == svc.secondaryLaunchConfigs[0].version assert c12_sec1.version == svc.secondaryLaunchConfigs[0].version assert c11_sec2.version == svc.secondaryLaunchConfigs[1].version assert c12_sec2.version == svc.secondaryLaunchConfigs[1].version return (env, svc) def _get_containers(super_client, service): i_maps = _wait_for_map_count(super_client, service) c11 = _wait_for_instance_start(super_client, i_maps[0].instanceId) c12 = _wait_for_instance_start(super_client, i_maps[1].instanceId) i_maps = _wait_for_map_count(super_client, service, 'secondary1') c11_sec1 = _wait_for_instance_start(super_client, i_maps[0].instanceId) c12_sec1 = _wait_for_instance_start(super_client, i_maps[1].instanceId) i_maps = _wait_for_map_count(super_client, service, 'secondary2') c11_sec2 = _wait_for_instance_start(super_client, i_maps[0].instanceId) c12_sec2 = _wait_for_instance_start(super_client, i_maps[1].instanceId) return (c11, c11_sec1, c11_sec2, c12, c12_sec1, c12_sec2) def _validate_upgrade(super_client, svc, upgraded_svc, primary='0', secondary1='0', secondary2='0'): _validate_upgraded_instances_count(super_client, upgraded_svc, primary, secondary1, secondary2) primary_v = svc.launchConfig.version sec1_v = svc.secondaryLaunchConfigs[0].version sec2_v = svc.secondaryLaunchConfigs[1].version primary_upgraded_v = primary_v sec1_upgraded_v = sec1_v sec2_upgraded_v = sec2_v strategy = upgraded_svc.upgrade.inServiceStrategy if primary == '1': primary_upgraded_v = upgraded_svc.launchConfig.version primary_prev_v = strategy.previousLaunchConfig.version assert primary_v != primary_upgraded_v assert primary_prev_v == primary_v if secondary1 == '1': sec1_upgraded_v = upgraded_svc.secondaryLaunchConfigs[0].version sec1_prev_v = strategy.previousSecondaryLaunchConfigs[0].version assert sec1_v != sec1_upgraded_v assert sec1_prev_v == sec1_v if secondary2 == '1': sec2_upgraded_v = upgraded_svc.secondaryLaunchConfigs[1].version sec2_prev_v = strategy.previousSecondaryLaunchConfigs[1].version assert sec2_v != sec2_upgraded_v assert sec2_prev_v == sec2_v (c21, c21_sec1, c21_sec2, c22, c22_sec1, c22_sec2) = _get_containers(super_client, upgraded_svc) assert upgraded_svc.launchConfig.version == primary_upgraded_v assert upgraded_svc.secondaryLaunchConfigs[0].version == sec1_upgraded_v assert upgraded_svc.secondaryLaunchConfigs[1].version == sec2_upgraded_v assert c21.version == upgraded_svc.launchConfig.version assert c22.version == upgraded_svc.launchConfig.version assert c21_sec1.version == upgraded_svc.secondaryLaunchConfigs[0].version assert c22_sec1.version == upgraded_svc.secondaryLaunchConfigs[0].version assert c21_sec2.version == upgraded_svc.secondaryLaunchConfigs[1].version assert c22_sec2.version == upgraded_svc.secondaryLaunchConfigs[1].version def _validate_rollback(super_client, svc, rolledback_svc, primary=0, secondary1=0, secondary2=0): _validate_upgraded_instances_count(super_client, svc, primary, secondary1, secondary2) strategy = svc.upgrade.inServiceStrategy if primary == 1: primary_v = rolledback_svc.launchConfig.version primary_prev_v = strategy.previousLaunchConfig.version assert primary_prev_v == primary_v maps = _wait_for_map_count(super_client, rolledback_svc) for map in maps: i = _wait_for_instance_start(super_client, map.instanceId) assert i.version == primary_v if secondary1 == 1: sec1_v = rolledback_svc.secondaryLaunchConfigs[0].version sec1_prev_v = strategy.previousSecondaryLaunchConfigs[0].version assert sec1_prev_v == sec1_v maps = _wait_for_map_count(super_client, rolledback_svc, 'secondary1') for map in maps: i = _wait_for_instance_start(super_client, map.instanceId) assert i.version == sec1_v if secondary2 == 1: sec2_v = rolledback_svc.secondaryLaunchConfigs[1].version sec2_prev_v = strategy.previousSecondaryLaunchConfigs[1].version assert sec2_prev_v == sec2_v maps = _wait_for_map_count(super_client, rolledback_svc, 'secondary2') for map in maps: i = _wait_for_instance_start(super_client, map.instanceId) assert i.version == sec2_v def _cancel_upgrade(client, svc): svc.cancelupgrade() wait_for(lambda : client.reload(svc).state == 'canceled-upgrade') svc = client.reload(svc) strategy = svc.upgrade.inServiceStrategy assert strategy.previousLaunchConfig is not None assert strategy.previousSecondaryLaunchConfigs is not None return svc def _rollback(client, super_client, svc, primary=0, secondary1=0, secondary2=0): rolledback_svc = client.wait_success(svc.rollback(), DEFAULT_TIMEOUT) assert rolledback_svc.state == 'active' roll_v = rolledback_svc.launchConfig.version strategy = svc.upgrade.inServiceStrategy assert roll_v == strategy.previousLaunchConfig.version _validate_rollback(super_client, svc, rolledback_svc, primary, secondary1, secondary2) def test_rollback_id(context, client, super_client): env = client.create_environment(name=random_str()) env = client.wait_success(env) assert env.state == 'active' image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid, 'networkMode': None} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config, image=image_uuid) svc = client.wait_success(svc) svc = client.wait_success(svc.activate(), timeout=DEFAULT_TIMEOUT) maps = _wait_for_map_count(super_client, svc) expose_map = maps[0] c1 = super_client.reload(expose_map.instance()) svc = _run_insvc_upgrade(svc, batchSize=2, launchConfig=launch_config, startFirst=False, intervalMillis=100) svc = client.wait_success(svc) svc = client.wait_success(svc.rollback(), DEFAULT_TIMEOUT) maps = _wait_for_map_count(super_client, svc) expose_map = maps[0] c2 = super_client.reload(expose_map.instance()) assert c1.uuid == c2.uuid def test_in_service_upgrade_port_mapping(context, client, super_client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid, 'ports': ['80', '82/tcp']} secondary1 = {'imageUuid': image_uuid, 'name': 'secondary1', 'ports': ['90']} secondary2 = {'imageUuid': image_uuid, 'name': 'secondary2', 'ports': ['100']} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) launch_config = {'imageUuid': image_uuid, 'ports': ['80', '82/tcp', '8083:83/udp']} u_svc = _run_insvc_upgrade(svc, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == 'upgraded' u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) svc.launchConfig.ports.append(unicode('8083:83/udp')) assert u_svc.launchConfig.ports == svc.launchConfig.ports assert u_svc.secondaryLaunchConfigs[0].ports == svc.secondaryLaunchConfigs[0].ports assert u_svc.secondaryLaunchConfigs[1].ports == svc.secondaryLaunchConfigs[1].ports def test_sidekick_addition(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid} secondary1 = {'imageUuid': image_uuid, 'name': 'secondary1'} secondary2 = {'imageUuid': image_uuid, 'name': 'secondary2'} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) c2_pre = _validate_compose_instance_start(client, svc, env, '1', 'secondary1') u_svc = _run_insvc_upgrade(svc, launchConfig=launch_config, secondaryLaunchConfigs=[secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == 'upgraded' u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) _wait_until_active_map_count(u_svc, 3, client) c1 = _validate_compose_instance_start(client, svc, env, '1') assert c1.version != '0' c2 = _validate_compose_instance_start(client, svc, env, '1', 'secondary1') assert c2.version == '0' assert c2.id == c2_pre.id c3 = _validate_compose_instance_start(client, svc, env, '1', 'secondary2') assert c3.version != '0' def test_sidekick_addition_rollback(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid} secondary1 = {'imageUuid': image_uuid, 'name': 'secondary1'} secondary2 = {'imageUuid': image_uuid, 'name': 'secondary2'} svc = client.create_service(name=random_str(), environmentId=env.id, scale=2, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) c11_pre = _validate_compose_instance_start(client, svc, env, '1') c12_pre = _validate_compose_instance_start(client, svc, env, '2') c21_pre = _validate_compose_instance_start(client, svc, env, '1', 'secondary1') c22_pre = _validate_compose_instance_start(client, svc, env, '2', 'secondary1') u_svc = _run_insvc_upgrade(svc, launchConfig=launch_config, secondaryLaunchConfigs=[secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == 'upgraded' u_svc = client.wait_success(u_svc.rollback(), DEFAULT_TIMEOUT) _wait_until_active_map_count(u_svc, 4, client) c11 = _validate_compose_instance_start(client, svc, env, '1') assert c11.version == '0' assert c11.id == c11_pre.id c12 = _validate_compose_instance_start(client, svc, env, '2') assert c12.version == '0' assert c12.id == c12_pre.id c21 = _validate_compose_instance_start(client, svc, env, '1', 'secondary1') assert c21.version == '0' assert c21.id == c21_pre.id c22 = _validate_compose_instance_start(client, svc, env, '2', 'secondary1') assert c22.version == '0' assert c22.id == c22_pre.id def test_sidekick_addition_wo_primary(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid} secondary1 = {'imageUuid': image_uuid, 'name': 'secondary1'} secondary2 = {'imageUuid': image_uuid, 'name': 'secondary2'} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) c1_pre = _validate_compose_instance_start(client, svc, env, '1') c2_pre = _validate_compose_instance_start(client, svc, env, '1', 'secondary1') u_svc = _run_insvc_upgrade(svc, secondaryLaunchConfigs=[secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == 'upgraded' u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) _wait_until_active_map_count(u_svc, 3, client) c1 = _validate_compose_instance_start(client, svc, env, '1') assert c1.version == '0' assert c1.id == c1_pre.id c2 = _validate_compose_instance_start(client, svc, env, '1', 'secondary1') assert c2.version == '0' assert c2.id == c2_pre.id c3 = _validate_compose_instance_start(client, svc, env, '1', 'secondary2') assert c3.version != '0' def test_sidekick_addition_two_sidekicks(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid} secondary1 = {'imageUuid': image_uuid, 'name': 'secondary1'} secondary2 = {'imageUuid': image_uuid, 'name': 'secondary2'} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) c1_pre = _validate_compose_instance_start(client, svc, env, '1') u_svc = _run_insvc_upgrade(svc, secondaryLaunchConfigs=[secondary1, secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == 'upgraded' u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) _wait_until_active_map_count(u_svc, 3, client) c1 = _validate_compose_instance_start(client, svc, env, '1') assert c1.version == '0' assert c1.id == c1_pre.id c2 = _validate_compose_instance_start(client, svc, env, '1', 'secondary1') assert c2.version != '0' c3 = _validate_compose_instance_start(client, svc, env, '1', 'secondary2') assert c3.version != '0' def test_sidekick_removal(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid} secondary1 = {'imageUuid': image_uuid, 'name': 'secondary1'} secondary2 = {'imageUuid': image_uuid, 'name': 'secondary2'} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) c1_pre = _validate_compose_instance_start(client, svc, env, '1') secondary2 = {'imageUuid': image_uuid, 'name': 'secondary2', 'imageUuid': 'rancher/none'} u_svc = _run_insvc_upgrade(svc, secondaryLaunchConfigs=[secondary1, secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == 'upgraded' u_svc = client.wait_success(u_svc.finishupgrade(), DEFAULT_TIMEOUT) _wait_until_active_map_count(u_svc, 2, client) c1 = _validate_compose_instance_start(client, svc, env, '1') assert c1.version == '0' assert c1.id == c1_pre.id c2 = _validate_compose_instance_start(client, svc, env, '1', 'secondary1') assert c2.version != '0' def test_sidekick_removal_rollback(context, client): env = client.create_environment(name=random_str()) env = client.wait_success(env) image_uuid = context.image_uuid launch_config = {'imageUuid': image_uuid} secondary1 = {'imageUuid': image_uuid, 'name': 'secondary1'} secondary2 = {'imageUuid': image_uuid, 'name': 'secondary2'} svc = client.create_service(name=random_str(), environmentId=env.id, scale=1, launchConfig=launch_config, secondaryLaunchConfigs=[secondary1, secondary2]) svc = client.wait_success(svc) svc = client.wait_success(svc.activate()) c1_pre = _validate_compose_instance_start(client, svc, env, '1') c2_pre = _validate_compose_instance_start(client, svc, env, '1', 'secondary1') c3_pre = _validate_compose_instance_start(client, svc, env, '1', 'secondary2') secondary2 = {'imageUuid': image_uuid, 'name': 'secondary2', 'imageUuid': 'rancher/none'} u_svc = _run_insvc_upgrade(svc, secondaryLaunchConfigs=[secondary1, secondary2], batchSize=1) u_svc = client.wait_success(u_svc, DEFAULT_TIMEOUT) assert u_svc.state == 'upgraded' u_svc = client.wait_success(u_svc.rollback(), DEFAULT_TIMEOUT) _wait_until_active_map_count(u_svc, 3, client) c1 = _validate_compose_instance_start(client, svc, env, '1') assert c1.version == '0' assert c1.id == c1_pre.id c2 = _validate_compose_instance_start(client, svc, env, '1', 'secondary1') assert c2.version == '0' assert c2.id == c2_pre.id c3 = _validate_compose_instance_start(client, svc, env, '1', 'secondary2') assert c3.version == '0' assert c3.id == c3_pre.id def _wait_until_active_map_count(service, count, client): def wait_for_map_count(service): m = client.list_serviceExposeMap(serviceId=service.id, state='active') return len(m) == count wait_for(lambda : wait_for_condition(client, service, wait_for_map_count)) return client.list_serviceExposeMap(serviceId=service.id, state='active') def _validate_compose_instance_start(client, service, env, number, launch_config_name=None): cn = launch_config_name + '-' if launch_config_name is not None else '' name = env.name + '-' + service.name + '-' + cn + number def wait_for_map_count(service): instances = client.list_container(name=name, state='running') return len(instances) == 1 wait_for(lambda : wait_for_condition(client, service, wait_for_map_count)) instances = client.list_container(name=name, state='running') return instances[0] def test_upgrade_global_service(new_context): client = new_context.client host1 = new_context.host host2 = register_simulated_host(new_context) host3 = register_simulated_host(new_context) client.wait_success(host1) client.wait_success(host2) client.wait_success(host3) env = _create_stack(client) image_uuid = new_context.image_uuid launch_config = {'imageUuid': image_uuid, 'labels': {'io.rancher.scheduler.global': 'true'}} service = client.create_service(name=random_str(), environmentId=env.id, launchConfig=launch_config) service = client.wait_success(service) assert service.state == 'inactive' service = client.wait_success(service.activate(), 120) assert service.state == 'active' c = client.list_serviceExposeMap(serviceId=service.id, state='active') strategy = {'launchConfig': launch_config, 'intervalMillis': 100} service.upgrade_action(inServiceStrategy=strategy) wait_for(lambda : client.reload(service).state == 'upgraded') service = client.reload(service) service = client.wait_success(service.rollback()) _wait_until_active_map_count(service, len(c), client)
#========================= # Armor List #========================= clothArmor = {'name':'Cloth Armor', 'arm':1, 'description':'This is some cloth armor with a little extra padding.'} leatherArmor = {'name':'Leather Armor', 'arm':3, 'description':'This is some heavy chunks of leather that have been fashioned into armor.'} woodenPlateArmor = {'name':'Wooden Plate Armor', 'arm':7, 'description':'This is some plated armor made from pieces of wood, it seems to be pretty sturdy.'} steelPlateArmor = {'name':'Steel Plate Armor', 'arm':9, 'description':'This is some very strong plate armor made of steel, and the way it is polished makes you look great.'} chainMailArmor = {'name': 'Chain Mail Armor', 'arm':12, 'description':'This is some armor made of chain mail but it shines with a brilliance unfamiler to your knowledge of metals.'} armorList = [clothArmor, leatherArmor, woodenPlateArmor, steelPlateArmor, chainMailArmor]
cloth_armor = {'name': 'Cloth Armor', 'arm': 1, 'description': 'This is some cloth armor with a little extra padding.'} leather_armor = {'name': 'Leather Armor', 'arm': 3, 'description': 'This is some heavy chunks of leather that have been fashioned into armor.'} wooden_plate_armor = {'name': 'Wooden Plate Armor', 'arm': 7, 'description': 'This is some plated armor made from pieces of wood, it seems to be pretty sturdy.'} steel_plate_armor = {'name': 'Steel Plate Armor', 'arm': 9, 'description': 'This is some very strong plate armor made of steel, and the way it is polished makes you look great.'} chain_mail_armor = {'name': 'Chain Mail Armor', 'arm': 12, 'description': 'This is some armor made of chain mail but it shines with a brilliance unfamiler to your knowledge of metals.'} armor_list = [clothArmor, leatherArmor, woodenPlateArmor, steelPlateArmor, chainMailArmor]
#This program estimates a painting job cost_per_hour = 35.00 base_hours = 8 def main(): square_feet = float(input('Enter the number of square feet to be painted: ')) price_per_gallon = float(input('Enter the price of a paint per a gallon: ')) number_of_gallons = calculates_number_of_gallons(square_feet) hours_required = calculates_hours_required(square_feet) paint_cost = calculate_paint_cost(price_per_gallon,number_of_gallons) labor_charges = calculate_labor_charge(hours_required) grand_total = calculate_overal_total_cost(paint_cost,labor_charges) #Displaying the above data print('\nThe number of gallons of paint required = '\ ,format(number_of_gallons,'.2f'),\ ' gallons\nThe hours of labor required = '\ ,format(hours_required,'.2f'),' hours'\ '\nThe total cost of the paint = $',format(paint_cost,',.2f'),\ '\nThe labor charges = $',format(labor_charges,',.2f'),\ '\nThe total cost of the paint job = $',format(grand_total,',.2f')\ ,sep='') def calculates_number_of_gallons(square_feet): total_gallons = square_feet / 112 return total_gallons def calculates_hours_required(square_feet): hours = (square_feet * base_hours)/ 112 return hours def calculate_paint_cost(price_per_gallon,number_of_gallons): paint_cost = price_per_gallon * number_of_gallons return paint_cost def calculate_labor_charge(hours): labor_charges = hours * cost_per_hour return labor_charges def calculate_overal_total_cost(paint_cost,labour_charges): total_cost = paint_cost + labour_charges return total_cost main()
cost_per_hour = 35.0 base_hours = 8 def main(): square_feet = float(input('Enter the number of square feet to be painted: ')) price_per_gallon = float(input('Enter the price of a paint per a gallon: ')) number_of_gallons = calculates_number_of_gallons(square_feet) hours_required = calculates_hours_required(square_feet) paint_cost = calculate_paint_cost(price_per_gallon, number_of_gallons) labor_charges = calculate_labor_charge(hours_required) grand_total = calculate_overal_total_cost(paint_cost, labor_charges) print('\nThe number of gallons of paint required = ', format(number_of_gallons, '.2f'), ' gallons\nThe hours of labor required = ', format(hours_required, '.2f'), ' hours\nThe total cost of the paint = $', format(paint_cost, ',.2f'), '\nThe labor charges = $', format(labor_charges, ',.2f'), '\nThe total cost of the paint job = $', format(grand_total, ',.2f'), sep='') def calculates_number_of_gallons(square_feet): total_gallons = square_feet / 112 return total_gallons def calculates_hours_required(square_feet): hours = square_feet * base_hours / 112 return hours def calculate_paint_cost(price_per_gallon, number_of_gallons): paint_cost = price_per_gallon * number_of_gallons return paint_cost def calculate_labor_charge(hours): labor_charges = hours * cost_per_hour return labor_charges def calculate_overal_total_cost(paint_cost, labour_charges): total_cost = paint_cost + labour_charges return total_cost main()
# spam.py print('imported spam') def foo(): print('spam.foo') def bar(): print('spam.bar')
print('imported spam') def foo(): print('spam.foo') def bar(): print('spam.bar')
# https://leetcode.com/problems/largest-rectangle-in-histogram class Solution: def largestRectangleArea(self, heights): if not heights: return 0 st = [0] idx = 1 ans = 0 while idx < len(heights): while heights[idx] < heights[st[-1]]: if len(st) == 1: l_idx = st.pop(-1) ans = max(ans, idx * heights[l_idx]) break l_idx = st.pop(-1) ans = max(ans, (idx - (st[-1] + 1)) * heights[l_idx]) st.append(idx) idx += 1 while 1 < len(st): l_idx = st.pop(-1) ans = max(ans, (len(heights) - (st[-1] + 1)) * heights[l_idx]) ans = max(ans, heights[st[0]] * len(heights)) return ans
class Solution: def largest_rectangle_area(self, heights): if not heights: return 0 st = [0] idx = 1 ans = 0 while idx < len(heights): while heights[idx] < heights[st[-1]]: if len(st) == 1: l_idx = st.pop(-1) ans = max(ans, idx * heights[l_idx]) break l_idx = st.pop(-1) ans = max(ans, (idx - (st[-1] + 1)) * heights[l_idx]) st.append(idx) idx += 1 while 1 < len(st): l_idx = st.pop(-1) ans = max(ans, (len(heights) - (st[-1] + 1)) * heights[l_idx]) ans = max(ans, heights[st[0]] * len(heights)) return ans
# Las tuplas no son mutables nombres = ("Ana", "Maria", "Rodrigo") try: nombres.append("Anita") except: print("No se puede nombres.append('Anita')") try: nombres[0]=("Anita") except: print("No se puede nombres[0]=('Anita')")
nombres = ('Ana', 'Maria', 'Rodrigo') try: nombres.append('Anita') except: print("No se puede nombres.append('Anita')") try: nombres[0] = 'Anita' except: print("No se puede nombres[0]=('Anita')")
def check(exampleGraph,startPoint,endPoint): global currentPath global final global string if bool(currentPath) == False: currentPath.append(startPoint) for p in exampleGraph: if p[0] == currentPath[-1]: if p[1] not in currentPath: currentPath.append(p[1]) if p[1] == endPoint: for i in currentPath: string += str(i) final.append(string) string = '' currentPath.pop() else: check(exampleGraph,startPoint,endPoint) currentPath.pop() else: for p in exampleGraph: if p[0] == currentPath[-1]: if p[1] not in currentPath: currentPath.append(p[1]) if currentPath[-1] == endPoint: for i in currentPath: string += str(i) final.append(string) string = '' currentPath.pop() else: check(exampleGraph,startPoint,endPoint) currentPath.pop() def finalCheck(exampleGraph,startPoint,endPoint): global finalfinal global currentPath global final global string finalfinal = [] final = [] currentPath = [] string = '' check(exampleGraph,startPoint,endPoint) for p in range(len(final)): pastPoint = final[p][0] currentRoad = '' finalfinal.append([]) for i in range(1,len(final[p])): currentRoad = pastPoint + final[p][i] pastPoint = final[p][i] finalfinal[p].append(currentRoad) return finalfinal #~~~~~~~~~~~~~~~~~~~~~~~~~let's see how it works for test~~~~~~~~~~~~~~~~~~~~~# # exampleGraph = ['ae','ab','ac','ad','cd','db','cb'] # print(finalCheck(exampleGraph,'a','b')) # # outPut ---> [['ab'], ['ac', 'cd', 'db'], ['ac', 'cb'], ['ad', 'db']] #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
def check(exampleGraph, startPoint, endPoint): global currentPath global final global string if bool(currentPath) == False: currentPath.append(startPoint) for p in exampleGraph: if p[0] == currentPath[-1]: if p[1] not in currentPath: currentPath.append(p[1]) if p[1] == endPoint: for i in currentPath: string += str(i) final.append(string) string = '' currentPath.pop() else: check(exampleGraph, startPoint, endPoint) currentPath.pop() else: for p in exampleGraph: if p[0] == currentPath[-1]: if p[1] not in currentPath: currentPath.append(p[1]) if currentPath[-1] == endPoint: for i in currentPath: string += str(i) final.append(string) string = '' currentPath.pop() else: check(exampleGraph, startPoint, endPoint) currentPath.pop() def final_check(exampleGraph, startPoint, endPoint): global finalfinal global currentPath global final global string finalfinal = [] final = [] current_path = [] string = '' check(exampleGraph, startPoint, endPoint) for p in range(len(final)): past_point = final[p][0] current_road = '' finalfinal.append([]) for i in range(1, len(final[p])): current_road = pastPoint + final[p][i] past_point = final[p][i] finalfinal[p].append(currentRoad) return finalfinal
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a boolean def hasCycle(self, head): d = dict() h = head while h != None: if h in d: return True else: d[h] = 1 h = h.next return False #another # class Solution: # # @param head, a ListNode # # @return a boolean # def hasCycle(self, head): # if not head: # return False # # slow = fast = head # while fast and fast.next: # slow = slow.next # fast = fast.next.next # if slow is fast: # return True # # return False
class Solution: def has_cycle(self, head): d = dict() h = head while h != None: if h in d: return True else: d[h] = 1 h = h.next return False
# Simon says # Do you know the game "Simon says?" The # instructor, "Simon", says what the players should # do, e.g. "jump in the air" or "close your eyes". The # players should follow the instructions only if the # phrase starts with "Simon says". Now let's # implement a digital version of this game! We will # modify it a bit: the correct instructions may not only # start but also end with the words "Simon says". # But be careful, instructions can be only at the # beginning, or at the end, but not in the middle! # Write a function that takes a string with # instructions: if it starts or ends with the words # "Simon says", your function should return the # string "I ", plus what you would do: the # instructions themselves. Otherwise, return "I # won't do it!". # You are NOT supposed to handle input or call your # function, just implement it. def what_to_do(instructions): return "I " + instructions.replace("Simon says", "").strip(" ") if instructions.startswith("Simon says") or instructions.endswith("Simon says") else "I won't do it!" print(what_to_do("Simon says make a wish"))
def what_to_do(instructions): return 'I ' + instructions.replace('Simon says', '').strip(' ') if instructions.startswith('Simon says') or instructions.endswith('Simon says') else "I won't do it!" print(what_to_do('Simon says make a wish'))
class OutputHelper: colors = { 'default_foreground': 39, 'black': 30, 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34, 'magenta': 35, 'cyan': 36, 'light_gray': 37, 'dark_gray': 90, 'light_red': 91, 'light_green': 92, 'light_yellow': 93, 'light_blue': 94, 'light_magenta': 95, 'light_cyan': 96, 'white': 97, } @staticmethod def colorize(text, color): if color in OutputHelper.colors: return "\033[" + str(OutputHelper.colors[color]) + "m" + text + "\033[0m" return text
class Outputhelper: colors = {'default_foreground': 39, 'black': 30, 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34, 'magenta': 35, 'cyan': 36, 'light_gray': 37, 'dark_gray': 90, 'light_red': 91, 'light_green': 92, 'light_yellow': 93, 'light_blue': 94, 'light_magenta': 95, 'light_cyan': 96, 'white': 97} @staticmethod def colorize(text, color): if color in OutputHelper.colors: return '\x1b[' + str(OutputHelper.colors[color]) + 'm' + text + '\x1b[0m' return text
# Determine if String Halves Are Alike # Runtime: 39 ms, faster than 82.91% of Python3 online submissions for Determine if String Halves Are Alike. # Memory Usage: 13.8 MB, less than 98.41% of Python3 online submissions for Determine if String Halves Are Alike. # https://leetcode.com/submissions/detail/714796669/ class Solution: def halvesAreAlike(self, s): return len([char for char in s[:len(s)//2] if char.lower() in "aeiou"]) == len([char for char in s[len(s)//2:] if char.lower() in "aeiou"]) print(Solution().halvesAreAlike("book"))
class Solution: def halves_are_alike(self, s): return len([char for char in s[:len(s) // 2] if char.lower() in 'aeiou']) == len([char for char in s[len(s) // 2:] if char.lower() in 'aeiou']) print(solution().halvesAreAlike('book'))
class Solution: # @param A : list of integers # @return a list of list of integers def twosum(self, arr, index, target): i = index j = len(arr) - 1 while i<j: if arr[i] + arr[j] == target: temp = [arr[index-1], arr[i], arr[j]] if len(self.res)>0: if self.res[0] != temp: self.res.insert(0, temp) else: self.res.insert(0, temp) i += 1 j -= 1 elif arr[i] + arr[j] < target: i += 1 else: j -= 1 def threeSum(self, arr): self.res = [] arr.sort() for i in range(len(arr)-2): if (i==0) or (i and arr[i] != arr[i-1]): self.twosum(arr, i+1, -arr[i]) return self.res if __name__ == '__main__': arr = [-1, 0, 1, 2, -1, -4] sol = Solution() print(sol.threeSum(arr))
class Solution: def twosum(self, arr, index, target): i = index j = len(arr) - 1 while i < j: if arr[i] + arr[j] == target: temp = [arr[index - 1], arr[i], arr[j]] if len(self.res) > 0: if self.res[0] != temp: self.res.insert(0, temp) else: self.res.insert(0, temp) i += 1 j -= 1 elif arr[i] + arr[j] < target: i += 1 else: j -= 1 def three_sum(self, arr): self.res = [] arr.sort() for i in range(len(arr) - 2): if i == 0 or (i and arr[i] != arr[i - 1]): self.twosum(arr, i + 1, -arr[i]) return self.res if __name__ == '__main__': arr = [-1, 0, 1, 2, -1, -4] sol = solution() print(sol.threeSum(arr))
#!/usr/bin/env python # Settings for synthesis.py (test cases) # Input files Processing path INPUTFILES_PATH = "/home/user/Documents/Development/AlexandriaConsulting/repos/trunk/synthesis/Staging" OUTPUTFILES_PATH = "/home/user/Documents/Development/AlexandriaConsulting/repos/trunk/synthesis/Staging" TEST_FILE = "anyfile" # Validation and processing of XML files XML_FILE_VALID = "Example_HUD_HMIS_2_8_Instance.xml" XML_FILE_INVALID = "coastal_sheila_invalid.xml" XML_FILE_MALFORMED = "coastal_sheila_malformed.xml" # Encryption Tests XML_ENCRYPTED_FILE = "BASE_Example_HUD_HMIS_2_8_Instance.xml.pgp" XML_DECRYPTED_FILE = "BASE_Example_HUD_HMIS_2_8_Instance.xml" XML_ENCRYPT_FINGERPRINT = "97A798CF9E8D9F470292975E70DE787C6B57800F" XML_DECRYPT_PASSPHRASE = "passwordlaumeyer#"
inputfiles_path = '/home/user/Documents/Development/AlexandriaConsulting/repos/trunk/synthesis/Staging' outputfiles_path = '/home/user/Documents/Development/AlexandriaConsulting/repos/trunk/synthesis/Staging' test_file = 'anyfile' xml_file_valid = 'Example_HUD_HMIS_2_8_Instance.xml' xml_file_invalid = 'coastal_sheila_invalid.xml' xml_file_malformed = 'coastal_sheila_malformed.xml' xml_encrypted_file = 'BASE_Example_HUD_HMIS_2_8_Instance.xml.pgp' xml_decrypted_file = 'BASE_Example_HUD_HMIS_2_8_Instance.xml' xml_encrypt_fingerprint = '97A798CF9E8D9F470292975E70DE787C6B57800F' xml_decrypt_passphrase = 'passwordlaumeyer#'
# Variables can store data a = 10 # Assigns the integer 10 to the variable a # In Python variables do not have one fixed type a = "hello" # Assigns the string "hello" to the variable a print(a) # Prints the value of a which is now "hello"
a = 10 a = 'hello' print(a)
#!/usr/bin/env python3 poly_derivative = __import__('10-matisse').poly_derivative poly = [5, 3, 0, 1] print(poly_derivative(poly))
poly_derivative = __import__('10-matisse').poly_derivative poly = [5, 3, 0, 1] print(poly_derivative(poly))
for x in range(16): with open(f'..\\data\\cpu\\functions\\opcode_switch\\opcode_8xx4\\opcode_8xx4_{x}.mcfunction', 'w') as f: for i in range(16): f.write(f'execute if score Global PC_nibble_3 matches {i} run scoreboard players operation Global V{hex(x)[2:].upper()} += Global V{hex(i)[2:].upper()}\n') f.write(f'execute if score Global V{hex(x)[2:].upper()} matches 256.. run scoreboard players set Global VF 1\n' f'execute unless score Global V{hex(x)[2:].upper()} matches 256.. run scoreboard players set Global VF 0\n' f'execute if score Global V{hex(x)[2:].upper()} matches 256.. run scoreboard players remove Global V{hex(x)[2:].upper()} 256\n') with open('..\\data\\cpu\\functions\\opcode_switch\\opcode_8xx4.mcfunction', 'a') as f: for x in range(16): f.write(f'execute if score Global PC_nibble_2 matches {x} run function cpu:opcode_switch/opcode_8xx4/opcode_8xx4_{x}\n')
for x in range(16): with open(f'..\\data\\cpu\\functions\\opcode_switch\\opcode_8xx4\\opcode_8xx4_{x}.mcfunction', 'w') as f: for i in range(16): f.write(f'execute if score Global PC_nibble_3 matches {i} run scoreboard players operation Global V{hex(x)[2:].upper()} += Global V{hex(i)[2:].upper()}\n') f.write(f'execute if score Global V{hex(x)[2:].upper()} matches 256.. run scoreboard players set Global VF 1\nexecute unless score Global V{hex(x)[2:].upper()} matches 256.. run scoreboard players set Global VF 0\nexecute if score Global V{hex(x)[2:].upper()} matches 256.. run scoreboard players remove Global V{hex(x)[2:].upper()} 256\n') with open('..\\data\\cpu\\functions\\opcode_switch\\opcode_8xx4.mcfunction', 'a') as f: for x in range(16): f.write(f'execute if score Global PC_nibble_2 matches {x} run function cpu:opcode_switch/opcode_8xx4/opcode_8xx4_{x}\n')
valor = int(input()) contadorBixo = contadorCoelho = contadorRato = contadorSapo = 0 for c in range(0, valor): experiencia = str(input()) dividir = experiencia.split() quantidade = int(dividir[0]) tipo = dividir[1] if quantidade > 0 and 'C' in tipo: contadorCoelho += quantidade elif quantidade > 0 and 'R' in tipo: contadorRato += quantidade elif quantidade > 0 and 'S' in tipo: contadorSapo += quantidade contadorBixo = contadorCoelho + contadorRato + contadorSapo print(f'Total: {contadorBixo} cobaias') print(f'Total de coelhos: {contadorCoelho}') print(f'Total de ratos: {contadorRato}') print(f'Total de sapos: {contadorSapo}') print(f'Percentual de coelhos: {(contadorCoelho*100) / contadorBixo:.2f} %') print(f'Percentual de ratos: {(contadorRato*100) / contadorBixo:.2f} %') print(f'Percentual de sapos: {(contadorSapo*100) / contadorBixo:.2f} %')
valor = int(input()) contador_bixo = contador_coelho = contador_rato = contador_sapo = 0 for c in range(0, valor): experiencia = str(input()) dividir = experiencia.split() quantidade = int(dividir[0]) tipo = dividir[1] if quantidade > 0 and 'C' in tipo: contador_coelho += quantidade elif quantidade > 0 and 'R' in tipo: contador_rato += quantidade elif quantidade > 0 and 'S' in tipo: contador_sapo += quantidade contador_bixo = contadorCoelho + contadorRato + contadorSapo print(f'Total: {contadorBixo} cobaias') print(f'Total de coelhos: {contadorCoelho}') print(f'Total de ratos: {contadorRato}') print(f'Total de sapos: {contadorSapo}') print(f'Percentual de coelhos: {contadorCoelho * 100 / contadorBixo:.2f} %') print(f'Percentual de ratos: {contadorRato * 100 / contadorBixo:.2f} %') print(f'Percentual de sapos: {contadorSapo * 100 / contadorBixo:.2f} %')
class Project: def __init__(self, id=None, x=None): self.x = x self.id = id def __eq__(self, other): return (self.id is None or other.id is None or self.id == other.id) and self.x == other.x
class Project: def __init__(self, id=None, x=None): self.x = x self.id = id def __eq__(self, other): return (self.id is None or other.id is None or self.id == other.id) and self.x == other.x
class bot_constant: bot_version: str = "0.0.1" bot_token: str = "<Replace token in here>" bot_author: str = "NgLam2911" bot_prefix: str = "?" bot_description: str = "Just a very simple discord bot that say Hi if you say Hello..."
class Bot_Constant: bot_version: str = '0.0.1' bot_token: str = '<Replace token in here>' bot_author: str = 'NgLam2911' bot_prefix: str = '?' bot_description: str = 'Just a very simple discord bot that say Hi if you say Hello...'
# # PySNMP MIB module HPN-ICF-RS485-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-RS485-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:29:05 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) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion") hpnicfCommon, = mibBuilder.importSymbols("HPN-ICF-OID-MIB", "hpnicfCommon") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") ObjectIdentity, TimeTicks, NotificationType, Integer32, IpAddress, Bits, Unsigned32, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Gauge32, iso, Counter32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "TimeTicks", "NotificationType", "Integer32", "IpAddress", "Bits", "Unsigned32", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Gauge32", "iso", "Counter32", "MibIdentifier") DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus") hpnicfRS485 = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109)) if mibBuilder.loadTexts: hpnicfRS485.setLastUpdated('200910210000Z') if mibBuilder.loadTexts: hpnicfRS485.setOrganization('') hpnicfRS485Properties = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1)) hpnicfRS485PropertiesTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1), ) if mibBuilder.loadTexts: hpnicfRS485PropertiesTable.setStatus('current') hpnicfRS485PropertiesEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: hpnicfRS485PropertiesEntry.setStatus('current') hpnicfRS485RawSessionNextIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfRS485RawSessionNextIndex.setStatus('current') hpnicfRS485BaudRate = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("bautRate300", 1), ("bautRate600", 2), ("bautRate1200", 3), ("bautRate2400", 4), ("bautRate4800", 5), ("bautRate9600", 6), ("bautRate19200", 7), ("bautRate38400", 8), ("bautRate57600", 9), ("bautRate115200", 10))).clone('bautRate9600')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfRS485BaudRate.setStatus('current') hpnicfRS485DataBits = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("five", 1), ("six", 2), ("seven", 3), ("eight", 4))).clone('eight')).setUnits('bit').setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfRS485DataBits.setStatus('current') hpnicfRS485Parity = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("none", 1), ("odd", 2), ("even", 3), ("mark", 4), ("space", 5))).clone('none')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfRS485Parity.setStatus('current') hpnicfRS485StopBits = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("one", 1), ("two", 2), ("oneAndHalf", 3))).clone('one')).setUnits('bit').setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfRS485StopBits.setStatus('current') hpnicfRS485FlowControl = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("hardware", 2), ("xonOrxoff", 3))).clone('none')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfRS485FlowControl.setStatus('current') hpnicfRS485TXCharacters = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfRS485TXCharacters.setStatus('current') hpnicfRS485RXCharacters = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfRS485RXCharacters.setStatus('current') hpnicfRS485TXErrCharacters = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfRS485TXErrCharacters.setStatus('current') hpnicfRS485RXErrCharacters = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 10), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfRS485RXErrCharacters.setStatus('current') hpnicfRS485ResetCharacters = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("counting", 1), ("clear", 2))).clone('counting')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfRS485ResetCharacters.setStatus('current') hpnicfRS485RawSessions = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2)) hpnicfRS485RawSessionSummary = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 1)) hpnicfRS485RawSessionMaxNum = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfRS485RawSessionMaxNum.setStatus('current') hpnicfRS485RawSessionTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2), ) if mibBuilder.loadTexts: hpnicfRS485RawSessionTable.setStatus('current') hpnicfRS485RawSessionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "HPN-ICF-RS485-MIB", "hpnicfRS485SessionIndex")) if mibBuilder.loadTexts: hpnicfRS485RawSessionEntry.setStatus('current') hpnicfRS485SessionIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64))) if mibBuilder.loadTexts: hpnicfRS485SessionIndex.setStatus('current') hpnicfRS485SessionType = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("udp", 1), ("tcpClient", 2), ("tcpServer", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfRS485SessionType.setStatus('current') hpnicfRS485SessionAddType = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 3), InetAddressType().clone('ipv4')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfRS485SessionAddType.setStatus('current') hpnicfRS485SessionRemoteIP = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 4), InetAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfRS485SessionRemoteIP.setStatus('current') hpnicfRS485SessionRemotePort = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1024, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfRS485SessionRemotePort.setStatus('current') hpnicfRS485SessionLocalPort = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1024, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfRS485SessionLocalPort.setStatus('current') hpnicfRS485SessionStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 7), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfRS485SessionStatus.setStatus('current') hpnicfRS485RawSessionErrInfoTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 3), ) if mibBuilder.loadTexts: hpnicfRS485RawSessionErrInfoTable.setStatus('current') hpnicfRS485RawSessionErrInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 3, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "HPN-ICF-RS485-MIB", "hpnicfRS485SessionIndex")) if mibBuilder.loadTexts: hpnicfRS485RawSessionErrInfoEntry.setStatus('current') hpnicfRS485RawSessionErrInfo = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 3, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfRS485RawSessionErrInfo.setStatus('current') mibBuilder.exportSymbols("HPN-ICF-RS485-MIB", hpnicfRS485RawSessionSummary=hpnicfRS485RawSessionSummary, hpnicfRS485StopBits=hpnicfRS485StopBits, hpnicfRS485RawSessionEntry=hpnicfRS485RawSessionEntry, hpnicfRS485RawSessionErrInfoTable=hpnicfRS485RawSessionErrInfoTable, hpnicfRS485RawSessions=hpnicfRS485RawSessions, hpnicfRS485=hpnicfRS485, PYSNMP_MODULE_ID=hpnicfRS485, hpnicfRS485SessionRemotePort=hpnicfRS485SessionRemotePort, hpnicfRS485ResetCharacters=hpnicfRS485ResetCharacters, hpnicfRS485SessionLocalPort=hpnicfRS485SessionLocalPort, hpnicfRS485RXErrCharacters=hpnicfRS485RXErrCharacters, hpnicfRS485RawSessionTable=hpnicfRS485RawSessionTable, hpnicfRS485RXCharacters=hpnicfRS485RXCharacters, hpnicfRS485SessionStatus=hpnicfRS485SessionStatus, hpnicfRS485TXErrCharacters=hpnicfRS485TXErrCharacters, hpnicfRS485PropertiesTable=hpnicfRS485PropertiesTable, hpnicfRS485PropertiesEntry=hpnicfRS485PropertiesEntry, hpnicfRS485RawSessionErrInfo=hpnicfRS485RawSessionErrInfo, hpnicfRS485Parity=hpnicfRS485Parity, hpnicfRS485TXCharacters=hpnicfRS485TXCharacters, hpnicfRS485RawSessionNextIndex=hpnicfRS485RawSessionNextIndex, hpnicfRS485RawSessionMaxNum=hpnicfRS485RawSessionMaxNum, hpnicfRS485Properties=hpnicfRS485Properties, hpnicfRS485SessionRemoteIP=hpnicfRS485SessionRemoteIP, hpnicfRS485SessionType=hpnicfRS485SessionType, hpnicfRS485SessionAddType=hpnicfRS485SessionAddType, hpnicfRS485BaudRate=hpnicfRS485BaudRate, hpnicfRS485DataBits=hpnicfRS485DataBits, hpnicfRS485FlowControl=hpnicfRS485FlowControl, hpnicfRS485RawSessionErrInfoEntry=hpnicfRS485RawSessionErrInfoEntry, hpnicfRS485SessionIndex=hpnicfRS485SessionIndex)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsUnion') (hpnicf_common,) = mibBuilder.importSymbols('HPN-ICF-OID-MIB', 'hpnicfCommon') (if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex') (inet_address_type, inet_address) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddressType', 'InetAddress') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (object_identity, time_ticks, notification_type, integer32, ip_address, bits, unsigned32, counter64, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, gauge32, iso, counter32, mib_identifier) = mibBuilder.importSymbols('SNMPv2-SMI', 'ObjectIdentity', 'TimeTicks', 'NotificationType', 'Integer32', 'IpAddress', 'Bits', 'Unsigned32', 'Counter64', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'Gauge32', 'iso', 'Counter32', 'MibIdentifier') (display_string, textual_convention, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention', 'RowStatus') hpnicf_rs485 = module_identity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109)) if mibBuilder.loadTexts: hpnicfRS485.setLastUpdated('200910210000Z') if mibBuilder.loadTexts: hpnicfRS485.setOrganization('') hpnicf_rs485_properties = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1)) hpnicf_rs485_properties_table = mib_table((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1)) if mibBuilder.loadTexts: hpnicfRS485PropertiesTable.setStatus('current') hpnicf_rs485_properties_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex')) if mibBuilder.loadTexts: hpnicfRS485PropertiesEntry.setStatus('current') hpnicf_rs485_raw_session_next_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 64))).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfRS485RawSessionNextIndex.setStatus('current') hpnicf_rs485_baud_rate = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=named_values(('bautRate300', 1), ('bautRate600', 2), ('bautRate1200', 3), ('bautRate2400', 4), ('bautRate4800', 5), ('bautRate9600', 6), ('bautRate19200', 7), ('bautRate38400', 8), ('bautRate57600', 9), ('bautRate115200', 10))).clone('bautRate9600')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfRS485BaudRate.setStatus('current') hpnicf_rs485_data_bits = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('five', 1), ('six', 2), ('seven', 3), ('eight', 4))).clone('eight')).setUnits('bit').setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfRS485DataBits.setStatus('current') hpnicf_rs485_parity = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('none', 1), ('odd', 2), ('even', 3), ('mark', 4), ('space', 5))).clone('none')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfRS485Parity.setStatus('current') hpnicf_rs485_stop_bits = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('one', 1), ('two', 2), ('oneAndHalf', 3))).clone('one')).setUnits('bit').setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfRS485StopBits.setStatus('current') hpnicf_rs485_flow_control = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('none', 1), ('hardware', 2), ('xonOrxoff', 3))).clone('none')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfRS485FlowControl.setStatus('current') hpnicf_rs485_tx_characters = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 7), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfRS485TXCharacters.setStatus('current') hpnicf_rs485_rx_characters = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 8), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfRS485RXCharacters.setStatus('current') hpnicf_rs485_tx_err_characters = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 9), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfRS485TXErrCharacters.setStatus('current') hpnicf_rs485_rx_err_characters = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 10), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfRS485RXErrCharacters.setStatus('current') hpnicf_rs485_reset_characters = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 1, 1, 1, 11), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('counting', 1), ('clear', 2))).clone('counting')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfRS485ResetCharacters.setStatus('current') hpnicf_rs485_raw_sessions = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2)) hpnicf_rs485_raw_session_summary = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 1)) hpnicf_rs485_raw_session_max_num = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 64))).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfRS485RawSessionMaxNum.setStatus('current') hpnicf_rs485_raw_session_table = mib_table((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2)) if mibBuilder.loadTexts: hpnicfRS485RawSessionTable.setStatus('current') hpnicf_rs485_raw_session_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'), (0, 'HPN-ICF-RS485-MIB', 'hpnicfRS485SessionIndex')) if mibBuilder.loadTexts: hpnicfRS485RawSessionEntry.setStatus('current') hpnicf_rs485_session_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 64))) if mibBuilder.loadTexts: hpnicfRS485SessionIndex.setStatus('current') hpnicf_rs485_session_type = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('udp', 1), ('tcpClient', 2), ('tcpServer', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfRS485SessionType.setStatus('current') hpnicf_rs485_session_add_type = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 3), inet_address_type().clone('ipv4')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfRS485SessionAddType.setStatus('current') hpnicf_rs485_session_remote_ip = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 4), inet_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfRS485SessionRemoteIP.setStatus('current') hpnicf_rs485_session_remote_port = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(1024, 65535))).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfRS485SessionRemotePort.setStatus('current') hpnicf_rs485_session_local_port = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(1024, 65535))).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfRS485SessionLocalPort.setStatus('current') hpnicf_rs485_session_status = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 2, 1, 7), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfRS485SessionStatus.setStatus('current') hpnicf_rs485_raw_session_err_info_table = mib_table((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 3)) if mibBuilder.loadTexts: hpnicfRS485RawSessionErrInfoTable.setStatus('current') hpnicf_rs485_raw_session_err_info_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 3, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'), (0, 'HPN-ICF-RS485-MIB', 'hpnicfRS485SessionIndex')) if mibBuilder.loadTexts: hpnicfRS485RawSessionErrInfoEntry.setStatus('current') hpnicf_rs485_raw_session_err_info = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 109, 2, 3, 1, 1), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfRS485RawSessionErrInfo.setStatus('current') mibBuilder.exportSymbols('HPN-ICF-RS485-MIB', hpnicfRS485RawSessionSummary=hpnicfRS485RawSessionSummary, hpnicfRS485StopBits=hpnicfRS485StopBits, hpnicfRS485RawSessionEntry=hpnicfRS485RawSessionEntry, hpnicfRS485RawSessionErrInfoTable=hpnicfRS485RawSessionErrInfoTable, hpnicfRS485RawSessions=hpnicfRS485RawSessions, hpnicfRS485=hpnicfRS485, PYSNMP_MODULE_ID=hpnicfRS485, hpnicfRS485SessionRemotePort=hpnicfRS485SessionRemotePort, hpnicfRS485ResetCharacters=hpnicfRS485ResetCharacters, hpnicfRS485SessionLocalPort=hpnicfRS485SessionLocalPort, hpnicfRS485RXErrCharacters=hpnicfRS485RXErrCharacters, hpnicfRS485RawSessionTable=hpnicfRS485RawSessionTable, hpnicfRS485RXCharacters=hpnicfRS485RXCharacters, hpnicfRS485SessionStatus=hpnicfRS485SessionStatus, hpnicfRS485TXErrCharacters=hpnicfRS485TXErrCharacters, hpnicfRS485PropertiesTable=hpnicfRS485PropertiesTable, hpnicfRS485PropertiesEntry=hpnicfRS485PropertiesEntry, hpnicfRS485RawSessionErrInfo=hpnicfRS485RawSessionErrInfo, hpnicfRS485Parity=hpnicfRS485Parity, hpnicfRS485TXCharacters=hpnicfRS485TXCharacters, hpnicfRS485RawSessionNextIndex=hpnicfRS485RawSessionNextIndex, hpnicfRS485RawSessionMaxNum=hpnicfRS485RawSessionMaxNum, hpnicfRS485Properties=hpnicfRS485Properties, hpnicfRS485SessionRemoteIP=hpnicfRS485SessionRemoteIP, hpnicfRS485SessionType=hpnicfRS485SessionType, hpnicfRS485SessionAddType=hpnicfRS485SessionAddType, hpnicfRS485BaudRate=hpnicfRS485BaudRate, hpnicfRS485DataBits=hpnicfRS485DataBits, hpnicfRS485FlowControl=hpnicfRS485FlowControl, hpnicfRS485RawSessionErrInfoEntry=hpnicfRS485RawSessionErrInfoEntry, hpnicfRS485SessionIndex=hpnicfRS485SessionIndex)
# message = 'umetumiwa kisi cha tsh2000 kutoka kwa JOSEPH ALEX salio lako ni ths 9000 kujua bonyeza *148*99# ili ' \ # 'kujiunga na salio ' # if message.strip(".islower()"): # print(message) # sentence = "XYThis is an example sentence.XY" # print(message.strip('')) number = input('enter dial codes') if number == '*142*99#': print('Karibu Tigo Chagua kifurushi chako') li = ['Ofa Maalum', 'Zawadi kwa Rafiki', 'Dakika & SMS', 'Internet & 4G', 'Royal', 'Kimataifa', 'Kisichoisha Muda', 'Burudani', 'Tunashea Bando', 'Salio & Language'] for i in range(len(li)): print(f'{i} {li[i]}') choice = input('chagua kifurushi unachotaka') while True: if choice == '0': print('your in one') elif choice == '1': print('your in 1') else: print('done') else: print('wrong dial')
number = input('enter dial codes') if number == '*142*99#': print('Karibu Tigo Chagua kifurushi chako') li = ['Ofa Maalum', 'Zawadi kwa Rafiki', 'Dakika & SMS', 'Internet & 4G', 'Royal', 'Kimataifa', 'Kisichoisha Muda', 'Burudani', 'Tunashea Bando', 'Salio & Language'] for i in range(len(li)): print(f'{i} {li[i]}') choice = input('chagua kifurushi unachotaka') while True: if choice == '0': print('your in one') elif choice == '1': print('your in 1') else: print('done') else: print('wrong dial')
dias = int(input()) ano = dias // 365 dias = dias - ano * 365 mes = dias // 30 dias = dias - mes * 30 print("%.0f ano(s)" % ano) print("%.0f mes(es)" % mes) print("%.0f dia(s)" % dias)
dias = int(input()) ano = dias // 365 dias = dias - ano * 365 mes = dias // 30 dias = dias - mes * 30 print('%.0f ano(s)' % ano) print('%.0f mes(es)' % mes) print('%.0f dia(s)' % dias)
SECRET_KEY = "secret", INSTALLED_APPS = [ 'sampleproject.sample', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME':':memory:' } }
secret_key = ('secret',) installed_apps = ['sampleproject.sample'] databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
# -*- coding: utf-8 -*- # item pipelines # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html class ScrapydemoPipeline(object): # item pipelines def process_item(self, item, spider): return item
class Scrapydemopipeline(object): def process_item(self, item, spider): return item
''' Min XOR value Asked in: Booking.com https://www.interviewbit.com/problems/min-xor-value/ Problem Setter: mihai.gheorghe Problem Tester: archit.rai Given an integer array A of N integers, find the pair of integers in the array which have minimum XOR value. Report the minimum XOR value. Input Format: First and only argument of input contains an integer array A Output Format: return a single integer denoting minimum xor value Constraints: 2 <= N <= 100 000 0 <= A[i] <= 1 000 000 000 For Examples : Example Input 1: A = [0, 2, 5, 7] Example Output 1: 2 Explanation: 0 xor 2 = 2 Example Input 2: A = [0, 4, 7, 9] Example Output 2: 3 ''' # @param A : list of integers # @return an integer def findMinXor(A): A = sorted(A) min_xor = A[-1] for i in range(1, len(A)): xor = A[i-1]^A[i] if min_xor>xor: min_xor = xor return min_xor if __name__ == "__main__": data = [ [[0, 2, 5, 7], 2] ] for d in data: print('input', d[0], 'output', findMinXor(d[0]))
""" Min XOR value Asked in: Booking.com https://www.interviewbit.com/problems/min-xor-value/ Problem Setter: mihai.gheorghe Problem Tester: archit.rai Given an integer array A of N integers, find the pair of integers in the array which have minimum XOR value. Report the minimum XOR value. Input Format: First and only argument of input contains an integer array A Output Format: return a single integer denoting minimum xor value Constraints: 2 <= N <= 100 000 0 <= A[i] <= 1 000 000 000 For Examples : Example Input 1: A = [0, 2, 5, 7] Example Output 1: 2 Explanation: 0 xor 2 = 2 Example Input 2: A = [0, 4, 7, 9] Example Output 2: 3 """ def find_min_xor(A): a = sorted(A) min_xor = A[-1] for i in range(1, len(A)): xor = A[i - 1] ^ A[i] if min_xor > xor: min_xor = xor return min_xor if __name__ == '__main__': data = [[[0, 2, 5, 7], 2]] for d in data: print('input', d[0], 'output', find_min_xor(d[0]))