prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>errors.py<|end_file_name|><|fim▁begin|>__author__ = 'Cedric Da Costa Faro' from flask import render_template from . import main @main.app_errorhandler(404) def page_not_found(e): <|fim_middle|> @main.app_errorhandler(405) def method_not_allowed(e): return render_template('405.html'), 405 @main.app_errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 <|fim▁end|>
return render_template('404.html'), 404
<|file_name|>errors.py<|end_file_name|><|fim▁begin|>__author__ = 'Cedric Da Costa Faro' from flask import render_template from . import main @main.app_errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @main.app_errorhandler(405) def method_not_allowed(e): <|fim_middle|> @main.app_errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 <|fim▁end|>
return render_template('405.html'), 405
<|file_name|>errors.py<|end_file_name|><|fim▁begin|>__author__ = 'Cedric Da Costa Faro' from flask import render_template from . import main @main.app_errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @main.app_errorhandler(405) def method_not_allowed(e): return render_template('405.html'), 405 @main.app_errorhandler(500) def internal_server_error(e): <|fim_middle|> <|fim▁end|>
return render_template('500.html'), 500
<|file_name|>errors.py<|end_file_name|><|fim▁begin|>__author__ = 'Cedric Da Costa Faro' from flask import render_template from . import main @main.app_errorhandler(404) def <|fim_middle|>(e): return render_template('404.html'), 404 @main.app_errorhandler(405) def method_not_allowed(e): return render_template('405.html'), 405 @main.app_errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 <|fim▁end|>
page_not_found
<|file_name|>errors.py<|end_file_name|><|fim▁begin|>__author__ = 'Cedric Da Costa Faro' from flask import render_template from . import main @main.app_errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @main.app_errorhandler(405) def <|fim_middle|>(e): return render_template('405.html'), 405 @main.app_errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 <|fim▁end|>
method_not_allowed
<|file_name|>errors.py<|end_file_name|><|fim▁begin|>__author__ = 'Cedric Da Costa Faro' from flask import render_template from . import main @main.app_errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @main.app_errorhandler(405) def method_not_allowed(e): return render_template('405.html'), 405 @main.app_errorhandler(500) def <|fim_middle|>(e): return render_template('500.html'), 500 <|fim▁end|>
internal_server_error
<|file_name|>stage_2.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File written by pyctools-editor. Do not edit. import argparse import logging from pyctools.core.compound import Compound import pyctools.components.arithmetic import pyctools.components.qt.qtdisplay import pyctools.components.zone.zoneplategenerator class Network(object): components = \ { 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 180)*219)'}", 'pos': (200.0, 200.0)}, 'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 230)*219)'}", 'pos': (200.0, 330.0)}, 'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay', 'config': "{'framerate': 60}", 'pos': (460.0, 200.0)}, 'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2', 'config': "{'func': 'numpy.vstack((data1,data2))'}", 'pos': (330.0, 200.0)}, 'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': " "400, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 200.0)}, 'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': " "200, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 330.0)}} linkages = \ { ('clipper', 'output'): [('stacker', 'input1')], ('clipper2', 'output'): [('stacker', 'input2')], ('stacker', 'output'): [('qd', 'input')], ('zpg', 'output'): [('clipper', 'input')], ('zpg2', 'output'): [('clipper2', 'input')]} def make(self): comps = {} for name, component in self.components.items(): comps[name] = eval(component['class'])(config=eval(component['config'])) return Compound(linkages=self.linkages, **comps) if __name__ == '__main__': from PyQt5 import QtCore, QtWidgets QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtWidgets.QApplication([]) comp = Network().make() cnf = comp.get_config() parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) cnf.parser_add(parser) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase verbosity of log messages') args = parser.parse_args() logging.basicConfig(level=logging.ERROR - (args.verbose * 10)) del args.verbose cnf.parser_set(args) comp.set_config(cnf) comp.start()<|fim▁hole|> app.exec_() comp.stop() comp.join()<|fim▁end|>
<|file_name|>stage_2.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File written by pyctools-editor. Do not edit. import argparse import logging from pyctools.core.compound import Compound import pyctools.components.arithmetic import pyctools.components.qt.qtdisplay import pyctools.components.zone.zoneplategenerator class Network(object): <|fim_middle|> if __name__ == '__main__': from PyQt5 import QtCore, QtWidgets QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtWidgets.QApplication([]) comp = Network().make() cnf = comp.get_config() parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) cnf.parser_add(parser) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase verbosity of log messages') args = parser.parse_args() logging.basicConfig(level=logging.ERROR - (args.verbose * 10)) del args.verbose cnf.parser_set(args) comp.set_config(cnf) comp.start() app.exec_() comp.stop() comp.join() <|fim▁end|>
components = \ { 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 180)*219)'}", 'pos': (200.0, 200.0)}, 'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 230)*219)'}", 'pos': (200.0, 330.0)}, 'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay', 'config': "{'framerate': 60}", 'pos': (460.0, 200.0)}, 'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2', 'config': "{'func': 'numpy.vstack((data1,data2))'}", 'pos': (330.0, 200.0)}, 'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': " "400, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 200.0)}, 'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': " "200, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 330.0)}} linkages = \ { ('clipper', 'output'): [('stacker', 'input1')], ('clipper2', 'output'): [('stacker', 'input2')], ('stacker', 'output'): [('qd', 'input')], ('zpg', 'output'): [('clipper', 'input')], ('zpg2', 'output'): [('clipper2', 'input')]} def make(self): comps = {} for name, component in self.components.items(): comps[name] = eval(component['class'])(config=eval(component['config'])) return Compound(linkages=self.linkages, **comps)
<|file_name|>stage_2.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File written by pyctools-editor. Do not edit. import argparse import logging from pyctools.core.compound import Compound import pyctools.components.arithmetic import pyctools.components.qt.qtdisplay import pyctools.components.zone.zoneplategenerator class Network(object): components = \ { 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 180)*219)'}", 'pos': (200.0, 200.0)}, 'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 230)*219)'}", 'pos': (200.0, 330.0)}, 'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay', 'config': "{'framerate': 60}", 'pos': (460.0, 200.0)}, 'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2', 'config': "{'func': 'numpy.vstack((data1,data2))'}", 'pos': (330.0, 200.0)}, 'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': " "400, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 200.0)}, 'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': " "200, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 330.0)}} linkages = \ { ('clipper', 'output'): [('stacker', 'input1')], ('clipper2', 'output'): [('stacker', 'input2')], ('stacker', 'output'): [('qd', 'input')], ('zpg', 'output'): [('clipper', 'input')], ('zpg2', 'output'): [('clipper2', 'input')]} def make(self): <|fim_middle|> if __name__ == '__main__': from PyQt5 import QtCore, QtWidgets QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtWidgets.QApplication([]) comp = Network().make() cnf = comp.get_config() parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) cnf.parser_add(parser) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase verbosity of log messages') args = parser.parse_args() logging.basicConfig(level=logging.ERROR - (args.verbose * 10)) del args.verbose cnf.parser_set(args) comp.set_config(cnf) comp.start() app.exec_() comp.stop() comp.join() <|fim▁end|>
comps = {} for name, component in self.components.items(): comps[name] = eval(component['class'])(config=eval(component['config'])) return Compound(linkages=self.linkages, **comps)
<|file_name|>stage_2.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File written by pyctools-editor. Do not edit. import argparse import logging from pyctools.core.compound import Compound import pyctools.components.arithmetic import pyctools.components.qt.qtdisplay import pyctools.components.zone.zoneplategenerator class Network(object): components = \ { 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 180)*219)'}", 'pos': (200.0, 200.0)}, 'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 230)*219)'}", 'pos': (200.0, 330.0)}, 'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay', 'config': "{'framerate': 60}", 'pos': (460.0, 200.0)}, 'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2', 'config': "{'func': 'numpy.vstack((data1,data2))'}", 'pos': (330.0, 200.0)}, 'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': " "400, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 200.0)}, 'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': " "200, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 330.0)}} linkages = \ { ('clipper', 'output'): [('stacker', 'input1')], ('clipper2', 'output'): [('stacker', 'input2')], ('stacker', 'output'): [('qd', 'input')], ('zpg', 'output'): [('clipper', 'input')], ('zpg2', 'output'): [('clipper2', 'input')]} def make(self): comps = {} for name, component in self.components.items(): comps[name] = eval(component['class'])(config=eval(component['config'])) return Compound(linkages=self.linkages, **comps) if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
from PyQt5 import QtCore, QtWidgets QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtWidgets.QApplication([]) comp = Network().make() cnf = comp.get_config() parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) cnf.parser_add(parser) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase verbosity of log messages') args = parser.parse_args() logging.basicConfig(level=logging.ERROR - (args.verbose * 10)) del args.verbose cnf.parser_set(args) comp.set_config(cnf) comp.start() app.exec_() comp.stop() comp.join()
<|file_name|>stage_2.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File written by pyctools-editor. Do not edit. import argparse import logging from pyctools.core.compound import Compound import pyctools.components.arithmetic import pyctools.components.qt.qtdisplay import pyctools.components.zone.zoneplategenerator class Network(object): components = \ { 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 180)*219)'}", 'pos': (200.0, 200.0)}, 'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 230)*219)'}", 'pos': (200.0, 330.0)}, 'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay', 'config': "{'framerate': 60}", 'pos': (460.0, 200.0)}, 'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2', 'config': "{'func': 'numpy.vstack((data1,data2))'}", 'pos': (330.0, 200.0)}, 'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': " "400, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 200.0)}, 'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': " "200, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 330.0)}} linkages = \ { ('clipper', 'output'): [('stacker', 'input1')], ('clipper2', 'output'): [('stacker', 'input2')], ('stacker', 'output'): [('qd', 'input')], ('zpg', 'output'): [('clipper', 'input')], ('zpg2', 'output'): [('clipper2', 'input')]} def <|fim_middle|>(self): comps = {} for name, component in self.components.items(): comps[name] = eval(component['class'])(config=eval(component['config'])) return Compound(linkages=self.linkages, **comps) if __name__ == '__main__': from PyQt5 import QtCore, QtWidgets QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtWidgets.QApplication([]) comp = Network().make() cnf = comp.get_config() parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) cnf.parser_add(parser) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase verbosity of log messages') args = parser.parse_args() logging.basicConfig(level=logging.ERROR - (args.verbose * 10)) del args.verbose cnf.parser_set(args) comp.set_config(cnf) comp.start() app.exec_() comp.stop() comp.join() <|fim▁end|>
make
<|file_name|>generate-chains.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. <|fim▁hole|>"""Valid certificate chain where the target certificate contains a public key with a 512-bit modulus (weak).""" import sys sys.path += ['../..'] import gencerts # Self-signed root certificate. root = gencerts.create_self_signed_root_certificate('Root') # Intermediate intermediate = gencerts.create_intermediate_certificate('Intermediate', root) # Target certificate. target = gencerts.create_end_entity_certificate('Target', intermediate) target.set_key(gencerts.get_or_generate_rsa_key( 512, gencerts.create_key_path(target.name))) chain = [target, intermediate, root] gencerts.write_chain(__doc__, chain, 'chain.pem')<|fim▁end|>
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0<|fim▁hole|> l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main()<|fim▁end|>
for i in xrange(N):
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): <|fim_middle|> if __name__ == '__main__': unittest.main() <|fim▁end|>
def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness))
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): <|fim_middle|> ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
self.nn = FLANN(log_level="warning")
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): <|fim_middle|> def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
self.__nd_random_test_autotune(2, 2)
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): <|fim_middle|> def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
self.__nd_random_test_autotune(2, 1000)
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): <|fim_middle|> def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
self.__nd_random_test_autotune(100, 1000)
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): <|fim_middle|> # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
self.__nd_random_test_autotune(500, 100)
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): <|fim_middle|> def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
self.__nd_random_test_autotune(1, 1)
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): <|fim_middle|> def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
if type(arg)!=list: return [arg] else: return arg
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): <|fim_middle|> if __name__ == '__main__': unittest.main() <|fim▁end|>
""" Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness))
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: <|fim_middle|> else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
return [arg]
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: <|fim_middle|> def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
return arg
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
unittest.main()
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def <|fim_middle|>(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
setUp
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def <|fim_middle|>(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_nn_2d_10pt
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def <|fim_middle|>(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_nn_autotune_2d_1000pt
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def <|fim_middle|>(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_nn_autotune_100d_1000pt
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def <|fim_middle|>(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_nn_autotune_500d_100pt
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def <|fim_middle|>(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_nn_stress_1d_1pt_kmeans_autotune
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def <|fim_middle|>(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
__ensure_list
<|file_name|>test_nn_autotune.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def <|fim_middle|>(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() <|fim▁end|>
__nd_random_test_autotune
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls.defaults import * urlpatterns = patterns('member.views', url(r'^$', 'login', name='passport_index'),<|fim▁hole|> url(r'^forget/$', 'forget', name='passport_forget'), url(r'^profile/$', 'profile', name='passport_profile'), )<|fim▁end|>
url(r'^register/$', 'register', name='passport_register'), url(r'^login/$', 'login', name='passport_login'), url(r'^logout/$', 'logout', name='passport_logout'), url(r'^active/$', 'active', name='passport_active'),
<|file_name|>brian2_benchmark_CUBA_nosyn_250.py<|end_file_name|><|fim▁begin|>""" # Notes: - This simulation seeks to emulate the CUBA benchmark simulations of (Brette et al. 2007) using the Brian2 simulator for speed benchmark comparison to DynaSim. However, this simulation does NOT include synapses, for better comparison to Figure 5 of (Goodman and Brette, 2008). - The time taken to simulate will be indicated in the stdout log file '~/batchdirs/brian_benchmark_CUBA_nosyn_250/pbsout/brian_benchmark_CUBA_nosyn_250.out' - Note that this code has been slightly modified from the original (Brette et al. 2007) benchmarking code, available here on ModelDB: https://senselab.med.yale.edu/modeldb/showModel.cshtml?model=83319 in order to work with version 2 of the Brian simulator (aka Brian2), and also modified to change the model being benchmarked, etc. # References: - Brette R, Rudolph M, Carnevale T, Hines M, Beeman D, Bower JM, et al. Simulation of networks of spiking neurons: A review of tools and strategies. Journal of Computational Neuroscience 2007;23:349–98. doi:10.1007/s10827-007-0038-6. - Goodman D, Brette R. Brian: a simulator for spiking neural networks in Python. Frontiers in Neuroinformatics 2008;2. doi:10.3389/neuro.11.005.2008. """ from brian2 import * # Parameters cells = 250 defaultclock.dt = 0.01*ms taum=20*ms Vt = -50*mV Vr = -60*mV El = -49*mV # The model<|fim▁hole|>''') P = NeuronGroup(cells, model=eqs,threshold="v>Vt",reset="v=Vr",refractory=5*ms, method='euler') proportion=int(0.8*cells) Pe = P[:proportion] Pi = P[proportion:] # Initialization P.v = Vr # Record a few traces trace = StateMonitor(P, 'v', record=[1, 10, 100]) totaldata = StateMonitor(P, 'v', record=True) run(0.5 * second, report='text') # plot(trace.t/ms, trace[1].v/mV) # plot(trace.t/ms, trace[10].v/mV) # plot(trace.t/ms, trace[100].v/mV) # xlabel('t (ms)') # ylabel('v (mV)') # show() # print("Saving TC cell voltages!") # numpy.savetxt("foo_totaldata.csv", totaldata.v/mV, delimiter=",")<|fim▁end|>
eqs = Equations(''' dv/dt = ((v-El))/taum : volt
<|file_name|>density_calc.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import math fin = open('figs/single-rod-in-water.dat', 'r') fout = open('figs/single-rods-calculated-density.dat', 'w') kB = 3.16681539628059e-6 # This is Boltzmann's constant in Hartree/Kelvin first = 1 nm = 18.8972613 for line in fin: current = str(line) pieces = current.split('\t')<|fim▁hole|> if first: r2 = float(pieces[0])/2*nm E2 = float(pieces[1]) first = 0 else: if ((float(pieces[0])/2*nm - r2) > 0.25): r1 = r2 r2 = float(pieces[0])/2*nm E1 = E2 E2 = float(pieces[1]) # actually it's energy per unit length! length = 1 # arbitrary r = (r1 + r2)/2 dEdR = (E2-E1)/(r2-r1)*length area = 2*math.pi*r*length force = dEdR pressure = force/area kT = kB*298 # about this ncontact = pressure/kT fout.write(str(r)+'\t'+str(ncontact)+'\n') fin.close() fout.close()<|fim▁end|>
<|file_name|>density_calc.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import math fin = open('figs/single-rod-in-water.dat', 'r') fout = open('figs/single-rods-calculated-density.dat', 'w') kB = 3.16681539628059e-6 # This is Boltzmann's constant in Hartree/Kelvin first = 1 nm = 18.8972613 for line in fin: current = str(line) pieces = current.split('\t') if first: <|fim_middle|> else: if ((float(pieces[0])/2*nm - r2) > 0.25): r1 = r2 r2 = float(pieces[0])/2*nm E1 = E2 E2 = float(pieces[1]) # actually it's energy per unit length! length = 1 # arbitrary r = (r1 + r2)/2 dEdR = (E2-E1)/(r2-r1)*length area = 2*math.pi*r*length force = dEdR pressure = force/area kT = kB*298 # about this ncontact = pressure/kT fout.write(str(r)+'\t'+str(ncontact)+'\n') fin.close() fout.close() <|fim▁end|>
r2 = float(pieces[0])/2*nm E2 = float(pieces[1]) first = 0
<|file_name|>density_calc.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import math fin = open('figs/single-rod-in-water.dat', 'r') fout = open('figs/single-rods-calculated-density.dat', 'w') kB = 3.16681539628059e-6 # This is Boltzmann's constant in Hartree/Kelvin first = 1 nm = 18.8972613 for line in fin: current = str(line) pieces = current.split('\t') if first: r2 = float(pieces[0])/2*nm E2 = float(pieces[1]) first = 0 else: <|fim_middle|> fin.close() fout.close() <|fim▁end|>
if ((float(pieces[0])/2*nm - r2) > 0.25): r1 = r2 r2 = float(pieces[0])/2*nm E1 = E2 E2 = float(pieces[1]) # actually it's energy per unit length! length = 1 # arbitrary r = (r1 + r2)/2 dEdR = (E2-E1)/(r2-r1)*length area = 2*math.pi*r*length force = dEdR pressure = force/area kT = kB*298 # about this ncontact = pressure/kT fout.write(str(r)+'\t'+str(ncontact)+'\n')
<|file_name|>density_calc.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import math fin = open('figs/single-rod-in-water.dat', 'r') fout = open('figs/single-rods-calculated-density.dat', 'w') kB = 3.16681539628059e-6 # This is Boltzmann's constant in Hartree/Kelvin first = 1 nm = 18.8972613 for line in fin: current = str(line) pieces = current.split('\t') if first: r2 = float(pieces[0])/2*nm E2 = float(pieces[1]) first = 0 else: if ((float(pieces[0])/2*nm - r2) > 0.25): <|fim_middle|> fin.close() fout.close() <|fim▁end|>
r1 = r2 r2 = float(pieces[0])/2*nm E1 = E2 E2 = float(pieces[1]) # actually it's energy per unit length! length = 1 # arbitrary r = (r1 + r2)/2 dEdR = (E2-E1)/(r2-r1)*length area = 2*math.pi*r*length force = dEdR pressure = force/area kT = kB*298 # about this ncontact = pressure/kT fout.write(str(r)+'\t'+str(ncontact)+'\n')
<|file_name|>detector.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python #********************************************************************* # Software License Agreement (BSD License) # # Copyright (c) 2011 andrewtron3000 # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of the Willow Garage nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. #********************************************************************/ import roslib; roslib.load_manifest('face_detection') import rospy import sys import cv from cv_bridge import CvBridge from sensor_msgs.msg import Image from geometry_msgs.msg import Point from geometry_msgs.msg import PointStamped # # Instantiate a new opencv to ROS bridge adaptor # cv_bridge = CvBridge() # # Define the callback that will be called when a new image is received. # def callback(publisher, coord_publisher, cascade, imagemsg): # # Convert the ROS imagemsg to an opencv image. # image = cv_bridge.imgmsg_to_cv(imagemsg, 'mono8') # # Blur the image. # cv.Smooth(image, image, cv.CV_GAUSSIAN) # # Allocate some storage for the haar detect operation. # storage = cv.CreateMemStorage(0) # # Call the face detector function. # faces = cv.HaarDetectObjects(image, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (100,100))<|fim▁hole|> # # If faces are detected, compute the centroid of all the faces # combined. # face_centroid_x = 0.0 face_centroid_y = 0.0 if len(faces) > 0: # # For each face, draw a rectangle around it in the image, # and also add the position of the face to the centroid # of all faces combined. # for (i, n) in faces: x = int(i[0]) y = int(i[1]) width = int(i[2]) height = int(i[3]) cv.Rectangle(image, (x, y), (x + width, y + height), cv.CV_RGB(0,255,0), 3, 8, 0) face_centroid_x += float(x) + (float(width) / 2.0) face_centroid_y += float(y) + (float(height) / 2.0) # # Finish computing the face_centroid by dividing by the # number of faces found above. # face_centroid_x /= float(len(faces)) face_centroid_y /= float(len(faces)) # # Lastly, if faces were detected, publish a PointStamped # message that contains the centroid values. # pt = Point(x = face_centroid_x, y = face_centroid_y, z = 0.0) pt_stamped = PointStamped(point = pt) coord_publisher.publish(pt_stamped) # # Convert the opencv image back to a ROS image using the # cv_bridge. # newmsg = cv_bridge.cv_to_imgmsg(image, 'mono8') # # Republish the image. Note this image has boxes around # faces if faces were found. # publisher.publish(newmsg) def listener(publisher, coord_publisher): rospy.init_node('face_detector', anonymous=True) # # Load the haar cascade. Note we get the # filename from the "classifier" parameter # that is configured in the launch script. # cascadeFileName = rospy.get_param("~classifier") cascade = cv.Load(cascadeFileName) rospy.Subscriber("/stereo/left/image_rect", Image, lambda image: callback(publisher, coord_publisher, cascade, image)) rospy.spin() # This is called first. if __name__ == '__main__': publisher = rospy.Publisher('face_view', Image) coord_publisher = rospy.Publisher('face_coords', PointStamped) listener(publisher, coord_publisher)<|fim▁end|>
<|file_name|>detector.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python #********************************************************************* # Software License Agreement (BSD License) # # Copyright (c) 2011 andrewtron3000 # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of the Willow Garage nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. #********************************************************************/ import roslib; roslib.load_manifest('face_detection') import rospy import sys import cv from cv_bridge import CvBridge from sensor_msgs.msg import Image from geometry_msgs.msg import Point from geometry_msgs.msg import PointStamped # # Instantiate a new opencv to ROS bridge adaptor # cv_bridge = CvBridge() # # Define the callback that will be called when a new image is received. # def callback(publisher, coord_publisher, cascade, imagemsg): # # Convert the ROS imagemsg to an opencv image. # <|fim_middle|> def listener(publisher, coord_publisher): rospy.init_node('face_detector', anonymous=True) # # Load the haar cascade. Note we get the # filename from the "classifier" parameter # that is configured in the launch script. # cascadeFileName = rospy.get_param("~classifier") cascade = cv.Load(cascadeFileName) rospy.Subscriber("/stereo/left/image_rect", Image, lambda image: callback(publisher, coord_publisher, cascade, image)) rospy.spin() # This is called first. if __name__ == '__main__': publisher = rospy.Publisher('face_view', Image) coord_publisher = rospy.Publisher('face_coords', PointStamped) listener(publisher, coord_publisher) <|fim▁end|>
image = cv_bridge.imgmsg_to_cv(imagemsg, 'mono8') # # Blur the image. # cv.Smooth(image, image, cv.CV_GAUSSIAN) # # Allocate some storage for the haar detect operation. # storage = cv.CreateMemStorage(0) # # Call the face detector function. # faces = cv.HaarDetectObjects(image, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (100,100)) # # If faces are detected, compute the centroid of all the faces # combined. # face_centroid_x = 0.0 face_centroid_y = 0.0 if len(faces) > 0: # # For each face, draw a rectangle around it in the image, # and also add the position of the face to the centroid # of all faces combined. # for (i, n) in faces: x = int(i[0]) y = int(i[1]) width = int(i[2]) height = int(i[3]) cv.Rectangle(image, (x, y), (x + width, y + height), cv.CV_RGB(0,255,0), 3, 8, 0) face_centroid_x += float(x) + (float(width) / 2.0) face_centroid_y += float(y) + (float(height) / 2.0) # # Finish computing the face_centroid by dividing by the # number of faces found above. # face_centroid_x /= float(len(faces)) face_centroid_y /= float(len(faces)) # # Lastly, if faces were detected, publish a PointStamped # message that contains the centroid values. # pt = Point(x = face_centroid_x, y = face_centroid_y, z = 0.0) pt_stamped = PointStamped(point = pt) coord_publisher.publish(pt_stamped) # # Convert the opencv image back to a ROS image using the # cv_bridge. # newmsg = cv_bridge.cv_to_imgmsg(image, 'mono8') # # Republish the image. Note this image has boxes around # faces if faces were found. # publisher.publish(newmsg)
<|file_name|>detector.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python #********************************************************************* # Software License Agreement (BSD License) # # Copyright (c) 2011 andrewtron3000 # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of the Willow Garage nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. #********************************************************************/ import roslib; roslib.load_manifest('face_detection') import rospy import sys import cv from cv_bridge import CvBridge from sensor_msgs.msg import Image from geometry_msgs.msg import Point from geometry_msgs.msg import PointStamped # # Instantiate a new opencv to ROS bridge adaptor # cv_bridge = CvBridge() # # Define the callback that will be called when a new image is received. # def callback(publisher, coord_publisher, cascade, imagemsg): # # Convert the ROS imagemsg to an opencv image. # image = cv_bridge.imgmsg_to_cv(imagemsg, 'mono8') # # Blur the image. # cv.Smooth(image, image, cv.CV_GAUSSIAN) # # Allocate some storage for the haar detect operation. # storage = cv.CreateMemStorage(0) # # Call the face detector function. # faces = cv.HaarDetectObjects(image, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (100,100)) # # If faces are detected, compute the centroid of all the faces # combined. # face_centroid_x = 0.0 face_centroid_y = 0.0 if len(faces) > 0: # # For each face, draw a rectangle around it in the image, # and also add the position of the face to the centroid # of all faces combined. # for (i, n) in faces: x = int(i[0]) y = int(i[1]) width = int(i[2]) height = int(i[3]) cv.Rectangle(image, (x, y), (x + width, y + height), cv.CV_RGB(0,255,0), 3, 8, 0) face_centroid_x += float(x) + (float(width) / 2.0) face_centroid_y += float(y) + (float(height) / 2.0) # # Finish computing the face_centroid by dividing by the # number of faces found above. # face_centroid_x /= float(len(faces)) face_centroid_y /= float(len(faces)) # # Lastly, if faces were detected, publish a PointStamped # message that contains the centroid values. # pt = Point(x = face_centroid_x, y = face_centroid_y, z = 0.0) pt_stamped = PointStamped(point = pt) coord_publisher.publish(pt_stamped) # # Convert the opencv image back to a ROS image using the # cv_bridge. # newmsg = cv_bridge.cv_to_imgmsg(image, 'mono8') # # Republish the image. Note this image has boxes around # faces if faces were found. # publisher.publish(newmsg) def listener(publisher, coord_publisher): <|fim_middle|> # This is called first. if __name__ == '__main__': publisher = rospy.Publisher('face_view', Image) coord_publisher = rospy.Publisher('face_coords', PointStamped) listener(publisher, coord_publisher) <|fim▁end|>
rospy.init_node('face_detector', anonymous=True) # # Load the haar cascade. Note we get the # filename from the "classifier" parameter # that is configured in the launch script. # cascadeFileName = rospy.get_param("~classifier") cascade = cv.Load(cascadeFileName) rospy.Subscriber("/stereo/left/image_rect", Image, lambda image: callback(publisher, coord_publisher, cascade, image)) rospy.spin()
<|file_name|>detector.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python #********************************************************************* # Software License Agreement (BSD License) # # Copyright (c) 2011 andrewtron3000 # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of the Willow Garage nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. #********************************************************************/ import roslib; roslib.load_manifest('face_detection') import rospy import sys import cv from cv_bridge import CvBridge from sensor_msgs.msg import Image from geometry_msgs.msg import Point from geometry_msgs.msg import PointStamped # # Instantiate a new opencv to ROS bridge adaptor # cv_bridge = CvBridge() # # Define the callback that will be called when a new image is received. # def callback(publisher, coord_publisher, cascade, imagemsg): # # Convert the ROS imagemsg to an opencv image. # image = cv_bridge.imgmsg_to_cv(imagemsg, 'mono8') # # Blur the image. # cv.Smooth(image, image, cv.CV_GAUSSIAN) # # Allocate some storage for the haar detect operation. # storage = cv.CreateMemStorage(0) # # Call the face detector function. # faces = cv.HaarDetectObjects(image, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (100,100)) # # If faces are detected, compute the centroid of all the faces # combined. # face_centroid_x = 0.0 face_centroid_y = 0.0 if len(faces) > 0: # # For each face, draw a rectangle around it in the image, # and also add the position of the face to the centroid # of all faces combined. # <|fim_middle|> # # Convert the opencv image back to a ROS image using the # cv_bridge. # newmsg = cv_bridge.cv_to_imgmsg(image, 'mono8') # # Republish the image. Note this image has boxes around # faces if faces were found. # publisher.publish(newmsg) def listener(publisher, coord_publisher): rospy.init_node('face_detector', anonymous=True) # # Load the haar cascade. Note we get the # filename from the "classifier" parameter # that is configured in the launch script. # cascadeFileName = rospy.get_param("~classifier") cascade = cv.Load(cascadeFileName) rospy.Subscriber("/stereo/left/image_rect", Image, lambda image: callback(publisher, coord_publisher, cascade, image)) rospy.spin() # This is called first. if __name__ == '__main__': publisher = rospy.Publisher('face_view', Image) coord_publisher = rospy.Publisher('face_coords', PointStamped) listener(publisher, coord_publisher) <|fim▁end|>
for (i, n) in faces: x = int(i[0]) y = int(i[1]) width = int(i[2]) height = int(i[3]) cv.Rectangle(image, (x, y), (x + width, y + height), cv.CV_RGB(0,255,0), 3, 8, 0) face_centroid_x += float(x) + (float(width) / 2.0) face_centroid_y += float(y) + (float(height) / 2.0) # # Finish computing the face_centroid by dividing by the # number of faces found above. # face_centroid_x /= float(len(faces)) face_centroid_y /= float(len(faces)) # # Lastly, if faces were detected, publish a PointStamped # message that contains the centroid values. # pt = Point(x = face_centroid_x, y = face_centroid_y, z = 0.0) pt_stamped = PointStamped(point = pt) coord_publisher.publish(pt_stamped)
<|file_name|>detector.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python #********************************************************************* # Software License Agreement (BSD License) # # Copyright (c) 2011 andrewtron3000 # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of the Willow Garage nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. #********************************************************************/ import roslib; roslib.load_manifest('face_detection') import rospy import sys import cv from cv_bridge import CvBridge from sensor_msgs.msg import Image from geometry_msgs.msg import Point from geometry_msgs.msg import PointStamped # # Instantiate a new opencv to ROS bridge adaptor # cv_bridge = CvBridge() # # Define the callback that will be called when a new image is received. # def callback(publisher, coord_publisher, cascade, imagemsg): # # Convert the ROS imagemsg to an opencv image. # image = cv_bridge.imgmsg_to_cv(imagemsg, 'mono8') # # Blur the image. # cv.Smooth(image, image, cv.CV_GAUSSIAN) # # Allocate some storage for the haar detect operation. # storage = cv.CreateMemStorage(0) # # Call the face detector function. # faces = cv.HaarDetectObjects(image, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (100,100)) # # If faces are detected, compute the centroid of all the faces # combined. # face_centroid_x = 0.0 face_centroid_y = 0.0 if len(faces) > 0: # # For each face, draw a rectangle around it in the image, # and also add the position of the face to the centroid # of all faces combined. # for (i, n) in faces: x = int(i[0]) y = int(i[1]) width = int(i[2]) height = int(i[3]) cv.Rectangle(image, (x, y), (x + width, y + height), cv.CV_RGB(0,255,0), 3, 8, 0) face_centroid_x += float(x) + (float(width) / 2.0) face_centroid_y += float(y) + (float(height) / 2.0) # # Finish computing the face_centroid by dividing by the # number of faces found above. # face_centroid_x /= float(len(faces)) face_centroid_y /= float(len(faces)) # # Lastly, if faces were detected, publish a PointStamped # message that contains the centroid values. # pt = Point(x = face_centroid_x, y = face_centroid_y, z = 0.0) pt_stamped = PointStamped(point = pt) coord_publisher.publish(pt_stamped) # # Convert the opencv image back to a ROS image using the # cv_bridge. # newmsg = cv_bridge.cv_to_imgmsg(image, 'mono8') # # Republish the image. Note this image has boxes around # faces if faces were found. # publisher.publish(newmsg) def listener(publisher, coord_publisher): rospy.init_node('face_detector', anonymous=True) # # Load the haar cascade. Note we get the # filename from the "classifier" parameter # that is configured in the launch script. # cascadeFileName = rospy.get_param("~classifier") cascade = cv.Load(cascadeFileName) rospy.Subscriber("/stereo/left/image_rect", Image, lambda image: callback(publisher, coord_publisher, cascade, image)) rospy.spin() # This is called first. if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
publisher = rospy.Publisher('face_view', Image) coord_publisher = rospy.Publisher('face_coords', PointStamped) listener(publisher, coord_publisher)
<|file_name|>detector.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python #********************************************************************* # Software License Agreement (BSD License) # # Copyright (c) 2011 andrewtron3000 # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of the Willow Garage nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. #********************************************************************/ import roslib; roslib.load_manifest('face_detection') import rospy import sys import cv from cv_bridge import CvBridge from sensor_msgs.msg import Image from geometry_msgs.msg import Point from geometry_msgs.msg import PointStamped # # Instantiate a new opencv to ROS bridge adaptor # cv_bridge = CvBridge() # # Define the callback that will be called when a new image is received. # def <|fim_middle|>(publisher, coord_publisher, cascade, imagemsg): # # Convert the ROS imagemsg to an opencv image. # image = cv_bridge.imgmsg_to_cv(imagemsg, 'mono8') # # Blur the image. # cv.Smooth(image, image, cv.CV_GAUSSIAN) # # Allocate some storage for the haar detect operation. # storage = cv.CreateMemStorage(0) # # Call the face detector function. # faces = cv.HaarDetectObjects(image, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (100,100)) # # If faces are detected, compute the centroid of all the faces # combined. # face_centroid_x = 0.0 face_centroid_y = 0.0 if len(faces) > 0: # # For each face, draw a rectangle around it in the image, # and also add the position of the face to the centroid # of all faces combined. # for (i, n) in faces: x = int(i[0]) y = int(i[1]) width = int(i[2]) height = int(i[3]) cv.Rectangle(image, (x, y), (x + width, y + height), cv.CV_RGB(0,255,0), 3, 8, 0) face_centroid_x += float(x) + (float(width) / 2.0) face_centroid_y += float(y) + (float(height) / 2.0) # # Finish computing the face_centroid by dividing by the # number of faces found above. # face_centroid_x /= float(len(faces)) face_centroid_y /= float(len(faces)) # # Lastly, if faces were detected, publish a PointStamped # message that contains the centroid values. # pt = Point(x = face_centroid_x, y = face_centroid_y, z = 0.0) pt_stamped = PointStamped(point = pt) coord_publisher.publish(pt_stamped) # # Convert the opencv image back to a ROS image using the # cv_bridge. # newmsg = cv_bridge.cv_to_imgmsg(image, 'mono8') # # Republish the image. Note this image has boxes around # faces if faces were found. # publisher.publish(newmsg) def listener(publisher, coord_publisher): rospy.init_node('face_detector', anonymous=True) # # Load the haar cascade. Note we get the # filename from the "classifier" parameter # that is configured in the launch script. # cascadeFileName = rospy.get_param("~classifier") cascade = cv.Load(cascadeFileName) rospy.Subscriber("/stereo/left/image_rect", Image, lambda image: callback(publisher, coord_publisher, cascade, image)) rospy.spin() # This is called first. if __name__ == '__main__': publisher = rospy.Publisher('face_view', Image) coord_publisher = rospy.Publisher('face_coords', PointStamped) listener(publisher, coord_publisher) <|fim▁end|>
callback
<|file_name|>detector.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python #********************************************************************* # Software License Agreement (BSD License) # # Copyright (c) 2011 andrewtron3000 # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of the Willow Garage nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. #********************************************************************/ import roslib; roslib.load_manifest('face_detection') import rospy import sys import cv from cv_bridge import CvBridge from sensor_msgs.msg import Image from geometry_msgs.msg import Point from geometry_msgs.msg import PointStamped # # Instantiate a new opencv to ROS bridge adaptor # cv_bridge = CvBridge() # # Define the callback that will be called when a new image is received. # def callback(publisher, coord_publisher, cascade, imagemsg): # # Convert the ROS imagemsg to an opencv image. # image = cv_bridge.imgmsg_to_cv(imagemsg, 'mono8') # # Blur the image. # cv.Smooth(image, image, cv.CV_GAUSSIAN) # # Allocate some storage for the haar detect operation. # storage = cv.CreateMemStorage(0) # # Call the face detector function. # faces = cv.HaarDetectObjects(image, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (100,100)) # # If faces are detected, compute the centroid of all the faces # combined. # face_centroid_x = 0.0 face_centroid_y = 0.0 if len(faces) > 0: # # For each face, draw a rectangle around it in the image, # and also add the position of the face to the centroid # of all faces combined. # for (i, n) in faces: x = int(i[0]) y = int(i[1]) width = int(i[2]) height = int(i[3]) cv.Rectangle(image, (x, y), (x + width, y + height), cv.CV_RGB(0,255,0), 3, 8, 0) face_centroid_x += float(x) + (float(width) / 2.0) face_centroid_y += float(y) + (float(height) / 2.0) # # Finish computing the face_centroid by dividing by the # number of faces found above. # face_centroid_x /= float(len(faces)) face_centroid_y /= float(len(faces)) # # Lastly, if faces were detected, publish a PointStamped # message that contains the centroid values. # pt = Point(x = face_centroid_x, y = face_centroid_y, z = 0.0) pt_stamped = PointStamped(point = pt) coord_publisher.publish(pt_stamped) # # Convert the opencv image back to a ROS image using the # cv_bridge. # newmsg = cv_bridge.cv_to_imgmsg(image, 'mono8') # # Republish the image. Note this image has boxes around # faces if faces were found. # publisher.publish(newmsg) def <|fim_middle|>(publisher, coord_publisher): rospy.init_node('face_detector', anonymous=True) # # Load the haar cascade. Note we get the # filename from the "classifier" parameter # that is configured in the launch script. # cascadeFileName = rospy.get_param("~classifier") cascade = cv.Load(cascadeFileName) rospy.Subscriber("/stereo/left/image_rect", Image, lambda image: callback(publisher, coord_publisher, cascade, image)) rospy.spin() # This is called first. if __name__ == '__main__': publisher = rospy.Publisher('face_view', Image) coord_publisher = rospy.Publisher('face_coords', PointStamped) listener(publisher, coord_publisher) <|fim▁end|>
listener
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm <|fim▁hole|> def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main()<|fim▁end|>
class TestUserBlueprint(BaseTestCase):
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): <|fim_middle|> if __name__ == "__main__": unittest.main() <|fim▁end|>
def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200)
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. <|fim_middle|> def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200)
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. <|fim_middle|> def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active)
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. <|fim_middle|> def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data)
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. <|fim_middle|> def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data)
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. <|fim_middle|> def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate())
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. <|fim_middle|> def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate())
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. <|fim_middle|> def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1)
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. <|fim_middle|> def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime)
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. <|fim_middle|> def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar"))
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. <|fim_middle|> def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data)
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. <|fim_middle|> def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data)
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. <|fim_middle|> if __name__ == "__main__": unittest.main() <|fim▁end|>
with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200)
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
unittest.main()
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def <|fim_middle|>(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
test_correct_login
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def <|fim_middle|>(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
test_logout_behaves_correctly
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def <|fim_middle|>(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
test_logout_route_requires_login
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def <|fim_middle|>(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
test_member_route_requires_login
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def <|fim_middle|>(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
test_validate_success_login_form
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def <|fim_middle|>(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
test_validate_invalid_email_format
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def <|fim_middle|>(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
test_get_by_id
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def <|fim_middle|>(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
test_registered_on_defaults_to_datetime
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def <|fim_middle|>(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
test_check_password
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def <|fim_middle|>(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
test_validate_invalid_password
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def <|fim_middle|>(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
test_register_route
<|file_name|>test_user.py<|end_file_name|><|fim▁begin|># project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def <|fim_middle|>(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main() <|fim▁end|>
test_user_registration
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:] def render(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view)<|fim▁hole|> else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return "" register.tag('view', ViewNode)<|fim▁end|>
except: if settings.TEMPLATE_DEBUG: raise
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): <|fim_middle|> register.tag('view', ViewNode) <|fim▁end|>
def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:] def render(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: raise else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return ""
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): <|fim_middle|> def render(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: raise else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return "" register.tag('view', ViewNode) <|fim▁end|>
self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:]
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:] def render(self, context): <|fim_middle|> register.tag('view', ViewNode) <|fim▁end|>
print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: raise else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return ""
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: <|fim_middle|> tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:] def render(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: raise else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return "" register.tag('view', ViewNode) <|fim▁end|>
raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0])
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: <|fim_middle|> else: self.kwargs[str(token[:equals])] = token[equals + 1:] def render(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: raise else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return "" register.tag('view', ViewNode) <|fim▁end|>
self.args.append(token)
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: <|fim_middle|> def render(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: raise else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return "" register.tag('view', ViewNode) <|fim▁end|>
self.kwargs[str(token[:equals])] = token[equals + 1:]
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:] def render(self, context): print('render view tag...') if 'request' not in context: <|fim_middle|> request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: raise else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return "" register.tag('view', ViewNode) <|fim▁end|>
return ""
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:] def render(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this <|fim_middle|> else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return "" register.tag('view', ViewNode) <|fim▁end|>
urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: raise
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:] def render(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): <|fim_middle|> raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: raise else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return "" register.tag('view', ViewNode) <|fim▁end|>
ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:] def render(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: <|fim_middle|> else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return "" register.tag('view', ViewNode) <|fim▁end|>
raise
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:] def render(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: raise else: <|fim_middle|> return "" register.tag('view', ViewNode) <|fim▁end|>
print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url}
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def <|fim_middle|>(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:] def render(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: raise else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return "" register.tag('view', ViewNode) <|fim▁end|>
__init__
<|file_name|>view_tag.py<|end_file_name|><|fim▁begin|>from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:] def <|fim_middle|>(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: raise else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return "" register.tag('view', ViewNode) <|fim▁end|>
render
<|file_name|>cnos_factory.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) __metaclass__ = type # # Copyright (C) 2017 Lenovo, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # Module to Reset to factory settings of Lenovo Switches # Lenovo Networking # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cnos_factory author: "Anil Kumar Muraleedharan (@amuraleedhar)" short_description: Reset the switch's startup configuration to default (factory) on devices running Lenovo CNOS description: - This module allows you to reset a switch's startup configuration. The method provides a way to reset the startup configuration to its factory settings. This is helpful when you want to move the switch to another topology as a new network device. This module uses SSH to manage network device configuration. The results of the operation can be viewed in results directory. For more information about this module from Lenovo and customizing it usage for your use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_factory.html) version_added: "2.3" extends_documentation_fragment: cnos options: {} ''' EXAMPLES = ''' Tasks : The following are examples of using the module cnos_reload. These are written in the main.yml file of the tasks directory. --- - name: Test Reset to factory cnos_factory: host: "{{ inventory_hostname }}" username: "{{ hostvars[inventory_hostname]['ansible_ssh_user'] }}" password: "{{ hostvars[inventory_hostname]['ansible_ssh_pass'] }}" deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}" outputfile: "./results/test_factory_{{ inventory_hostname }}_output.txt" ''' RETURN = ''' msg: description: Success or failure message returned: always type: string sample: "Switch Startup Config is Reset to factory settings" ''' import sys try: import paramiko HAS_PARAMIKO = True except ImportError: HAS_PARAMIKO = False import time import socket import array import json import time import re try: from ansible.module_utils.network.cnos import cnos HAS_LIB = True except: HAS_LIB = False from ansible.module_utils.basic import AnsibleModule from collections import defaultdict def main(): module = AnsibleModule( argument_spec=dict( outputfile=dict(required=True), host=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), enablePassword=dict(required=False, no_log=True), deviceType=dict(required=True),), supports_check_mode=False) username = module.params['username'] password = module.params['password'] enablePassword = module.params['enablePassword'] cliCommand = "save erase \n" outputfile = module.params['outputfile'] hostIP = module.params['host'] deviceType = module.params['deviceType'] output = "" if not HAS_PARAMIKO: module.fail_json(msg='paramiko is required for this module') # Create instance of SSHClient object remote_conn_pre = paramiko.SSHClient()<|fim▁hole|> remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # initiate SSH connection with the switch remote_conn_pre.connect(hostIP, username=username, password=password) time.sleep(2) # Use invoke_shell to establish an 'interactive session' remote_conn = remote_conn_pre.invoke_shell() time.sleep(2) # Enable and enter configure terminal then send command output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn) output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn) # Make terminal length = 0 output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn) # cnos.debugOutput(cliCommand) # Send the CLi command output = output + cnos.waitForDeviceResponse(cliCommand, "[n]", 2, remote_conn) output = output + cnos.waitForDeviceResponse("y" + "\n", "#", 2, remote_conn) # Save it into the file file = open(outputfile, "a") file.write(output) file.close() errorMsg = cnos.checkOutputForError(output) if(errorMsg is None): module.exit_json(changed=True, msg="Switch Startup Config is Reset to factory settings ") else: module.fail_json(msg=errorMsg) if __name__ == '__main__': main()<|fim▁end|>
# Automatically add untrusted hosts (make sure okay for security policy in your environment)
<|file_name|>cnos_factory.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) __metaclass__ = type # # Copyright (C) 2017 Lenovo, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # Module to Reset to factory settings of Lenovo Switches # Lenovo Networking # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cnos_factory author: "Anil Kumar Muraleedharan (@amuraleedhar)" short_description: Reset the switch's startup configuration to default (factory) on devices running Lenovo CNOS description: - This module allows you to reset a switch's startup configuration. The method provides a way to reset the startup configuration to its factory settings. This is helpful when you want to move the switch to another topology as a new network device. This module uses SSH to manage network device configuration. The results of the operation can be viewed in results directory. For more information about this module from Lenovo and customizing it usage for your use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_factory.html) version_added: "2.3" extends_documentation_fragment: cnos options: {} ''' EXAMPLES = ''' Tasks : The following are examples of using the module cnos_reload. These are written in the main.yml file of the tasks directory. --- - name: Test Reset to factory cnos_factory: host: "{{ inventory_hostname }}" username: "{{ hostvars[inventory_hostname]['ansible_ssh_user'] }}" password: "{{ hostvars[inventory_hostname]['ansible_ssh_pass'] }}" deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}" outputfile: "./results/test_factory_{{ inventory_hostname }}_output.txt" ''' RETURN = ''' msg: description: Success or failure message returned: always type: string sample: "Switch Startup Config is Reset to factory settings" ''' import sys try: import paramiko HAS_PARAMIKO = True except ImportError: HAS_PARAMIKO = False import time import socket import array import json import time import re try: from ansible.module_utils.network.cnos import cnos HAS_LIB = True except: HAS_LIB = False from ansible.module_utils.basic import AnsibleModule from collections import defaultdict def main(): <|fim_middle|> if __name__ == '__main__': main() <|fim▁end|>
module = AnsibleModule( argument_spec=dict( outputfile=dict(required=True), host=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), enablePassword=dict(required=False, no_log=True), deviceType=dict(required=True),), supports_check_mode=False) username = module.params['username'] password = module.params['password'] enablePassword = module.params['enablePassword'] cliCommand = "save erase \n" outputfile = module.params['outputfile'] hostIP = module.params['host'] deviceType = module.params['deviceType'] output = "" if not HAS_PARAMIKO: module.fail_json(msg='paramiko is required for this module') # Create instance of SSHClient object remote_conn_pre = paramiko.SSHClient() # Automatically add untrusted hosts (make sure okay for security policy in your environment) remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # initiate SSH connection with the switch remote_conn_pre.connect(hostIP, username=username, password=password) time.sleep(2) # Use invoke_shell to establish an 'interactive session' remote_conn = remote_conn_pre.invoke_shell() time.sleep(2) # Enable and enter configure terminal then send command output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn) output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn) # Make terminal length = 0 output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn) # cnos.debugOutput(cliCommand) # Send the CLi command output = output + cnos.waitForDeviceResponse(cliCommand, "[n]", 2, remote_conn) output = output + cnos.waitForDeviceResponse("y" + "\n", "#", 2, remote_conn) # Save it into the file file = open(outputfile, "a") file.write(output) file.close() errorMsg = cnos.checkOutputForError(output) if(errorMsg is None): module.exit_json(changed=True, msg="Switch Startup Config is Reset to factory settings ") else: module.fail_json(msg=errorMsg)
<|file_name|>cnos_factory.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) __metaclass__ = type # # Copyright (C) 2017 Lenovo, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # Module to Reset to factory settings of Lenovo Switches # Lenovo Networking # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cnos_factory author: "Anil Kumar Muraleedharan (@amuraleedhar)" short_description: Reset the switch's startup configuration to default (factory) on devices running Lenovo CNOS description: - This module allows you to reset a switch's startup configuration. The method provides a way to reset the startup configuration to its factory settings. This is helpful when you want to move the switch to another topology as a new network device. This module uses SSH to manage network device configuration. The results of the operation can be viewed in results directory. For more information about this module from Lenovo and customizing it usage for your use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_factory.html) version_added: "2.3" extends_documentation_fragment: cnos options: {} ''' EXAMPLES = ''' Tasks : The following are examples of using the module cnos_reload. These are written in the main.yml file of the tasks directory. --- - name: Test Reset to factory cnos_factory: host: "{{ inventory_hostname }}" username: "{{ hostvars[inventory_hostname]['ansible_ssh_user'] }}" password: "{{ hostvars[inventory_hostname]['ansible_ssh_pass'] }}" deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}" outputfile: "./results/test_factory_{{ inventory_hostname }}_output.txt" ''' RETURN = ''' msg: description: Success or failure message returned: always type: string sample: "Switch Startup Config is Reset to factory settings" ''' import sys try: import paramiko HAS_PARAMIKO = True except ImportError: HAS_PARAMIKO = False import time import socket import array import json import time import re try: from ansible.module_utils.network.cnos import cnos HAS_LIB = True except: HAS_LIB = False from ansible.module_utils.basic import AnsibleModule from collections import defaultdict def main(): module = AnsibleModule( argument_spec=dict( outputfile=dict(required=True), host=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), enablePassword=dict(required=False, no_log=True), deviceType=dict(required=True),), supports_check_mode=False) username = module.params['username'] password = module.params['password'] enablePassword = module.params['enablePassword'] cliCommand = "save erase \n" outputfile = module.params['outputfile'] hostIP = module.params['host'] deviceType = module.params['deviceType'] output = "" if not HAS_PARAMIKO: <|fim_middle|> # Create instance of SSHClient object remote_conn_pre = paramiko.SSHClient() # Automatically add untrusted hosts (make sure okay for security policy in your environment) remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # initiate SSH connection with the switch remote_conn_pre.connect(hostIP, username=username, password=password) time.sleep(2) # Use invoke_shell to establish an 'interactive session' remote_conn = remote_conn_pre.invoke_shell() time.sleep(2) # Enable and enter configure terminal then send command output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn) output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn) # Make terminal length = 0 output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn) # cnos.debugOutput(cliCommand) # Send the CLi command output = output + cnos.waitForDeviceResponse(cliCommand, "[n]", 2, remote_conn) output = output + cnos.waitForDeviceResponse("y" + "\n", "#", 2, remote_conn) # Save it into the file file = open(outputfile, "a") file.write(output) file.close() errorMsg = cnos.checkOutputForError(output) if(errorMsg is None): module.exit_json(changed=True, msg="Switch Startup Config is Reset to factory settings ") else: module.fail_json(msg=errorMsg) if __name__ == '__main__': main() <|fim▁end|>
module.fail_json(msg='paramiko is required for this module')
<|file_name|>cnos_factory.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) __metaclass__ = type # # Copyright (C) 2017 Lenovo, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # Module to Reset to factory settings of Lenovo Switches # Lenovo Networking # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cnos_factory author: "Anil Kumar Muraleedharan (@amuraleedhar)" short_description: Reset the switch's startup configuration to default (factory) on devices running Lenovo CNOS description: - This module allows you to reset a switch's startup configuration. The method provides a way to reset the startup configuration to its factory settings. This is helpful when you want to move the switch to another topology as a new network device. This module uses SSH to manage network device configuration. The results of the operation can be viewed in results directory. For more information about this module from Lenovo and customizing it usage for your use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_factory.html) version_added: "2.3" extends_documentation_fragment: cnos options: {} ''' EXAMPLES = ''' Tasks : The following are examples of using the module cnos_reload. These are written in the main.yml file of the tasks directory. --- - name: Test Reset to factory cnos_factory: host: "{{ inventory_hostname }}" username: "{{ hostvars[inventory_hostname]['ansible_ssh_user'] }}" password: "{{ hostvars[inventory_hostname]['ansible_ssh_pass'] }}" deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}" outputfile: "./results/test_factory_{{ inventory_hostname }}_output.txt" ''' RETURN = ''' msg: description: Success or failure message returned: always type: string sample: "Switch Startup Config is Reset to factory settings" ''' import sys try: import paramiko HAS_PARAMIKO = True except ImportError: HAS_PARAMIKO = False import time import socket import array import json import time import re try: from ansible.module_utils.network.cnos import cnos HAS_LIB = True except: HAS_LIB = False from ansible.module_utils.basic import AnsibleModule from collections import defaultdict def main(): module = AnsibleModule( argument_spec=dict( outputfile=dict(required=True), host=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), enablePassword=dict(required=False, no_log=True), deviceType=dict(required=True),), supports_check_mode=False) username = module.params['username'] password = module.params['password'] enablePassword = module.params['enablePassword'] cliCommand = "save erase \n" outputfile = module.params['outputfile'] hostIP = module.params['host'] deviceType = module.params['deviceType'] output = "" if not HAS_PARAMIKO: module.fail_json(msg='paramiko is required for this module') # Create instance of SSHClient object remote_conn_pre = paramiko.SSHClient() # Automatically add untrusted hosts (make sure okay for security policy in your environment) remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # initiate SSH connection with the switch remote_conn_pre.connect(hostIP, username=username, password=password) time.sleep(2) # Use invoke_shell to establish an 'interactive session' remote_conn = remote_conn_pre.invoke_shell() time.sleep(2) # Enable and enter configure terminal then send command output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn) output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn) # Make terminal length = 0 output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn) # cnos.debugOutput(cliCommand) # Send the CLi command output = output + cnos.waitForDeviceResponse(cliCommand, "[n]", 2, remote_conn) output = output + cnos.waitForDeviceResponse("y" + "\n", "#", 2, remote_conn) # Save it into the file file = open(outputfile, "a") file.write(output) file.close() errorMsg = cnos.checkOutputForError(output) if(errorMsg is None): <|fim_middle|> else: module.fail_json(msg=errorMsg) if __name__ == '__main__': main() <|fim▁end|>
module.exit_json(changed=True, msg="Switch Startup Config is Reset to factory settings ")
<|file_name|>cnos_factory.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) __metaclass__ = type # # Copyright (C) 2017 Lenovo, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # Module to Reset to factory settings of Lenovo Switches # Lenovo Networking # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cnos_factory author: "Anil Kumar Muraleedharan (@amuraleedhar)" short_description: Reset the switch's startup configuration to default (factory) on devices running Lenovo CNOS description: - This module allows you to reset a switch's startup configuration. The method provides a way to reset the startup configuration to its factory settings. This is helpful when you want to move the switch to another topology as a new network device. This module uses SSH to manage network device configuration. The results of the operation can be viewed in results directory. For more information about this module from Lenovo and customizing it usage for your use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_factory.html) version_added: "2.3" extends_documentation_fragment: cnos options: {} ''' EXAMPLES = ''' Tasks : The following are examples of using the module cnos_reload. These are written in the main.yml file of the tasks directory. --- - name: Test Reset to factory cnos_factory: host: "{{ inventory_hostname }}" username: "{{ hostvars[inventory_hostname]['ansible_ssh_user'] }}" password: "{{ hostvars[inventory_hostname]['ansible_ssh_pass'] }}" deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}" outputfile: "./results/test_factory_{{ inventory_hostname }}_output.txt" ''' RETURN = ''' msg: description: Success or failure message returned: always type: string sample: "Switch Startup Config is Reset to factory settings" ''' import sys try: import paramiko HAS_PARAMIKO = True except ImportError: HAS_PARAMIKO = False import time import socket import array import json import time import re try: from ansible.module_utils.network.cnos import cnos HAS_LIB = True except: HAS_LIB = False from ansible.module_utils.basic import AnsibleModule from collections import defaultdict def main(): module = AnsibleModule( argument_spec=dict( outputfile=dict(required=True), host=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), enablePassword=dict(required=False, no_log=True), deviceType=dict(required=True),), supports_check_mode=False) username = module.params['username'] password = module.params['password'] enablePassword = module.params['enablePassword'] cliCommand = "save erase \n" outputfile = module.params['outputfile'] hostIP = module.params['host'] deviceType = module.params['deviceType'] output = "" if not HAS_PARAMIKO: module.fail_json(msg='paramiko is required for this module') # Create instance of SSHClient object remote_conn_pre = paramiko.SSHClient() # Automatically add untrusted hosts (make sure okay for security policy in your environment) remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # initiate SSH connection with the switch remote_conn_pre.connect(hostIP, username=username, password=password) time.sleep(2) # Use invoke_shell to establish an 'interactive session' remote_conn = remote_conn_pre.invoke_shell() time.sleep(2) # Enable and enter configure terminal then send command output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn) output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn) # Make terminal length = 0 output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn) # cnos.debugOutput(cliCommand) # Send the CLi command output = output + cnos.waitForDeviceResponse(cliCommand, "[n]", 2, remote_conn) output = output + cnos.waitForDeviceResponse("y" + "\n", "#", 2, remote_conn) # Save it into the file file = open(outputfile, "a") file.write(output) file.close() errorMsg = cnos.checkOutputForError(output) if(errorMsg is None): module.exit_json(changed=True, msg="Switch Startup Config is Reset to factory settings ") else: <|fim_middle|> if __name__ == '__main__': main() <|fim▁end|>
module.fail_json(msg=errorMsg)
<|file_name|>cnos_factory.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) __metaclass__ = type # # Copyright (C) 2017 Lenovo, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # Module to Reset to factory settings of Lenovo Switches # Lenovo Networking # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cnos_factory author: "Anil Kumar Muraleedharan (@amuraleedhar)" short_description: Reset the switch's startup configuration to default (factory) on devices running Lenovo CNOS description: - This module allows you to reset a switch's startup configuration. The method provides a way to reset the startup configuration to its factory settings. This is helpful when you want to move the switch to another topology as a new network device. This module uses SSH to manage network device configuration. The results of the operation can be viewed in results directory. For more information about this module from Lenovo and customizing it usage for your use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_factory.html) version_added: "2.3" extends_documentation_fragment: cnos options: {} ''' EXAMPLES = ''' Tasks : The following are examples of using the module cnos_reload. These are written in the main.yml file of the tasks directory. --- - name: Test Reset to factory cnos_factory: host: "{{ inventory_hostname }}" username: "{{ hostvars[inventory_hostname]['ansible_ssh_user'] }}" password: "{{ hostvars[inventory_hostname]['ansible_ssh_pass'] }}" deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}" outputfile: "./results/test_factory_{{ inventory_hostname }}_output.txt" ''' RETURN = ''' msg: description: Success or failure message returned: always type: string sample: "Switch Startup Config is Reset to factory settings" ''' import sys try: import paramiko HAS_PARAMIKO = True except ImportError: HAS_PARAMIKO = False import time import socket import array import json import time import re try: from ansible.module_utils.network.cnos import cnos HAS_LIB = True except: HAS_LIB = False from ansible.module_utils.basic import AnsibleModule from collections import defaultdict def main(): module = AnsibleModule( argument_spec=dict( outputfile=dict(required=True), host=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), enablePassword=dict(required=False, no_log=True), deviceType=dict(required=True),), supports_check_mode=False) username = module.params['username'] password = module.params['password'] enablePassword = module.params['enablePassword'] cliCommand = "save erase \n" outputfile = module.params['outputfile'] hostIP = module.params['host'] deviceType = module.params['deviceType'] output = "" if not HAS_PARAMIKO: module.fail_json(msg='paramiko is required for this module') # Create instance of SSHClient object remote_conn_pre = paramiko.SSHClient() # Automatically add untrusted hosts (make sure okay for security policy in your environment) remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # initiate SSH connection with the switch remote_conn_pre.connect(hostIP, username=username, password=password) time.sleep(2) # Use invoke_shell to establish an 'interactive session' remote_conn = remote_conn_pre.invoke_shell() time.sleep(2) # Enable and enter configure terminal then send command output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn) output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn) # Make terminal length = 0 output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn) # cnos.debugOutput(cliCommand) # Send the CLi command output = output + cnos.waitForDeviceResponse(cliCommand, "[n]", 2, remote_conn) output = output + cnos.waitForDeviceResponse("y" + "\n", "#", 2, remote_conn) # Save it into the file file = open(outputfile, "a") file.write(output) file.close() errorMsg = cnos.checkOutputForError(output) if(errorMsg is None): module.exit_json(changed=True, msg="Switch Startup Config is Reset to factory settings ") else: module.fail_json(msg=errorMsg) if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
main()
<|file_name|>cnos_factory.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) __metaclass__ = type # # Copyright (C) 2017 Lenovo, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # Module to Reset to factory settings of Lenovo Switches # Lenovo Networking # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cnos_factory author: "Anil Kumar Muraleedharan (@amuraleedhar)" short_description: Reset the switch's startup configuration to default (factory) on devices running Lenovo CNOS description: - This module allows you to reset a switch's startup configuration. The method provides a way to reset the startup configuration to its factory settings. This is helpful when you want to move the switch to another topology as a new network device. This module uses SSH to manage network device configuration. The results of the operation can be viewed in results directory. For more information about this module from Lenovo and customizing it usage for your use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_factory.html) version_added: "2.3" extends_documentation_fragment: cnos options: {} ''' EXAMPLES = ''' Tasks : The following are examples of using the module cnos_reload. These are written in the main.yml file of the tasks directory. --- - name: Test Reset to factory cnos_factory: host: "{{ inventory_hostname }}" username: "{{ hostvars[inventory_hostname]['ansible_ssh_user'] }}" password: "{{ hostvars[inventory_hostname]['ansible_ssh_pass'] }}" deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}" outputfile: "./results/test_factory_{{ inventory_hostname }}_output.txt" ''' RETURN = ''' msg: description: Success or failure message returned: always type: string sample: "Switch Startup Config is Reset to factory settings" ''' import sys try: import paramiko HAS_PARAMIKO = True except ImportError: HAS_PARAMIKO = False import time import socket import array import json import time import re try: from ansible.module_utils.network.cnos import cnos HAS_LIB = True except: HAS_LIB = False from ansible.module_utils.basic import AnsibleModule from collections import defaultdict def <|fim_middle|>(): module = AnsibleModule( argument_spec=dict( outputfile=dict(required=True), host=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), enablePassword=dict(required=False, no_log=True), deviceType=dict(required=True),), supports_check_mode=False) username = module.params['username'] password = module.params['password'] enablePassword = module.params['enablePassword'] cliCommand = "save erase \n" outputfile = module.params['outputfile'] hostIP = module.params['host'] deviceType = module.params['deviceType'] output = "" if not HAS_PARAMIKO: module.fail_json(msg='paramiko is required for this module') # Create instance of SSHClient object remote_conn_pre = paramiko.SSHClient() # Automatically add untrusted hosts (make sure okay for security policy in your environment) remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # initiate SSH connection with the switch remote_conn_pre.connect(hostIP, username=username, password=password) time.sleep(2) # Use invoke_shell to establish an 'interactive session' remote_conn = remote_conn_pre.invoke_shell() time.sleep(2) # Enable and enter configure terminal then send command output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn) output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn) # Make terminal length = 0 output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn) # cnos.debugOutput(cliCommand) # Send the CLi command output = output + cnos.waitForDeviceResponse(cliCommand, "[n]", 2, remote_conn) output = output + cnos.waitForDeviceResponse("y" + "\n", "#", 2, remote_conn) # Save it into the file file = open(outputfile, "a") file.write(output) file.close() errorMsg = cnos.checkOutputForError(output) if(errorMsg is None): module.exit_json(changed=True, msg="Switch Startup Config is Reset to factory settings ") else: module.fail_json(msg=errorMsg) if __name__ == '__main__': main() <|fim▁end|>
main
<|file_name|>HUnitDaughter2Woman_ConnectedLHS.py<|end_file_name|><|fim▁begin|>from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now<|fim▁hole|> super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): return True<|fim▁end|>
self.is_compiled = True
<|file_name|>HUnitDaughter2Woman_ConnectedLHS.py<|end_file_name|><|fim▁begin|>from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): <|fim_middle|> <|fim▁end|>
def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): return True
<|file_name|>HUnitDaughter2Woman_ConnectedLHS.py<|end_file_name|><|fim▁begin|>from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): <|fim_middle|> # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): return True <|fim▁end|>
""" Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ])
<|file_name|>HUnitDaughter2Woman_ConnectedLHS.py<|end_file_name|><|fim▁begin|>from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): <|fim_middle|> def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): return True <|fim▁end|>
return True
<|file_name|>HUnitDaughter2Woman_ConnectedLHS.py<|end_file_name|><|fim▁begin|>from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): <|fim_middle|> # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): return True <|fim▁end|>
return True
<|file_name|>HUnitDaughter2Woman_ConnectedLHS.py<|end_file_name|><|fim▁begin|>from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): <|fim_middle|> def constraint(self, PreNode, graph): return True <|fim▁end|>
return attr_value == "daughters"