<commit_before>from subprocess import run, CalledProcessError, PIPE
import os
from time import sleep
from pkg_resources import resource_filename

from OrthoEvol.Tools.logit import LogIt
from OrthoEvol.Tools.sge import basejobids, writecodefile, import_temp, file2str
from OrthoEvol.Tools.sge.sgeconfig import __DEFAULT__
from OrthoEvol.Manager.config import templates
from OrthoEvol.Tools.sge import Qstat

class BaseSGEJob(object):
    """Base class for simple jobs."""
    def __init__(self, base_jobname):
        """Initialize job attributes."""
        self.base_jobname = base_jobname
        self.default_job_attributes = __DEFAULT__
        self.file2str = file2str
        self.sgejob_log = LogIt().default(logname="SGE JOB", logfile=None)
        self.pbsworkdir = os.getcwd()

        # Import the temp.pbs file using pkg_resources
        self.temp_pbs = resource_filename(templates.__name__, "temp.pbs")

    @classmethod
    def _configure(cls, length, base_jobname):
        """Configure job attributes or set it up."""
        baseid, base = basejobids(length, base_jobname)
        return baseid, base

    def debug(self, code):
        """Debug the SGEJob."""
        raise NotImplementedError

    def _cleanup(self, jobname):
        """Clean up job scripts."""
        self.sgejob_log.warning('Your job will now be cleaned up.')
        os.remove(jobname + '.pbs')
        self.sgejob_log.warning('%s.pbs has been deleted.', jobname)
        os.remove(jobname + '.py')
        self.sgejob_log.warning('%s.py has been deleted.' % jobname)

    def wait_on_job_completion(self, job_id):
        """Use Qstat to monitor your job."""
        # TODO Allow either slack notifications or email or text.
        qwatch = Qstat().watch(job_id)
        if qwatch == 'Job id not found.':
            self.sgejob_log.info('%s has finished.' % job_id)
            sleep(30)
        elif qwatch == 'Waiting for %s to start running.' % job_id:
            self.sgejob_log.info('%s is queued to run.' % job_id)
            self.sgejob_log.info('Waiting for %s to start.' % job_id)
            sleep(30)
            self.wait_on_job_completion(job_id)
        elif qwatch == 'Waiting for %s to finish running.' % job_id:
            self.sgejob_log.info('%s is running.' % job_id)
            self.sgejob_log.info('Waiting for %s to finish.' % job_id)
            sleep(30)
            self.wait_on_job_completion(job_id)
        else:
            self.wait_on_job_completion(job_id)

    def submitjob(self, cleanup):
        """Submit a job using qsub."""
        try:
            cmd = ['qsub ' + self.jobname + '.pbs']  # this is the command
            # Shell MUST be True
            cmd_status = run(cmd, stdout=PIPE, stderr=PIPE, shell=True, check=True)
        except CalledProcessError as err:
            self.sgejob_log.error(err.stderr.decode('utf-8'))
            if cleanup:
                self._cleanup(self.jobname)
        else:
            if cmd_status.returncode == 0:  # Command was successful.
                # The cmd_status has stdout that must be decoded.
                # When a qsub job is submitted, the stdout is the job id.
                submitted_jobid = cmd_status.stdout.decode('utf-8')
                self.sgejob_log.info(self.jobname + ' was submitted.')
                self.sgejob_log.info('Your job id is: %s' % submitted_jobid)
                self.wait_on_job_completion(submitted_jobid)
                self._cleanup(self.jobname)

            else:  # Unsuccessful. Stdout will be '1'
                self.sgejob_log.error('PBS job not submitted.')

class SGEJob(BaseSGEJob):
    """Create a qsub/pbs job & script to submit python code."""
    def __init__(self, email_address, base_jobname=None):
        super().__init__(base_jobname=base_jobname)
        self.email = email_address
        self.attributes = self.default_job_attributes
        self.jobname = self.default_job_attributes['job_name']
        if base_jobname is not None:
            _, self.jobname = self._configure(base_jobname=base_jobname,
                                              length=5)
            self.attributes = self._update_default_attributes()

    def _update_default_attributes(self):
        pyfile_path = os.path.join(self.pbsworkdir, self.jobname + '.py')
        # These attributes are automatically updated if a jobname is given.
        new_attributes = {'email': self.email,
                          'job_name': self.jobname,
                          'outfile': self.jobname + '.o',
                          'errfile': self.jobname + '.e',
                          'script': self.jobname,
                          'log_name': self.jobname + '.log',
                          'cmd': 'python3.6 ' + pyfile_path,
                          }
        self.default_job_attributes.update(new_attributes)

        return self.default_job_attributes

    def submit_pycode(self, code, cleanup=True, default=True):
        """Create and submit a qsub job.

        Submit python code."""
        # TIP If python is in your environment as only 'python' update that.
        # If default, a python file will be created from code that is used.
        # Allow user input to be a python file
        if os.path.isfile(code) and str(code).endswith('.py'):
            code_str = self.file2str(code)
            self.sgejob_log.info('%s converted to string.' % code)
        elif type(code) == str:
            code_str = code

        if default:
            self.sgejob_log.info('You are running a job with default attributes.')
            writecodefile(filename=self.jobname, code=code_str, language='python')
            pyfilename = self.jobname + '.py'
            self.sgejob_log.info('%s has been created.' % pyfilename)

            # Create the pbs script from the template or dict
            pbstemp = import_temp(self.temp_pbs)
            pbsfilename = self.jobname + '.pbs'

            with open(pbsfilename, 'w') as pbsfile:
                pbsfile.write(pbstemp.substitute(self.attributes))
                pbsfile.close()
            self.sgejob_log.info('%s has been created.' % pbsfilename)

            # Submit the job using qsub
            self.submitjob(cleanup=cleanup)
        else:
            msg = 'Custom SGEJob creation is not yet implemented.'
            raise NotImplementedError(msg)
            # TODO Add custom job creation

        # Submit the job using qsub
        self.submitjob(cleanup=cleanup)

class MultiSGEJobs(SGEJob):
    """Create multiple qsub/pbs jobs."""
    def __init__(self, email_address):
        super().__init__(email_address=email_address, base_jobname='multi')
        _, self.jobname = self._configure(base_jobname=self.base_jobname,
                                          length=5)
        self.attributes = self._update_default_attributes()
<commit_msg>Added the wait (bool) parameter to the SGE submitjob method.<commit_after>from subprocess import run, CalledProcessError, PIPE
import os
from time import sleep
from pkg_resources import resource_filename

from OrthoEvol.Tools.logit import LogIt
from OrthoEvol.Tools.sge import basejobids, writecodefile, import_temp, file2str
from OrthoEvol.Tools.sge.sgeconfig import __DEFAULT__
from OrthoEvol.Manager.config import templates
from OrthoEvol.Tools.sge import Qstat

class BaseSGEJob(object):
    """Base class for simple jobs."""
    def __init__(self, base_jobname):
        """Initialize job attributes."""
        self.base_jobname = base_jobname
        self.default_job_attributes = __DEFAULT__
        self.file2str = file2str
        self.sgejob_log = LogIt().default(logname="SGE JOB", logfile=None)
        self.pbsworkdir = os.getcwd()

        # Import the temp.pbs file using pkg_resources
        self.temp_pbs = resource_filename(templates.__name__, "temp.pbs")

    @classmethod
    def _configure(cls, length, base_jobname):
        """Configure job attributes or set it up."""
        baseid, base = basejobids(length, base_jobname)
        return baseid, base

    def debug(self, code):
        """Debug the SGEJob."""
        raise NotImplementedError

    def _cleanup(self, jobname):
        """Clean up job scripts."""
        self.sgejob_log.warning('Your job will now be cleaned up.')
        os.remove(jobname + '.pbs')
        self.sgejob_log.warning('%s.pbs has been deleted.', jobname)
        os.remove(jobname + '.py')
        self.sgejob_log.warning('%s.py has been deleted.' % jobname)

    def wait_on_job_completion(self, job_id):
        """Use Qstat to monitor your job."""
        # TODO Allow either slack notifications or email or text.
        qwatch = Qstat().watch(job_id)
        if qwatch == 'Job id not found.':
            self.sgejob_log.info('%s has finished.' % job_id)
            sleep(30)
        elif qwatch == 'Waiting for %s to start running.' % job_id:
            self.sgejob_log.info('%s is queued to run.' % job_id)
            self.sgejob_log.info('Waiting for %s to start.' % job_id)
            sleep(30)
            self.wait_on_job_completion(job_id)
        elif qwatch == 'Waiting for %s to finish running.' % job_id:
            self.sgejob_log.info('%s is running.' % job_id)
            self.sgejob_log.info('Waiting for %s to finish.' % job_id)
            sleep(30)
            self.wait_on_job_completion(job_id)
        else:
            self.wait_on_job_completion(job_id)

    def submitjob(self, cleanup, wait=True):
        """Submit a job using qsub."""
        try:
            cmd = ['qsub ' + self.jobname + '.pbs']  # this is the command
            # Shell MUST be True
            cmd_status = run(cmd, stdout=PIPE, stderr=PIPE, shell=True, check=True)
        except CalledProcessError as err:
            self.sgejob_log.error(err.stderr.decode('utf-8'))
            if cleanup:
                self._cleanup(self.jobname)
        else:
            if cmd_status.returncode == 0:  # Command was successful.
                # The cmd_status has stdout that must be decoded.
                # When a qsub job is submitted, the stdout is the job id.
                submitted_jobid = cmd_status.stdout.decode('utf-8')
                self.sgejob_log.info(self.jobname + ' was submitted.')
                self.sgejob_log.info('Your job id is: %s' % submitted_jobid)
                if wait is True:
                    self.wait_on_job_completion(submitted_jobid)
                self._cleanup(self.jobname)

            else:  # Unsuccessful. Stdout will be '1'
                self.sgejob_log.error('PBS job not submitted.')

class SGEJob(BaseSGEJob):
    """Create a qsub/pbs job & script to submit python code."""
    def __init__(self, email_address, base_jobname=None):
        super().__init__(base_jobname=base_jobname)
        self.email = email_address
        self.attributes = self.default_job_attributes
        self.jobname = self.default_job_attributes['job_name']
        if base_jobname is not None:
            _, self.jobname = self._configure(base_jobname=base_jobname,
                                              length=5)
            self.attributes = self._update_default_attributes()

    def _update_default_attributes(self):
        pyfile_path = os.path.join(self.pbsworkdir, self.jobname + '.py')
        # These attributes are automatically updated if a jobname is given.
        new_attributes = {'email': self.email,
                          'job_name': self.jobname,
                          'outfile': self.jobname + '.o',
                          'errfile': self.jobname + '.e',
                          'script': self.jobname,
                          'log_name': self.jobname + '.log',
                          'cmd': 'python3.6 ' + pyfile_path,
                          }
        self.default_job_attributes.update(new_attributes)

        return self.default_job_attributes

    def submit_pycode(self, code, cleanup=True, default=True):
        """Create and submit a qsub job.

        Submit python code."""
        # TIP If python is in your environment as only 'python' update that.
        # If default, a python file will be created from code that is used.
        # Allow user input to be a python file
        if os.path.isfile(code) and str(code).endswith('.py'):
            code_str = self.file2str(code)
            self.sgejob_log.info('%s converted to string.' % code)
        elif type(code) == str:
            code_str = code

        if default:
            self.sgejob_log.info('You are running a job with default attributes.')
            writecodefile(filename=self.jobname, code=code_str, language='python')
            pyfilename = self.jobname + '.py'
            self.sgejob_log.info('%s has been created.' % pyfilename)

            # Create the pbs script from the template or dict
            pbstemp = import_temp(self.temp_pbs)
            pbsfilename = self.jobname + '.pbs'

            with open(pbsfilename, 'w') as pbsfile:
                pbsfile.write(pbstemp.substitute(self.attributes))
                pbsfile.close()
            self.sgejob_log.info('%s has been created.' % pbsfilename)

            # Submit the job using qsub
            self.submitjob(cleanup=cleanup)
        else:
            msg = 'Custom SGEJob creation is not yet implemented.'
            raise NotImplementedError(msg)
            # TODO Add custom job creation

        # Submit the job using qsub
        self.submitjob(cleanup=cleanup)

class MultiSGEJobs(SGEJob):
    """Create multiple qsub/pbs jobs."""
    def __init__(self, email_address):
        super().__init__(email_address=email_address, base_jobname='multi')
        _, self.jobname = self._configure(base_jobname=self.base_jobname,
                                          length=5)
        self.attributes = self._update_default_attributes()
<|endoftext|>


<commit_before>from django.contrib import admin
from core.models import Engine

admin.site.register(Engine)
<commit_msg>Added Vendor class to the admin import.<commit_after>from django.contrib import admin
from core.models import Engine, Vendor

admin.site.register(Engine)
<|endoftext|>


<commit_before>import sublime, sublime_plugin
import gspatch, margo, gscommon as gs
from os.path import dirname, relpath, basename

class Loc(object):
	def __init__(self, fn, row, col=0):
		self.fn = fn
		self.row = row
		self.col = col

class GsPaletteCommand(sublime_plugin.WindowCommand):
	def run(self, palette='auto'):
		if not hasattr(self, 'items'):
			self.items = []
			self.bookmarks = []
			self.last_activate_palette = ''
			self.requires_margo = ['declarations', 'imports']
			self.palettes = {
				'declarations': self.palette_declarations,
				'imports': self.palette_imports,
				'errors': self.palette_errors,
			}

		self.show_palette(palette)

	def show_palette(self, palette):
		view = gs.active_valid_go_view(self.window)
		if not view:
			return

		palette = palette.lower().strip()
		if palette == 'auto':
			palette = self.last_activate_palette
		elif palette == 'main':
			palette = ''

		pcb = None
		if palette:
			pcb = self.palettes.get(palette)
			if pcb:
				self.last_activate_palette = palette
			else:
				gs.notice('GsPalette', 'Invalid palette `%s`' % palette)
				palette = ''

		re_margo = ''
		if not gs.setting('margo_enabled', False):
			re_margo = 'Requires MarGo: https://github.com/DisposaBoy/MarGo'

		if len(self.bookmarks) > 0:
			loc = self.bookmarks[-1]
			line = 'line %d' % (loc.row + 1)
			if view.file_name() == loc.fn:
				fn = ''
			else:
				fn = relpath(loc.fn, dirname(loc.fn))
				if fn.startswith('..'):
					fn = loc.fn
				fn = '%s ' % fn
			self.add_item(u'\u2190 Go Back (%s%s)' % (fn, line), self.jump_back, None)

		if palette:
			self.add_item(u'@%s \u21B5' % palette.title(), self.show_palette, 'main')

		li1 = len(self.items)
		if pcb:
			pcb(view)

		for k in sorted(self.palettes.keys()):
			if k:
				if k != palette:
					ttl = '@' + k.title()
					if k == 'errors':
						l = len(gs.l_errors.get(view.id(), {}))
						if l == 0:
							continue
						ttl = '%s (%d)' % (ttl, l)
					if k in self.requires_margo and re_margo:
						itm = [ttl, re_margo]
					else:
						itm = ttl
					self.add_item(itm, self.show_palette, k)

		items = []
		actions = {}
		for tup in self.items:
			item, action, args = tup
			actions[len(items)] = (action, args)
			items.append(item)
		self.items = []

		def on_done(i):
			action, args = actions.get(i, (None, None))
			if i >= 0 and action:
				action(args)
		self.window.show_quick_panel(items, on_done)

	def add_item(self, item, action=None, args=None):
		self.items.append((item, action, args))

	def log_bookmark(self, view, loc):
		bks = self.bookmarks
		if len(bks) == 0 or (bks[-1].row != loc.row and bks[-1].fn != view.file_name()):
			bks.append(loc)

	def goto(self, loc):
		self.window.open_file('%s:%d:%d' % (loc.fn, loc.row+1, loc.col+1), sublime.ENCODED_POSITION)

	def jump_back(self, _):
		if len(self.bookmarks) > 0:
			self.goto(self.bookmarks.pop())

	def palette_errors(self, view):
		errors = gs.l_errors.get(view.id(), {})
		for k in sorted(errors.keys()):
			er = errors[k]
			loc = Loc(view.file_name(), er.row, er.col)
			self.add_item("    line %d: %s" % ((er.row+1), er.err), self.jump_to, (view, loc))

	def palette_imports(self, view):
		im, err = margo.imports(
			view.file_name(),
			view.substr(sublime.Region(0, view.size())),
			True,
			[]
		)
		if err:
			gs.notice('GsPalette', err)

		delete_imports = []
		add_imports = []
		imports = im.get('file_imports', [])
		for path in im.get('import_paths', []):
			skipAdd = False
			for i in imports:
				if i.get('path') == path:
					skipAdd = True
					name = i.get('name', '')
					if not name:
						name = basename(path)
					if name == path:
						delete_imports.append(('    %s - ( delete import )' % name, i))
					else:
						delete_imports.append(('    %s `%s` - ( delete import )' % (name, path), i))

			if not skipAdd:
				add_imports.append(('    %s' % path, {'path': path}))
		for i in sorted(delete_imports):
			self.add_item(i[0], self.toggle_import, (view, i[1]))
		self.add_item('    -', self.show_palette, 'imports')
		for i in sorted(add_imports):
			self.add_item(i[0], self.toggle_import, (view, i[1]))

	def toggle_import(self, a):
		view, decl = a
		im, err = margo.imports(
			view.file_name(),
			view.substr(sublime.Region(0, view.size())),
			False,
			[decl]
		)
		if err:
			gs.notice('GsImports', err)
		else:
			src = im.get('src', '')
			size_ref = im.get('size_ref', 0)
			if src and size_ref > 0:
				dirty, err = gspatch.merge(view, size_ref, src)
				if err:
					gs.notice_undo('GsImports', err, view, dirty)
				elif dirty:
					gs.notice('GsImports', 'imports updated...')

	def jump_to(self, a):
		view, loc = a
		row, col = gs.rowcol(view)
		if loc.row != row:
			self.log_bookmark(view, Loc(view.file_name(), row, col))
		self.goto(loc)

	def palette_declarations(self, view):
		decls, err = margo.declarations(
			view.file_name(),
			view.substr(sublime.Region(0, view.size()))
		)
		if err:
			gs.notice('GsDeclarations', err)
		decls.sort(key=lambda v: v['line'])
		for i, v in enumerate(decls):
			if v['name'] == '_':
				continue
			loc = Loc(v['filename'], v['line']-1, v['column']-1)
			prefix = u'    %s \u00B7   ' % gs.CLASS_PREFIXES.get(v['kind'], '')
			self.add_item(prefix+v['name'], self.jump_to, (view, loc))
<commit_msg>- misc change wording<commit_after>import sublime, sublime_plugin
import gspatch, margo, gscommon as gs
from os.path import dirname, relpath, basename

class Loc(object):
	def __init__(self, fn, row, col=0):
		self.fn = fn
		self.row = row
		self.col = col

class GsPaletteCommand(sublime_plugin.WindowCommand):
	def run(self, palette='auto'):
		if not hasattr(self, 'items'):
			self.items = []
			self.bookmarks = []
			self.last_activate_palette = ''
			self.requires_margo = ['declarations', 'imports']
			self.palettes = {
				'declarations': self.palette_declarations,
				'imports': self.palette_imports,
				'errors': self.palette_errors,
			}

		self.show_palette(palette)

	def show_palette(self, palette):
		view = gs.active_valid_go_view(self.window)
		if not view:
			return

		palette = palette.lower().strip()
		if palette == 'auto':
			palette = self.last_activate_palette
		elif palette == 'main':
			palette = ''

		pcb = None
		if palette:
			pcb = self.palettes.get(palette)
			if pcb:
				self.last_activate_palette = palette
			else:
				gs.notice('GsPalette', 'Invalid palette `%s`' % palette)
				palette = ''

		re_margo = ''
		if not gs.setting('margo_enabled', False):
			re_margo = 'Requires MarGo: https://github.com/DisposaBoy/MarGo'

		if len(self.bookmarks) > 0:
			loc = self.bookmarks[-1]
			line = 'line %d' % (loc.row + 1)
			if view.file_name() == loc.fn:
				fn = ''
			else:
				fn = relpath(loc.fn, dirname(loc.fn))
				if fn.startswith('..'):
					fn = loc.fn
				fn = '%s ' % fn
			self.add_item(u'\u2190 Go Back (%s%s)' % (fn, line), self.jump_back, None)

		if palette:
			self.add_item(u'@%s \u21B5' % palette.title(), self.show_palette, 'main')

		li1 = len(self.items)
		if pcb:
			pcb(view)

		for k in sorted(self.palettes.keys()):
			if k:
				if k != palette:
					ttl = '@' + k.title()
					if k == 'errors':
						l = len(gs.l_errors.get(view.id(), {}))
						if l == 0:
							continue
						ttl = '%s (%d)' % (ttl, l)
					if k in self.requires_margo and re_margo:
						itm = [ttl, re_margo]
					else:
						itm = ttl
					self.add_item(itm, self.show_palette, k)

		items = []
		actions = {}
		for tup in self.items:
			item, action, args = tup
			actions[len(items)] = (action, args)
			items.append(item)
		self.items = []

		def on_done(i):
			action, args = actions.get(i, (None, None))
			if i >= 0 and action:
				action(args)
		self.window.show_quick_panel(items, on_done)

	def add_item(self, item, action=None, args=None):
		self.items.append((item, action, args))

	def log_bookmark(self, view, loc):
		bks = self.bookmarks
		if len(bks) == 0 or (bks[-1].row != loc.row and bks[-1].fn != view.file_name()):
			bks.append(loc)

	def goto(self, loc):
		self.window.open_file('%s:%d:%d' % (loc.fn, loc.row+1, loc.col+1), sublime.ENCODED_POSITION)

	def jump_back(self, _):
		if len(self.bookmarks) > 0:
			self.goto(self.bookmarks.pop())

	def palette_errors(self, view):
		errors = gs.l_errors.get(view.id(), {})
		for k in sorted(errors.keys()):
			er = errors[k]
			loc = Loc(view.file_name(), er.row, er.col)
			self.add_item("    line %d: %s" % ((er.row+1), er.err), self.jump_to, (view, loc))

	def palette_imports(self, view):
		im, err = margo.imports(
			view.file_name(),
			view.substr(sublime.Region(0, view.size())),
			True,
			[]
		)
		if err:
			gs.notice('GsPalette', err)

		delete_imports = []
		add_imports = []
		imports = im.get('file_imports', [])
		for path in im.get('import_paths', []):
			skipAdd = False
			for i in imports:
				if i.get('path') == path:
					skipAdd = True
					name = i.get('name', '')
					if not name:
						name = basename(path)
					if name == path:
						delete_imports.append(('    %s - ( delete )' % name, i))
					else:
						delete_imports.append(('    %s - ( delete %s )' % (name, path), i))

			if not skipAdd:
				add_imports.append(('    %s' % path, {'path': path}))
		for i in sorted(delete_imports):
			self.add_item(i[0], self.toggle_import, (view, i[1]))
		self.add_item('    -', self.show_palette, 'imports')
		for i in sorted(add_imports):
			self.add_item(i[0], self.toggle_import, (view, i[1]))

	def toggle_import(self, a):
		view, decl = a
		im, err = margo.imports(
			view.file_name(),
			view.substr(sublime.Region(0, view.size())),
			False,
			[decl]
		)
		if err:
			gs.notice('GsImports', err)
		else:
			src = im.get('src', '')
			size_ref = im.get('size_ref', 0)
			if src and size_ref > 0:
				dirty, err = gspatch.merge(view, size_ref, src)
				if err:
					gs.notice_undo('GsImports', err, view, dirty)
				elif dirty:
					gs.notice('GsImports', 'imports updated...')

	def jump_to(self, a):
		view, loc = a
		row, col = gs.rowcol(view)
		if loc.row != row:
			self.log_bookmark(view, Loc(view.file_name(), row, col))
		self.goto(loc)

	def palette_declarations(self, view):
		decls, err = margo.declarations(
			view.file_name(),
			view.substr(sublime.Region(0, view.size()))
		)
		if err:
			gs.notice('GsDeclarations', err)
		decls.sort(key=lambda v: v['line'])
		for i, v in enumerate(decls):
			if v['name'] == '_':
				continue
			loc = Loc(v['filename'], v['line']-1, v['column']-1)
			prefix = u'    %s \u00B7   ' % gs.CLASS_PREFIXES.get(v['kind'], '')
			self.add_item(prefix+v['name'], self.jump_to, (view, loc))
<|endoftext|>


<commit_before>from django.contrib import admin
from django.contrib.admin.forms import AdminAuthenticationForm
from django import forms

class NavigatorLoginForm(AdminAuthenticationForm):
    username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'}))

admin.site.login_form = NavigatorLoginForm

def get_actions_replacer(orig_func):
    def fixed_get_actions(self, request):
        """
        Remove the delete action (if present) if user does not have the
        necessary permission
        """

        # Get the base actions
        actions = orig_func(self, request)
        # Get the app label and model name to form the permission name
        app_label = self.model._meta.app_label
        model_name = self.model._meta.model_name
        perm = "%s.delete_%s" % (app_label, model_name)
        # If the user does not have the specific delete perm, remove the action
        if not request.user.has_perm(perm):
            if 'delete_selected' in actions:
                del actions['delete_selected']

        return actions
    return fixed_get_actions

admin.ModelAdmin.get_actions = get_actions_replacer(admin.ModelAdmin.get_actions)
<commit_msg>Include the thumber data on the admin interface<commit_after>from django.contrib import admin
from django.contrib.admin.forms import AdminAuthenticationForm
from django import forms

from thumber.models import ContentFeedback

class NavigatorLoginForm(AdminAuthenticationForm):
    username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'}))

admin.site.login_form = NavigatorLoginForm

def get_actions_replacer(orig_func):
    def fixed_get_actions(self, request):
        """
        Remove the delete action (if present) if user does not have the
        necessary permission
        """

        # Get the base actions
        actions = orig_func(self, request)
        # Get the app label and model name to form the permission name
        app_label = self.model._meta.app_label
        model_name = self.model._meta.model_name
        perm = "%s.delete_%s" % (app_label, model_name)
        # If the user does not have the specific delete perm, remove the action
        if not request.user.has_perm(perm):
            if 'delete_selected' in actions:
                del actions['delete_selected']

        return actions
    return fixed_get_actions

admin.ModelAdmin.get_actions = get_actions_replacer(admin.ModelAdmin.get_actions)

@admin.register(ContentFeedback)
class ContentFeedbackAdmin(admin.ModelAdmin):

    list_display = ['created', 'satisfied', 'view_name', 'comment']
    ordering = ['created']
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
Created on Tue Mar 14 09:34:17 2017

@author: lamahamadeh
"""

'''
Case Study about an introduction to kNN classifiction
'''

#Finding the Euclidean Distance Between Two Points
#---------------------------------------------------

import numpy as np

def distance(p1,p2):
    "find the distance betweeen points p1 and p2"
    return np.sqrt(np.sum(np.power(p2 - p1, 2)))

p1 = np.array([1,1])
p2 = np.array([4,4])

print (distance(p1,p2))

#------------------------------------------------------------------------------

#Majority Vote
#-------------

import random

def majority_vote(votes):
    "Return the most common element in votes"
    vote_counts = {}
    for vote in votes:
        if vote in vote_counts:
            vote_counts[vote] += 1
        else:
            vote_counts[vote] = 1
    #items method
    winners = []
    max_counts = max(vote_counts.values()) #ask Python about the frequency the most appearing value has
    for vote, count in vote_counts.items(): #this returns a tuple of (vote,count)
        if count == max_counts:
            winners.append(vote)

    return random.choice(winners) #in case of a tie situation, Python picks a random candidate (element) and returns it.

votes = [1, 2, 3, 1, 2 ,3 ,3 ,3 ,3, 2, 2, 2] #here number 2 and 3 has the same appearing frequency: 5 (tie situation)
winner = majority_vote(votes)
print (winner) #it can be seen after running the code several times that this method picks one of the candidates
#and returns it randomly.

#another method
#--------------
import scipy.stats as ss

def majority_vote_short(votes):
    "Return the most common element in votes "
    mode , count = ss.mstats.mode(votes)
    return mode

votes = [1, 2, 3, 1, 2 ,3 ,3 ,3 ,3]
winner_short = majority_vote_short(votes)
print (winner_short) # it can be seen after running the code several times that this method always
#returns number 3 as the most common candidate and forgets about the other one: 2

#------------------------------------------------------------------------------

#Finding Nearest Neighbors
#--------------------------

points = np.array([[1,1], [1,2], [1,3], [2,1], [2,2], [2,3], [3,1], [3,2], [3,3]]) #points as a vector
p = np.array([2.5,2])#a single point with coordinates: x=2.5 and y=2

#plotting the points and point p
import matplotlib.pyplot as plt

plt.plot(points[:,0], points[:,1],"ro")
plt.plot(p[0],p[1],"bo")
plt.axis([0.5, 3.5, 0.5, 3.5])

distances = np.zeros(points.shape[0])#'.shape[0]' here reutrn a tuple of array dimensions.
for i in range(len(distances)):# loop over all points
    distances[i] = distance(p,points[i]) # compute the distance between point p and every other point using the function 'distnace'

print(distances)#reutrn the distances values between all the points and the point p
print(points[4])#return the point number 4
print(distances[4])#calculate the distnace between point number 4 and point p
print(points[7])#return the point 7
print(distances[7])#calculate the distnace between point number 7 and point p

#construct a 'find_nearest_neighbor' function
def find_nearest_neighbor(p, points, k=5):
    """find the k nearest neighbors of point p nd return their indices """
    distances = np.zeros(points.shape[0])#'.shape[0]' here reutrn a tuple of array dimensions.
    for i in range(len(distances)):# loop over all points
        distances[i] = distance(p,points[i]) # compute the distance between point p and every other point using the function 'distnace'
    ind = np.argsort(distances)#'argsort' is a function to sort the distnaces from short to long.
    #np.argsort(distances) It sorts an array according to a single argument and returns the sorted indices
    return ind[0:k] # or for short ind[:k]. This step is to return those k points that are nearest to point p

ind = find_nearest_neighbor(p, points, 2); print(points[ind])# return the first 2 nearest neighbors
ind = find_nearest_neighbor(p, points, 3); print(points[ind])# return the first 3 nearest neighbors
ind = find_nearest_neighbor(p, points, 4); print(points[ind])# return the first 4 nearest neighbors

#construct a 'knn_predict' function
def knn_predict(p, points, outcomes, k=5):
    #find k nearest neighbors
    ind = find_nearest_neighbor(p, points, k)
    return majority_vote(outcomes[ind])
    #predict the class/ categroy of p based on majority vote

outcomes = np.array([0,0,0,0,1,1,1,1,1]) # classes definition

print(len(outcomes))

print(knn_predict(np.array([2.5, 2.7]), points, outcomes, k=2)) #class 1
print(knn_predict(np.array([1.0, 2.7]), points, outcomes, k=2)) #class 0

#------------------------------------------------------------------------------

#Generating Synthetic Data
#-------------------------

#------------------------------------------------------------------------------
<commit_msg>Update kNN_Classification.py<commit_after># -*- coding: utf-8 -*-
"""
Created on Tue Mar 14 09:34:17 2017

@author: lamahamadeh
"""

'''
Case Study about an introduction to kNN classifiction
'''

#Finding the Euclidean Distance Between Two Points
#---------------------------------------------------

import numpy as np

def distance(p1,p2):
    "find the distance betweeen points p1 and p2"
    return np.sqrt(np.sum(np.power(p2 - p1, 2)))

p1 = np.array([1,1])
p2 = np.array([4,4])

print (distance(p1,p2))

#------------------------------------------------------------------------------

#Majority Vote
#-------------

import random

def majority_vote(votes):
    "Return the most common element in votes"
    vote_counts = {}
    for vote in votes:
        if vote in vote_counts:
            vote_counts[vote] += 1
        else:
            vote_counts[vote] = 1
    #items method
    winners = []
    max_counts = max(vote_counts.values()) #ask Python about the frequency the most appearing value has
    for vote, count in vote_counts.items(): #this returns a tuple of (vote,count)
        if count == max_counts:
            winners.append(vote)

    return random.choice(winners) #in case of a tie situation, Python picks a random candidate (element) and returns it.

votes = [1, 2, 3, 1, 2 ,3 ,3 ,3 ,3, 2, 2, 2] #here number 2 and 3 has the same appearing frequency: 5 (tie situation)
winner = majority_vote(votes)
print (winner) #it can be seen after running the code several times that this method picks one of the candidates
#and returns it randomly.

#another method
#--------------
import scipy.stats as ss

def majority_vote_short(votes):
    "Return the most common element in votes "
    mode , count = ss.mstats.mode(votes)
    return mode

votes = [1, 2, 3, 1, 2 ,3 ,3 ,3 ,3]
winner_short = majority_vote_short(votes)
print (winner_short) # it can be seen after running the code several times that this method always
#returns number 3 as the most common candidate and forgets about the other one: 2

#------------------------------------------------------------------------------

#Finding Nearest Neighbors
#--------------------------

points = np.array([[1,1], [1,2], [1,3], [2,1], [2,2], [2,3], [3,1], [3,2], [3,3]]) #points as a vector
p = np.array([2.5,2])#a single point with coordinates: x=2.5 and y=2

#plotting the points and point p
import matplotlib.pyplot as plt

plt.plot(points[:,0], points[:,1],"ro")
plt.plot(p[0],p[1],"bo")
plt.axis([0.5, 3.5, 0.5, 3.5])

distances = np.zeros(points.shape[0])#'.shape[0]' here reutrn a tuple of array dimensions.
for i in range(len(distances)):# loop over all points
    distances[i] = distance(p,points[i]) # compute the distance between point p and every other point using the function 'distnace'

print(distances)#reutrn the distances values between all the points and the point p
print(points[4])#return the point number 4
print(distances[4])#calculate the distnace between point number 4 and point p
print(points[7])#return the point 7
print(distances[7])#calculate the distnace between point number 7 and point p

#construct a 'find_nearest_neighbor' function
def find_nearest_neighbor(p, points, k=5):
    """find the k nearest neighbors of point p nd return their indices """
    distances = np.zeros(points.shape[0])#'.shape[0]' here reutrn a tuple of array dimensions.
    for i in range(len(distances)):# loop over all points
        distances[i] = distance(p,points[i]) # compute the distance between point p and every other point using the function 'distnace'
    ind = np.argsort(distances)#'argsort' is a function that sorts the distnaces indinces from short to long.
    #np.argsort(distances) it sorts an array according to a single argument and returns the sorted indices
    return ind[0:k] # or for short ind[:k]. This step is to return those k points that are nearest to point p

ind = find_nearest_neighbor(p, points, 2); print(points[ind])# return the first 2 nearest neighbors
ind = find_nearest_neighbor(p, points, 3); print(points[ind])# return the first 3 nearest neighbors
ind = find_nearest_neighbor(p, points, 4); print(points[ind])# return the first 4 nearest neighbors

#construct a 'knn_predict' function
def knn_predict(p, points, outcomes, k=5):
    #find k nearest neighbors
    ind = find_nearest_neighbor(p, points, k)
    return majority_vote(outcomes[ind])
    #predict the class/ categroy of p based on majority vote

outcomes = np.array([0,0,0,0,1,1,1,1,1]) # classes definition

print(len(outcomes))

print(knn_predict(np.array([2.5, 2.7]), points, outcomes, k=2)) #class 1
print(knn_predict(np.array([1.0, 2.7]), points, outcomes, k=2)) #class 0

#------------------------------------------------------------------------------

#Generating Synthetic Data
#-------------------------

#------------------------------------------------------------------------------
<|endoftext|>


<commit_before>"""The instruments module contains functions to open and close VISA, NI-DAQ or COM instruments.
"""

import traceback, sys, importlib, pkgutil, os

class InstrumentError(Exception):
    pass

# Get VISA resource manager
try:
    import visa
    from pyvisa import VisaIOError
    # VISA resource manager
    __visa__rm__ = visa.ResourceManager()
except:
    __visa__rm__ = None

# Get NIDAQ module
try:
    import PyDAQmx as __ni__
    import ctypes
except:
    __ni__ = None

# Get serial (COM) module
try:
    import serial as __com__
except:
    __com__ = None

# Parse drivers directory to build driver list
def __drivers__():
    drivers = {}
    loader = pkgutil.get_loader('pyslave.drivers')
    for sub_module in pkgutil.iter_modules([os.path.dirname(loader.get_filename())]):
        try:
            m = importlib.import_module( '.{0}'.format(sub_module.name), 'pyslave.drivers')
            drivers.update(m.__drivers__)
        except:
            pass
    return drivers

# Open the instrument and set missing attributes
def __open__(address, driver, resource):
    app = driver(address)
    app.__ressource__ = resource
    app.__driver_name__ = driver.__name__
    app.__driver_module__ = driver.__module__
    if not hasattr(app, '__inst_id__'):
        app.__inst_id__ = 'Unknown instrument'
    if not hasattr(app, '__instr_type__'):
        app.__instr_type__ = 'instr'
    if not hasattr(app,'__address__'):
        if resource in ('VISA','NIDAQ','COM'):
            app.__address__ = address
        else:
            app.__address__ = ''
    return app

def openVISA(address, driver=None):
    """Open the instrument with the specified VISA address and python driver.
    The address must be a valid VISA resource or alias.

    If driver is None, the instrument id is queried and a corresponding driver
    is searched. If the instrument does not answer (e.g. Yoko) or a matching
    driver is not found, the generic VISA instrument driver is selected.

    The function returns an instance of the driver class.
    """
    if __visa__rm__ is None:
        raise InstrumentError('PyVISA module not loaded')
    # Check if valid VISA identifier
    info = __visa__rm__.resource_info(address)
    address = info.resource_name
    # Automatic driver selection
    if driver is None:
        app = __visa__rm__.open_resource(address)
        try:
            app.clear()
            id = app.query('*IDN?')
            id = id.split(',')[:2]
            id = str(' '.join(id)).strip()
        except:
            error_msgs = traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)
            for e in error_msgs: print(e)
            print("""Identification of {0} failed, using generic VISA instrument.
                  If the instrument is a Yoko, set the driver to 'yokogawa.yokogawa7651'.""".format(address))
            id = None
        finally:
            app.close()
        if id is not None:
            known_devices = __drivers__()
            if id in known_devices:
                driver = known_devices[id]
            else:
                print('No driver found for instrument {0}, using generic VISA instrument.'.format(id))
    # Import driver
    if driver is not None:
        try:
            pkg_name, driver_name = driver.rsplit('.',1)
            m = importlib.import_module( '.{0}'.format(pkg_name), 'pyslave.drivers')
            driver = getattr(m, driver_name)
        except:
            error_msgs = traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)
            for e in error_msgs: print(e)
            print('Error while importing instrument driver {0}, using generic VISA instrument.'.format(driver))
            driver = __visa__rm__.open_resource
    else:
        driver = __visa__rm__.open_resource
    return __open__(address, driver, 'VISA')

def openNIDAQ(devname, driver=None):
    """Open the NI-DAQ device with the specified name and python driver.

    If driver is None, the device id is queried and a matching driver
    is looked for. If no driver is found for the corresponding id,
    an error is raised.

    The function returns an instance of the driver class.
    """
    if __ni__ is None:
        raise InstrumentError('PyDAQmx module not loaded.')

    if driver is None:
        buffer = ctypes.create_string_buffer('',1024)
        __ni__.DAQmxGetDeviceAttribute(devname, __ni__.DAQmx_Dev_ProductType, buffer, 1024)
        id = buffer.value.strip()
    known_devices = __drivers__()
    if id in known_devices:
        pkg_name, driver_name = known_devices[id].rsplit('.',1)
        m = importlib.import_module( '.{0}'.format(pkg_name), 'pyslave.drivers')
        driver = getattr(m, driver_name)
    else:
        raise InstrumentError('No driver for NI-DAQ device {0}.'.format(id))
    return __open__(devname, driver,'NIDAQ')

def openCOM(com, driver=None):
    """Open the COM device with the specified COM port and python driver.

    If driver is None, the generic com interface driver is used.

    The function returns an instance of the driver class.
    """
    if __com__ is None:
        raise InstrumentError('PySerial module not loaded.')

    if driver is not None:
        try:
            pkg_name, driver_name = driver.rsplit('.',1)
            m = importlib.import_module( '.{0}'.format(pkg_name), 'pyslave.drivers')
            driver = getattr(m, driver_name)
        except:
            error_msgs = traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)
            for e in error_msgs: print(e)
            print('Error while importing instrument driver {0}, using generic COM driver.'.format(driver))
            driver = __com__.Serial
    else:
        driver = __com__.Serial
    return __open__(com, driver,'COM')

def openOther(arg, driver):
    """Open specific types of instruments.

    The function returns an instance of the driver. The first
    argument is passed to the driver."""
    return __open__(arg, driver, 'Other')
<commit_msg>Merging<commit_after>"""The instruments module contains functions to open and close VISA, NI-DAQ or COM instruments.
"""

import traceback, sys, importlib, pkgutil, os

class InstrumentError(Exception):
    pass

# Get VISA resource manager
try:
    import visa
    from pyvisa import VisaIOError
    # VISA resource manager
    __visa__rm__ = visa.ResourceManager()
except:
    __visa__rm__ = None

# Get NIDAQ module
try:
    import PyDAQmx as __ni__
    import ctypes
except:
    __ni__ = None

# Get serial (COM) module
try:
    import serial as __com__
except:
    __com__ = None

# Parse drivers directory to build driver list
def __drivers__():
    drivers = {}
    loader = pkgutil.get_loader('pyslave.drivers')
    for sub_module in pkgutil.iter_modules([os.path.dirname(loader.get_filename())]):
        try:
            m = importlib.import_module( '.{0}'.format(sub_module.name), 'pyslave.drivers')
            drivers.update(m.__drivers__)
        except:
            pass
    return drivers

# Open the instrument and set missing attributes
def __open__(address, driver, resource):
    app = driver(address)
    app.__resource__ = resource
    app.__driver_name__ = driver.__name__
    app.__driver_module__ = driver.__module__
    if not hasattr(app, '__inst_id__'):
        app.__inst_id__ = 'Unknown instrument'
    if not hasattr(app, '__instr_type__'):
        app.__instr_type__ = 'instr'
    if not hasattr(app,'__address__'):
        if resource in ('VISA','NIDAQ','COM'):
            app.__address__ = address
        else:
            app.__address__ = ''
    return app

def openVISA(address, driver=None):
    """Open the instrument with the specified VISA address and python driver.
    The address must be a valid VISA resource or alias.

    If driver is None, the instrument id is queried and a corresponding driver
    is searched. If the instrument does not answer (e.g. Yoko) or a matching
    driver is not found, the generic VISA instrument driver is selected.

    The function returns an instance of the driver class.
    """
    if __visa__rm__ is None:
        raise InstrumentError('PyVISA module not loaded')
    # Check if valid VISA identifier
    info = __visa__rm__.resource_info(address)
    address = info.resource_name
    # Automatic driver selection
    if driver is None:
        app = __visa__rm__.open_resource(address)
        try:
            app.clear()
            id = app.query('*IDN?')
            id = id.split(',')[:2]
            id = str(' '.join(id)).strip()
        except:
            error_msgs = traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)
            for e in error_msgs: print(e)
            print("""Identification of {0} failed, using generic VISA instrument.
                  If the instrument is a Yoko, set the driver to 'yokogawa.yokogawa7651'.""".format(address))
            id = None
        finally:
            app.close()
        if id is not None:
            known_devices = __drivers__()
            if id in known_devices:
                driver = known_devices[id]
            else:
                print('No driver found for instrument {0}, using generic VISA instrument.'.format(id))
    # Import driver
    if driver is not None:
        try:
            pkg_name, driver_name = driver.rsplit('.',1)
            m = importlib.import_module( '.{0}'.format(pkg_name), 'pyslave.drivers')
            driver = getattr(m, driver_name)
        except:
            error_msgs = traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)
            for e in error_msgs: print(e)
            print('Error while importing instrument driver {0}, using generic VISA instrument.'.format(driver))
            driver = __visa__rm__.open_resource
    else:
        driver = __visa__rm__.open_resource
    return __open__(address, driver, 'VISA')

def openNIDAQ(devname, driver=None):
    """Open the NI-DAQ device with the specified name and python driver.

    If driver is None, the device id is queried and a matching driver
    is looked for. If no driver is found for the corresponding id,
    an error is raised.

    The function returns an instance of the driver class.
    """
    if __ni__ is None:
        raise InstrumentError('PyDAQmx module not loaded.')

    if driver is None:
        buffer = ctypes.create_string_buffer('',1024)
        __ni__.DAQmxGetDeviceAttribute(devname, __ni__.DAQmx_Dev_ProductType, buffer, 1024)
        id = buffer.value.strip()
    known_devices = __drivers__()
    if id in known_devices:
        pkg_name, driver_name = known_devices[id].rsplit('.',1)
        m = importlib.import_module( '.{0}'.format(pkg_name), 'pyslave.drivers')
        driver = getattr(m, driver_name)
    else:
        raise InstrumentError('No driver for NI-DAQ device {0}.'.format(id))
    return __open__(devname, driver,'NIDAQ')

def openCOM(com, driver=None):
    """Open the COM device with the specified COM port and python driver.

    If driver is None, the generic com interface driver is used.

    The function returns an instance of the driver class.
    """
    if __com__ is None:
        raise InstrumentError('PySerial module not loaded.')

    if driver is not None:
        try:
            pkg_name, driver_name = driver.rsplit('.',1)
            m = importlib.import_module( '.{0}'.format(pkg_name), 'pyslave.drivers')
            driver = getattr(m, driver_name)
        except:
            error_msgs = traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)
            for e in error_msgs: print(e)
            print('Error while importing instrument driver {0}, using generic COM driver.'.format(driver))
            driver = __com__.Serial
    else:
        driver = __com__.Serial
    return __open__(com, driver,'COM')

def openOther(arg, driver):
    """Open specific types of instruments.

    The function returns an instance of the driver. The first
    argument is passed to the driver."""
    return __open__(arg, driver, 'Other')
<|endoftext|>


<commit_before># -*- encoding: UTF-8 -*-

#
#    Copyright 2014-2015
#
#      STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es>
#
#    This file is part of Portal del Investigador.
#
#    Portal del Investigador is free software: you can redistribute it and/or
#    modify it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    Portal del Investigador 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 Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with Portal del Investigador.  If not, see
#    <http://www.gnu.org/licenses/>.
#

from .forms import PageForm
from .models import UserProfile, Log
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.contrib.flatpages.admin import FlatPageAdmin  # Don't delete
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from modeltranslation.admin import TranslationAdmin
from modeltranslation.translator import translator, TranslationOptions

# Options for the flatpages (faq)
class FlatPageTranslationOptions(TranslationOptions):
        fields = ('title', 'content',)

translator.register(FlatPage, FlatPageTranslationOptions)

class CustomFlatPageAdmin(TranslationAdmin):
    form = PageForm
    list_editable = []
    list_display = ('url', 'title', )
    list_filter = ()
    fieldsets = (
        (None, {'fields': ('title', 'content')}),
    )

FlatPage._meta.verbose_name = _("Preguntas Frecuentes")
FlatPage._meta.verbose_name_plural = _("Preguntas Frecuentes")

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    extra = 0
    readonly_fields = ('rrhh_code', )

UserAdmin.list_display = (
    'username', 'first_name', 'last_name', 'email', 'is_active', 'is_staff'
)

UserAdmin.readonly_fields = ('first_name', 'last_name', 'email')

UserAdmin.search_fields += ('profile__documento', 'profile__rrhh_code', )

UserAdmin.inlines = [
    UserProfileInline,
]

class LogAdmin(admin.ModelAdmin):

    list_display = ('application', 'entry_type', 'user_profile', 'date')

    list_filter = ('entry_type', 'application')

    search_fields = (
        'user_profile__user__username', 'user_profile__documento',
    )

    def has_add_permission(self, request):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

    def get_actions(self, request):
        """ Remove action delete object from list of actions """
        actions = super(LogAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

    def get_readonly_fields(self, request, obj=None):
        return tuple(Log._meta.get_all_field_names())

admin.site.unregister(User)
admin.site.register(User, UserAdmin)
admin.site.register(Log, LogAdmin)
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, CustomFlatPageAdmin)
admin.site.unregister(Site)
<commit_msg>Deleted user permissions<commit_after># -*- encoding: UTF-8 -*-

#
#    Copyright 2014-2015
#
#      STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es>
#
#    This file is part of Portal del Investigador.
#
#    Portal del Investigador is free software: you can redistribute it and/or
#    modify it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    Portal del Investigador 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 Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with Portal del Investigador.  If not, see
#    <http://www.gnu.org/licenses/>.
#

from .forms import PageForm
from .models import UserProfile, Log
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.contrib.flatpages.admin import FlatPageAdmin  # Don't delete
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from modeltranslation.admin import TranslationAdmin
from modeltranslation.translator import translator, TranslationOptions

# Options for the flatpages (faq)
class FlatPageTranslationOptions(TranslationOptions):
        fields = ('title', 'content',)

translator.register(FlatPage, FlatPageTranslationOptions)

class CustomFlatPageAdmin(TranslationAdmin):
    form = PageForm
    list_editable = []
    list_display = ('url', 'title', )
    list_filter = ()
    fieldsets = (
        (None, {'fields': ('title', 'content')}),
    )

FlatPage._meta.verbose_name = _("Preguntas Frecuentes")
FlatPage._meta.verbose_name_plural = _("Preguntas Frecuentes")

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    extra = 0
    readonly_fields = ('rrhh_code', )

class CustomUserAdmin(UserAdmin):
    list_display = ('username', 'first_name', 'last_name', 'email',
                    'is_active', 'is_staff')

    readonly_fields = ('first_name', 'last_name', 'email')

    search_fields = UserAdmin.search_fields + (
        'profile__documento', 'profile__rrhh_code', )

    inlines = [
        UserProfileInline,
    ]

    lst = list(UserAdmin.fieldsets)
    for sets in lst:
        if 'user_permissions' in sets[1]['fields']:
            field = list(sets[1]['fields'])
            field.remove('user_permissions')
            sets[1]['fields'] = tuple(field)
    fieldsets = tuple(lst)

class LogAdmin(admin.ModelAdmin):

    list_display = ('application', 'entry_type', 'user_profile', 'date')

    list_filter = ('entry_type', 'application')

    search_fields = (
        'user_profile__user__username', 'user_profile__documento',
    )

    def has_add_permission(self, request):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

    def get_actions(self, request):
        """ Remove action delete object from list of actions """
        actions = super(LogAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

    def get_readonly_fields(self, request, obj=None):
        return tuple(Log._meta.get_all_field_names())

admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
admin.site.register(Log, LogAdmin)
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, CustomFlatPageAdmin)
admin.site.unregister(Site)
<|endoftext|>


<commit_before>import os
import os.path
import glob
import time
import multiprocessing

from avocado import Test

HWMON_DIR = '/sys/class/hwmon'

def _cat(file_name):
    return open(file_name).read().strip()

class Temps(Test):

    def __init__(self):
        self.__probes = glob.glob(
                os.path.join(HWMON_DIR, 'hwmon[0-9]/temp[1-9]_input')
        )

    def get_values(self):
        """
        Get the temperature of the probes in the device

        returns an dict with path and temperatures
        """

        temperatures = {}

        # Iterate over probes
        for probe in self.__probes:
            # Get the temperature
            temperatures[probe] = int(_cat(probe))/1000

        return temperatures

    def test_idle(self):
        # be idle
        time.sleep(60)

        #check them
        for probe, temp in self.get_values():
            if temp > 60:
                self.fail("%s is more than 60 degrees: %i", probe, temp)

    def test_load(self):
        cores_idle = {}
        procs = []

        # Get idle results for cpu('s)
        for probe, temp in self.get_values():
            label = probe.replace('input', 'label')
            if os.stat(label) and 'Cpu' in _cat(label):
                cores[probe] = temp

        # Create cpu load
        for core in range(multiprocessing.cpu_count()):
            procs.append(subprocess.Popen(['sha256sum','/dev/random']))

        # Give some heat-up time
        time.sleep(20)

        # test them again
        for probe, temp in self.get_values():
            if probe in cores_idle.keys():
               if cores_idle[probe] + 5 < temp:
                   self.fail('No rise in temperature detected for %s', probe)

        # clean the processes
        for proc in procs:
            proc.kill()
<commit_msg>add some probe checks<commit_after>import os
import os.path
import glob
import time
import multiprocessing

from avocado import Test

HWMON_DIR = '/sys/class/hwmon'

def _cat(file_name):
    return open(file_name).read().strip()

class Temps(Test):

    def __init__(self):
        self.__probes = glob.glob(
                os.path.join(HWMON_DIR, 'hwmon[0-9]/temp[1-9]_input')
        )

    def get_values(self):
        """
        Get the temperature of the probes in the device

        returns an dict with path and temperatures
        """

        temperatures = {}

        # Iterate over probes
        for probe in self.__probes:
            # Get the temperature
            temperatures[probe] = int(_cat(probe))/1000

        return temperatures

    def test_idle(self):
        if len(self.__probes):
            self.fail('No probes found')
            return 1

        # be idle
        time.sleep(60)

        #check them
        for probe, temp in self.get_values():
            if temp > 60:
                self.fail("%s is more than 60 degrees: %i", probe, temp)

    def test_load(self):
        if len(self.__probes) < 1:
            self.fail('No probes found')
            return 1

        cores_idle = {}
        procs = []

        # Get idle results for cpu('s)
        for probe, temp in self.get_values():
            label = probe.replace('input', 'label')
            if os.stat(label) and 'Cpu' in _cat(label):
                cores[probe] = temp

        if len(cores_idle.keys()) < 1:
            self.fail("no probes found with cpu label")
            return 1

        # Create cpu load
        for core in range(multiprocessing.cpu_count()):
            procs.append(subprocess.Popen(['sha256sum','/dev/random']))

        # Give some heat-up time
        time.sleep(20)

        # test them again
        for probe, temp in self.get_values():
            if probe in cores_idle.keys():
               if cores_idle[probe] + 5 < temp:
                   self.fail('No rise in temperature detected for %s', probe)

        # clean the processes
        for proc in procs:
            proc.kill()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

from ooop import OOOP
import psycopg2
import sys
from datetime import datetime
from dateutil.relativedelta import relativedelta
from collections import defaultdict

#ENVIAMENT MENSUAL
#Enviament/execució petició de lectures estimades
#Executar script peticio_lectures_estimades.py
#Recordar que s'ha de canviar la data de l'interval i afegir que tingui en compte que si hi ha F1 no és
#necessari pq en aquest cas ja tindrem lectures reals
# Mirar la implementació de l'omplir correu per a l'accés als F1

import configdb

polisses_process_prev = []

# Default
TODAY_ = datetime.today()
TODAY = TODAY_.strftime('%Y/%m/%d')

DEFAULT_MIN_DATE_ = TODAY_+relativedelta(months=-5)
DEFAULT_MIN_DATE = DEFAULT_MIN_DATE_.strftime('%Y/%m/%d')
DEFAULT_SENT_DATE_ = TODAY_+relativedelta(months=-2)
DEFAULT_SENT_DATE = DEFAULT_SENT_DATE_.strftime('%Y/%m/%d')

# Constants
ORIGEN_ID = [7,9] #Identificacio dels origens de les lectures estimades i sense lectura
DISTR_AUTO_ID = [2273,2280,2437,2316] # Identificador distribuidores tractament automàtic ENDESA,Iberdrola, EON, Union Fenosa

def getPolissesExcesEstimades(db,min_data,in_,distrs):

    not_in = ''
    if not in_:
        not_in = 'NOT'

    sql_query = """
                SELECT polissa.id
                FROM giscedata_polissa AS polissa
                LEFT JOIN res_partner AS rp ON rp.id = polissa.distribuidora
                LEFT JOIN giscedata_polissa_category_rel AS category_rel ON polissa.id=category_rel.polissa_id
                LEFT JOIN giscedata_polissa_category AS category ON category.id = category_rel.category_id
                LEFT JOIN giscedata_polissa_category AS category_ ON category_.id = category.parent_id
                WHERE polissa.id NOT IN
                (  SELECT comptador.polissa
                    FROM giscedata_lectures_lectura_pool AS lectura
                    LEFT JOIN giscedata_lectures_comptador AS comptador on comptador.id = lectura.comptador
                    WHERE lectura.name > '%s'
                    AND lectura.origen_id NOT IN (%s)
                    GROUP BY lectura.comptador, comptador.polissa
                    ORDER BY comptador.polissa
                )
                AND (category_.name IS NULL OR category_.name != 'En curs')
                AND polissa.active
                AND polissa.state ='activa'
                AND polissa.data_alta < '%s'
                AND polissa.distribuidora %s IN (%s)""" % \
                (min_data,
                 ','.join(map(str,ORIGEN_ID)),
                 min_data,
                 not_in,
                 ','.join(map(str,distrs)))

    try:
        db.execute(sql_query)
    except Exception ,ex:
        print 'Failed executing query'
        print sql_query
        raise ex

    return [record[0] for record in db.fetchall()]

#if __name__ == "__main__":

min_date = DEFAULT_MIN_DATE
sent_date = DEFAULT_SENT_DATE
args = sys.argv[1:]
n_msgs = int(args[0])

try:
    dbconn=psycopg2.connect(**configdb.psycopg)
except Exception, ex:
    print "Unable to connect to database " + str(configdb.psycopg)
    raise ex

dbcur = dbconn.cursor()

polisses_process_auto = []
try:
    polisses_process_auto = getPolissesExcesEstimades(dbcur,min_date,True,DISTR_AUTO_ID)
except Exception, ex:
    print "Error llegint polisses amb lectures estimades"
    raise ex

polisses_process_manual = []
try:
    polisses_process_manual = getPolissesExcesEstimades(dbcur,min_date,False,DISTR_AUTO_ID)
except Exception, ex:
    print "Error llegint polisses amb lectures estimades"
    raise ex

O = OOOP(**configdb.ooop)

avui = datetime.today()
avui_ = avui.strftime('%Y/%m/%d')

from_id = O.PoweremailCore_accounts.search([('email_id','=','factura@somenergia.coop')])
template_id = O.PoweremailTemplates.search([('name','=',u'Petici\xf3 lectura comptador OV')])
#enviats_ids = O.PoweremailMailbox.search([('pem_subject','ilike','Som energia: Lectura de consum (contracte'),('date_mail','>',min_date)])
enviats_ids = O.PoweremailMailbox.search([('pem_subject','ilike',u'Petici\xf3 lectura comptador'),('date_mail','>',sent_date), ('folder','=','sent')])
enviats = O.PoweremailMailbox.read(enviats_ids,['reference','date_mail'])
polisses_enviats_auto = [int(polissa_ref['reference'].split(',')[1]) for polissa_ref in enviats]

polisses_enviats_auto = O.GiscedataPolissa.search([('id','in',polisses_enviats_auto)])

polisses_process_auto = list(set(polisses_process_auto)-set(polisses_process_prev))
polisses_process_auto = list(set(polisses_process_auto)-set(polisses_enviats_auto))

enviats = []
noenviats = []
tarifa30A = []

for polissa_id in polisses_process_auto[:n_msgs]:
    polissa = O.GiscedataPolissa.read(polissa_id,['name','tarifa','observacions'])

    if polissa['tarifa'][1] == '3.0A':
        tarifa30A.append(polissa_id)
        continue

    #enviar mail de petició de lectura
    ctx = {'active_ids': [polissa_id],
           'active_id': polissa_id,
           'template_id': template_id[0],
           'src_model': 'giscedata.polissa',
           'src_rec_ids': [polissa_id],
           'from': from_id}

    params = {'state': 'single',
              'priority':0,
              'from': ctx['from']}

    try:
        wz_id = O.PoweremailSendWizard.create(params, ctx)
        O.PoweremailSendWizard.send_mail([wz_id], ctx)
        enviats.append(polissa_id)
    except Exception , ex:
        noenviats.append(polissa_id)
        print ex
        continue

    print "Mail enviat a la polissa %s " % (polissa['name'])
    if polissa['observacions']:
        obs = "%s (automaticament,script) \nMail de peticio de lectura: 5 mesos sense recepcio lectura real\n\n" % avui_ + polissa['observacions']
    else:
        obs = "%s (automaticament,script) \nMail de peticio de lectura: 5 mesos sense recepcio lectura real\n\n" % avui_
    O.GiscedataPolissa.write(polissa_id,{'observacions':obs})
<commit_msg>Minor fix, OOOP return a list of one element<commit_after># -*- coding: utf-8 -*-

from ooop import OOOP
import psycopg2
import sys
from datetime import datetime
from dateutil.relativedelta import relativedelta
from collections import defaultdict

#ENVIAMENT MENSUAL
#Enviament/execució petició de lectures estimades
#Executar script peticio_lectures_estimades.py
#Recordar que s'ha de canviar la data de l'interval i afegir que tingui en compte que si hi ha F1 no és
#necessari pq en aquest cas ja tindrem lectures reals
# Mirar la implementació de l'omplir correu per a l'accés als F1

import configdb

polisses_process_prev = []

# Default
TODAY_ = datetime.today()
TODAY = TODAY_.strftime('%Y/%m/%d')

DEFAULT_MIN_DATE_ = TODAY_+relativedelta(months=-5)
DEFAULT_MIN_DATE = DEFAULT_MIN_DATE_.strftime('%Y/%m/%d')
DEFAULT_SENT_DATE_ = TODAY_+relativedelta(months=-2)
DEFAULT_SENT_DATE = DEFAULT_SENT_DATE_.strftime('%Y/%m/%d')

# Constants
ORIGEN_ID = [7,9] #Identificacio dels origens de les lectures estimades i sense lectura
DISTR_AUTO_ID = [2273,2280,2437,2316] # Identificador distribuidores tractament automàtic ENDESA,Iberdrola, EON, Union Fenosa

def getPolissesExcesEstimades(db,min_data,in_,distrs):

    not_in = ''
    if not in_:
        not_in = 'NOT'

    sql_query = """
                SELECT polissa.id
                FROM giscedata_polissa AS polissa
                LEFT JOIN res_partner AS rp ON rp.id = polissa.distribuidora
                LEFT JOIN giscedata_polissa_category_rel AS category_rel ON polissa.id=category_rel.polissa_id
                LEFT JOIN giscedata_polissa_category AS category ON category.id = category_rel.category_id
                LEFT JOIN giscedata_polissa_category AS category_ ON category_.id = category.parent_id
                WHERE polissa.id NOT IN
                (  SELECT comptador.polissa
                    FROM giscedata_lectures_lectura_pool AS lectura
                    LEFT JOIN giscedata_lectures_comptador AS comptador on comptador.id = lectura.comptador
                    WHERE lectura.name > '%s'
                    AND lectura.origen_id NOT IN (%s)
                    GROUP BY lectura.comptador, comptador.polissa
                    ORDER BY comptador.polissa
                )
                AND (category_.name IS NULL OR category_.name != 'En curs')
                AND polissa.active
                AND polissa.state ='activa'
                AND polissa.data_alta < '%s'
                AND polissa.distribuidora %s IN (%s)""" % \
                (min_data,
                 ','.join(map(str,ORIGEN_ID)),
                 min_data,
                 not_in,
                 ','.join(map(str,distrs)))

    try:
        db.execute(sql_query)
    except Exception ,ex:
        print 'Failed executing query'
        print sql_query
        raise ex

    return [record[0] for record in db.fetchall()]

#if __name__ == "__main__":

min_date = DEFAULT_MIN_DATE
sent_date = DEFAULT_SENT_DATE
args = sys.argv[1:]
n_msgs = int(args[0])

try:
    dbconn=psycopg2.connect(**configdb.psycopg)
except Exception, ex:
    print "Unable to connect to database " + str(configdb.psycopg)
    raise ex

dbcur = dbconn.cursor()

polisses_process_auto = []
try:
    polisses_process_auto = getPolissesExcesEstimades(dbcur,min_date,True,DISTR_AUTO_ID)
except Exception, ex:
    print "Error llegint polisses amb lectures estimades"
    raise ex

polisses_process_manual = []
try:
    polisses_process_manual = getPolissesExcesEstimades(dbcur,min_date,False,DISTR_AUTO_ID)
except Exception, ex:
    print "Error llegint polisses amb lectures estimades"
    raise ex

O = OOOP(**configdb.ooop)

avui = datetime.today()
avui_ = avui.strftime('%Y/%m/%d')

from_id = O.PoweremailCore_accounts.search([('email_id','=','factura@somenergia.coop')])
template_id = O.PoweremailTemplates.search([('name','=',u'Petici\xf3 lectura comptador OV')])
#enviats_ids = O.PoweremailMailbox.search([('pem_subject','ilike','Som energia: Lectura de consum (contracte'),('date_mail','>',min_date)])
enviats_ids = O.PoweremailMailbox.search([('pem_subject','ilike',u'Petici\xf3 lectura comptador'),('date_mail','>',sent_date), ('folder','=','sent')])
enviats = O.PoweremailMailbox.read(enviats_ids,['reference','date_mail'])
polisses_enviats_auto = [int(polissa_ref['reference'].split(',')[1]) for polissa_ref in enviats]

polisses_enviats_auto = O.GiscedataPolissa.search([('id','in',polisses_enviats_auto)])

polisses_process_auto = list(set(polisses_process_auto)-set(polisses_process_prev))
polisses_process_auto = list(set(polisses_process_auto)-set(polisses_enviats_auto))

enviats = []
noenviats = []
tarifa30A = []

for polissa_id in polisses_process_auto[:n_msgs]:
    polissa = O.GiscedataPolissa.read(polissa_id,['name','tarifa','observacions'])

    if polissa['tarifa'][1] == '3.0A':
        tarifa30A.append(polissa_id)
        continue

    #enviar mail de petició de lectura
    ctx = {'active_ids': [polissa_id],
           'active_id': polissa_id,
           'template_id': template_id[0],
           'src_model': 'giscedata.polissa',
           'src_rec_ids': [polissa_id],
           'from': from_id[0]}

    params = {'state': 'single',
              'priority':0,
              'from': ctx['from']}

    try:
        wz_id = O.PoweremailSendWizard.create(params, ctx)
        O.PoweremailSendWizard.send_mail([wz_id], ctx)
        enviats.append(polissa_id)
    except Exception , ex:
        noenviats.append(polissa_id)
        print ex
        continue

    print "Mail enviat a la polissa %s " % (polissa['name'])
    if polissa['observacions']:
        obs = "%s (automaticament,script) \nMail de peticio de lectura: 5 mesos sense recepcio lectura real\n\n" % avui_ + polissa['observacions']
    else:
        obs = "%s (automaticament,script) \nMail de peticio de lectura: 5 mesos sense recepcio lectura real\n\n" % avui_
    O.GiscedataPolissa.write(polissa_id,{'observacions':obs})
<|endoftext|>


<commit_before>#Main program executor
import pyRecipeBook
import FoodGroups
import ShoppingList as List

#Welcome screen
welcomeMessage =  "Welcome to pyRecipeBook!\n"
welcomeMessage += "Enter a command below:\n"
print(welcomeMessage)

myShoppingList = []

#Method for `exit` command
def exitCom(args):
	#Predefined so args is never less than 1
	#Too many arguements
	if len(args) > 1:
		return True
	#Interactive mode should is not on
	return False

#Method to run commands
def runCommand(command,myShoppingList=[]):
	#Split command
	args = command.split()

	#
	if len(args) < 1: #No command -> pass
		return True
	elif args[0] == 'exit': #Exit command
		print('Exiting...')
		return exitCom(args)
	elif args[0] == 'add': #Proceed to add what is given
		#Test whether the arguements are valid
		if len(args) == 1: #Not enough arguements
			print "Minimum of 2 arguements must be given"
		elif len(args) >4:
			print "Maximum of 4 arguements must be given"
		else: #Add item to list
			#Convert the arguements to something to input into Python method
			newArgs = (myShoppingList,) + tuple(args[1:])
			#Add to the shopping list
			myShoppingList = addToList(*newArgs)
		return True
	elif args[0] == 'shoppingList': #Operate on the shopping list
		#
		if len(args) == 1: #Print the list
			print myShoppingList
		else: #Not valid arguments
			print "Command not valid"
		return True

	else: #Command isn't defined in this tool
		print('That command doesn\'t exist.')
		return True

#Add item to shopping list
def addToList(myList,item,quantity=1,unit=''):
	myItem = List.Item(item,quantity,unit)
	myList.append(myItem)
	return myList
#
pre = '# '
on = True

#Keep asking for inpyt
while(on):
	#Enter a command
	command = raw_input(pre)
	#Run command
	on = runCommand(command)

#Exiting commands
exitMessage = "\nThank you for choosing to use pyRecipeBook!\n"
print(exitMessage)
<commit_msg>Update interactive.py<commit_after>#Main program executor
import pyRecipeBook
import FoodGroups
import ShoppingList as List

#Welcome screen
welcomeMessage =  "Welcome to pyRecipeBook!\n"
welcomeMessage += "Enter a command below:\n"
print(welcomeMessage)

#Initiate a shopping list
myShoppingList = []

#Method for `exit` command
def exitCom(args):
	#Predefined so args is never less than 1
	if len(args) > 1: #Too many arguements
		return True
	#Interactive mode should is not on
	return False

#Method to print the shopping list
def printShoppingList(myList):
	print myList

#Method to run commands
def runCommand(command,myShoppingList=[]):
	#Split command
	args = command.split()
	#
	if len(args) < 1: #No command -> pass
		return True
	elif args[0] == 'exit': #Exit command
		print('Exiting...')
		return exitCom(args)
	#Proceed to add what is given
	elif args[0] == 'add':
		#Test whether the arguements are valid
		if len(args) == 1: #Not enough arguements
			print "Minimum of 2 arguements must be given"
		elif len(args) >4:
			print "Maximum of 4 arguements must be given"
		else: #Add item to list
			#Convert the arguements to something to input into Python method
			newArgs = (myShoppingList,) + tuple(args[1:]) #list, item, (quantity), (unit)
			#Add to the shopping list
			myShoppingList = addToList(*newArgs)
		return True
	#Operate on the shopping list
	elif args[0] == 'shoppingList':
		#
		if len(args) == 1: #Print the list
			printShoppingList()
		else: #Not valid arguments
			print "Command not valid"
		return True
	#Command isn't defined
	else:
		print('That command doesn\'t exist.')
		return True

#Add item to shopping list
def addToList(myList,item,quantity=1,unit=''):
	myItem = List.Item(item,quantity,unit)
	myList.append(myItem)
	return myList
#
pre = '# '
on = True

#Keep asking for inpyt
while(on):
	#Enter a command
	command = raw_input(pre)
	#Run command
	on = runCommand(command)

#Exiting commands
exitMessage = "\nThank you for choosing to use pyRecipeBook!\n"
print(exitMessage)
<|endoftext|>


<commit_before># Copyright 2015-2019 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).

from datetime import datetime, timedelta

import odoo.tests.common as common
from odoo.exceptions import UserError
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT

class TestAccountConstraintChronology(common.SavepointCase):

    @classmethod
    def setUpClass(cls):
        super(TestAccountConstraintChronology, cls).setUpClass()

        # Needed to create invoice

        cls.account_type1 = cls.env['account.account.type'].\
            create({'name': 'acc type test 1',
                    'type': 'receivable',
                    'include_initial_balance': True})
        cls.account_type2 = cls.env['account.account.type']. \
            create({'name': 'acc type test 2',
                    'type': 'other',
                    'include_initial_balance': True})
        cls.account_account = cls.env['account.account'].\
            create({'name': 'acc test',
                    'code': 'X2020',
                    'user_type_id': cls.account_type1.id,
                    'reconcile': True})
        cls.account_account_line = cls.env['account.account']. \
            create({'name': 'acc inv line test',
                    'code': 'X2021',
                    'user_type_id': cls.account_type2.id,
                    'reconcile': True})
        cls.sequence = cls.env['ir.sequence'].create(
            {'name': 'Journal Sale',
             'prefix': 'SALE', 'padding': 6,
             'company_id': cls.env.ref("base.main_company").id})
        cls.account_journal_sale = cls.env['account.journal']\
            .create({'name': 'Sale journal',
                     'code': 'SALE',
                     'type': 'sale',
                     'sequence_id': cls.sequence.id})
        cls.product = cls.env['product.product'].create(
            {'name': 'product name'})
        cls.analytic_account = cls.env['account.analytic.account'].\
            create({'name': 'test account'})

    def get_journal_check(self, value):
        journal = self.account_journal_sale.copy()
        journal.check_chronology = value
        return journal

    def create_simple_invoice(self, journal_id, date):
        invoice = self.env['account.invoice'].create({
            'partner_id': self.env.ref('base.res_partner_2').id,
            'account_id': self.account_account.id,
            'type': 'in_invoice',
            'journal_id': journal_id,
            'date_invoice': date,
            'state': 'draft',
        })

        self.env['account.invoice.line'].create({
            'product_id': self.product.id,
            'quantity': 1.0,
            'price_unit': 100.0,
            'invoice_id': invoice.id,
            'name': 'product that cost 100',
            'account_id': self.account_account_line.id,
            'account_analytic_id': self.analytic_account.id,
        })
        return invoice

    def test_invoice_draft(self):
        journal = self.get_journal_check(True)
        today = datetime.now()
        yesterday = today - timedelta(days=1)
        date = yesterday.strftime(DEFAULT_SERVER_DATE_FORMAT)
        self.create_simple_invoice(journal.id, date)
        date = today.strftime(DEFAULT_SERVER_DATE_FORMAT)
        invoice_2 = self.create_simple_invoice(journal.id, date)
        self.assertTrue((invoice_2.state == 'draft'),
                        "Initial invoice state is not Draft")
        with self.assertRaises(UserError):
            invoice_2.action_invoice_open()

    def test_invoice_validate(self):
        journal = self.get_journal_check(True)
        today = datetime.now()
        tomorrow = today + timedelta(days=1)
        date_tomorrow = tomorrow.strftime(DEFAULT_SERVER_DATE_FORMAT)
        invoice_1 = self.create_simple_invoice(journal.id, date_tomorrow)
        self.assertTrue((invoice_1.state == 'draft'),
                        "Initial invoice state is not Draft")
        invoice_1.action_invoice_open()
        date = today.strftime(DEFAULT_SERVER_DATE_FORMAT)
        invoice_2 = self.create_simple_invoice(journal.id, date)
        self.assertTrue((invoice_2.state == 'draft'),
                        "Initial invoice state is not Draft")
        with self.assertRaises(UserError):
            invoice_2.action_invoice_open()

    def test_invoice_without_date(self):
        journal = self.get_journal_check(True)
        today = datetime.now()
        yesterday = today - timedelta(days=1)
        date = yesterday.strftime(DEFAULT_SERVER_DATE_FORMAT)
        self.create_simple_invoice(journal.id, date)
        invoice_2 = self.create_simple_invoice(journal.id, False)
        self.assertTrue((invoice_2.state == 'draft'),
                        "Initial invoice state is not Draft")
        with self.assertRaises(UserError):
            invoice_2.action_invoice_open()
<commit_msg>[REF] Account Invoice Constraint Chronology: improve code coverage<commit_after># Copyright 2015-2019 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).

from datetime import datetime, timedelta

import odoo.tests.common as common
from odoo.exceptions import UserError
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT

class TestAccountConstraintChronology(common.SavepointCase):

    @classmethod
    def setUpClass(cls):
        super(TestAccountConstraintChronology, cls).setUpClass()

        # Needed to create invoice

        cls.account_type1 = cls.env['account.account.type'].\
            create({'name': 'acc type test 1',
                    'type': 'receivable',
                    'include_initial_balance': True})
        cls.account_type2 = cls.env['account.account.type']. \
            create({'name': 'acc type test 2',
                    'type': 'other',
                    'include_initial_balance': True})
        cls.account_account = cls.env['account.account'].\
            create({'name': 'acc test',
                    'code': 'X2020',
                    'user_type_id': cls.account_type1.id,
                    'reconcile': True})
        cls.account_account_line = cls.env['account.account']. \
            create({'name': 'acc inv line test',
                    'code': 'X2021',
                    'user_type_id': cls.account_type2.id,
                    'reconcile': True})
        cls.sequence = cls.env['ir.sequence'].create(
            {'name': 'Journal Sale',
             'prefix': 'SALE', 'padding': 6,
             'company_id': cls.env.ref("base.main_company").id})
        cls.account_journal_sale = cls.env['account.journal']\
            .create({'name': 'Sale journal',
                     'code': 'SALE',
                     'type': 'sale',
                     'sequence_id': cls.sequence.id})
        cls.product = cls.env['product.product'].create(
            {'name': 'product name'})
        cls.analytic_account = cls.env['account.analytic.account'].\
            create({'name': 'test account'})

    def get_journal_check(self, value):
        journal = self.account_journal_sale.copy()
        journal.check_chronology = value
        return journal

    def create_simple_invoice(self, journal_id, date):
        invoice = self.env['account.invoice'].create({
            'partner_id': self.env.ref('base.res_partner_2').id,
            'account_id': self.account_account.id,
            'type': 'in_invoice',
            'journal_id': journal_id,
            'date_invoice': date,
            'state': 'draft',
        })

        self.env['account.invoice.line'].create({
            'product_id': self.product.id,
            'quantity': 1.0,
            'price_unit': 100.0,
            'invoice_id': invoice.id,
            'name': 'product that cost 100',
            'account_id': self.account_account_line.id,
            'account_analytic_id': self.analytic_account.id,
        })
        return invoice

    def test_invoice_draft(self):
        journal = self.get_journal_check(True)
        today = datetime.now()
        yesterday = today - timedelta(days=1)
        date = yesterday.strftime(DEFAULT_SERVER_DATE_FORMAT)
        self.create_simple_invoice(journal.id, date)
        date = today.strftime(DEFAULT_SERVER_DATE_FORMAT)
        invoice_2 = self.create_simple_invoice(journal.id, date)
        self.assertTrue((invoice_2.state == 'draft'),
                        "Initial invoice state is not Draft")
        with self.assertRaises(UserError):
            invoice_2.action_invoice_open()

    def test_invoice_draft_no_check(self):
        journal = self.get_journal_check(False)
        today = datetime.now()
        yesterday = today - timedelta(days=1)
        date = yesterday.strftime(DEFAULT_SERVER_DATE_FORMAT)
        self.create_simple_invoice(journal.id, date)
        date = today.strftime(DEFAULT_SERVER_DATE_FORMAT)
        invoice_2 = self.create_simple_invoice(journal.id, date)
        self.assertTrue((invoice_2.state == 'draft'),
                        "Initial invoice state is not Draft")
        self.assertTrue(invoice_2.action_invoice_open())

    def test_invoice_validate(self):
        journal = self.get_journal_check(True)
        today = datetime.now()
        tomorrow = today + timedelta(days=1)
        date_tomorrow = tomorrow.strftime(DEFAULT_SERVER_DATE_FORMAT)
        invoice_1 = self.create_simple_invoice(journal.id, date_tomorrow)
        self.assertTrue((invoice_1.state == 'draft'),
                        "Initial invoice state is not Draft")
        invoice_1.action_invoice_open()
        date = today.strftime(DEFAULT_SERVER_DATE_FORMAT)
        invoice_2 = self.create_simple_invoice(journal.id, date)
        self.assertTrue((invoice_2.state == 'draft'),
                        "Initial invoice state is not Draft")
        with self.assertRaises(UserError):
            invoice_2.action_invoice_open()

    def test_invoice_without_date(self):
        journal = self.get_journal_check(True)
        today = datetime.now()
        yesterday = today - timedelta(days=1)
        date = yesterday.strftime(DEFAULT_SERVER_DATE_FORMAT)
        self.create_simple_invoice(journal.id, date)
        invoice_2 = self.create_simple_invoice(journal.id, False)
        self.assertTrue((invoice_2.state == 'draft'),
                        "Initial invoice state is not Draft")
        with self.assertRaises(UserError):
            invoice_2.action_invoice_open()

    def test_journal_change_type(self):
        self.account_journal_sale.check_chronology = True
        self.assertTrue(self.account_journal_sale.check_chronology)
        self.account_journal_sale.type = 'bank'
        self.account_journal_sale._onchange_type()
        self.assertFalse(self.account_journal_sale.check_chronology)
<|endoftext|>