<commit_before># -*- coding: utf-8 -*-
from datetime import datetime
from openerp import api, fields, models

class account_invoice(models.Model):
    _inherit = 'account.invoice'

    subscription_request = fields.Many2one('subscription.request',
                                           string='Subscription request')
    release_capital_request = fields.Boolean(
                                        string='Release of capital request')

    @api.model
    def _prepare_refund(self, invoice, date_invoice=None, date=None,
                        description=None, journal_id=None):
        values = super(account_invoice, self)._prepare_refund(
                                        invoice, date_invoice, date,
                                        description, journal_id)
        values['release_capital_request'] = self.release_capital_request

        return values

    def create_user(self, partner):
        user_obj = self.env['res.users']
        # TODO replace self by partner
        email = self.email
        if self.is_company:
            email = self.company_email

        user = user_obj.search([('login', '=', email)])
        if not user:
            user_values = {'partner_id': partner.id, 'login': email}
            user_id = user_obj.sudo()._signup_create_user(user_values)
            user = user_obj.browse(user_id)
            user.sudo().with_context({'create_user': True}).action_reset_password()

        return True

    def set_cooperator_effective(self, effective_date):
        # flag the partner as a effective member
        mail_template_id = 'easy_my_coop.email_template_certificat'

        # if not yet cooperator we generate a cooperator number
        if self.partner_id.member is False and self.partner_id.old_member is False:
            sequence_id = self.env.ref('easy_my_coop.sequence_subscription', False)
            sub_reg_num = sequence_id.next_by_id()
            self.partner_id.write({
                'member': True, 'old_member': False,
                'cooperator_register_number': int(sub_reg_num)})
        elif self.partner_id.old_member:
            self.partner_id.write({'member': True, 'old_member': False})
        else:
            mail_template_id = 'easy_my_coop.email_template_certificat_increase'
        sequence_operation = self.env.ref('easy_my_coop.sequence_register_operation', False)
        sub_reg_operation = sequence_operation.next_by_id()

        for line in self.invoice_line_ids:
            self.env['subscription.register'].create({
                'name': sub_reg_operation,
                'register_number_operation': int(sub_reg_operation),
                'partner_id': self.partner_id.id,
                'quantity': line.quantity,
                'share_product_id': line.product_id.id,
                'share_unit_price': line.price_unit,
                'date': effective_date,
                'type': 'subscription'})

            self.env['share.line'].create({
                'share_number': line.quantity,
                'share_product_id': line.product_id.id,
                'partner_id': self.partner_id.id,
                'share_unit_price': line.price_unit,
                'effective_date': effective_date
                })

        certificat_email_template = self.env.ref(mail_template_id, False)
        # we send the email with the certificat in attachment
        certificat_email_template.send_mail(self.partner_id.id, False)

        if self.company_id.create_user:
            self.create_user(self.partner_id)

        return True

    def post_process_confirm_paid(self, effective_date):
        self.set_cooperator_effective(effective_date)

        return True

    @api.multi
    def confirm_paid(self):
        for invoice in self:
            super(account_invoice, invoice).confirm_paid()
            # we check if there is an open refund for this invoice. in this
            # case we don't run the process_subscription function as the
            # invoice has been reconciled with a refund and not a payment.
            refund = self.search([('type', '=', 'out_refund'),
                                  ('origin', '=', invoice.move_name)])

            if invoice.partner_id.cooperator and invoice.release_capital_request \
                    and invoice.type == 'out_invoice' and not refund:
                # take the effective date from the payment.
                # by default the confirmation date is the payment date
                effective_date = datetime.now().strftime("%d/%m/%Y")

                if invoice.payment_move_line_ids:
                    move_line = invoice.payment_move_line_ids[0]
                    effective_date = move_line.date

                invoice.subscription_request.state = 'paid'
                invoice.post_process_confirm_paid(effective_date)
            # if there is a open refund we mark the subscription as cancelled
            elif invoice.partner_id.cooperator and invoice.release_capital_request \
                    and invoice.type == 'out_invoice' and refund:
                invoice.subscription_request.state = 'cancelled'
        return True
<commit_msg>[IMP] in case of a user has previously been created and deactivated<commit_after># -*- coding: utf-8 -*-
from datetime import datetime
from openerp import api, fields, models

class account_invoice(models.Model):
    _inherit = 'account.invoice'

    subscription_request = fields.Many2one('subscription.request',
                                           string='Subscription request')
    release_capital_request = fields.Boolean(
                                        string='Release of capital request')

    @api.model
    def _prepare_refund(self, invoice, date_invoice=None, date=None,
                        description=None, journal_id=None):
        values = super(account_invoice, self)._prepare_refund(
                                        invoice, date_invoice, date,
                                        description, journal_id)
        values['release_capital_request'] = self.release_capital_request

        return values

    def create_user(self, partner):
        user_obj = self.env['res.users']
        # TODO replace self by partner
        email = self.email
        if self.is_company:
            email = self.company_email

        user = user_obj.search([('login', '=', email)])
        if not user:
            user = user_obj.search([('login', '=', email),
                                    ('active', '=', False)])
            if user:
                user.sudo().write({'active': True})
            else:
                user_values = {'partner_id': partner.id, 'login': email}
                user_id = user_obj.sudo()._signup_create_user(user_values)
                user = user_obj.browse(user_id)
                user.sudo().with_context({'create_user': True}).action_reset_password()

        return True

    def set_cooperator_effective(self, effective_date):
        # flag the partner as a effective member
        mail_template_id = 'easy_my_coop.email_template_certificat'

        # if not yet cooperator we generate a cooperator number
        if self.partner_id.member is False and self.partner_id.old_member is False:
            sequence_id = self.env.ref('easy_my_coop.sequence_subscription', False)
            sub_reg_num = sequence_id.next_by_id()
            self.partner_id.write({
                'member': True, 'old_member': False,
                'cooperator_register_number': int(sub_reg_num)})
        elif self.partner_id.old_member:
            self.partner_id.write({'member': True, 'old_member': False})
        else:
            mail_template_id = 'easy_my_coop.email_template_certificat_increase'
        sequence_operation = self.env.ref('easy_my_coop.sequence_register_operation', False)
        sub_reg_operation = sequence_operation.next_by_id()

        for line in self.invoice_line_ids:
            self.env['subscription.register'].create({
                'name': sub_reg_operation,
                'register_number_operation': int(sub_reg_operation),
                'partner_id': self.partner_id.id,
                'quantity': line.quantity,
                'share_product_id': line.product_id.id,
                'share_unit_price': line.price_unit,
                'date': effective_date,
                'type': 'subscription'})

            self.env['share.line'].create({
                'share_number': line.quantity,
                'share_product_id': line.product_id.id,
                'partner_id': self.partner_id.id,
                'share_unit_price': line.price_unit,
                'effective_date': effective_date
                })

        certificat_email_template = self.env.ref(mail_template_id, False)
        # we send the email with the certificat in attachment
        certificat_email_template.send_mail(self.partner_id.id, False)

        if self.company_id.create_user:
            self.create_user(self.partner_id)

        return True

    def post_process_confirm_paid(self, effective_date):
        self.set_cooperator_effective(effective_date)

        return True

    @api.multi
    def confirm_paid(self):
        for invoice in self:
            super(account_invoice, invoice).confirm_paid()
            # we check if there is an open refund for this invoice. in this
            # case we don't run the process_subscription function as the
            # invoice has been reconciled with a refund and not a payment.
            refund = self.search([('type', '=', 'out_refund'),
                                  ('origin', '=', invoice.move_name)])

            if invoice.partner_id.cooperator and invoice.release_capital_request \
                    and invoice.type == 'out_invoice' and not refund:
                # take the effective date from the payment.
                # by default the confirmation date is the payment date
                effective_date = datetime.now().strftime("%d/%m/%Y")

                if invoice.payment_move_line_ids:
                    move_line = invoice.payment_move_line_ids[0]
                    effective_date = move_line.date

                invoice.subscription_request.state = 'paid'
                invoice.post_process_confirm_paid(effective_date)
            # if there is a open refund we mark the subscription as cancelled
            elif invoice.partner_id.cooperator and invoice.release_capital_request \
                    and invoice.type == 'out_invoice' and refund:
                invoice.subscription_request.state = 'cancelled'
        return True
<|endoftext|>


<commit_before># Copyright (C) 2013 SignalFuse, Inc.
#
# Docker container orchestration utility.

import docker
import logging
import sys
import time

class BaseScore:

    def __init__(self, containers=[], offline=False):
        self._containers = containers
        self._offline = offline

    def __cond_label(self, cond, t, f): return cond and t or f
    def _color(self, cond): return self.__cond_label(cond, 32, 31)
    def _up(self, cond): return self.__cond_label(cond, 'up', 'down')

    def run(self):
        raise NotImplementedError

class OutputFormatter:
    def __init__(self, prefix):
        self._committed = prefix

    def commit(self, s=None):
        self._committed = '{} {}'.format(self._committed, s)
        print '{}\033[K\r'.format(self._committed),
        sys.stdout.flush()

    def pending(self, s):
        print '{} {}\033[K\r'.format(self._committed, s),
        sys.stdout.flush()

    def end(self):
        print
        sys.stdout.flush()

class Status(BaseScore):
    """The Status score is a Maestro orchestration play that displays the
    status of the given services."""

    def __init__(self, containers=[], offline=False):
        BaseScore.__init__(self, containers, offline)

    def run(self):
        print '{:>3s}  {:<20s} {:<15s} {:<20s} {:<15s} {:<10s}'.format(
            '  #', 'COMPONENT', 'SERVICE', 'SHIP', 'CONTAINER', 'STATUS')

        for order, container in enumerate(self._containers, 1):
            o = OutputFormatter(
                '{:>3d}. \033[37;1m{:<20s}\033[;0m {:<15s} {:<20s}'.format(
                order, container.name, container.service.name, container.ship.ip[:25]))

            try:
                o.pending('checking container...')
                status = container.status()
                o.commit('\033[{:d};1m{:<15s}\033[;0m'.format(
                    self._color(status and status['State']['Running']),
                    (status and status['State']['Running'] and container.id[:7] or 'down')))

                o.pending('checking service...')
                ping = container.ping(1)
                o.commit('\033[{:d};1m{:<10s}\033[;0m'.format(
                    self._color(ping), self._up(ping)))
            except Exception, e:
                o.commit('\033[31;1m{:<15s} {:<10s}\033[;0m'.format('host down', 'down'))
            o.end()

class Start(BaseScore):
    """The Start score is a Maestro orchestration play that will execute the
    start sequence of the requested services, starting each container for each
    instance of the services, in the given start order, waiting for each
    container's application to become available before moving to the next
    one."""

    def __init__(self, containers=[], offline=False):
        BaseScore.__init__(self, containers, offline)

    def run(self):
        print '{:>3s}  {:<20s} {:<15s} {:<20s} {:<15s} {:<10s}'.format(
            '  #', 'COMPONENT', 'SERVICE', 'SHIP', 'CONTAINER', 'STATUS')

        for order, container in enumerate(self._containers, 1):
            o = OutputFormatter(
                '{:>3d}. \033[37;1m{:<20s}\033[;0m {:<15s} {:<20s}'.format(
                order, container.name, container.service.name, container.ship.ip[:25]))

            error = None
            try:
                result = self._start_container(o, container)
                o.commit('\033[{:d};1m{:<10s}\033[;0m'.format(
                    self._color(result), result and 'up' or 'service did not start!'))

                if not result:
                    error = container.ship.backend.logs(container.id)
            except docker.client.APIError, e:
                o.commit('\033[31;1mfailed to start container!\033[;0m')
                error = e

            o.end()

            # Halt the sequence if a container failed to start.
            if error:
                logging.error('%s/%s failed to start. Halting sequence.',
                    container.service.name, container.name)
                logging.error(error)
                return

    def _start_container(self, o, container):
        o.pending('checking service...')
        if container.ping(retries=2):
            o.commit('\033[34;0m{:<15s}\033[;0m'.format(container.id[:7]))
            return True

        # Otherwise we need to start it.
        if container.id:
            o.pending('removing old container {}...'.format(container.id[:7]))
            container.ship.backend.remove_container(container.id)

        if not self._offline:
            o.pending('pulling image {}...'.format(container.service.image))
            container.ship.backend.pull(**container.service.get_image_details())

        o.pending('creating container...')
        c = container.ship.backend.create_container(
            image=container.service.image,
            hostname=container.name,
            name=container.name,
            environment=container.env,
            ports=dict([('%d/tcp' % port['exposed'], {})
                for port in container.ports.itervalues()]))

        container.status(refresh=True)
        o.commit('\033[32;1m{:<15s}\033[;0m'.format(container.id[:7]))

        o.pending('starting container...')
        container.ship.backend.start(c,
            binds=container.volumes,
            port_bindings=dict([('%d/tcp' % port['exposed'],
                    [{'HostIp': '0.0.0.0', 'HostPort': str(port['external'])}])
                for port in container.ports.itervalues()]),
            create_local_bind_dirs=True)

        # Waiting one second and checking container state again to make sure
        # initialization didn't fail.
        o.pending('waiting for container initialization...')
        time.sleep(1)
        status = container.status(refresh=True)
        if not status or not status['State']['Running']:
            return False

        # Wait up to 30 seconds for the container's application to come online.
        o.pending('waiting for service...')
        return container.ping(retries=30)

class Stop(BaseScore):
    """The Stop score is a Maestro orchestration play that will stop and remove
    the containers of the requested services, in the inverse dependency
    order."""

    def __init__(self, containers=[], offline=False):
        BaseScore.__init__(self, containers, offline)

    def run(self):
        print '{:>3s}  {:<20s} {:<15s} {:<20s} {:<15s} {:<10s}'.format(
            '  #', 'COMPONENT', 'SERVICE', 'SHIP', 'CONTAINER', 'STATUS')

        for order, container in enumerate(self._containers):
            o = OutputFormatter(
                '{:>3d}. \033[37;1m{:<20s}\033[;0m {:<15s} {:<20s}'.format(
                len(self._containers) - order, container.name,
                container.service.name, container.ship.ip[:25]))

            o.pending('checking container...')
            try:
                if not container.status():
                    o.commit('{:<15s} {:<10s}'.format('n/a', 'already down'))
                    o.end()
                    continue
            except:
                o.commit('\033[31;1m{:<15s} {:<10s}\033[;0m'.format('host down', 'down'))
                o.end()
                continue

            o.commit('{:<15s}'.format(container.id[:7]))

            try:
                o.pending('stopping service...')
                container.ship.backend.stop(container.id)
                o.commit('\033[32;1mstopped\033[;0m')
            except:
                o.commit('\033[31;1mfail!\033[;0m')

            o.end()
<commit_msg>Fix ship hostname field width<commit_after># Copyright (C) 2013 SignalFuse, Inc.
#
# Docker container orchestration utility.

import docker
import logging
import sys
import time

class BaseScore:

    def __init__(self, containers=[], offline=False):
        self._containers = containers
        self._offline = offline

    def __cond_label(self, cond, t, f): return cond and t or f
    def _color(self, cond): return self.__cond_label(cond, 32, 31)
    def _up(self, cond): return self.__cond_label(cond, 'up', 'down')

    def run(self):
        raise NotImplementedError

class OutputFormatter:
    def __init__(self, prefix):
        self._committed = prefix

    def commit(self, s=None):
        self._committed = '{} {}'.format(self._committed, s)
        print '{}\033[K\r'.format(self._committed),
        sys.stdout.flush()

    def pending(self, s):
        print '{} {}\033[K\r'.format(self._committed, s),
        sys.stdout.flush()

    def end(self):
        print
        sys.stdout.flush()

class Status(BaseScore):
    """The Status score is a Maestro orchestration play that displays the
    status of the given services."""

    def __init__(self, containers=[], offline=False):
        BaseScore.__init__(self, containers, offline)

    def run(self):
        print '{:>3s}  {:<20s} {:<15s} {:<20s} {:<15s} {:<10s}'.format(
            '  #', 'COMPONENT', 'SERVICE', 'SHIP', 'CONTAINER', 'STATUS')

        for order, container in enumerate(self._containers, 1):
            o = OutputFormatter(
                '{:>3d}. \033[37;1m{:<20s}\033[;0m {:<15s} {:<20.20s}'.format(
                order, container.name, container.service.name, container.ship.ip))

            try:
                o.pending('checking container...')
                status = container.status()
                o.commit('\033[{:d};1m{:<15s}\033[;0m'.format(
                    self._color(status and status['State']['Running']),
                    (status and status['State']['Running'] and container.id[:7] or 'down')))

                o.pending('checking service...')
                ping = container.ping(1)
                o.commit('\033[{:d};1m{:<10s}\033[;0m'.format(
                    self._color(ping), self._up(ping)))
            except Exception, e:
                o.commit('\033[31;1m{:<15s} {:<10s}\033[;0m'.format('host down', 'down'))
            o.end()

class Start(BaseScore):
    """The Start score is a Maestro orchestration play that will execute the
    start sequence of the requested services, starting each container for each
    instance of the services, in the given start order, waiting for each
    container's application to become available before moving to the next
    one."""

    def __init__(self, containers=[], offline=False):
        BaseScore.__init__(self, containers, offline)

    def run(self):
        print '{:>3s}  {:<20s} {:<15s} {:<20s} {:<15s} {:<10s}'.format(
            '  #', 'COMPONENT', 'SERVICE', 'SHIP', 'CONTAINER', 'STATUS')

        for order, container in enumerate(self._containers, 1):
            o = OutputFormatter(
                '{:>3d}. \033[37;1m{:<20s}\033[;0m {:<15s} {:<20.20s}'.format(
                order, container.name, container.service.name, container.ship.ip))

            error = None
            try:
                result = self._start_container(o, container)
                o.commit('\033[{:d};1m{:<10s}\033[;0m'.format(
                    self._color(result), result and 'up' or 'service did not start!'))

                if not result:
                    error = container.ship.backend.logs(container.id)
            except docker.client.APIError, e:
                o.commit('\033[31;1mfailed to start container!\033[;0m')
                error = e

            o.end()

            # Halt the sequence if a container failed to start.
            if error:
                logging.error('%s/%s failed to start. Halting sequence.',
                    container.service.name, container.name)
                logging.error(error)
                return

    def _start_container(self, o, container):
        o.pending('checking service...')
        if container.ping(retries=2):
            o.commit('\033[34;0m{:<15s}\033[;0m'.format(container.id[:7]))
            return True

        # Otherwise we need to start it.
        if container.id:
            o.pending('removing old container {}...'.format(container.id[:7]))
            container.ship.backend.remove_container(container.id)

        if not self._offline:
            o.pending('pulling image {}...'.format(container.service.image))
            container.ship.backend.pull(**container.service.get_image_details())

        o.pending('creating container...')
        c = container.ship.backend.create_container(
            image=container.service.image,
            hostname=container.name,
            name=container.name,
            environment=container.env,
            ports=dict([('%d/tcp' % port['exposed'], {})
                for port in container.ports.itervalues()]))

        container.status(refresh=True)
        o.commit('\033[32;1m{:<15s}\033[;0m'.format(container.id[:7]))

        o.pending('starting container...')
        container.ship.backend.start(c,
            binds=container.volumes,
            port_bindings=dict([('%d/tcp' % port['exposed'],
                    [{'HostIp': '0.0.0.0', 'HostPort': str(port['external'])}])
                for port in container.ports.itervalues()]),
            create_local_bind_dirs=True)

        # Waiting one second and checking container state again to make sure
        # initialization didn't fail.
        o.pending('waiting for container initialization...')
        time.sleep(1)
        status = container.status(refresh=True)
        if not status or not status['State']['Running']:
            return False

        # Wait up to 30 seconds for the container's application to come online.
        o.pending('waiting for service...')
        return container.ping(retries=30)

class Stop(BaseScore):
    """The Stop score is a Maestro orchestration play that will stop and remove
    the containers of the requested services, in the inverse dependency
    order."""

    def __init__(self, containers=[], offline=False):
        BaseScore.__init__(self, containers, offline)

    def run(self):
        print '{:>3s}  {:<20s} {:<15s} {:<20s} {:<15s} {:<10s}'.format(
            '  #', 'COMPONENT', 'SERVICE', 'SHIP', 'CONTAINER', 'STATUS')

        for order, container in enumerate(self._containers):
            o = OutputFormatter(
                '{:>3d}. \033[37;1m{:<20s}\033[;0m {:<15s} {:<20.20s}'.format(
                len(self._containers) - order, container.name,
                container.service.name, container.ship.ip))

            o.pending('checking container...')
            try:
                if not container.status():
                    o.commit('{:<15s} {:<10s}'.format('n/a', 'already down'))
                    o.end()
                    continue
            except:
                o.commit('\033[31;1m{:<15s} {:<10s}\033[;0m'.format('host down', 'down'))
                o.end()
                continue

            o.commit('{:<15s}'.format(container.id[:7]))

            try:
                o.pending('stopping service...')
                container.ship.backend.stop(container.id)
                o.commit('\033[32;1mstopped\033[;0m')
            except:
                o.commit('\033[31;1mfail!\033[;0m')

            o.end()
<|endoftext|>


<commit_before>#Memory Management Simulation System
import sys

class Process(object):
    """docstring for Process"""
    def __init__(self, processArgs):
        if len(processArgs) < 4:                        # Process wasn't provided at least a name, req frames
            print "Error Initializing Process!"         #   and one set of arrival and exit times
            print "Not Enough Arguments..."
            return

        self.name = processArgs[0]                      # Process Name
        self.reqMemFrames = int(processArgs[1])              # Process Size
        self.arrivalTimes = []
        self.exitTimes = []
        i = 0
        for x in processArgs[2:]:                   # List of arrival and exit times
            if i%2 == 0:
                self.arrivalTimes.append(int(x))
            else:
                self.exitTimes.append(int(x))
            i += 1

class MainMemorySimulator(object):
    """docstring for MainMemory"""
    def __init__(self, processList):
        self.simTime = 0                    # Master Time Handler
        self.lastTime = 0                   # Time that last process exits
        self.processes = processList        # Master List of all Processes
        self.runningProcesses = []          # List of Processes currently running
        self.memFrames = ""                 # String Representation of Memory
        self.numMemFrames = 1600            # Total amount of space (memFrames size)
        self.numOpSysProc = 80              # Number of spaces in Memory Representation
                                            #   dedicated to op sys processes

        for p in processList:                   # Finding all processes that start at 0
            if p.arrivalTimes[0] == 0:
                self.runningProcesses.append(p) # and adding them to runningProcesses list
            for et in p.exitTimes:
                if et > self.lastTime:
                    self.lastTime = et

        runningProcessListItr = 0           # Index handler for running processes
        inProcFrameItr = 1                  # Index handler for each frame in a process
        roomLeft = False                    # Bool to check for memory overflow
        memFrameItr = self.numOpSysProc     # Master index handler for memory representation

        for i in range(0, self.numOpSysProc):   # Adding Operating System Frames to beginning
            self.memFrames += "#"

        while memFrameItr < self.numMemFrames:      # Fill in each spot of memory representation
            if runningProcessListItr < len(self.runningProcesses): # If there are running processes
                self.memFrames += self.processes[runningProcessListItr].name # Add process name to mem rep
                inProcFrameItr += 1                                        # Move to next frame in process
                if inProcFrameItr > self.processes[runningProcessListItr].reqMemFrames: # If process needs no more frames
                    runningProcessListItr += 1               # Move to next process
                    inProcFrameItr = 1              # Reset in process index handler
            else:                                   # If no more processes need to be added
                roomLeft = True                     # Indicate there is no overflow issue
                self.memFrames += "."               # Indicate free memory spots

            memFrameItr += 1

        if not roomLeft:                            # State there is an overflow issue
            print "ERROR: OUT-OF-MEMORY"

        self.printMemory()                          # Print the structure

    def printMemory(self):
        print "Memory at time %d" %self.simTime
        i = 0
        printList = []
        while i < self.numMemFrames:
            if i + 79 < self.numMemFrames:
                printList.append(self.memFrames[i:i + 80])
            else:
                printList.append(self.memFrames[i:])
            i += 80

        for m in printList:
            print m

    def incrementTime(self):
        self.simTime += 1

    def run(self, quiet_mode, alloc_method):
        while self.simTime <= self.lastTime:
            change = False
            t = 0
            if not quiet_mode:
                #get time, t, input from user
                pass

            #increment time
            self.incrementTime()
            print "time incremented to " + str(self.simTime)

            #check for exiting processes

            #check for entering processes
            if alloc_method == "first":
                self.exec_first()
            elif alloc_method == "best":
                self.exec_best()
            elif alloc_method == "next":
                self.exec_next()
            elif alloc_method == "worst":
                self.exec_worst()
            elif alloc_method == "noncontig":
                self.exec_noncontig()

            #prints at time requested or on every change for quiet_mode
            if quiet_mode and change:
                self.printMemory()
            elif self.simTime == t:
                self.printMemory()

    def exec_first(self):
        pass

    def exec_best(self):
        pass

    def exec_next(self):
        pass

    def exec_worst(self):
        pass

    def exec_noncontig(self):
        pass

def check_filename(file_name):
    if file_name[len(file_name) - 4:] == ".txt":
        return True
    return False

def check_allocmethod(alloc_method):
    possible = ["first", "best", "next", "worst", "noncontig"]
    for a in possible:
        if alloc_method == a:
            return True
    return False

def parse(argv):
    #memsim -q <input-file> { first | best | next | worst }
    quiet_mode = False
    file_name = ""
    alloc_method = ""
    if len(argv) == 4:
        if argv[1] == "-q":
            quiet_mode = True
        else:
            print "USAGE: memsim [-q] <input-file> { first | best | next | worst }"
            sys.exit()
        file_name = argv[2]
        alloc_method = argv[3]
    elif len(argv) == 3:
        file_name = argv[1]
        alloc_method = argv[2]
    else:
        print "USAGE: memsim [-q] <input-file> { first | best | next | worst }"
        sys.exit()
    if check_allocmethod(alloc_method) and check_filename(file_name):
        return (quiet_mode, file_name, alloc_method)
    else:
        print "USAGE: memsim [-q] <input-file> { first | best | next | worst }"
        sys.exit()

#main function
if __name__ == '__main__':
    #Some Pseudocode

    #parse cli arguments
    (quiet_mode, file_name, alloc_method) = parse(sys.argv)

    #Creating Process and populating list
    processList = []
    with open(file_name, "r") as in_file:
        for line in in_file:
            line = line.split()
            if len(line) > 1:
                processList.append(Process(line))

    #initializing MainMemorySimulator
    M = MainMemorySimulator(processList)

    #Run Iterations
    M.run( quiet_mode, alloc_method )<commit_msg>more structure created to be implemented<commit_after>#Memory Management Simulation System
import sys

class Process(object):
    """docstring for Process"""
    def __init__(self, processArgs):
        if len(processArgs) < 4:                        # Process wasn't provided at least a name, req frames
            print "Error Initializing Process!"         #   and one set of arrival and exit times
            print "Not Enough Arguments..."
            return

        self.name = processArgs[0]                      # Process Name
        self.reqMemFrames = int(processArgs[1])              # Process Size
        self.arrivalTimes = []
        self.exitTimes = []
        i = 0
        for x in processArgs[2:]:                   # List of arrival and exit times
            if i%2 == 0:
                self.arrivalTimes.append(int(x))
            else:
                self.exitTimes.append(int(x))
            i += 1

class MainMemorySimulator(object):
    """docstring for MainMemory"""
    def __init__(self, processList):
        self.simTime = 0                    # Master Time Handler
        self.lastTime = 0                   # Time that last process exits
        self.processes = processList        # Master List of all Processes
        self.freeSpace = [(0,1600)]                 # List of tuples of start and end of free space
        self.runningProcesses = []          # List of Processes currently running
        self.memFrames = ""                 # String Representation of Memory
        self.numMemFrames = 1600            # Total amount of space (memFrames size)
        self.numOpSysProc = 80              # Number of spaces in Memory Representation
                                            #   dedicated to op sys processes

        for p in processList:                   # Finding all processes that start at 0
            if p.arrivalTimes[0] == 0:
                self.runningProcesses.append(p) # and adding them to runningProcesses list
            for et in p.exitTimes:
                if et > self.lastTime:
                    self.lastTime = et

        runningProcessListItr = 0           # Index handler for running processes
        inProcFrameItr = 1                  # Index handler for each frame in a process
        roomLeft = False                    # Bool to check for memory overflow
        memFrameItr = self.numOpSysProc     # Master index handler for memory representation

        for i in range(0, self.numOpSysProc):   # Adding Operating System Frames to beginning
            self.memFrames += "#"

        while memFrameItr < self.numMemFrames:      # Fill in each spot of memory representation
            if runningProcessListItr < len(self.runningProcesses): # If there are running processes
                self.memFrames += self.processes[runningProcessListItr].name # Add process name to mem rep
                inProcFrameItr += 1                                        # Move to next frame in process
                if inProcFrameItr > self.processes[runningProcessListItr].reqMemFrames: # If process needs no more frames
                    runningProcessListItr += 1               # Move to next process
                    inProcFrameItr = 1              # Reset in process index handler
            else:                                   # If no more processes need to be added
                roomLeft = True                     # Indicate there is no overflow issue
                self.memFrames += "."               # Indicate free memory spots

            memFrameItr += 1

        if not roomLeft:                            # State there is an overflow issue
            print "ERROR: OUT-OF-MEMORY"

        self.printMemory()                          # Print the structure

    def printMemory(self):
        print "Memory at time %d" %self.simTime
        i = 0
        printList = []
        while i < self.numMemFrames:
            if i + 79 < self.numMemFrames:
                printList.append(self.memFrames[i:i + 80])
            else:
                printList.append(self.memFrames[i:])
            i += 80

        for m in printList:
            print m

    def incrementTime(self):
        self.simTime += 1

    def run(self, quiet_mode, alloc_method):
        while self.simTime <= self.lastTime:
            change = False
            t = 0
            if not quiet_mode:
                #get time, t, input from user
                pass

            #increment time
            self.incrementTime()
            print "time incremented to " + str(self.simTime)

            #check for exiting processes
            for p in self.processes:
                if p.exitTimes[0] == self.simTime:
                    self.deallocate(p)

            #check for entering processes
            for p in self.processes:
                if p.arrivalTimes[0] == self.simTime:
                    self.select_n_cal( alloc_method, p )

            #prints at time requested or on every change for quiet_mode
            if quiet_mode and change:
                self.printMemory()
            elif self.simTime == t:
                self.printMemory()

    def defragment(self):
        pass

    def deallocate(self, aProcess):
        pass

    def select_n_cal(self, alloc_method, aProcess):
        if alloc_method == "first":
            self.exec_first()
        elif alloc_method == "best":
            self.exec_best()
        elif alloc_method == "next":
            self.exec_next()
        elif alloc_method == "worst":
            self.exec_worst()
        elif alloc_method == "noncontig":
            self.exec_noncontig()

    def exec_first(self):
        pass

    def exec_best(self):
        pass

    def exec_next(self):
        pass

    def exec_worst(self):
        pass

    def exec_noncontig(self):
        pass

def check_filename(file_name):
    if file_name[len(file_name) - 4:] == ".txt":
        return True
    return False

def check_allocmethod(alloc_method):
    possible = ["first", "best", "next", "worst", "noncontig"]
    for a in possible:
        if alloc_method == a:
            return True
    return False

def parse(argv):
    #memsim -q <input-file> { first | best | next | worst }
    quiet_mode = False
    file_name = ""
    alloc_method = ""
    if len(argv) == 4:
        if argv[1] == "-q":
            quiet_mode = True
        else:
            print "USAGE: memsim [-q] <input-file> { first | best | next | worst }"
            sys.exit()
        file_name = argv[2]
        alloc_method = argv[3]
    elif len(argv) == 3:
        file_name = argv[1]
        alloc_method = argv[2]
    else:
        print "USAGE: memsim [-q] <input-file> { first | best | next | worst }"
        sys.exit()
    if check_allocmethod(alloc_method) and check_filename(file_name):
        return (quiet_mode, file_name, alloc_method)
    else:
        print "USAGE: memsim [-q] <input-file> { first | best | next | worst }"
        sys.exit()

#main function
if __name__ == '__main__':
    #Some Pseudocode

    #parse cli arguments
    (quiet_mode, file_name, alloc_method) = parse(sys.argv)

    #Creating Process and populating list
    processList = []
    with open(file_name, "r") as in_file:
        for line in in_file:
            line = line.split()
            if len(line) > 1:
                processList.append(Process(line))

    #initializing MainMemorySimulator
    M = MainMemorySimulator(processList)

    #Run Iterations
    M.run( quiet_mode, alloc_method )<|endoftext|>


<commit_before>from yarl import URL
import requests
import curio
__all__ = ['TestClient']

HOST = '127.0.0.1'
PORT = 40404

class Proxy:
    ret = None

class TestClient:
    app = None
    loop = None
    server = None
    res = None

    def __init__(self, app):
        self.app = app
        self.server = None

    async def real_request(self):
        print("doing it")
        return requests.get("http://localhost:40404/")

    async def async_request(self, proxy):
        async with curio.timeout_after(10):
            server = await curio.spawn(self.app.start_server, HOST, PORT)
            await curio.sleep(1)
            proxy.ret = await self.real_request()
            print("done")
        await server.cancel()

    def __request(self, method, url, *args, **kwargs):
        p = Proxy()
        curio.run(self.async_request, p)

        return p.ret

    def head(self, url, *args, **kwargs):
        return self.__request('head', url, *args, **kwargs)

    def get(self, url, *args, **kwargs):
        return self.__request('get', url, *args, **kwargs)

    def post(self, url, *args, **kwargs):
        return self.__request('post', url, *args, **kwargs)

    def put(self, url, *args, **kwargs):
        return self.__request('put', url, *args, **kwargs)

    def delete(self, url, *args, **kwargs):
        return self.__request('delete', url, *args, **kwargs)

    def options(self, url, *args, **kwargs):
        return self.__request('options', url, *args, **kwargs)

    def patch(self, url, *args, **kwargs):
        return self.__request('patch', url, *args, **kwargs)

    def url(self, path=""):
        """
        generate the abstract url for test case
        """

        return URL('http://{}:{}{}'.format(HOST, PORT, path))
<commit_msg>feature: use aiohttp as test client<commit_after>import aiohttp
from yarl import URL
import asyncio

__all__ = ['TestClient']

HOST = '127.0.0.1'
PORT = 40404

class Proxy:
    ret = None

class TestClient:
    app = None
    loop = None
    server = None

    def __init__(self, app=None):
        self.app = app
        self.loop = asyncio.new_event_loop()
        self.server = None

    async def stop_server(self):
        loop = asyncio.get_event_loop()
        print("Stop")
        loop.stop()

    def __request(self, method, url, *args, **kwargs):

        async def __local_request(method, url, *args, **kwargs):

            server_loop = await self.app.start_server(HOST, PORT)

            url = 'http://{host}:{port}{uri}'.format(host=HOST, port=PORT, uri=url)
            async with aiohttp.ClientSession(loop=self.loop) as session:
                async with getattr(session, method)(url, *args, **kwargs) as response:
                    response.text = await response.text()
                    server_loop.close()
                    await server_loop.wait_closed()
                    return response

        asyncio.set_event_loop(self.loop)

        ret = self.loop.run_until_complete(__local_request(method, url, *args, **kwargs))

        # cancel all task
        tasks = asyncio.Task.all_tasks()
        for task in tasks:
            task.cancel()
        self.loop.run_until_complete(self.stop_server())

        return ret

    def head(self, url, *args, **kwargs):
        return self.__request('head', url, *args, **kwargs)

    def get(self, url, *args, **kwargs):
        return self.__request('get', url, *args, **kwargs)

    def post(self, url, *args, **kwargs):
        return self.__request('post', url, *args, **kwargs)

    def put(self, url, *args, **kwargs):
        return self.__request('put', url, *args, **kwargs)

    def delete(self, url, *args, **kwargs):
        return self.__request('delete', url, *args, **kwargs)

    def options(self, url, *args, **kwargs):
        return self.__request('options', url, *args, **kwargs)

    def patch(self, url, *args, **kwargs):
        return self.__request('patch', url, *args, **kwargs)

    def url(self, path=""):
        """
        generate the abstract url for test case
        """

        return URL('http://{}:{}{}'.format(HOST, PORT, path))<|endoftext|>


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

import sys
import os
import msmbuilder
import msmbuilder.version
import msmb_theme

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))

# -- General configuration -----------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.mathjax', 'sphinx.ext.ifconfig',
              'sphinx.ext.autosummary', 'sphinx.ext.viewcode',
              'sphinx.ext.autodoc', 'numpydoc',
              'sphinx.ext.intersphinx', 'sphinx.ext.viewcode',
              'matplotlib.sphinxext.plot_directive',
              'IPython.sphinxext.ipython_console_highlighting',
              'IPython.sphinxext.ipython_directive']

autosummary_generate = True
autodoc_default_flags = ['members', 'inherited-members']

html_context = {
    'github_user': 'msmbuilder',
    'display_github': True,
    'github_repo': 'msmbuilder',
    'github_version': 'master',
    'conf_py_path': '/doc/',
    'html_logo' : 'logo-200px.png',
    'base_url' : 'http://msmbuilder.org'
}

sys.path.insert(0, os.path.abspath('sphinxext'))
extensions.append('notebook_sphinxext')

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'msmbuilder'
copyright = u'2014, Stanford University and the Authors'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = msmbuilder.version.short_version
# The full version, including alpha/beta/rc tags.
release = msmbuilder.version.short_version

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']

# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = "msmb_theme"

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {'base_url' : 'http://msmbuilder.org'}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
html_theme_path = [msmb_theme.get_html_theme_path()]

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = '_static/mdtraj_logo-small.png'
html_logo = 'logo-200px.png'

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'msmbuilderdoc'

# -- Options for LaTeX output --------------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    #'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    #'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
    ('index', 'msmbuilder.tex', u'MSMBuilder Documentation',
     u'Robert McGibbon', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output --------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'msmbuilder', u'MSMBuilder Documentation',
     [u'Robert McGibbon'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output ------------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    ('index', 'MSMBuilder', u'MSMBuilder Documentation',
     u'Robert McGibbon', 'MSMBuilder', 'One line description of project.',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

autodoc_member_order = 'bysource'
<commit_msg>Update conf.py<commit_after># -*- coding: utf-8 -*-

import sys
import os
import msmbuilder
import msmbuilder.version
import msmb_theme

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))

# -- General configuration -----------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.mathjax', 'sphinx.ext.ifconfig',
              'sphinx.ext.autosummary', 'sphinx.ext.viewcode',
              'sphinx.ext.autodoc', 'numpydoc',
              'sphinx.ext.intersphinx', 'sphinx.ext.viewcode',
              'matplotlib.sphinxext.plot_directive',
              'IPython.sphinxext.ipython_console_highlighting',
              'IPython.sphinxext.ipython_directive']

autosummary_generate = True
autodoc_default_flags = ['members', 'inherited-members']

html_context = {
    'github_user': 'msmbuilder',
    'display_github': True,
    'github_repo': 'msmbuilder',
    'github_version': 'master',
    'conf_py_path': '/doc/',
    'html_logo' : 'logo-200px.png',
    'base_url' : 'http://msmbuilder.org'
}

sys.path.insert(0, os.path.abspath('sphinxext'))
extensions.append('notebook_sphinxext')

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'msmbuilder'
copyright = u'2015, Stanford University and the Authors'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = msmbuilder.version.short_version
# The full version, including alpha/beta/rc tags.
release = msmbuilder.version.short_version

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']

# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = "msmb_theme"

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {'base_url' : 'http://msmbuilder.org'}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
html_theme_path = [msmb_theme.get_html_theme_path()]

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = '_static/mdtraj_logo-small.png'
html_logo = 'logo-200px.png'

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'msmbuilderdoc'

# -- Options for LaTeX output --------------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    #'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    #'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
    ('index', 'msmbuilder.tex', u'MSMBuilder Documentation',
     u'Robert McGibbon', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output --------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'msmbuilder', u'MSMBuilder Documentation',
     [u'Robert McGibbon'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output ------------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    ('index', 'MSMBuilder', u'MSMBuilder Documentation',
     u'Robert McGibbon', 'MSMBuilder', 'One line description of project.',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

autodoc_member_order = 'bysource'
<|endoftext|>


<commit_before># Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

import base64
import logging

from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools.pdf import merge_pdf

_logger = logging.getLogger(__name__)

class AccountInvoice(models.Model):

    _inherit = "account.move"

    @api.onchange("partner_id", "company_id")
    def _transmit_method_partner_change(self):
        super()._transmit_method_partner_change()
        if self.type not in ("out_invoice", "out_refund"):
            return
        paynet_method = self.env.ref("ebill_paynet.paynet_transmit_method")
        if self.transmit_method_id == paynet_method:
            contract = self.partner_id.get_active_contract(self.transmit_method_id)
            if contract:
                self.invoice_partner_bank_id = (
                    contract.paynet_service_id.partner_bank_id
                )

    def _export_invoice(self):
        """Export invoice with the help of account_invoice_export module."""
        paynet_method = self.env.ref("ebill_paynet.paynet_transmit_method")
        if self.transmit_method_id != paynet_method:
            return super()._export_invoice()
        message = self.create_paynet_message()
        if not message:
            raise UserError(_("Error generating Paynet message"))
        message.send_to_paynet()
        self.invoice_exported = True
        return "Paynet invoice generated and in state {}".format(message.state)

    def create_paynet_message(self):
        """Generate the paynet message for an invoice."""
        self.ensure_one()
        contract = self.partner_id.get_active_contract(self.transmit_method_id)
        if not contract:
            return
        # Generate PDf to be send
        pdf_data = []
        report_names = ["account.report_invoice"]
        if contract.payment_type == "qr":
            report_names.append("l10n_ch.qr_report_main")
        elif contract.payment_type == "esr":
            report_names.append("l10n_ch.isr_report_main")
        for report_name in report_names:
            r = self.env["ir.actions.report"]._get_report_from_name(report_name)
            # Add the force_report_rendering or pdf merge will fail in tests
            pdf_content, _ = r.with_context(force_report_rendering=True).render(
                [self.id]
            )
            pdf_data.append(pdf_content)
        pdf = merge_pdf(pdf_data)

        message = self.env["paynet.invoice.message"].create(
            {
                "service_id": contract.paynet_service_id.id,
                "invoice_id": self.id,
                "ebill_account_number": contract.paynet_account_number,
                "payment_type": contract.payment_type,
            }
        )
        attachment = self.env["ir.attachment"].create(
            {
                "name": "paynet ebill",
                "type": "binary",
                "datas": base64.b64encode(pdf).decode("ascii"),
                "res_model": "paynet.invoice.message",
                "res_id": message.id,
                "mimetype": "application/x-pdf",
            }
        )
        message.attachment_id = attachment.id
        return message

    def paynet_invoice_line_ids(self):
        """Filter invoice line to be included in XML message.

        Invoicing line that are UX based (notes, sections) are removed.

        """
        self.ensure_one()
        return self.invoice_line_ids.filtered(lambda r: not r.display_type)

    def log_invoice_accepted_by_system(self):
        """ """
        self.activity_feedback(
            ["ebill_paynet.mail_activity_dws_error"],
            feedback="It worked on a later try",
        )
        self.message_post(body=_("Invoice accepted by the Paynet system"))
        self.invoice_export_confirmed = True

    def log_invoice_refused_by_system(self):
        """ """
        activity_type = "ebill_paynet.mail_activity_dws_error"
        activity = self.activity_reschedule(
            [activity_type], date_deadline=fields.Date.today()
        )
        values = {}
        if not activity:
            message = self.env.ref("ebill_paynet.dws_reject_invoice").render(
                values=values
            )
            activity = self.activity_schedule(
                activity_type, summary="Invoice rejected by Paynet", note=message
            )
        # error_log = values.get("error_detail")
        # if not error_log:
        #     error_log = _("An error of type {} occured.").format(
        #         values.get("error_type")
        #     )
        # activity.note += "

{}

".format(error_log)
<commit_msg>ebill_paynet: Fix travis for pdf generated<commit_after># Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

import base64
import logging

import odoo
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools.pdf import merge_pdf

_logger = logging.getLogger(__name__)

class AccountInvoice(models.Model):

    _inherit = "account.move"

    @api.onchange("partner_id", "company_id")
    def _transmit_method_partner_change(self):
        super()._transmit_method_partner_change()
        if self.type not in ("out_invoice", "out_refund"):
            return
        paynet_method = self.env.ref("ebill_paynet.paynet_transmit_method")
        if self.transmit_method_id == paynet_method:
            contract = self.partner_id.get_active_contract(self.transmit_method_id)
            if contract:
                self.invoice_partner_bank_id = (
                    contract.paynet_service_id.partner_bank_id
                )

    def _export_invoice(self):
        """Export invoice with the help of account_invoice_export module."""
        paynet_method = self.env.ref("ebill_paynet.paynet_transmit_method")
        if self.transmit_method_id != paynet_method:
            return super()._export_invoice()
        message = self.create_paynet_message()
        if not message:
            raise UserError(_("Error generating Paynet message"))
        message.send_to_paynet()
        self.invoice_exported = True
        return "Paynet invoice generated and in state {}".format(message.state)

    def create_paynet_message(self):
        """Generate the paynet message for an invoice."""
        self.ensure_one()
        contract = self.partner_id.get_active_contract(self.transmit_method_id)
        if not contract:
            return
        # Generate PDf to be send
        pdf_data = []
        report_names = ["account.report_invoice"]
        if contract.payment_type == "qr":
            report_names.append("l10n_ch.qr_report_main")
        elif contract.payment_type == "esr":
            report_names.append("l10n_ch.isr_report_main")
        for report_name in report_names:
            r = self.env["ir.actions.report"]._get_report_from_name(report_name)
            pdf_content, _ = r.render([self.id])
            pdf_data.append(pdf_content)
        if not odoo.tools.config["test_enable"]:
            pdf = merge_pdf(pdf_data)
        else:
            # When test are run, pdf are not generated, so use an empty pdf
            pdf = b""

        message = self.env["paynet.invoice.message"].create(
            {
                "service_id": contract.paynet_service_id.id,
                "invoice_id": self.id,
                "ebill_account_number": contract.paynet_account_number,
                "payment_type": contract.payment_type,
            }
        )
        attachment = self.env["ir.attachment"].create(
            {
                "name": "paynet ebill",
                "type": "binary",
                "datas": base64.b64encode(pdf).decode("ascii"),
                "res_model": "paynet.invoice.message",
                "res_id": message.id,
                "mimetype": "application/x-pdf",
            }
        )
        message.attachment_id = attachment.id
        return message

    def paynet_invoice_line_ids(self):
        """Filter invoice line to be included in XML message.

        Invoicing line that are UX based (notes, sections) are removed.

        """
        self.ensure_one()
        return self.invoice_line_ids.filtered(lambda r: not r.display_type)

    def log_invoice_accepted_by_system(self):
        """ """
        self.activity_feedback(
            ["ebill_paynet.mail_activity_dws_error"],
            feedback="It worked on a later try",
        )
        self.message_post(body=_("Invoice accepted by the Paynet system"))
        self.invoice_export_confirmed = True

    def log_invoice_refused_by_system(self):
        """ """
        activity_type = "ebill_paynet.mail_activity_dws_error"
        activity = self.activity_reschedule(
            [activity_type], date_deadline=fields.Date.today()
        )
        values = {}
        if not activity:
            message = self.env.ref("ebill_paynet.dws_reject_invoice").render(
                values=values
            )
            activity = self.activity_schedule(
                activity_type, summary="Invoice rejected by Paynet", note=message
            )
        # error_log = values.get("error_detail")
        # if not error_log:
        #     error_log = _("An error of type {} occured.").format(
        #         values.get("error_type")
        #     )
        # activity.note += "

{}

".format(error_log)
<|endoftext|>


<commit_before>import ocl
import math
from nc.nc import *

def STLSurfFromFile(filepath):
    s = ocl.STLSurf()
    ocl.STLReader(filepath, s)
    return s

def zigzag( filepath, tool_diameter = 3.0, corner_radius = 0.0, step_over = 1.0, x0= -10.0, x1 = 10.0, y0 = -10.0, y1 = 10.0, direction = 'X', mat_allowance = 0.0, style = 0, clearance = 5.0, rapid_down_to_height = 2.0, start_depth = 0.0, step_down = 2.0, final_depth = -10.0, units = 1.0):
   mm = True
   if math.fabs(units)>0.000000001:
      # ocl works in mm, so convert all values to mm
      mm = False
      tool_diameter *= units
      corner_radius *= units
      step_over *= units
      x0 *= units
      x1 *= units
      y0 *= units
      y1 *= units
      mat_allowance *= units
      clearance *= units
      rapid_down_to_height *= units
      start_depth *= units
      step_down *= units
      final_depth *= units
      # read the stl file, we know it is an ascii file because HeeksCNC made it
      s = STLSurfFromFile(filepath)
   dcf = ocl.PathDropCutter(s)
   cutter = ocl.CylCutter()
   if corner_radius == 0.0:
      cutter = ocl.CylCutter(tool_diameter + mat_allowance)
   elif corner_radius > tool_diameter / 2 - 0.000000001:
      cutter = ocl.BallCutter(tool_diameter + mat_allowance)
   else:
      cutter = ocl.BullCutter(tool_diameter + mat_allowance, corner_radius)
   dcf.setCutter(cutter)
   if final_depth > start_depth:
      raise 'final_depth > start_depth'
   height = start_depth - final_depth
   zsteps = int( height / math.fabs(step_down) + 0.999999 )
   zstep_down = height / zsteps
   incremental_rapid_to = rapid_down_to_height - start_depth
   if incremental_rapid_to < 0: incremental_rapid_to = 0.1
   for k in range(0, zsteps):
      z1 = start_depth - k * zstep_down
      z0 = start_depth - (k + 1) * zstep_down
      dcf.minimumZ = z0
      steps = int((y1 - y0)/step_over) + 1
      if direction == 'Y': steps = int((x1 - x0)/step_over) + 1
      sub_step_over = (y1 - y0)/ steps
      if direction == 'Y': sub_step_over = (x1 - x0)/ steps
      rapid_to = z1 + incremental_rapid_to
      for i in range(0, steps + 1):
         odd_numbered_pass = (i%2 == 1)
         u = y0 + float(i) * sub_step_over
         if direction == 'Y': u = x0 + float(i) * sub_step_over
         path = ocl.Path()
         if style == 0: # one way
            if direction == 'Y': path.append(ocl.Line(ocl.Point(u, y0, 0), ocl.Point(u, y1, 0)))
            else: path.append(ocl.Line(ocl.Point(x0, u, 0), ocl.Point(x1, u, 0)))
         else: # back and forth
            if direction == 'Y':
               if odd_numbered_pass:
                  path.append(ocl.Line(ocl.Point(u, y1, 0), ocl.Point(u, y0, 0)))
                  if i < steps: path.append(ocl.Line(ocl.Point(u, y0, 0), ocl.Point(u + sub_step_over, y0, 0))) # feed across to next pass
               else:
                  path.append(ocl.Line(ocl.Point(u, y0, 0), ocl.Point(u, y1, 0)))
                  if i < steps: path.append(ocl.Line(ocl.Point(u, y1, 0), ocl.Point(u + sub_step_over, y1, 0))) # feed across to next pass
            else: # 'X'
               if odd_numbered_pass:
                  path.append(ocl.Line(ocl.Point(x1, u, 0), ocl.Point(x0, u, 0)))
                  if i < steps: path.append(ocl.Line(ocl.Point(x0, u, 0), ocl.Point(x0, u + sub_step_over, 0))) # feed across to next pass
               else:
                  path.append(ocl.Line(ocl.Point(x0, u, 0), ocl.Point(x1, u, 0)))
                  if i < steps: path.append(ocl.Line(ocl.Point(x1, u, 0), ocl.Point(x1, u + sub_step_over, 0))) # feed across to next pass
         dcf.setPath(path)
         dcf.run()
         plist = dcf.getCLPoints()
         f = ocl.LineCLFilter()
         f.setTolerance(0.01)
         for p in plist:
             f.addCLPoint(p)
         f.run()
         plist = f.getCLPoints()
         n = 0
         for p in plist:
            p.z = p.z + mat_allowance
            if i == 0 or style == 0:
               if n == 0:
                  if mm: rapid(p.x, p.y)
                  else: rapid(p.x / units, p.y / units)
                  rz = rapid_to
                  if p.z > z1: rz = p.z + incremental_rapid_to
                  if mm:
                     rapid(z = rz)
                     feed(z = p.z)
                  else:
                     rapid(z = rz / units)
                     feed(z = p.z / units)
               else:
                  if mm:
                     feed(p.x, p.y, p.z)
                  else:
                     feed(p.x / units, p.y / units, p.z / units)
            else:
               if n > 0:
                  if mm:
                     feed(p.x, p.y, p.z)
                  else:
                     feed(p.x / units, p.y / units, p.z / units)
            n = n + 1
         if style == 0: # one way
            if mm:
               rapid(z = clearance)
            else:
               rapid(z = clearance / units)
      if style != 0: # back and forth
         if mm:
            rapid(z = clearance)
         else:
            rapid(z = clearance / units)

def cutting_tool( diameter, corner_radius, length ):
   cutter = ocl.CylCutter()
   if corner_radius == 0.0:
      cutter = ocl.CylCutter(diameter)
   elif corner_radius > diameter / 2 - 0.000000001:
      cutter = ocl.BallCutter(diameter)
   else:
      cutter = ocl.BullCutter(diameter, corner_radius)

   cutter.length = length
   return(cutter)

def waterline( filepath, tool_diameter = 3.0, corner_radius = 0.0, step_over = 1.0, x0= -10.0, x1 = 10.0, y0 = -10.0, y1 = 10.0, mat_allowance = 0.0, clearance = 5.0, rapid_down_to_height = 2.0, start_depth = 0.0, step_down = 2.0, final_depth = -10.0, units = 1.0, tolerance = 0.01 ):
   mm = True
   if math.fabs(units)>0.000000001:
      # ocl works in mm, so convert all values to mm
      mm = False
      tool_diameter *= units
      corner_radius *= units
      step_over *= units
      x0 *= units
      x1 *= units
      y0 *= units
      y1 *= units
      mat_allowance *= units
      clearance *= units
      rapid_down_to_height *= units
      start_depth *= units
      step_down *= units
      final_depth *= units
      tolerance *= units

   # read the stl file, we know it is an ascii file because HeeksCNC made it
   s = STLSurfFromFile(filepath)

   if final_depth > start_depth:
      raise 'final_depth > start_depth'
   height = start_depth - final_depth
   zsteps = int( height / math.fabs(step_down) + 0.999999 )
   zstep_down = height / zsteps
   incremental_rapid_to = rapid_down_to_height - start_depth
   if incremental_rapid_to < 0: incremental_rapid_to = 0.1

   tool_location = ocl.Point(0.0, 0.0, 0.0)

   for k in range(0, zsteps):
      z = start_depth - k * zstep_down
      working_diameter = tool_diameter + mat_allowance

      room_to_expand = True
      while (room_to_expand == True):
         cutter = cutting_tool(working_diameter, corner_radius, 10)

         waterline = ocl.Waterline()
         waterline.setSTL(s)
         waterline.setTolerance(tolerance)
         waterline.setCutter(cutter)
         waterline.setZ(z)
         waterline.run()
         cutter_loops = waterline.getLoops()

         for cutter_loop in cutter_loops:
            if ((cutter_loop[0].z != tool_location.z) or (tool_location.distance(cutter_loop[0]) > (tool_diameter / 2.0))):
               # Move above the starting point.
               rapid(z = clearance / units)
               rapid(x=cutter_loop[0].x, y=cutter_loop[0].y)
               tool_location.x = cutter_loop[0].x
               tool_location.y = cutter_loop[0].y
               tool_location.z = clearance / units

               # Feed down to the cutting depth
               rapid(x=cutter_loop[0].x, y=cutter_loop[0].y)
               tool_location.x = cutter_loop[0].x
               tool_location.y = cutter_loop[0].y

            # Cut around the solid at this level.
            for point in cutter_loop:
               feed( x=point.x, y=point.y, z=point.z )
               tool_location = point;

               if (point.x < (x0-step_over)) or (point.x > (x1+step_over)) or (point.y < (y0-step_over)) or (point.y > (y1+step_over)):
                  room_to_expand = False

            # And retract to the clearance height
            rapid(z = clearance / units)
            tool_location.z = clearance / units

         working_diameter += step_over
<commit_msg>CylCutter uses 2 paramaters now.<commit_after>import ocl
import math
from nc.nc import *

def STLSurfFromFile(filepath):
    s = ocl.STLSurf()
    ocl.STLReader(filepath, s)
    return s

def zigzag( filepath, tool_diameter = 3.0, corner_radius = 0.0, step_over = 1.0, x0= -10.0, x1 = 10.0, y0 = -10.0, y1 = 10.0, direction = 'X', mat_allowance = 0.0, style = 0, clearance = 5.0, rapid_down_to_height = 2.0, start_depth = 0.0, step_down = 2.0, final_depth = -10.0, units = 1.0):
   mm = True
   if math.fabs(units)>0.000000001:
      # ocl works in mm, so convert all values to mm
      mm = False
      tool_diameter *= units
      corner_radius *= units
      step_over *= units
      x0 *= units
      x1 *= units
      y0 *= units
      y1 *= units
      mat_allowance *= units
      clearance *= units
      rapid_down_to_height *= units
      start_depth *= units
      step_down *= units
      final_depth *= units
      # read the stl file, we know it is an ascii file because HeeksCNC made it
      s = STLSurfFromFile(filepath)
   dcf = ocl.PathDropCutter(s)
   cutter = ocl.CylCutter()
   if corner_radius == 0.0:
      cutter = ocl.CylCutter(tool_diameter + mat_allowance, 100.0)
   elif corner_radius > tool_diameter / 2 - 0.000000001:
      cutter = ocl.BallCutter(tool_diameter + mat_allowance)
   else:
      cutter = ocl.BullCutter(tool_diameter + mat_allowance, corner_radius)
   dcf.setCutter(cutter)
   if final_depth > start_depth:
      raise 'final_depth > start_depth'
   height = start_depth - final_depth
   zsteps = int( height / math.fabs(step_down) + 0.999999 )
   zstep_down = height / zsteps
   incremental_rapid_to = rapid_down_to_height - start_depth
   if incremental_rapid_to < 0: incremental_rapid_to = 0.1
   for k in range(0, zsteps):
      z1 = start_depth - k * zstep_down
      z0 = start_depth - (k + 1) * zstep_down
      dcf.minimumZ = z0
      steps = int((y1 - y0)/step_over) + 1
      if direction == 'Y': steps = int((x1 - x0)/step_over) + 1
      sub_step_over = (y1 - y0)/ steps
      if direction == 'Y': sub_step_over = (x1 - x0)/ steps
      rapid_to = z1 + incremental_rapid_to
      for i in range(0, steps + 1):
         odd_numbered_pass = (i%2 == 1)
         u = y0 + float(i) * sub_step_over
         if direction == 'Y': u = x0 + float(i) * sub_step_over
         path = ocl.Path()
         if style == 0: # one way
            if direction == 'Y': path.append(ocl.Line(ocl.Point(u, y0, 0), ocl.Point(u, y1, 0)))
            else: path.append(ocl.Line(ocl.Point(x0, u, 0), ocl.Point(x1, u, 0)))
         else: # back and forth
            if direction == 'Y':
               if odd_numbered_pass:
                  path.append(ocl.Line(ocl.Point(u, y1, 0), ocl.Point(u, y0, 0)))
                  if i < steps: path.append(ocl.Line(ocl.Point(u, y0, 0), ocl.Point(u + sub_step_over, y0, 0))) # feed across to next pass
               else:
                  path.append(ocl.Line(ocl.Point(u, y0, 0), ocl.Point(u, y1, 0)))
                  if i < steps: path.append(ocl.Line(ocl.Point(u, y1, 0), ocl.Point(u + sub_step_over, y1, 0))) # feed across to next pass
            else: # 'X'
               if odd_numbered_pass:
                  path.append(ocl.Line(ocl.Point(x1, u, 0), ocl.Point(x0, u, 0)))
                  if i < steps: path.append(ocl.Line(ocl.Point(x0, u, 0), ocl.Point(x0, u + sub_step_over, 0))) # feed across to next pass
               else:
                  path.append(ocl.Line(ocl.Point(x0, u, 0), ocl.Point(x1, u, 0)))
                  if i < steps: path.append(ocl.Line(ocl.Point(x1, u, 0), ocl.Point(x1, u + sub_step_over, 0))) # feed across to next pass
         dcf.setPath(path)
         dcf.run()
         plist = dcf.getCLPoints()
         f = ocl.LineCLFilter()
         f.setTolerance(0.01)
         for p in plist:
             f.addCLPoint(p)
         f.run()
         plist = f.getCLPoints()
         n = 0
         for p in plist:
            p.z = p.z + mat_allowance
            if i == 0 or style == 0:
               if n == 0:
                  if mm: rapid(p.x, p.y)
                  else: rapid(p.x / units, p.y / units)
                  rz = rapid_to
                  if p.z > z1: rz = p.z + incremental_rapid_to
                  if mm:
                     rapid(z = rz)
                     feed(z = p.z)
                  else:
                     rapid(z = rz / units)
                     feed(z = p.z / units)
               else:
                  if mm:
                     feed(p.x, p.y, p.z)
                  else:
                     feed(p.x / units, p.y / units, p.z / units)
            else:
               if n > 0:
                  if mm:
                     feed(p.x, p.y, p.z)
                  else:
                     feed(p.x / units, p.y / units, p.z / units)
            n = n + 1
         if style == 0: # one way
            if mm:
               rapid(z = clearance)
            else:
               rapid(z = clearance / units)
      if style != 0: # back and forth
         if mm:
            rapid(z = clearance)
         else:
            rapid(z = clearance / units)

def cutting_tool( diameter, corner_radius, length ):
   cutter = ocl.CylCutter()
   if corner_radius == 0.0:
      cutter = ocl.CylCutter(diameter)
   elif corner_radius > diameter / 2 - 0.000000001:
      cutter = ocl.BallCutter(diameter)
   else:
      cutter = ocl.BullCutter(diameter, corner_radius)

   cutter.length = length
   return(cutter)

def waterline( filepath, tool_diameter = 3.0, corner_radius = 0.0, step_over = 1.0, x0= -10.0, x1 = 10.0, y0 = -10.0, y1 = 10.0, mat_allowance = 0.0, clearance = 5.0, rapid_down_to_height = 2.0, start_depth = 0.0, step_down = 2.0, final_depth = -10.0, units = 1.0, tolerance = 0.01 ):
   mm = True
   if math.fabs(units)>0.000000001:
      # ocl works in mm, so convert all values to mm
      mm = False
      tool_diameter *= units
      corner_radius *= units
      step_over *= units
      x0 *= units
      x1 *= units
      y0 *= units
      y1 *= units
      mat_allowance *= units
      clearance *= units
      rapid_down_to_height *= units
      start_depth *= units
      step_down *= units
      final_depth *= units
      tolerance *= units

   # read the stl file, we know it is an ascii file because HeeksCNC made it
   s = STLSurfFromFile(filepath)

   if final_depth > start_depth:
      raise 'final_depth > start_depth'
   height = start_depth - final_depth
   zsteps = int( height / math.fabs(step_down) + 0.999999 )
   zstep_down = height / zsteps
   incremental_rapid_to = rapid_down_to_height - start_depth
   if incremental_rapid_to < 0: incremental_rapid_to = 0.1

   tool_location = ocl.Point(0.0, 0.0, 0.0)

   for k in range(0, zsteps):
      z = start_depth - k * zstep_down
      working_diameter = tool_diameter + mat_allowance

      room_to_expand = True
      while (room_to_expand == True):
         cutter = cutting_tool(working_diameter, corner_radius, 10)

         waterline = ocl.Waterline()
         waterline.setSTL(s)
         waterline.setTolerance(tolerance)
         waterline.setCutter(cutter)
         waterline.setZ(z)
         waterline.run()
         cutter_loops = waterline.getLoops()

         for cutter_loop in cutter_loops:
            if ((cutter_loop[0].z != tool_location.z) or (tool_location.distance(cutter_loop[0]) > (tool_diameter / 2.0))):
               # Move above the starting point.
               rapid(z = clearance / units)
               rapid(x=cutter_loop[0].x, y=cutter_loop[0].y)
               tool_location.x = cutter_loop[0].x
               tool_location.y = cutter_loop[0].y
               tool_location.z = clearance / units

               # Feed down to the cutting depth
               rapid(x=cutter_loop[0].x, y=cutter_loop[0].y)
               tool_location.x = cutter_loop[0].x
               tool_location.y = cutter_loop[0].y

            # Cut around the solid at this level.
            for point in cutter_loop:
               feed( x=point.x, y=point.y, z=point.z )
               tool_location = point;

               if (point.x < (x0-step_over)) or (point.x > (x1+step_over)) or (point.y < (y0-step_over)) or (point.y > (y1+step_over)):
                  room_to_expand = False

            # And retract to the clearance height
            rapid(z = clearance / units)
            tool_location.z = clearance / units

         working_diameter += step_over
<|endoftext|>


<commit_before>import attr
import re
from .debugging import debug_print_dict, logger
from .generators import BaseGenerator, SeedGenerator

__all__ = ['CustomGeneratorMetaV2']

def add_field_generators(field_gens, dct):
    for name, gen in dct.items():
        if isinstance(gen, BaseGenerator):
            field_gens[name] = gen

def find_field_generators(obj):
    """
    Return dictionary with the names and instances of
    all tohu.BaseGenerator occurring in the given
    object's class & instance namespaces.
    """

    cls_dict = obj.__class__.__dict__
    obj_dict = obj.__dict__
    logger.debug(f'[FFF]')
    debug_print_dict(cls_dict, 'cls_dict')
    debug_print_dict(obj_dict, 'obj_dict')

    field_gens = {}
    add_field_generators(field_gens, cls_dict)
    add_field_generators(field_gens, obj_dict)

    return field_gens

def set_item_class_name(cls_obj):
    """
    Return the first part of the class name of this custom generator.
    This will be used for the class name of the items produced by this
    generator.

    Examples:
        FoobarGenerator -> Foobar
        QuuxGenerator   -> Quux
    """
    if hasattr(cls_obj, '__tohu_items_name__'):
        logger.debug(f"Using item class name '{cls_obj.__tohu_items_name__}' (derived from attribute '__tohu_items_name__')")
    else:
        m = re.match('^(.*)Generator$', cls_obj.__name__)
        if m is not None:
            cls_obj.__tohu_items_name__ = m.group(1)
            logger.debug(f"Using item class name '{cls_obj.__tohu_items_name__}' (derived from custom generator name)")
        else:
            raise ValueError(
                "Cannot derive class name for items to be produced by custom generator. "
                "Please set '__tohu_items_name__' at the top of the custom generator's "
                "definition or change its name so that it ends in '...Generator'")

def make_item_class(obj):
    """
    Parameters
    ----------
    obj:
        The custom generator instance for which to create an item class
    """
    clsname = obj.__tohu_items_name__
    attr_names = obj.field_gens.keys()

    item_cls = attr.make_class(clsname, {name: attr.ib() for name in attr_names}, repr=False, cmp=True)

    def new_repr(obj):
        all_fields = ', '.join([f'{name}={repr(value)}' for name, value in attr.asdict(obj).items()])
        return f'{clsname}({all_fields})'

    item_cls.__repr__ = new_repr

    return item_cls

def attach_new_init_method(obj):
    """
    Replace the existing obj.__init__() method with a new one
    which calls the original one and in addition performs the
    following actions:

    (1) Finds all instances of tohu.BaseGenerator in the namespace
        and collects them in the dictionary `self.field_gens`.
    (2) ..to do..
    """

    orig_init = obj.__init__

    def new_init(self, *args, **kwargs):
        # Call original __init__ function to ensure we pick up
        # any tohu generators that are defined there.
        orig_init(self, *args, **kwargs)

        #
        # Find field generator templates and attach spawned copies
        #
        field_gens_templates = find_field_generators(self)
        logger.debug(f'Found {len(field_gens_templates)} field generator template(s):')
        debug_print_dict(field_gens_templates)

        logger.debug('Spawning field generator templates...')
        self.field_gens = {name: gen._spawn() for (name, gen) in field_gens_templates.items()}

        logger.debug(f'Field generators attached to custom generator:')
        debug_print_dict(self.field_gens)

        #
        # Add seed generator
        #
        self.seed_generator = SeedGenerator()

        #
        # Create class for the items produced by this generator
        #
        self.__class__.item_cls = make_item_class(self)

    obj.__init__ = new_init

def attach_new_reset_method(obj):
    """
    Attach a new `reset()` method to `obj` which resets the internal
    seed generator of `obj` and then resets each of its constituent
    field generators found in `obj.field_gens`.
    """
    #
    # Create and assign automatically generated reset() method
    #

    def new_reset(self, seed=None):
        logger.debug(f'[EEE] Inside automatically generated reset() method for {self} (seed={seed})')

        if seed is not None:
            self.seed_generator.reset(seed)
            for name, gen in self.field_gens.items():
                next_seed = next(self.seed_generator)
                logger.debug(f'Resetting field generator {name}={gen} with seed={next_seed}')
                gen.reset(next_seed)

        return self

    obj.reset = new_reset

def attach_new_next_method(obj):
    """
    TODO
    """

    def new_next(self):
        field_values = [next(g) for g in self.field_gens.values()]
        return self.item_cls(*field_values)

    obj.__next__ = new_next

class CustomGeneratorMetaV2(type):

    def __new__(metacls, cg_name, bases, clsdict):
        logger.debug('[DDD]')
        logger.debug('CustomGeneratorMetaV2.__new__')
        logger.debug(f'   - metacls={metacls}')
        logger.debug(f'   - cg_name={cg_name}')
        logger.debug(f'   - bases={bases}')
        logger.debug(f'   - clsdict={clsdict}')

        #
        # Create new custom generator object
        #
        new_obj = super(CustomGeneratorMetaV2, metacls).__new__(metacls, cg_name, bases, clsdict)
        logger.debug(f'   - new_obj={new_obj}')

        set_item_class_name(new_obj)
        attach_new_init_method(new_obj)
        attach_new_reset_method(new_obj)
        attach_new_next_method(new_obj)

        return new_obj
<commit_msg>Create custom __eq__ method for more convenient comparison with tuples and dicts<commit_after>import attr
import pandas as pd
import re
from .debugging import debug_print_dict, logger
from .generators import BaseGenerator, SeedGenerator

__all__ = ['CustomGeneratorMetaV2']

def add_field_generators(field_gens, dct):
    for name, gen in dct.items():
        if isinstance(gen, BaseGenerator):
            field_gens[name] = gen

def find_field_generators(obj):
    """
    Return dictionary with the names and instances of
    all tohu.BaseGenerator occurring in the given
    object's class & instance namespaces.
    """

    cls_dict = obj.__class__.__dict__
    obj_dict = obj.__dict__
    logger.debug(f'[FFF]')
    debug_print_dict(cls_dict, 'cls_dict')
    debug_print_dict(obj_dict, 'obj_dict')

    field_gens = {}
    add_field_generators(field_gens, cls_dict)
    add_field_generators(field_gens, obj_dict)

    return field_gens

def set_item_class_name(cls_obj):
    """
    Return the first part of the class name of this custom generator.
    This will be used for the class name of the items produced by this
    generator.

    Examples:
        FoobarGenerator -> Foobar
        QuuxGenerator   -> Quux
    """
    if hasattr(cls_obj, '__tohu_items_name__'):
        logger.debug(f"Using item class name '{cls_obj.__tohu_items_name__}' (derived from attribute '__tohu_items_name__')")
    else:
        m = re.match('^(.*)Generator$', cls_obj.__name__)
        if m is not None:
            cls_obj.__tohu_items_name__ = m.group(1)
            logger.debug(f"Using item class name '{cls_obj.__tohu_items_name__}' (derived from custom generator name)")
        else:
            raise ValueError(
                "Cannot derive class name for items to be produced by custom generator. "
                "Please set '__tohu_items_name__' at the top of the custom generator's "
                "definition or change its name so that it ends in '...Generator'")

def make_item_class(obj):
    """
    Parameters
    ----------
    obj:
        The custom generator instance for which to create an item class
    """
    clsname = obj.__tohu_items_name__
    attr_names = obj.field_gens.keys()

    item_cls = attr.make_class(clsname, {name: attr.ib() for name in attr_names}, repr=False, cmp=True)

    def new_repr(obj):
        all_fields = ', '.join([f'{name}={repr(value)}' for name, value in attr.asdict(obj).items()])
        return f'{clsname}({all_fields})'

    orig_eq = item_cls.__eq__
    def new_eq(obj, other):
        """
        Custom __eq__() method which also allows comparisons with
        tuples and dictionaries. This is mostly for convenience
        during testing.
        """

        if isinstance(other, obj.__class__):
            return orig_eq(obj, other)
        else:
            if isinstance(other, tuple):
                return attr.astuple(obj) == other
            elif isinstance(other, dict):
                return attr.asdict(obj) == other
            else:
                return NotImplemented

    item_cls.__repr__ = new_repr
    item_cls.__eq__ = new_eq
    item_cls.__getitem__ = lambda self, key: getattr(self, key)
    item_cls.as_dict = lambda self: attr.asdict(self)
    item_cls.to_series = lambda self: pd.Series(attr.asdict(self))

    return item_cls

def attach_new_init_method(obj):
    """
    Replace the existing obj.__init__() method with a new one
    which calls the original one and in addition performs the
    following actions:

    (1) Finds all instances of tohu.BaseGenerator in the namespace
        and collects them in the dictionary `self.field_gens`.
    (2) ..to do..
    """

    orig_init = obj.__init__

    def new_init(self, *args, **kwargs):
        # Call original __init__ function to ensure we pick up
        # any tohu generators that are defined there.
        orig_init(self, *args, **kwargs)

        #
        # Find field generator templates and attach spawned copies
        #
        field_gens_templates = find_field_generators(self)
        logger.debug(f'Found {len(field_gens_templates)} field generator template(s):')
        debug_print_dict(field_gens_templates)

        logger.debug('Spawning field generator templates...')
        self.field_gens = {name: gen._spawn() for (name, gen) in field_gens_templates.items()}

        logger.debug(f'Field generators attached to custom generator:')
        debug_print_dict(self.field_gens)

        #
        # Add seed generator
        #
        self.seed_generator = SeedGenerator()

        #
        # Create class for the items produced by this generator
        #
        self.__class__.item_cls = make_item_class(self)

    obj.__init__ = new_init

def attach_new_reset_method(obj):
    """
    Attach a new `reset()` method to `obj` which resets the internal
    seed generator of `obj` and then resets each of its constituent
    field generators found in `obj.field_gens`.
    """
    #
    # Create and assign automatically generated reset() method
    #

    def new_reset(self, seed=None):
        logger.debug(f'[EEE] Inside automatically generated reset() method for {self} (seed={seed})')

        if seed is not None:
            self.seed_generator.reset(seed)
            for name, gen in self.field_gens.items():
                next_seed = next(self.seed_generator)
                logger.debug(f'Resetting field generator {name}={gen} with seed={next_seed}')
                gen.reset(next_seed)

        return self

    obj.reset = new_reset

def attach_new_next_method(obj):
    """
    TODO
    """

    def new_next(self):
        field_values = [next(g) for g in self.field_gens.values()]
        return self.item_cls(*field_values)

    obj.__next__ = new_next

class CustomGeneratorMetaV2(type):

    def __new__(metacls, cg_name, bases, clsdict):
        logger.debug('[DDD]')
        logger.debug('CustomGeneratorMetaV2.__new__')
        logger.debug(f'   - metacls={metacls}')
        logger.debug(f'   - cg_name={cg_name}')
        logger.debug(f'   - bases={bases}')
        logger.debug(f'   - clsdict={clsdict}')

        #
        # Create new custom generator object
        #
        new_obj = super(CustomGeneratorMetaV2, metacls).__new__(metacls, cg_name, bases, clsdict)
        logger.debug(f'   - new_obj={new_obj}')

        set_item_class_name(new_obj)
        attach_new_init_method(new_obj)
        attach_new_reset_method(new_obj)
        attach_new_next_method(new_obj)

        return new_obj
<|endoftext|>