<commit_before>from parsimonious.nodes import RegexNode
from grammar import Grammar

class AST:

    def origin(self, node):
        if not hasattr(self, "node"):
            self.node = node

    def traverse(self, visitor):
        visit = getattr(visitor, "visit_%s" % self.__class__.__name__, lambda s: None)
        leave = getattr(visitor, "leave_%s" % self.__class__.__name__, lambda s: None)
        visit(self)
        if self.children:
            for c in self.children:
                if c is not None:
                    c.traverse(visitor)
        leave(self)

def joindent(items):
    st = "\n".join(map(str, items))
    if st:
        st = ("\n" + st).replace("\n", "\n  ")
        st += "\n"
    return st

class Module(AST):

    def __init__(self, name, definitions):
        self.name = name
        self.definitions = definitions

    @property
    def children(self):
        return self.definitions

    def __str__(self):
        return "module %s {%s}" % (self.name, joindent(self.definitions))

class Struct(AST):

    def __init__(self, name, fields):
        self.name = name
        self.fields = fields

    @property
    def children(self):
        return self.fields

    def __str__(self):
        return "struct %s {%s}" % (self.name, joindent(self.fields))

class Fieldish(AST):

    def __init__(self, name, type, default):
        self.name = name
        self.type = type
        self.default = default

    @property
    def children(self):
        yield self.type

    def __str__(self):
        if self.default:
            return "%s %s = %s" % (self.type, self.name, self.default)
        else:
            return "%s %s" % (self.type, self.name)

class Field(Fieldish):

    def __str__(self):
        return Fieldish.__str__(self) + ";"

class Parameter(Fieldish):
    pass

class Operation(AST):

    def __init__(self, name, parameters, type):
        self.name = name
        self.parameters = parameters
        self.type = type

    @property
    def children(self):
        yield self.type
        for p in self.parameters:
            yield p

    def __str__(self):
        return "%s %s(%s);" % (self.type, self.name, ", ".join(map(str, self.parameters)))

class Type(AST):

    def __init__(self, name, parameters=None):
        self.name = name
        self.parameters = parameters

    @property
    def children(self):
        return self.parameters

    def __str__(self):
        if self.parameters:
            return "%s<%s>" % (self.name, ", ".join([str(s) for s in self.parameters]))
        else:
            return self.name

g = Grammar()

@g.parser
class SDL:

    keywords = ["module", "struct", "desc", "defaults"]
    symbols = {"EQ": "=",
               "SEMI": ";",
               "COMMA": ",",
               "LA": "<",
               "RA": ">",
               "LBR": "{",
               "RBR": "}",
               "LPR": "(",
               "RPR": ")",
               "NULL": "null"}

    @g.rule('module = MODULE name LBR definition* RBR SEMI ~"$"')
    def visit_module(self, node, (m, name, l, definitions, r, s, eof)):
        return Module(name, definitions)

    @g.rule('definition = struct / operation / desc / defaults')
    def visit_definition(self, node, (dfn,)):
        return dfn

    @g.rule('desc = DESC STRING SEMI')
    def visit_desc(self, node, children): pass

    @g.rule('defaults = DEFAULTS LBR ~"[^}]*" RBR SEMI')
    def visit_defaults(self, node, children): pass

    @g.rule('struct = STRUCT name LBR field* RBR SEMI')
    def visit_struct(self, node, (s, name, l, fields, r, sc)):
        return Struct(name, fields)

    # should think about queries and/or idempotency
    @g.rule('operation = type name LPR parameters? RPR (LBR ~"[^}]*" RBR)? SEMI')
    def visit_operation(self, node, (type, name, l, params, r, _, s)):
        if params:
            params = params[0]
        else:
            params = []
        return Operation(name, params, type)

    @g.rule('parameters = param (COMMA param)*')
    def visit_parameters(self, node, (first, rest)):
        return [first] + [n[-1] for n in rest]

    @g.rule('param = type name (EQ literal)?')
    def visit_param(self, node, (type, name, default)):
        if default:
            literal = default[0][-1]
        else:
            literal = None
        return Parameter(name, type, literal)

    @g.rule('field = type name (EQ literal)? SEMI')
    def visit_field(self, node, (type, name, default, _)):
        if default:
            literal = default[0][-1]
        else:
            literal = None
        return Field(name, type, literal)

    @g.rule('literal = STRING / NULL')
    def visit_literal(self, node, (literal,)):
        return literal

    @g.rule('type = name (LA types RA)?')
    def visit_type(self, node, (name, params)):
        if params:
            _, types, _ = params[0]
            return Type(name, types)
        else:
            return Type(name)

    @g.rule('types = type (COMMA type)*')
    def visit_types(self, node, (first, rest)):
        return [first] + [n[-1] for n in rest]

    @g.rule('name = _ ~"[a-zA-Z][a-zA-Z0-9]*" _')
    def visit_name(self, node, (pre, name, post)):
        return name.text

    # lame string literals here
    @g.rule(r'STRING = _ ~"\"[^\"]*\"" _')
    def visit_STRING(self, node, (pre, string, post)):
        return string.text

    @g.rule('_ = __?')
    def visit__(self, node, children):
        return None

    @g.rule(r'__ = ~"[ \t\n\r]*//[^\n]*[ \t\n\r]+" / ~"[ \t\n\r]+"')
    def visit___(self, node, children):
        return None

    def visit_(self, node, children):
        if isinstance(node, RegexNode):
            return node
        else:
            return children

if __name__ == "__main__":
    m = SDL().parse("""
    // this is a test, hey this works
    module asdf {};
    """)
    print m
    m = SDL().parse("""
    module asdf {
      struct A {
        a b = null;
        c d = "asdf"; //asdf
        x y;
      };

      List<A, B, C> funge(List<int> a, int b, int c);
      List<A, B> funge(int a, int b);
      List<A> funge(int a);
      void funge();
    };
    """)
    print m
    m = SDL().parse(open("examples/petstore/petstore.sdl").read())
    print m

    class Visitor:

        def visit_Module(self, m):
            print "## module %s {" % m.name
        def leave_Module(self, m):
            print "## };"

        def visit_Struct(self, s):
            print "##   struct %s {" % s.name

        def visit_Field(self, f):
            print "##     %s %s;" % (f.type, f.name)

        def leave_Struct(self, m):
            print "##   };"

    m.traverse(Visitor())
<commit_msg>renamed Fieldish to Declaration; added Operation to example visitor<commit_after>from parsimonious.nodes import RegexNode
from grammar import Grammar

class AST:

    def origin(self, node):
        if not hasattr(self, "node"):
            self.node = node

    def traverse(self, visitor):
        visit = getattr(visitor, "visit_%s" % self.__class__.__name__, lambda s: None)
        leave = getattr(visitor, "leave_%s" % self.__class__.__name__, lambda s: None)
        visit(self)
        if self.children:
            for c in self.children:
                if c is not None:
                    c.traverse(visitor)
        leave(self)

def joindent(items):
    st = "\n".join(map(str, items))
    if st:
        st = ("\n" + st).replace("\n", "\n  ")
        st += "\n"
    return st

class Module(AST):

    def __init__(self, name, definitions):
        self.name = name
        self.definitions = definitions

    @property
    def children(self):
        return self.definitions

    def __str__(self):
        return "module %s {%s}" % (self.name, joindent(self.definitions))

class Struct(AST):

    def __init__(self, name, fields):
        self.name = name
        self.fields = fields

    @property
    def children(self):
        return self.fields

    def __str__(self):
        return "struct %s {%s}" % (self.name, joindent(self.fields))

class Declaration(AST):

    def __init__(self, name, type, default):
        self.name = name
        self.type = type
        self.default = default

    @property
    def children(self):
        yield self.type

    def __str__(self):
        if self.default:
            return "%s %s = %s" % (self.type, self.name, self.default)
        else:
            return "%s %s" % (self.type, self.name)

class Field(Declaration):

    def __str__(self):
        return Declaration.__str__(self) + ";"

class Parameter(Declaration):
    pass

class Operation(AST):

    def __init__(self, name, parameters, type):
        self.name = name
        self.parameters = parameters
        self.type = type

    @property
    def children(self):
        yield self.type
        for p in self.parameters:
            yield p

    def __str__(self):
        return "%s %s(%s);" % (self.type, self.name, ", ".join(map(str, self.parameters)))

class Type(AST):

    def __init__(self, name, parameters=None):
        self.name = name
        self.parameters = parameters

    @property
    def children(self):
        return self.parameters

    def __str__(self):
        if self.parameters:
            return "%s<%s>" % (self.name, ", ".join([str(s) for s in self.parameters]))
        else:
            return self.name

g = Grammar()

@g.parser
class SDL:

    keywords = ["module", "struct", "desc", "defaults"]
    symbols = {"EQ": "=",
               "SEMI": ";",
               "COMMA": ",",
               "LA": "<",
               "RA": ">",
               "LBR": "{",
               "RBR": "}",
               "LPR": "(",
               "RPR": ")",
               "NULL": "null"}

    @g.rule('module = MODULE name LBR definition* RBR SEMI ~"$"')
    def visit_module(self, node, (m, name, l, definitions, r, s, eof)):
        return Module(name, definitions)

    @g.rule('definition = struct / operation / desc / defaults')
    def visit_definition(self, node, (dfn,)):
        return dfn

    @g.rule('desc = DESC STRING SEMI')
    def visit_desc(self, node, children): pass

    @g.rule('defaults = DEFAULTS LBR ~"[^}]*" RBR SEMI')
    def visit_defaults(self, node, children): pass

    @g.rule('struct = STRUCT name LBR field* RBR SEMI')
    def visit_struct(self, node, (s, name, l, fields, r, sc)):
        return Struct(name, fields)

    # should think about queries and/or idempotency
    @g.rule('operation = type name LPR parameters? RPR (LBR ~"[^}]*" RBR)? SEMI')
    def visit_operation(self, node, (type, name, l, params, r, _, s)):
        if params:
            params = params[0]
        else:
            params = []
        return Operation(name, params, type)

    @g.rule('parameters = param (COMMA param)*')
    def visit_parameters(self, node, (first, rest)):
        return [first] + [n[-1] for n in rest]

    @g.rule('param = type name (EQ literal)?')
    def visit_param(self, node, (type, name, default)):
        if default:
            literal = default[0][-1]
        else:
            literal = None
        return Parameter(name, type, literal)

    @g.rule('field = type name (EQ literal)? SEMI')
    def visit_field(self, node, (type, name, default, _)):
        if default:
            literal = default[0][-1]
        else:
            literal = None
        return Field(name, type, literal)

    @g.rule('literal = STRING / NULL')
    def visit_literal(self, node, (literal,)):
        return literal

    @g.rule('type = name (LA types RA)?')
    def visit_type(self, node, (name, params)):
        if params:
            _, types, _ = params[0]
            return Type(name, types)
        else:
            return Type(name)

    @g.rule('types = type (COMMA type)*')
    def visit_types(self, node, (first, rest)):
        return [first] + [n[-1] for n in rest]

    @g.rule('name = _ ~"[a-zA-Z][a-zA-Z0-9]*" _')
    def visit_name(self, node, (pre, name, post)):
        return name.text

    # lame string literals here
    @g.rule(r'STRING = _ ~"\"[^\"]*\"" _')
    def visit_STRING(self, node, (pre, string, post)):
        return string.text

    @g.rule('_ = __?')
    def visit__(self, node, children):
        return None

    @g.rule(r'__ = ~"[ \t\n\r]*//[^\n]*[ \t\n\r]+" / ~"[ \t\n\r]+"')
    def visit___(self, node, children):
        return None

    def visit_(self, node, children):
        if isinstance(node, RegexNode):
            return node
        else:
            return children

if __name__ == "__main__":
    m = SDL().parse("""
    // this is a test, hey this works
    module asdf {};
    """)
    print m
    m = SDL().parse("""
    module asdf {
      struct A {
        a b = null;
        c d = "asdf"; //asdf
        x y;
      };

      List<A, B, C> funge(List<int> a, int b, int c);
      List<A, B> funge(int a, int b);
      List<A> funge(int a);
      void funge();
      List<A<B, C>> funge(int a = null);
    };
    """)
    print m
    m = SDL().parse(open("examples/petstore/petstore.sdl").read())
    print m

    class Visitor:

        def visit_Module(self, m):
            print "## module %s {" % m.name
        def leave_Module(self, m):
            print "## };"

        def visit_Struct(self, s):
            print "##   struct %s {" % s.name
        def visit_Field(self, f):
            print "##     %s %s;" % (f.type, f.name)
        def leave_Struct(self, m):
            print "##   };"

        def visit_Operation(self, o):
            print "##   %s %s(%s);" % (o.type, o.name, ", ".join(str(p) for p in o.parameters))

    m.traverse(Visitor())
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program 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.
#
#    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import fields, osv
import logging
import addons

class hr_employee_category(osv.osv):

    def name_get(self, cr, uid, ids, context=None):
        if not ids:
            return []
        reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
        res = []
        for record in reads:
            name = record['name']
            if record['parent_id']:
                name = record['parent_id'][1]+' / '+name
            res.append((record['id'], name))
        return res

    def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
        res = self.name_get(cr, uid, ids, context=context)
        return dict(res)

    _name = "hr.employee.category"
    _description = "Employee Category"
    _columns = {
        'name': fields.char("Category", size=64, required=True),
        'complete_name': fields.function(_name_get_fnc, type="char", string='Name'),
        'parent_id': fields.many2one('hr.employee.category', 'Parent Category', select=True),
        'child_ids': fields.one2many('hr.employee.category', 'parent_id', 'Child Categories'),
        'employee_ids': fields.many2many('hr.employee', 'employee_category_rel', 'category_id', 'emp_id', 'Employees'),
    }

    def _check_recursion(self, cr, uid, ids, context=None):
        level = 100
        while len(ids):
            cr.execute('select distinct parent_id from hr_employee_category where id IN %s', (tuple(ids), ))
            ids = filter(None, map(lambda x:x[0], cr.fetchall()))
            if not level:
                return False
            level -= 1
        return True

    _constraints = [
        (_check_recursion, 'Error ! You cannot create recursive Categories.', ['parent_id'])
    ]

hr_employee_category()

class hr_job(osv.osv):

    def _no_of_employee(self, cr, uid, ids, name, args, context=None):
        res = {}
        for job in self.browse(cr, uid, ids, context=context):
            nb_employees = len(job.employee_ids or [])
            res[job.id] = {
                'no_of_employee': nb_employees,
                'expected_employees': nb_employees + job.no_of_recruitment,
            }
        return res

    def _get_job_position(self, cr, uid, ids, context=None):
        result = {}
        for data in self.pool.get('hr.employee').browse(cr, uid, ids, context=context):
            if data.job_id:
                result[data.job_id.id] = True
        return result.keys()

    _name = "hr.job"
    _description = "Job Description"
    _columns = {
        'name': fields.char('Job Name', size=128, required=True, select=True),
        'expected_employees': fields.function(_no_of_employee, string='Expected Employees', help='Required number of Employees in total for that job.',
            store = {
                'hr.employee': (_get_job_position, ['job_id'], 10),
            },
            multi='no_of_employee'),
        'no_of_employee': fields.function(_no_of_employee, string="No of Employee", help='Number of employee with that job.',
            store = {
                'hr.employee': (_get_job_position, ['job_id'], 10),
            },
            multi='no_of_employee'),
        'no_of_recruitment': fields.float('Expected in Recruitment'),
        'employee_ids': fields.one2many('hr.employee', 'job_id', 'Employees'),
        'description': fields.text('Job Description'),
        'requirements': fields.text('Requirements'),
        'department_id': fields.many2one('hr.department', 'Department'),
        'company_id': fields.many2one('res.company', 'Company'),
        'state': fields.selection([('open', 'In Position'),('old', 'Old'),('recruit', 'In Recruitement')], 'State', readonly=True, required=True),
    }
    _defaults = {
        'expected_employees': 1,
        'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr.job', context=c),
        'state': 'open',
    }

    _sql_constraints = [
        ('name_company_uniq', 'unique(name, company_id)', 'The name of the job position must be unique per company!'),
    ]

    def on_change_expected_employee(self, cr, uid, ids, no_of_recruitment, no_of_employee, context=None):
        if context is None:
            context = {}
        return {'value': {'expected_employees': no_of_recruitment + no_of_employee}}

    def job_old(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {'state': 'old', 'no_of_recruitment': 0})
        return True

    def job_recruitement(self, cr, uid, ids, *args):
        for job in self.browse(cr, uid, ids):
            no_of_recruitment = job.no_of_recruitment == 0 and 1 or job.no_of_recruitment
            self.write(cr, uid, [job.id], {'state': 'recruit', 'no_of_recruitment': no_of_recruitment})
        return True

    def job_open(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {'state': 'open', 'no_of_recruitment': 0})
        return True

hr_job()

class hr_employee(osv.osv):
    _name = "hr.employee"
    _description = "Employee"
    _inherits = {'resource.resource': "resource_id"}
    _columns = {
        'country_id': fields.many2one('res.country', 'Nationality'),
        'birthday': fields.date("Date of Birth"),
        'ssnid': fields.char('SSN No', size=32, help='Social Security Number'),
        'sinid': fields.char('SIN No', size=32, help="Social Insurance Number"),
        'identification_id': fields.char('Identification No', size=32),
        'otherid': fields.char('Other Id', size=64),
        'gender': fields.selection([('male', 'Male'),('female', 'Female')], 'Gender'),
        'marital': fields.selection([('single', 'Single'), ('married', 'Married'), ('widower', 'Widower'), ('divorced', 'Divorced')], 'Marital Status'),
        'department_id':fields.many2one('hr.department', 'Department'),
        'address_id': fields.many2one('res.partner.address', 'Working Address'),
        'address_home_id': fields.many2one('res.partner.address', 'Home Address'),
        'partner_id': fields.related('address_home_id', 'partner_id', type='many2one', relation='res.partner', readonly=True, help="Partner that is related to the current employee. Accounting transaction will be written on this partner belongs to employee."),
        'bank_account_id':fields.many2one('res.partner.bank', 'Bank Account Number', domain="[('partner_id','=',partner_id)]", help="Employee bank salary account"),
        'work_phone': fields.char('Work Phone', size=32, readonly=False),
        'mobile_phone': fields.char('Work Mobile', size=32, readonly=False),
        'work_email': fields.char('Work E-mail', size=240),
        'work_location': fields.char('Office Location', size=32),
        'notes': fields.text('Notes'),
        'parent_id': fields.many2one('hr.employee', 'Manager'),
        'category_ids': fields.many2many('hr.employee.category', 'employee_category_rel', 'emp_id', 'category_id', 'Categories'),
        'child_ids': fields.one2many('hr.employee', 'parent_id', 'Subordinates'),
        'resource_id': fields.many2one('resource.resource', 'Resource', ondelete='cascade', required=True),
        'coach_id': fields.many2one('hr.employee', 'Coach'),
        'job_id': fields.many2one('hr.job', 'Job'),
        'photo': fields.binary('Photo'),
        'passport_id':fields.char('Passport No', size=64),
        'color': fields.integer('Color Index'),
        'city': fields.related('address_id', 'city', type='char', string='City'),
    }

    def unlink(self, cr, uid, ids, context=None):
        resource_obj = self.pool.get('resource.resource')
        resource_ids = []
        for employee in self.browse(cr, uid, ids, context=context):
            resource = employee.resource_id
            if resource:
                resource_ids.append(resource.id)
        if resource_ids:
            resource_obj.unlink(cr, uid, resource_ids, context=context)
        return super(hr_employee, self).unlink(cr, uid, ids, context=context)

    def onchange_address_id(self, cr, uid, ids, address, context=None):
        if address:
            address = self.pool.get('res.partner.address').browse(cr, uid, address, context=context)
            return {'value': {'work_email': address.email, 'work_phone': address.phone, 'mobile_phone': address.mobile}}
        return {'value': {}}

    def onchange_company(self, cr, uid, ids, company, context=None):
        address_id = False
        if company:
            company_id = self.pool.get('res.company').browse(cr, uid, company, context=context)
            address = self.pool.get('res.partner').address_get(cr, uid, [company_id.partner_id.id], ['default'])
            address_id = address and address['default'] or False
        return {'value': {'address_id' : address_id}}

    def onchange_department_id(self, cr, uid, ids, department_id, context=None):
        value = {'parent_id': False}
        if department_id:
            department = self.pool.get('hr.department').browse(cr, uid, department_id)
            value['parent_id'] = department.manager_id.id
        return {'value': value}

    def onchange_user(self, cr, uid, ids, user_id, context=None):
        work_email = False
        if user_id:
            work_email = self.pool.get('res.users').browse(cr, uid, user_id, context=context).user_email
        return {'value': {'work_email' : work_email}}

    def _get_photo(self, cr, uid, context=None):
        photo_path = addons.get_module_resource('hr','images','photo.png')
        return open(photo_path, 'rb').read().encode('base64')

    _defaults = {
        'active': 1,
        'photo': _get_photo,
        'marital': 'single',
        'color': 0,
    }

    def _check_recursion(self, cr, uid, ids, context=None):
        level = 100
        while len(ids):
            cr.execute('SELECT DISTINCT parent_id FROM hr_employee WHERE id IN %s AND parent_id!=id',(tuple(ids),))
            ids = filter(None, map(lambda x:x[0], cr.fetchall()))
            if not level:
                return False
            level -= 1
        return True

    _constraints = [
        (_check_recursion, 'Error ! You cannot create recursive Hierarchy of Employees.', ['parent_id']),
    ]

hr_employee()

class hr_department(osv.osv):
    _description = "Department"
    _inherit = 'hr.department'
    _columns = {
        'manager_id': fields.many2one('hr.employee', 'Manager'),
        'member_ids': fields.one2many('hr.employee', 'department_id', 'Members', readonly=True),
    }

hr_department()

class res_users(osv.osv):
    _name = 'res.users'
    _inherit = 'res.users'

    def create(self, cr, uid, data, context=None):
        user_id = super(res_users, self).create(cr, uid, data, context=context)

        # add shortcut unless 'noshortcut' is True in context
        if not(context and context.get('noshortcut', False)):
            data_obj = self.pool.get('ir.model.data')
            try:
                data_id = data_obj._get_id(cr, uid, 'hr', 'ir_ui_view_sc_employee')
                view_id  = data_obj.browse(cr, uid, data_id, context=context).res_id
                self.pool.get('ir.ui.view_sc').copy(cr, uid, view_id, default = {
                                            'user_id': user_id}, context=context)
            except:
                # Tolerate a missing shortcut. See product/product.py for similar code.
                logging.getLogger('orm').debug('Skipped meetings shortcut for user "%s"', data.get('name','<new'))

        return user_id

res_users()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>[IMP] hr : Improve the functionality<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program 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.
#
#    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import fields, osv
import logging
import addons

class hr_employee_category(osv.osv):

    def name_get(self, cr, uid, ids, context=None):
        if not ids:
            return []
        reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
        res = []
        for record in reads:
            name = record['name']
            if record['parent_id']:
                name = record['parent_id'][1]+' / '+name
            res.append((record['id'], name))
        return res

    def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
        res = self.name_get(cr, uid, ids, context=context)
        return dict(res)

    _name = "hr.employee.category"
    _description = "Employee Category"
    _columns = {
        'name': fields.char("Category", size=64, required=True),
        'complete_name': fields.function(_name_get_fnc, type="char", string='Name'),
        'parent_id': fields.many2one('hr.employee.category', 'Parent Category', select=True),
        'child_ids': fields.one2many('hr.employee.category', 'parent_id', 'Child Categories'),
        'employee_ids': fields.many2many('hr.employee', 'employee_category_rel', 'category_id', 'emp_id', 'Employees'),
    }

    def _check_recursion(self, cr, uid, ids, context=None):
        level = 100
        while len(ids):
            cr.execute('select distinct parent_id from hr_employee_category where id IN %s', (tuple(ids), ))
            ids = filter(None, map(lambda x:x[0], cr.fetchall()))
            if not level:
                return False
            level -= 1
        return True

    _constraints = [
        (_check_recursion, 'Error ! You cannot create recursive Categories.', ['parent_id'])
    ]

hr_employee_category()

class hr_job(osv.osv):

    def _no_of_employee(self, cr, uid, ids, name, args, context=None):
        res = {}
        for job in self.browse(cr, uid, ids, context=context):
            nb_employees = len(job.employee_ids or [])
            res[job.id] = {
                'no_of_employee': nb_employees,
                'expected_employees': nb_employees + job.no_of_recruitment,
            }
        return res

    def _get_job_position(self, cr, uid, ids, context=None):
        result = {}
        for data in self.pool.get('hr.employee').browse(cr, uid, ids, context=context):
            if data.job_id:
                result[data.job_id.id] = True
        return result.keys()

    _name = "hr.job"
    _description = "Job Description"
    _columns = {
        'name': fields.char('Job Name', size=128, required=True, select=True),
        'expected_employees': fields.function(_no_of_employee, string='Expected Employees', help='Required number of Employees in total for that job.',
            store = {
                'hr.job': (lambda self, cr, uid, ids, c={}: ids, ['no_of_recruitment'], 10),
                'hr.employee': (_get_job_position, ['job_id'], 10),
            },
            multi='no_of_employee'),
        'no_of_employee': fields.function(_no_of_employee, string="No of Employee", help='Number of employee with that job.',
            store = {
                'hr.employee': (_get_job_position, ['job_id'], 10),
            },
            multi='no_of_employee'),
        'no_of_recruitment': fields.float('Expected in Recruitment'),
        'employee_ids': fields.one2many('hr.employee', 'job_id', 'Employees'),
        'description': fields.text('Job Description'),
        'requirements': fields.text('Requirements'),
        'department_id': fields.many2one('hr.department', 'Department'),
        'company_id': fields.many2one('res.company', 'Company'),
        'state': fields.selection([('open', 'In Position'),('old', 'Old'),('recruit', 'In Recruitement')], 'State', readonly=True, required=True),
    }
    _defaults = {
        'expected_employees': 1,
        'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr.job', context=c),
        'state': 'open',
    }

    _sql_constraints = [
        ('name_company_uniq', 'unique(name, company_id)', 'The name of the job position must be unique per company!'),
    ]

    def on_change_expected_employee(self, cr, uid, ids, no_of_recruitment, no_of_employee, context=None):
        if context is None:
            context = {}
        return {'value': {'expected_employees': no_of_recruitment + no_of_employee}}

    def job_old(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {'state': 'old', 'no_of_recruitment': 0})
        return True

    def job_recruitement(self, cr, uid, ids, *args):
        for job in self.browse(cr, uid, ids):
            no_of_recruitment = job.no_of_recruitment == 0 and 1 or job.no_of_recruitment
            self.write(cr, uid, [job.id], {'state': 'recruit', 'no_of_recruitment': no_of_recruitment})
        return True

    def job_open(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {'state': 'open', 'no_of_recruitment': 0})
        return True

hr_job()

class hr_employee(osv.osv):
    _name = "hr.employee"
    _description = "Employee"
    _inherits = {'resource.resource': "resource_id"}
    _columns = {
        'country_id': fields.many2one('res.country', 'Nationality'),
        'birthday': fields.date("Date of Birth"),
        'ssnid': fields.char('SSN No', size=32, help='Social Security Number'),
        'sinid': fields.char('SIN No', size=32, help="Social Insurance Number"),
        'identification_id': fields.char('Identification No', size=32),
        'otherid': fields.char('Other Id', size=64),
        'gender': fields.selection([('male', 'Male'),('female', 'Female')], 'Gender'),
        'marital': fields.selection([('single', 'Single'), ('married', 'Married'), ('widower', 'Widower'), ('divorced', 'Divorced')], 'Marital Status'),
        'department_id':fields.many2one('hr.department', 'Department'),
        'address_id': fields.many2one('res.partner.address', 'Working Address'),
        'address_home_id': fields.many2one('res.partner.address', 'Home Address'),
        'partner_id': fields.related('address_home_id', 'partner_id', type='many2one', relation='res.partner', readonly=True, help="Partner that is related to the current employee. Accounting transaction will be written on this partner belongs to employee."),
        'bank_account_id':fields.many2one('res.partner.bank', 'Bank Account Number', domain="[('partner_id','=',partner_id)]", help="Employee bank salary account"),
        'work_phone': fields.char('Work Phone', size=32, readonly=False),
        'mobile_phone': fields.char('Work Mobile', size=32, readonly=False),
        'work_email': fields.char('Work E-mail', size=240),
        'work_location': fields.char('Office Location', size=32),
        'notes': fields.text('Notes'),
        'parent_id': fields.many2one('hr.employee', 'Manager'),
        'category_ids': fields.many2many('hr.employee.category', 'employee_category_rel', 'emp_id', 'category_id', 'Categories'),
        'child_ids': fields.one2many('hr.employee', 'parent_id', 'Subordinates'),
        'resource_id': fields.many2one('resource.resource', 'Resource', ondelete='cascade', required=True),
        'coach_id': fields.many2one('hr.employee', 'Coach'),
        'job_id': fields.many2one('hr.job', 'Job'),
        'photo': fields.binary('Photo'),
        'passport_id':fields.char('Passport No', size=64),
        'color': fields.integer('Color Index'),
        'city': fields.related('address_id', 'city', type='char', string='City'),
    }

    def unlink(self, cr, uid, ids, context=None):
        resource_obj = self.pool.get('resource.resource')
        resource_ids = []
        for employee in self.browse(cr, uid, ids, context=context):
            resource = employee.resource_id
            if resource:
                resource_ids.append(resource.id)
        if resource_ids:
            resource_obj.unlink(cr, uid, resource_ids, context=context)
        return super(hr_employee, self).unlink(cr, uid, ids, context=context)

    def onchange_address_id(self, cr, uid, ids, address, context=None):
        if address:
            address = self.pool.get('res.partner.address').browse(cr, uid, address, context=context)
            return {'value': {'work_email': address.email, 'work_phone': address.phone, 'mobile_phone': address.mobile}}
        return {'value': {}}

    def onchange_company(self, cr, uid, ids, company, context=None):
        address_id = False
        if company:
            company_id = self.pool.get('res.company').browse(cr, uid, company, context=context)
            address = self.pool.get('res.partner').address_get(cr, uid, [company_id.partner_id.id], ['default'])
            address_id = address and address['default'] or False
        return {'value': {'address_id' : address_id}}

    def onchange_department_id(self, cr, uid, ids, department_id, context=None):
        value = {'parent_id': False}
        if department_id:
            department = self.pool.get('hr.department').browse(cr, uid, department_id)
            value['parent_id'] = department.manager_id.id
        return {'value': value}

    def onchange_user(self, cr, uid, ids, user_id, context=None):
        work_email = False
        if user_id:
            work_email = self.pool.get('res.users').browse(cr, uid, user_id, context=context).user_email
        return {'value': {'work_email' : work_email}}

    def _get_photo(self, cr, uid, context=None):
        photo_path = addons.get_module_resource('hr','images','photo.png')
        return open(photo_path, 'rb').read().encode('base64')

    _defaults = {
        'active': 1,
        'photo': _get_photo,
        'marital': 'single',
        'color': 0,
    }

    def _check_recursion(self, cr, uid, ids, context=None):
        level = 100
        while len(ids):
            cr.execute('SELECT DISTINCT parent_id FROM hr_employee WHERE id IN %s AND parent_id!=id',(tuple(ids),))
            ids = filter(None, map(lambda x:x[0], cr.fetchall()))
            if not level:
                return False
            level -= 1
        return True

    _constraints = [
        (_check_recursion, 'Error ! You cannot create recursive Hierarchy of Employees.', ['parent_id']),
    ]

hr_employee()

class hr_department(osv.osv):
    _description = "Department"
    _inherit = 'hr.department'
    _columns = {
        'manager_id': fields.many2one('hr.employee', 'Manager'),
        'member_ids': fields.one2many('hr.employee', 'department_id', 'Members', readonly=True),
    }

hr_department()

class res_users(osv.osv):
    _name = 'res.users'
    _inherit = 'res.users'

    def create(self, cr, uid, data, context=None):
        user_id = super(res_users, self).create(cr, uid, data, context=context)

        # add shortcut unless 'noshortcut' is True in context
        if not(context and context.get('noshortcut', False)):
            data_obj = self.pool.get('ir.model.data')
            try:
                data_id = data_obj._get_id(cr, uid, 'hr', 'ir_ui_view_sc_employee')
                view_id  = data_obj.browse(cr, uid, data_id, context=context).res_id
                self.pool.get('ir.ui.view_sc').copy(cr, uid, view_id, default = {
                                            'user_id': user_id}, context=context)
            except:
                # Tolerate a missing shortcut. See product/product.py for similar code.
                logging.getLogger('orm').debug('Skipped meetings shortcut for user "%s"', data.get('name','<new'))

        return user_id

res_users()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>


<commit_before>#!/usr/bin/env python
import codecs
import logging
import os
import sys
from decimal import *

import synctools

__all__ = ['adjustoffset']

def adjustoffset(simfile):
    log = logging.getLogger('synctools')
    cfg = synctools.get_config()
    synctools.backup(simfile)
    with codecs.open(simfile.filename, 'w', 'utf-8') as output:
        for param in simfile.params:
            if param[0].upper() == 'OFFSET':
                # Process offset
                offset = Decimal(param[1])
                offset2 = offset + Decimal(cfg['adjustoffset']['amount'])
                log.info('%s -> %s' % (str(offset), str(offset2)))
                # Rewrite parameter
                param[1] = str(offset2)
            output.write(unicode(param) + '\n')

if __name__ == '__main__':
    os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))
    synctools.main_iterator(adjustoffset, sys.argv[1:])<commit_msg>Reworked adjustoffset to use new Simfile methods<commit_after>#!/usr/bin/env python
import codecs
import logging
import os
import sys
from decimal import *

import synctools

__all__ = ['adjustoffset']

def adjustoffset(simfile):
    log = logging.getLogger('synctools')
    cfg = synctools.get_config()
    synctools.backup(simfile)
    offset_param = simfile.get('OFFSET')
    # Process offset
    offset = Decimal(offset_param[1])
    offset2 = offset + Decimal(cfg['adjustoffset']['amount'])
    log.info('%s -> %s' % (str(offset), str(offset2)))
    # Rewrite parameter
    offset_param[1] = str(offset2)
    simfile.save()

if __name__ == '__main__':
    os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))
    synctools.main_iterator(adjustoffset, sys.argv[1:])<|endoftext|>


<commit_before><commit_msg>Add tests for probscores<commit_after><|endoftext|>


<commit_before><commit_msg>new stacked bar for metabolites inhibiting subsystems<commit_after><|endoftext|>


<commit_before><commit_msg>remove code that will never be reached<commit_after><|endoftext|>


<commit_before>import turtle as t

GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"

t.fillcolor(FARBE)
t.shape(SHAPE)
t.pu()

def zeichneKerze(brennt):
    t.pd()
    t.fillcolor(FARBE)
    t.begin_fill()
    t.forward(GROESSE*100)
    t.left(90)
    t.forward(GROESSE*400)
    t.left(90)
    t.forward(GROESSE*100)
    t.right(90)
    t.forward(GROESSE*30)
    t.back(GROESSE*30)
    t.left(90)
    t.forward(GROESSE*100)
    t.left(90)
    t.forward(GROESSE*400)
    t.left(90)
    t.forward(GROESSE*100)
    t.end_fill()
    t.pu()
    if brennt:
        zeichneFlamme()

def zeichneFlamme():
    t.left(90)
    t.fd(GROESSE*430)
    t.pd()
    t.color("yellow")
    t.dot(GROESSE*60)
    t.color("black")
    t.back(GROESSE*30)
    t.pu()
    t.bk(GROESSE*400)
    t.right(90)

def zeichneZweige(numCandles):
    t.pd()
    t.pensize(100)
    t.color("darkgreen")
    t.fd(numCandles * 75)
    t.bk(numCandles * 150)
    t.pu()

def zeichneKranz(numCandles, numBurning):
    t.pu()
    if numCandles in [2,4]:
        t.bk(GROESSE * 125)
    t.bk(GROESSE * 250) # equivalent to numCandles * GROESSE * 250/numCandles
    for i in range(numCandles):
        isBurning = (i < numBurning)
        zeichneKerze(isBurning)
        t.fd(GROESSE * 250)
    t.pu()
    t.home()
    zeichneZweige(numCandles)

if __name__=="__main__":
    zeichneKranz(4, 4)
    t.hideturtle()
<commit_msg>Make identifiers consistent by translating them into English<commit_after>import turtle as t

SIZE = 0.5
CANDLE_COLOR = "red"
DYE = True
SHAPE = "turtle"

t.fillcolor(CANDLE_COLOR)
t.shape(SHAPE)
t.pu()

def drawCandle(is_candle_burning):
    t.pd()
    t.fillcolor(CANDLE_COLOR)
    t.begin_fill()
    t.forward(SIZE*100)
    t.left(90)
    t.forward(SIZE*400)
    t.left(90)
    t.forward(SIZE*100)
    t.right(90)
    t.forward(SIZE*30)
    t.back(SIZE*30)
    t.left(90)
    t.forward(SIZE*100)
    t.left(90)
    t.forward(SIZE*400)
    t.left(90)
    t.forward(SIZE*100)
    t.end_fill()
    t.pu()
    if is_candle_burning:
        drawFlame()

def drawFlame():
    t.left(90)
    t.fd(SIZE*430)
    t.pd()
    t.color("yellow")
    t.dot(SIZE*60)
    t.color("black")
    t.back(SIZE*30)
    t.pu()
    t.bk(SIZE*400)
    t.right(90)

def drawLop(numCandles):
    t.pd()
    t.pensize(100)
    t.color("darkgreen")
    t.fd(numCandles * 75)
    t.bk(numCandles * 150)
    t.pu()

def drawWreath(numCandles, numBurning):
    t.pu()
    if numCandles in [2,4]:
        t.bk(SIZE * 125)
    t.bk(SIZE * 250) # equivalent to numCandles * SIZE * 250/numCandles
    for i in range(numCandles):
        isBurning = (i < numBurning)
        drawCandle(isBurning)
        t.fd(SIZE * 250)
    t.pu()
    t.home()
    drawLop(numCandles)

if __name__=="__main__":
    drawWreath(4, 4)
    t.hideturtle()
<|endoftext|>


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

__author__ = 'nickl-'

import sys
import textwrap

from .__version__ import __version_info__

from .cache import CacheProviderFactory
from .adapters import AVAILABLE_ADAPTERS

def coroutine(func):
    def start(*args,**kwargs):
        cr = func(*args,**kwargs)
        cr.next()
        return cr
    return start

class ProgressTicker():

    ref = None
    result = None
    steps = len(AVAILABLE_ADAPTERS)
    taken = 0

    def routine(self, routine):
        self.ref = routine

    def done(self):
        return int(float(self.taken) / float(self.steps) * 100)

    def terminate(self):
        self.taken = self.steps
        self.ref.send('terminate')

    def send(self, args):
        if isinstance(args, int):
            self.taken += args
        elif isinstance(args[0], str) and args[0] == 'step':
            self.steps += args[1]
        else:
            self.taken += args[0]
            if isinstance(args[1], dict):
                if not self.result:
                    self.result = {}
                self.result.update(args[1])
            elif isinstance(args[1], list):
                if not self.result:
                    self.result = []
                self.result.extend(args[1])
        self.ref.send(self.result)

class CommandProcessor():

    cache = CacheProviderFactory().whichProvider()
    data = None
    out = None
    ticker = ProgressTicker()
    clear = '\x1b[2J\x1b[0;0H'

    def __init__(self, data):
        self.data = data
        self.out = self.write()
        if self.data.invalidate:
            self.cache.invalidate(True)
        self.out.send(
            self.clear +
            'aero v{}.{}.{} {} {}\n\n'.format(*__version_info__)
        )

    def execute(self):
        try:
            next = self.wiring()
            self.do(self.data.packages, next)
        except BaseException as e:
            self.out.send(
                '\n\n[{}{}] Terminating...\n'.format(
                    type(e).__name__,
                    ': {}'.format(e) if len('{}'.format(e)) else ''
                ))
            self.ticker.terminate()

    # wire coroutines
    def wiring(self):
        self.ticker.routine(self.progress(self.res()))
        return self.each(self.call(self.ticker))

    @coroutine
    def res(self):
        while True: (yield)

    def cmd(self):
        return self.__class__.__name__.replace('Command', '').lower()

    def do(self, packages, adapters):
        self.ticker.steps = len(packages) * len(AVAILABLE_ADAPTERS)
        for package in packages:
            if ':' in package:
                mngr = package.partition(':')
                pkg = mngr[2]
                mngr = mngr[0]
            else:
                mngr = None
                pkg = package
            adapters.send((pkg, mngr))

    @coroutine
    def write(self):
        from cStringIO import StringIO
        out = StringIO()
        while True:
            text = (yield)
            out.write(text)
            print out.getvalue()

    def seen(self, command, adapter, package, result=False):
        cache_key = command + "+" + adapter + ":" + package
        return self.cache.seen(cache_key, result)

    @coroutine
    def each(self, target):
        while True:
            args = (yield)
            package = args[0]
            manager = args[1]
            for adapter in AVAILABLE_ADAPTERS:
                adapter_name = adapter[0]
                if adapter_name not in self.data.disabled:
                    if not manager or manager == adapter_name:
                        length = str(max([len(a[0]) for a in AVAILABLE_ADAPTERS]))
                        self.out.send(
                            ('Doing an aero {} of package: {} using {:<' + length + '} ').format(
                                self.cmd(), package, adapter_name
                            )
                        )
                        res = self.seen(self.cmd(), adapter_name, package)
                        if self.data.invalidate or res is False:
                            target.send((adapter, package))
                        else:
                            self.out.send('Found {:>4} options [CACHED]\n'.format(len(res)))
                            self.ticker.send((1, res))
                    else:
                        self.ticker.send(1)
                else:
                    self.ticker.send(1)

    @coroutine
    def progress(self, target):
        from progbar import ProgBar
        bar = ProgBar('Progress: ', 30)
        bar.start()
        while True:
            result = (yield)
            self.out.send('')
            bar.percent = self.ticker.done()
            if self.ticker.done() == 100:
                if bar.isAlive():
                    bar.stop()
                bar.join()
                self.out.send('')
                if not isinstance(result, str): # terminate
                    target.send(result)

    @coroutine
    def call(self, target):
        while True:
            adapter_name = ''
            payload = (yield)
            adapter_name = payload[0][0]
            adapter = payload[0][1]
            package = payload[1]
            try:
                adapter.passthruArgs(self.data.passthru)
                aero = getattr(adapter, self.cmd())(package)
                if self.cmd() == 'search':
                    self.out.send('Found {:>4} options\n'.format(len(aero)))
                else:
                    self.out.send('\n')
                target.send((1,
                    self.seen(
                        self.cmd(),
                        adapter_name,
                        package,
                        aero
                    ))
                )
            except Exception as e:
                target.send((1,
                    ['Aborted: {} has no implementation for command: {}\nWith message: {}\n'.format(
                        adapter_name, self.cmd(), e
                    )]
                ))

class DebugCommandProcessor(CommandProcessor):

    def seen(self, command, adapter, package, result=False):
        if not isinstance(result, bool):
            print '\n{:=^100}'.format('')
            print '{:=^100}'.format(' '+command+' '+adapter+' '+package+' ')
            print '{:=^100}'.format('')
            print 'Result type: ', type(result).__name__
            itr = result
            if isinstance(result, dict):
                itr = result.items()
            for r in itr:
                print '{} | {:^5} | {}'.format(type(r).__name__, len(r), r)
            print '\n'
        return result

    @coroutine
    def write(self):
        import sys
        out = sys.stdout
        while True:
            text = (yield)
            out.write(text)

    @coroutine
    def progress(self, target):
        while True:
            result = (yield)
            if self.ticker.done() == 100:
                target.send(result)

    def execute(self):
        next = self.wiring()
        self.do(self.data.packages, next)

class SearchCommand(CommandProcessor):

    @coroutine
    def res(self):
        while True:
            res = (yield)
            if res:
                res = sorted(res.items())
                from cStringIO import StringIO
                pager = StringIO()
                pager.write(u"\n{:>48}   {:<52}\n".format("PACKAGE NAME", "DESCRIPTION"))
                pager.write(u"{:>48}   {:<52}\n".format("_" * 40, "_" * 50))
                for key, value in res:
                    try:
                        value = value.decode('utf-8')
                        if value.startswith(u'\ufeff'):
                            value = value[len(u'\ufeff'):]
                    except UnicodeDecodeError:
                        value = value.decode('latin1')
                    try:
                        key = key.decode('utf-8')
                        if key.startswith(u'\ufeff'):
                            key = key[len(u'\ufeff'):]
                    except UnicodeDecodeError:
                        key = key.decode('latin1')

                    key = key.encode('utf')
                    for line in value.splitlines():
                        line = line.encode('utf')
                        if key:
                            key += ' :'
                        if len(line) > 50:
                            for wrap in textwrap.wrap(line, 50):
                                pager.write("{:>50} {:<50}\n".format(key, wrap))
                                key = ''
                        else:
                            pager.write("{:>50} {:<50}\n".format(key, line))
                        key = ''
                pager.write('\n')
                from pygments import highlight
                from pygments.lexers import CppLexer
                from pygments.formatters import Terminal256Formatter
                out = pager.getvalue()
                out = highlight(out, CppLexer(), Terminal256Formatter())
                out = out.encode('utf')
                if len(out.splitlines()) > 30:
                    from subprocess import Popen, PIPE
                    Popen(self.data.pager, shell=True, stdin=PIPE).communicate(input=out)
                else:
                    print out

class InstallCommand(CommandProcessor):

    def wiring(self):
        self.out = self.write()
        self.ticker.routine(self.progress(None))
        return self.each(self.spacing(self.call(self.res())))

    def seen(self, command, adapter, package, result=False):
        return result

    @coroutine
    def write(self):
        import sys
        out = sys.stdout
        while True:
            text = (yield)
            out.write(text)

    @coroutine
    def spacing(self, target):
        while True:
            payload = (yield)
            print '\n'
            target.send(payload)

    @coroutine
    def progress(self, responder):
        while True: (yield)

class InfoCommand(CommandProcessor):

    @coroutine
    def res(self):
        while True:
            res = (yield)
            if 'Aborted:' in res[0]:
                print res[0]
                continue
            key = ''
            from cStringIO import StringIO
            pager = StringIO()
            pager.write("\n{:>48}   {:<52}\n".format('', 'INFORMATION: '))
            pager.write("{:>47}    {:<52}\n".format("_" * 40, "_" * 50))
            for line in res:
                if isinstance(line, tuple) or isinstance(line, list):
                    if len(line) >= 2:
                        key = line[0] + ': : ' if line[0] else '   '
                        line = line[1]
                    else:
                        line = line[0]
                if line:
                    for l in line.splitlines():
                        if len(l) > 50:
                            for wrap in textwrap.wrap(l, 50):
                                pager.write("{:>50} {:50}\n".format(key, wrap))
                                key = ''
                        else:
                            pager.write("{:>50} {:50}\n".format(key, l))
                            key = ''
            from pygments import highlight
            from pygments.lexers import CppLexer
            from pygments.formatters import Terminal256Formatter
            print highlight(pager.getvalue(), CppLexer(), Terminal256Formatter())

<commit_msg>Use str convert instead of format<commit_after># -*- coding: utf-8 -*-

__author__ = 'nickl-'

import sys
import textwrap

from .__version__ import __version_info__

from .cache import CacheProviderFactory
from .adapters import AVAILABLE_ADAPTERS

def coroutine(func):
    def start(*args,**kwargs):
        cr = func(*args,**kwargs)
        cr.next()
        return cr
    return start

class ProgressTicker():

    ref = None
    result = None
    steps = len(AVAILABLE_ADAPTERS)
    taken = 0

    def routine(self, routine):
        self.ref = routine

    def done(self):
        return int(float(self.taken) / float(self.steps) * 100)

    def terminate(self):
        self.taken = self.steps
        self.ref.send('terminate')

    def send(self, args):
        if isinstance(args, int):
            self.taken += args
        elif isinstance(args[0], str) and args[0] == 'step':
            self.steps += args[1]
        else:
            self.taken += args[0]
            if isinstance(args[1], dict):
                if not self.result:
                    self.result = {}
                self.result.update(args[1])
            elif isinstance(args[1], list):
                if not self.result:
                    self.result = []
                self.result.extend(args[1])
        self.ref.send(self.result)

class CommandProcessor():

    cache = CacheProviderFactory().whichProvider()
    data = None
    out = None
    ticker = ProgressTicker()
    clear = '\x1b[2J\x1b[0;0H'

    def __init__(self, data):
        self.data = data
        self.out = self.write()
        if self.data.invalidate:
            self.cache.invalidate(True)
        self.out.send(
            self.clear +
            'aero v{}.{}.{} {} {}\n\n'.format(*__version_info__)
        )

    def execute(self):
        try:
            next = self.wiring()
            self.do(self.data.packages, next)
        except BaseException as e:
            self.out.send(
                '\n\n[{}{}] Terminating...\n'.format(
                    type(e).__name__,
                    ': {}'.format(e) if len(str(e)) else ''
                ))
            self.ticker.terminate()

    # wire coroutines
    def wiring(self):
        self.ticker.routine(self.progress(self.res()))
        return self.each(self.call(self.ticker))

    @coroutine
    def res(self):
        while True: (yield)

    def cmd(self):
        return self.__class__.__name__.replace('Command', '').lower()

    def do(self, packages, adapters):
        self.ticker.steps = len(packages) * len(AVAILABLE_ADAPTERS)
        for package in packages:
            if ':' in package:
                mngr = package.partition(':')
                pkg = mngr[2]
                mngr = mngr[0]
            else:
                mngr = None
                pkg = package
            adapters.send((pkg, mngr))

    @coroutine
    def write(self):
        from cStringIO import StringIO
        out = StringIO()
        while True:
            text = (yield)
            out.write(text)
            print out.getvalue()

    def seen(self, command, adapter, package, result=False):
        cache_key = command + "+" + adapter + ":" + package
        return self.cache.seen(cache_key, result)

    @coroutine
    def each(self, target):
        while True:
            args = (yield)
            package = args[0]
            manager = args[1]
            for adapter in AVAILABLE_ADAPTERS:
                adapter_name = adapter[0]
                if adapter_name not in self.data.disabled:
                    if not manager or manager == adapter_name:
                        length = str(max([len(a[0]) for a in AVAILABLE_ADAPTERS]))
                        self.out.send(
                            ('Doing an aero {} of package: {} using {:<' + length + '} ').format(
                                self.cmd(), package, adapter_name
                            )
                        )
                        res = self.seen(self.cmd(), adapter_name, package)
                        if self.data.invalidate or res is False:
                            target.send((adapter, package))
                        else:
                            self.out.send('Found {:>4} options [CACHED]\n'.format(len(res)))
                            self.ticker.send((1, res))
                    else:
                        self.ticker.send(1)
                else:
                    self.ticker.send(1)

    @coroutine
    def progress(self, target):
        from progbar import ProgBar
        bar = ProgBar('Progress: ', 30)
        bar.start()
        while True:
            result = (yield)
            self.out.send('')
            bar.percent = self.ticker.done()
            if self.ticker.done() == 100:
                if bar.isAlive():
                    bar.stop()
                bar.join()
                self.out.send('')
                if not isinstance(result, str): # terminate
                    target.send(result)

    @coroutine
    def call(self, target):
        while True:
            adapter_name = ''
            payload = (yield)
            adapter_name = payload[0][0]
            adapter = payload[0][1]
            package = payload[1]
            try:
                adapter.passthruArgs(self.data.passthru)
                aero = getattr(adapter, self.cmd())(package)
                if self.cmd() == 'search':
                    self.out.send('Found {:>4} options\n'.format(len(aero)))
                else:
                    self.out.send('\n')
                target.send((1,
                    self.seen(
                        self.cmd(),
                        adapter_name,
                        package,
                        aero
                    ))
                )
            except Exception as e:
                target.send((1,
                    ['Aborted: {} has no implementation for command: {}\nWith message: {}\n'.format(
                        adapter_name, self.cmd(), e
                    )]
                ))

class DebugCommandProcessor(CommandProcessor):

    def seen(self, command, adapter, package, result=False):
        if not isinstance(result, bool):
            print '\n{:=^100}'.format('')
            print '{:=^100}'.format(' '+command+' '+adapter+' '+package+' ')
            print '{:=^100}'.format('')
            print 'Result type: ', type(result).__name__
            itr = result
            if isinstance(result, dict):
                itr = result.items()
            for r in itr:
                print '{} | {:^5} | {}'.format(type(r).__name__, len(r), r)
            print '\n'
        return result

    @coroutine
    def write(self):
        import sys
        out = sys.stdout
        while True:
            text = (yield)
            out.write(text)

    @coroutine
    def progress(self, target):
        while True:
            result = (yield)
            if self.ticker.done() == 100:
                target.send(result)

    def execute(self):
        next = self.wiring()
        self.do(self.data.packages, next)

class SearchCommand(CommandProcessor):

    @coroutine
    def res(self):
        while True:
            res = (yield)
            if res:
                res = sorted(res.items())
                from cStringIO import StringIO
                pager = StringIO()
                pager.write(u"\n{:>48}   {:<52}\n".format("PACKAGE NAME", "DESCRIPTION"))
                pager.write(u"{:>48}   {:<52}\n".format("_" * 40, "_" * 50))
                for key, value in res:
                    try:
                        value = value.decode('utf-8')
                        if value.startswith(u'\ufeff'):
                            value = value[len(u'\ufeff'):]
                    except UnicodeDecodeError:
                        value = value.decode('latin1')
                    try:
                        key = key.decode('utf-8')
                        if key.startswith(u'\ufeff'):
                            key = key[len(u'\ufeff'):]
                    except UnicodeDecodeError:
                        key = key.decode('latin1')

                    key = key.encode('utf')
                    for line in value.splitlines():
                        line = line.encode('utf')
                        if key:
                            key += ' :'
                        if len(line) > 50:
                            for wrap in textwrap.wrap(line, 50):
                                pager.write("{:>50} {:<50}\n".format(key, wrap))
                                key = ''
                        else:
                            pager.write("{:>50} {:<50}\n".format(key, line))
                        key = ''
                pager.write('\n')
                from pygments import highlight
                from pygments.lexers import CppLexer
                from pygments.formatters import Terminal256Formatter
                out = pager.getvalue()
                out = highlight(out, CppLexer(), Terminal256Formatter())
                out = out.encode('utf')
                if len(out.splitlines()) > 30:
                    from subprocess import Popen, PIPE
                    Popen(self.data.pager, shell=True, stdin=PIPE).communicate(input=out)
                else:
                    print out

class InstallCommand(CommandProcessor):

    def wiring(self):
        self.out = self.write()
        self.ticker.routine(self.progress(None))
        return self.each(self.spacing(self.call(self.res())))

    def seen(self, command, adapter, package, result=False):
        return result

    @coroutine
    def write(self):
        import sys
        out = sys.stdout
        while True:
            text = (yield)
            out.write(text)

    @coroutine
    def spacing(self, target):
        while True:
            payload = (yield)
            print '\n'
            target.send(payload)

    @coroutine
    def progress(self, responder):
        while True: (yield)

class InfoCommand(CommandProcessor):

    @coroutine
    def res(self):
        while True:
            res = (yield)
            if 'Aborted:' in res[0]:
                print res[0]
                continue
            key = ''
            from cStringIO import StringIO
            pager = StringIO()
            pager.write("\n{:>48}   {:<52}\n".format('', 'INFORMATION: '))
            pager.write("{:>47}    {:<52}\n".format("_" * 40, "_" * 50))
            for line in res:
                if isinstance(line, tuple) or isinstance(line, list):
                    if len(line) >= 2:
                        key = line[0] + ': : ' if line[0] else '   '
                        line = line[1]
                    else:
                        line = line[0]
                if line:
                    for l in line.splitlines():
                        if len(l) > 50:
                            for wrap in textwrap.wrap(l, 50):
                                pager.write("{:>50} {:50}\n".format(key, wrap))
                                key = ''
                        else:
                            pager.write("{:>50} {:50}\n".format(key, l))
                            key = ''
            from pygments import highlight
            from pygments.lexers import CppLexer
            from pygments.formatters import Terminal256Formatter
            print highlight(pager.getvalue(), CppLexer(), Terminal256Formatter())

<|endoftext|>


<commit_before><commit_msg>wrote script to convert the modified Johnson et al. instances to STP. This gives us 72 new instances<commit_after><|endoftext|>


<commit_before>
class Fragment(object):

	def __init__(self,
				label,
				species_repr):
		self.index = -1
		self.label = label
		self.species_repr = species_repr

	def __str__(self):
		"""
		Return a string representation, in the form 'label(id)'.
		"""
		if self.index == -1: return self.label
		else: return '{0}({1:d})'.format(self.label, self.index)

	def _repr_png_(self):
		if len(self.species_repr.molecule) > 0:
			return self.species_repr.molecule[0]._repr_png_()
		else:
			return None<commit_msg>add Graph as super class for Fragment<commit_after>
from rmgpy.molecule.graph import Graph

class Fragment(Graph):

	def __init__(self,
				label,
				species_repr,
				atoms=None):
		self.index = -1
		self.label = label
		self.species_repr = species_repr
		Graph.__init__(self, atoms)

	def __str__(self):
		"""
		Return a string representation, in the form 'label(id)'.
		"""
		if self.index == -1: return self.label
		else: return '{0}({1:d})'.format(self.label, self.index)

	def _repr_png_(self):
		if len(self.species_repr.molecule) > 0:
			return self.species_repr.molecule[0]._repr_png_()
		else:
			return None<|endoftext|>


<commit_before>#!/usr/bin/env python
from EPPs.common import StepEPP, step_argparser, get_workflow_stage

class AssignContainerName(StepEPP):

    def _run(self):
        #projects = self.projects(unique=True)
        #projectName=projects[0].name
        #print(projectName)
        artifacts = self.process.all_outputs(unique=True)
        artifacts[0].container.name = 'test'
        artifacts[0].container.name.put()

def main():
    p = step_argparser()
    args = p.parse_args()
    action = AssignContainerName(args.step_uri, args.username, args.password)
    action.run()
    action.run()

if __name__ == '__main__':
    main()
<commit_msg>New script for naming containers in FluidX Transfer from Rack to Plate<commit_after>#!/opt/gls/clarity/users/glsai/Applications/clarity_scripts/import_prod_script/bin/python3.4
from EPPs.common import StepEPP, step_argparser, get_workflow_stage

class AssignContainerName(StepEPP):
    # assigns the container automatically for the FluidX Transfer from Rack to Plate step using rule of Project+P+9.
    # Checks to see if thecontainer name has already been used.

    def _run(self):
        # lists all of the output artifacts for the process.
        processOutputs = list(self.process.all_outputs(unique=True))

        # loops through each artifact, when an analyte type artifact is found it updates the container name with the rule stated above then breaks the loop
        # as this only needs to occur once as the step can only process a single rack of tubes from a single project.
        for p in processOutputs:
            if p.output_type == 'Analyte':
                print(p)
                project = p.samples[0].project.name
                newContainerName = FindAvailableContainer(self, project=project, count=1)
                p.container.name = newContainerName
                p.container.put()

                break

        print(newContainerName)

def FindAvailableContainer(self, project, count):
    if self.lims.get_artifacts(containername=project + 'P' + str(count)) == []:
        newContainerName = project + 'P' + str(count)
        return newContainerName
    else:
        count = count + 1
        print(self.lims.get_artifacts(containername=project + 'P' + str(count)) == [])
        newContainerName = FindAvailableContainer(self, project=project, count=count)

        return newContainerName

def main():
    p = step_argparser()
    args = p.parse_args()
    action = AssignContainerName(args.step_uri, args.username, args.password)
    action.run()

if __name__ == '__main__':
    main()<|endoftext|>


<commit_before># coding: utf-8
import os
import logging
from normality import slugify
from ingestors.util import decode_path
from flask_script import Manager, commands as flask_script_commands
from flask_script.commands import ShowUrls
from flask_migrate import MigrateCommand

from aleph.core import create_app, archive
from aleph.model import db, upgrade_db, Collection, Document, Role
from aleph.views import mount_app_blueprints
from aleph.analyze import install_analyzers
from aleph.ingest import ingest_document
from aleph.index import delete_index, upgrade_search
from aleph.index import index_document_id
from aleph.logic import reindex_entities, delete_collection, process_collection
from aleph.logic import update_collection
from aleph.logic.alerts import check_alerts
from aleph.logic.entities import bulk_load
from aleph.logic.xref import xref_collection
from aleph.util import load_config_file

log = logging.getLogger('aleph')
flask_script_commands.text_type = str

app = create_app()
mount_app_blueprints(app)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
manager.add_command('routes', ShowUrls)

@manager.command
def collections():
    """List all collections."""
    for collection in Collection.all():
        print collection.id, collection.foreign_id, collection.label

@manager.command
def alerts():
    """Generate alert notifications."""
    check_alerts.delay()

@manager.command
@manager.option('-l', '--language', dest='language', nargs='*')
@manager.option('-c', '--country', dest='country', nargs='*')
@manager.option('-f', '--foreign_id', dest='foreign_id')
def crawldir(path, language=None, country=None, foreign_id=None):
    """Crawl the given directory."""
    path = decode_path(path)
    if path is None or not os.path.exists(path):
        log.error("Invalid path: %r", path)
        return
    path = os.path.abspath(os.path.normpath(path))
    path_name = os.path.basename(path)

    if foreign_id is None:
        foreign_id = 'directory:%s' % slugify(path)
    collection = Collection.by_foreign_id(foreign_id)
    if collection is None:
        collection = Collection.create({
            'foreign_id': foreign_id,
            'label': path_name,
            'managed': True
        })

    if language is not None:
        collection.languages = [language]
    if country is not None:
        collection.countries = [country]
    db.session.commit()
    update_collection(collection)

    log.info('Crawling %r to %r...', path, collection.foreign_id)
    document = Document.by_keys(collection=collection,
                                foreign_id=path)
    document.file_name = path_name
    ingest_document(document, path)

@manager.command
def flush(foreign_id):
    """Reset the crawler state for a given collecton."""
    collection = Collection.by_foreign_id(foreign_id, deleted=True)
    if collection is None:
        raise ValueError("No such collection: %r" % foreign_id)
    delete_collection(collection.id)

@manager.command
def process(foreign_id):
    """Re-process documents in the given collection."""
    collection = Collection.by_foreign_id(foreign_id)
    if collection is None:
        raise ValueError("No such collection: %r" % foreign_id)
    process_collection(collection.id)

@manager.command
def xref(foreign_id):
    """Cross-reference all entities and documents in a collection."""
    collection = Collection.by_foreign_id(foreign_id)
    if collection is None:
        raise ValueError("No such collection: %r" % foreign_id)
    xref_collection(collection)

@manager.command
def index(foreign_id=None):
    """Index documents in the given collection (or throughout)."""
    q = Document.all_ids()
    # re-index newest document first.
    q = q.order_by(Document.id.desc())
    if foreign_id:
        collection = Collection.by_foreign_id(foreign_id)
        if collection is None:
            raise ValueError("No such collection: %r" % foreign_id)
        q = q.filter(Document.collection_id == collection.id)
    for idx, (doc_id,) in enumerate(q.yield_per(5000), 1):
        index_document_id.delay(doc_id)
        if idx % 1000 == 0:
            log.info("Index: %s documents...", idx)
    if foreign_id is None:
        reindex_entities()

@manager.command
def bulkload(file_name):
    """Index all the entities in a given dataset."""
    log.info("Loading bulk data from: %s", file_name)
    config = load_config_file(file_name)
    bulk_load(config)

@manager.command
def resetindex():
    """Re-create the ES index configuration, dropping all data."""
    delete_index()
    upgrade_search()

@manager.command
def indexentities():
    """Re-index all the entities."""
    reindex_entities()

@manager.command
@manager.option('-n', '--name', dest='name')
@manager.option('-e', '--email', dest='email')
@manager.option('-i', '--is_admin', dest='is_admin')
def createuser(foreign_id, name=None, email=None, is_admin=False):
    """Create a user and show their API key."""
    role = Role.load_or_create(foreign_id, Role.USER,
                               name or foreign_id,
                               email=email or "user@example.com",
                               is_admin=is_admin)
    db.session.commit()
    return role.api_key

@manager.command
def upgrade():
    """Create or upgrade the search index and database."""
    upgrade_db()
    upgrade_search()
    archive.upgrade()

@manager.command
def installdata():
    """Install data needed for linguistic processing."""
    install_analyzers()

@manager.command
def evilshit():
    """EVIL: Delete all data and recreate the database."""
    delete_index()
    from sqlalchemy import MetaData, inspect
    from sqlalchemy.exc import InternalError
    from sqlalchemy.dialects.postgresql import ENUM
    metadata = MetaData()
    metadata.bind = db.engine
    metadata.reflect()
    tables = list(metadata.sorted_tables)
    while len(tables):
        for table in tables:
            try:
                table.drop(checkfirst=True)
                tables.remove(table)
            except InternalError:
                pass
    for enum in inspect(db.engine).get_enums():
        enum = ENUM(name=enum['name'])
        enum.drop(bind=db.engine, checkfirst=True)
    upgrade()

def main():
    manager.run()

if __name__ == "__main__":
    main()
<commit_msg>command-line option to publish a collection.<commit_after># coding: utf-8
import os
import logging
from normality import slugify
from ingestors.util import decode_path
from flask_script import Manager, commands as flask_script_commands
from flask_script.commands import ShowUrls
from flask_migrate import MigrateCommand

from aleph.core import create_app, archive
from aleph.model import db, upgrade_db
from aleph.model import Collection, Document, Role
from aleph.views import mount_app_blueprints
from aleph.analyze import install_analyzers
from aleph.ingest import ingest_document
from aleph.index.admin import delete_index, upgrade_search
from aleph.index.documents import index_document_id
from aleph.logic.collections import reindex_entities, delete_collection
from aleph.logic.collections import update_collection, process_collection
from aleph.logic.alerts import check_alerts
from aleph.logic.entities import bulk_load
from aleph.logic.xref import xref_collection
from aleph.logic.permissions import update_permission
from aleph.util import load_config_file

log = logging.getLogger('aleph')
flask_script_commands.text_type = str

app = create_app()
mount_app_blueprints(app)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
manager.add_command('routes', ShowUrls)

@manager.command
def collections():
    """List all collections."""
    for collection in Collection.all():
        print collection.id, collection.foreign_id, collection.label

@manager.command
def alerts():
    """Generate alert notifications."""
    check_alerts.delay()

@manager.command
@manager.option('-l', '--language', dest='language', nargs='*')
@manager.option('-c', '--country', dest='country', nargs='*')
@manager.option('-f', '--foreign_id', dest='foreign_id')
def crawldir(path, language=None, country=None, foreign_id=None):
    """Crawl the given directory."""
    path = decode_path(path)
    if path is None or not os.path.exists(path):
        log.error("Invalid path: %r", path)
        return
    path = os.path.abspath(os.path.normpath(path))
    path_name = os.path.basename(path)

    if foreign_id is None:
        foreign_id = 'directory:%s' % slugify(path)
    collection = Collection.by_foreign_id(foreign_id)
    if collection is None:
        collection = Collection.create({
            'foreign_id': foreign_id,
            'label': path_name,
            'managed': True
        })

    if language is not None:
        collection.languages = [language]
    if country is not None:
        collection.countries = [country]
    db.session.commit()
    update_collection(collection)

    log.info('Crawling %r to %r...', path, collection.foreign_id)
    document = Document.by_keys(collection=collection,
                                foreign_id=path)
    document.file_name = path_name
    ingest_document(document, path)

@manager.command
def flush(foreign_id):
    """Reset the crawler state for a given collecton."""
    collection = Collection.by_foreign_id(foreign_id, deleted=True)
    if collection is None:
        raise ValueError("No such collection: %r" % foreign_id)
    delete_collection(collection.id)

@manager.command
def process(foreign_id):
    """Re-process documents in the given collection."""
    collection = Collection.by_foreign_id(foreign_id)
    if collection is None:
        raise ValueError("No such collection: %r" % foreign_id)
    process_collection(collection.id)

@manager.command
def xref(foreign_id):
    """Cross-reference all entities and documents in a collection."""
    collection = Collection.by_foreign_id(foreign_id)
    if collection is None:
        raise ValueError("No such collection: %r" % foreign_id)
    xref_collection(collection)

@manager.command
def index(foreign_id=None):
    """Index documents in the given collection (or throughout)."""
    q = Document.all_ids()
    # re-index newest document first.
    q = q.order_by(Document.id.desc())
    if foreign_id:
        collection = Collection.by_foreign_id(foreign_id)
        if collection is None:
            raise ValueError("No such collection: %r" % foreign_id)
        q = q.filter(Document.collection_id == collection.id)
    for idx, (doc_id,) in enumerate(q.yield_per(5000), 1):
        index_document_id.delay(doc_id)
        if idx % 1000 == 0:
            log.info("Index: %s documents...", idx)
    if foreign_id is None:
        reindex_entities()

@manager.command
def bulkload(file_name):
    """Index all the entities in a given dataset."""
    log.info("Loading bulk data from: %s", file_name)
    config = load_config_file(file_name)
    bulk_load(config)

@manager.command
def resetindex():
    """Re-create the ES index configuration, dropping all data."""
    delete_index()
    upgrade_search()

@manager.command
def indexentities():
    """Re-index all the entities."""
    reindex_entities()

@manager.command
@manager.option('-n', '--name', dest='name')
@manager.option('-e', '--email', dest='email')
@manager.option('-i', '--is_admin', dest='is_admin')
def createuser(foreign_id, name=None, email=None, is_admin=False):
    """Create a user and show their API key."""
    role = Role.load_or_create(foreign_id, Role.USER,
                               name or foreign_id,
                               email=email or "user@example.com",
                               is_admin=is_admin)
    db.session.commit()
    return role.api_key

@manager.command
def publish(foreign_id):
    """Make a collection visible to all users."""
    collection = Collection.by_foreign_id(foreign_id)
    if collection is None:
        raise ValueError("No such collection: %r" % foreign_id)
    role = Role.by_foreign_id(Role.SYSTEM_GUEST)
    update_permission(role, collection, True, False)
    db.session.commit()

@manager.command
def upgrade():
    """Create or upgrade the search index and database."""
    upgrade_db()
    upgrade_search()
    archive.upgrade()

@manager.command
def installdata():
    """Install data needed for linguistic processing."""
    install_analyzers()

@manager.command
def evilshit():
    """EVIL: Delete all data and recreate the database."""
    delete_index()
    from sqlalchemy import MetaData, inspect
    from sqlalchemy.exc import InternalError
    from sqlalchemy.dialects.postgresql import ENUM
    metadata = MetaData()
    metadata.bind = db.engine
    metadata.reflect()
    tables = list(metadata.sorted_tables)
    while len(tables):
        for table in tables:
            try:
                table.drop(checkfirst=True)
                tables.remove(table)
            except InternalError:
                pass
    for enum in inspect(db.engine).get_enums():
        enum = ENUM(name=enum['name'])
        enum.drop(bind=db.engine, checkfirst=True)
    upgrade()

def main():
    manager.run()

if __name__ == "__main__":
    main()
<|endoftext|>