예제 #1
0
    def __call__(self):
        plone.protect.CheckAuthenticator(self.request)
        uc = getToolByName(self, 'uid_catalog')
        st_uid = self.request.get('st_uid', [])
        st = st_uid and uc(UID=st_uid)[0].getObject() or None
        allow_blank = self.request.get('allow_blank', False) == 'true'
        pres_uid = json.loads(self.request.get('pres_uid', '[]'))
        minvol = self.request.get('minvol', '').split(" ")
        try:
            minvol = mg(float(minvol[0]), " ".join(minvol[1:]))
        except:
            minvol = mg(0)

        if not type(pres_uid) in (list, tuple):
            pres_uid = [
                pres_uid,
            ]
        preservations = [
            p and uc(UID=p)[0].getObject() or '' for p in pres_uid
        ]

        containers = getContainers(self.context,
                                   preservation=preservations and preservations
                                   or [],
                                   minvol=minvol,
                                   allow_blank=allow_blank)

        return json.dumps(containers)
예제 #2
0
    def __call__(self):
        plone.protect.CheckAuthenticator(self.request)
        uc = getToolByName(self, 'uid_catalog')

        allow_blank = self.request.get('allow_blank', False) == 'true'
        show_container_types = json.loads(
            self.request.get('show_container_types', 'true'))
        show_containers = json.loads(
            self.request.get('show_containers', 'true'))
        minvol = self.request.get("minvol", "0")
        try:
            minvol = minvol.split()
            minvol = mg(float(minvol[0]), " ".join(minvol[1:]))
        except:
            minvol = mg(0)

        containers = getContainers(
            self.context,
            minvol=minvol,
            allow_blank=allow_blank,
            show_containers=show_containers,
            show_container_types=show_container_types,
        )

        return json.dumps(containers)
예제 #3
0
def compare_containers(a, b):
    a_capacity = a.getCapacity().lower().split(" ", 1)
    b_capacity = b.getCapacity().lower().split(" ", 1)
    a_magnitude = mg(float(a_capacity[0]), a_capacity[1])
    b_magnitude = mg(float(b_capacity[0]), b_capacity[1])
    return cmp(a.getCapacity() and a_magnitude or mg(0, 'ml'),
               b.getCapacity() and b_magnitude or mg(0, 'ml'))
예제 #4
0
def compare_containers(a, b):
    a_capacity = a.getCapacity().lower().split(" ", 1)
    b_capacity = b.getCapacity().lower().split(" ", 1)
    a_magnitude = mg(float(a_capacity[0]), a_capacity[1])
    b_magnitude = mg(float(b_capacity[0]), b_capacity[1])
    return cmp(
        a.getCapacity() and a_magnitude or mg(0, 'ml'),
        b.getCapacity() and b_magnitude or mg(0, 'ml')
    )
예제 #5
0
파일: test_mg.py 프로젝트: juanre/magnitude
def test_unit():
    m = mg(1, '1/s')
    assert (m.val, m.unit) == (1.0, [0, -1, 0, 0, 0, 0, 0, 0, 0])

    m = mg(10, 'm2 K / min')
    assert m.val-10.0/60.0 < 1e-6
    assert m.unit == [2, -1, 1, 0, 0, 0, 0, 0, 0]
    m = mg(10, 'Gib')
    assert m.val == 10737418240.0
    a = mg(1000, 'm/s')
    b = a.ounit('km/s')
    assert b.toval() == 1.0
예제 #6
0
def test_unit():
    m = mg(1, '1/s')
    assert (m.val, m.unit) == (1.0, [0, -1, 0, 0, 0, 0, 0, 0, 0])

    m = mg(10, 'm2 K / min')
    assert m.val - 10.0 / 60.0 < 1e-6
    assert m.unit == [2, -1, 1, 0, 0, 0, 0, 0, 0]
    m = mg(10, 'Gib')
    assert m.val == 10737418240.0
    a = mg(1000, 'm/s')
    b = a.ounit('km/s')
    assert b.toval() == 1.0
예제 #7
0
def new_goal(session, args):
    energy = mg(args.energy_amount, args.energy_unit)
    n = NutritionGoal(name=args.name, 
                      energy=energy,
                      carbohydrates_percentage = args.carbs,
                      fats_percentage = args.fats,
                      proteins_percentage = args.proteins)
    session.add(n)
    session.commit()
    print 'Added Nutrition Goal', args.name
예제 #8
0
파일: sampletype.py 프로젝트: nafwa03/olims
 def getJSMinimumVolume(self, **kw):
     """Try convert the MinimumVolume to 'ml' or 'g' so that JS has an
     easier time working with it.  If conversion fails, return raw value.
     """
     default = self.Schema()['MinimumVolume'].get(self)
     try:
         mgdefault = default.split(' ', 1)
         mgdefault = mg(float(mgdefault[0]), mgdefault[1])
     except:
         mgdefault = mg(0, 'ml')
     try:
         return str(mgdefault.ounit('ml'))
     except:
         pass
     try:
         return str(mgdefault.ounit('g'))
     except:
         pass
     return str(default)
예제 #9
0
 def getJSCapacity(self, **kw):
     """Try convert the Capacity to 'ml' or 'g' so that JS has an
     easier time working with it.  If conversion fails, return raw value.
     """
     default = self.Schema()['Capacity'].get(self)
     try:
         mgdefault = default.split(' ', 1)
         mgdefault = mg(float(mgdefault[0]), mgdefault[1])
     except:
         mgdefault = mg(0, 'ml')
     try:
         return str(mgdefault.ounit('ml'))
     except:
         pass
     try:
         return str(mgdefault.ounit('g'))
     except:
         pass
     return str(default)
예제 #10
0
 def getJSCapacity(self, **kw):
     """Try convert the Capacity to 'ml' or 'g' so that JS has an
     easier time working with it.  If conversion fails, return raw value.
     """
     default = self.Schema()["Capacity"].get(self)
     try:
         mgdefault = default.split(" ", 1)
         mgdefault = mg(float(mgdefault[0]), mgdefault[1])
     except:
         mgdefault = mg(0, "ml")
     try:
         return str(mgdefault.ounit("ml"))
     except:
         pass
     try:
         return str(mgdefault.ounit("g"))
     except:
         pass
     return str(default)
예제 #11
0
def mg(value):
    tokens = value.split(" ") if value else [0, '']
    val = float(tokens[0]) if isinstance(tokens[0], (int, long)) else 0
    unit = tokens[1] if len(tokens) > 1 else ''
    # Magnitude doesn't support mL units.
    # Since mL is commonly used instead of ml to avoid confusion with the
    # number one, add "L" (for liter) as a 'recognizable' unit.
    # L unit as liter is also recommended by the NIST Guide
    # http://physics.nist.gov/Pubs/SP811/sec05.html#table6
    # Further info: https://jira.bikalabs.com/browse/LIMS-1441
    unit = unit[:-1] + 'l' if unit.endswith('L') else unit
    return magnitude.mg(val, unit)
예제 #12
0
def add_goal(session, args):
    # TODO Add error handling/
    #  - unknown nutrient
    #  - unknown ingredient
    #  - unknown unit
    goal = session.query(NutritionGoal).filter(NutritionGoal.name == args.goal)[0]
    nutrient = session.query(Nutrient).filter(Nutrient.name == args.nutrient)[0]
    nutrient_goal = NutrientGoal(goal,
                                 nutrient,
                                 mg(args.quantity, args.unit))
    session.add(nutrient_goal)
    session.commit()
예제 #13
0
def mg(value):
    tokens = value.split(" ") if value else [0, '']
    val = float(tokens[0]) if isinstance(tokens[0], (int, long)) else 0
    unit = tokens[1] if len(tokens) > 1 else ''
    # Magnitude doesn't support mL units.
    # Since mL is commonly used instead of ml to avoid confusion with the
    # number one, add "L" (for liter) as a 'recognizable' unit.
    # L unit as liter is also recommended by the NIST Guide
    # http://physics.nist.gov/Pubs/SP811/sec05.html#table6
    # Further info: https://jira.bikalabs.com/browse/LIMS-1441
    unit = unit[:-1]+'l' if unit.endswith('L') else unit
    return magnitude.mg(val, unit)
예제 #14
0
    def __call__(self):
        plone.protect.CheckAuthenticator(self.request)

        allow_blank = self.request.get('allow_blank', False) == 'true'
        show_container_types = json.loads(self.request.get('show_container_types', 'true'))
        show_containers = json.loads(self.request.get('show_containers', 'true'))
        minvol = self.request.get("minvol", "0")
        try:
            minvol = minvol.split()
            minvol = mg(float(minvol[0]), " ".join(minvol[1:]))
        except:
            minvol = mg(0)

        containers = getContainers(
            self.context,
            minvol=minvol,
            allow_blank=allow_blank,
            show_containers=show_containers,
            show_container_types=show_container_types,
        )

        return json.dumps(containers)
예제 #15
0
파일: test_mg.py 프로젝트: juanre/magnitude
def test_construct():
    m = mg(10, 'm/s') + (1, 'lightyear/year')
    n = mg(10, 'm/s') + mg(1, 'lightyear/year')
    o = (1, 'lightyear/year') + mg(10, 'm/s')
    p = (5, 'm/s') + mg(1, 'lightyear/year') + (5, 'm/s')
    assert m == n == o == p and m.unit == [1, -1, 0, 0, 0, 0, 0, 0, 0]

    m = mg(10, 'km/h') - (1, 'km/h')
    n = (10, 'km/h') - mg(1, 'km/h')
    assert m.unit == [1, -1, 0, 0, 0, 0, 0, 0, 0]
    assert m.val == 10000.0 / 3600 - 1000.0 / 3600
    assert m == n
예제 #16
0
def test_construct():
    m = mg(10, 'm/s') + (1, 'lightyear/year')
    n = mg(10, 'm/s') + mg(1, 'lightyear/year')
    o = (1, 'lightyear/year') + mg(10, 'm/s')
    p = (5, 'm/s') + mg(1, 'lightyear/year') + (5, 'm/s')
    assert m == n == o == p and m.unit == [1, -1, 0, 0, 0, 0, 0, 0, 0]

    m = mg(10, 'km/h') - (1, 'km/h')
    n = (10, 'km/h') - mg(1, 'km/h')
    assert m.unit == [1, -1, 0, 0, 0, 0, 0, 0, 0]
    assert m.val == 10000.0 / 3600 - 1000.0 / 3600
    assert m == n
예제 #17
0
def getContainers(instance,
                  preservation=None,
                  minvol=None,
                  allow_blank=True,
                  container_type_entries=False):
    """ Containers vocabulary

    This is a separate class so that it can be called from ajax to
    filter the container list.

    >>> bsc = self.portal.bika_setup_catalog

    >>> obj = bsc(getKeyword='Moist')[0].getObject()
    >>> u'Canvas bag' in obj.getContainers().values()
    True

    >>> obj = bsc(getKeyword='Aflatox')[0].getObject()
    >>> u'20 ml glass vial' in obj.getContainers().values()
    True
    >>> u'Canvas bag' in obj.getContainers().values()
    False

    """
    bsc = getToolByName(instance, 'bika_setup_catalog')
    if allow_blank:
        items = [['', '']]
    else:
        items = []

    if not type(preservation) in (list, tuple):
        preservation = [
            preservation,
        ]
    pres_c_types = []
    for pres in preservation:
        if pres:
            for pres_ct in pres.getContainerType():
                if pres_ct not in pres_c_types:
                    pres_c_types.append(pres_ct)

    containers = {}
    containers_notype = []
    ctype_to_uid = {}
    all_ctypes = [
        ct.title
        for ct in bsc(portal_type='ContainerType', sort_on='sortable_title')
    ]
    for container in bsc(portal_type='Container', sort_on='sortable_title'):
        container = container.getObject()
        if minvol:
            try:
                # If the units match, verify container is large enough.
                # all other containers are considered valid
                cvol = container.getCapacity()
                cvol = cvol.split(" ")
                cvol = mg(float(cvol[0]), " ".join(cvol[1:]).strip())
                if cvol.out_unit == minvol.out_unit and cvol.val < minvol.val:
                    continue
            except MagnitudeError:
                pass

        # This is to sort the container dropdown contents by type
        ctype = container.getContainerType()
        if ctype:
            if ctype.Title() in all_ctypes:
                all_ctypes.remove(ctype.Title())
            # and discard those containers that don't match the preservation
            # requirement
            if pres_c_types and ctype not in pres_c_types:
                continue
            if ctype.Title() in containers:
                containers[ctype.Title()].append(
                    (container.UID(), container.Title()))
            else:
                containers[ctype.Title()] = [
                    (container.UID(), container.Title()),
                ]
                ctype_to_uid[ctype.Title()] = ctype.UID()
        else:
            if not pres_c_types:
                containers_notype.append((container.UID(), container.Title()))

    translate = instance.translation_service.translate
    cat_str = translate(_('Container Type'))

    for ctype in containers.keys():
        if container_type_entries:
            items.append([ctype_to_uid[ctype], "%s: %s" % (cat_str, ctype)])
        for container in containers[ctype]:
            items.append(container)

    # all remaining containers
    for container in containers_notype:
        items.append(list(container))

    items = tuple(items)
    return items
예제 #18
0
파일: test_mg.py 프로젝트: juanre/magnitude
def test_arithmetic():
    m = mg(10, 'm/s') * (2, 's')
    n = mg(20, 'm')
    assert m == n
    assert (10, 'm/s') * mg(2, 's') == n
    assert mg(10, 'm/s') / (0.5, 'm') == mg(20, '1/s')
    assert (10, 'm/s') / mg(0.5, 'm') == mg(20, '1/s')
    assert 1 / mg(2, 's') == mg(0.5, '1/s')
    assert mg(5, 'kg/m2') % 3 == mg(2, 'kg/m2')
    assert mg(5, 'm/s') // mg(3, 'm') == mg(1, '1/s')
    assert mg(10, 'm/s') ** 2 == mg(100, 'm2/s2')
    assert mg(100, 'm2/s2') ** 0.5 == mg(10, 'm/s')
    assert (-mg(10, 'm/s')).val == -10.0
    assert (+mg(10, 'm/s')).val == 10.0
    assert abs(-mg(10, 'm/s')) == mg(10, 'm/s')
    assert int(mg(10.9, 'm/s')) == 10
    assert float(mg(10.9, 'm/s')) == 10.9
    assert long(mg(10.9, 'm/s')) == 10
예제 #19
0
def test_selfmod():
    m = mg(10, 'm/s')
    m += mg(3, 'm/s')
    assert m.val == 13.0
    m -= mg(43, 'm/s')
    assert m.val == -30.0
    m *= mg(2, 's')
    assert m == mg(-60, 'm')

    m = mg(10, 'm2/s')
    m /= (5, 'm')
    assert m == mg(2, 'm/s')

    m = mg(5, 'm/s')
    m //= mg(3, 'm')
    assert m == mg(1, '1/s')

    m = mg(5, 'm/s')
    m **= 2
    assert m == mg(25, 'm2/s2')
예제 #20
0
파일: utils.py 프로젝트: RaulKite/Bika-LIMS
    def __call__(self):
        translate = self.context.translate
        bsc = getToolByName(self.context, 'bika_setup_catalog')

        data = {
            'categories':{},  # services keyed by "POC_category"
            'services':{},    # service info, keyed by UID
        }

        ## Loop ALL SERVICES
        services = dict([(b.UID, b.getObject()) for b
                         in bsc(portal_type = "AnalysisService",
                                inactive_state = "active")])

        for uid, service in services.items():
            ## Store categories
            ## data['categories'][poc_catUID]: [uid, uid]
            key = "%s_%s" % (service.getPointOfCapture(),
                             service.getCategoryUID())
            if key in data['categories']:
                data['categories'][key].append(uid)
            else:
                data['categories'][key] = [uid, ]

            ## Get dependants
            ## (this service's Calculation backrefs' dependencies)
            backrefs = []
            # this function follows all backreferences so we need skip to
            # avoid recursion. It should maybe be modified to be more smart...
            skip = []
            def walk(items):
                for item in items:
                    if item.portal_type == 'AnalysisService'\
                       and item.UID() != service.UID():
                        backrefs.append(item)
                    if item not in skip:
                        skip.append(item)
                        brefs = item.getBackReferences()
                        walk(brefs)
            walk([service, ])

            ## Get dependencies
            ## (services we depend on)
            deps = {}
            calc = service.getCalculation()
            if calc:
                td = calc.getCalculationDependencies()
                def walk(td):
                    for depserv_uid, depserv_deps in td.items():
                        if depserv_uid == uid:
                            continue
                        depserv = services[depserv_uid]
                        category = depserv.getCategory()
                        cat = '%s_%s' % (category.UID(), category.Title())
                        poc = '%s_%s' % \
                            (depserv.getPointOfCapture(),
                             POINTS_OF_CAPTURE.getValue(depserv.getPointOfCapture()))
                        srv = '%s_%s' % (depserv.UID(), depserv.Title())
                        if not deps.has_key(poc): deps[poc] = {}
                        if not deps[poc].has_key(cat): deps[poc][cat] = []
                        if not srv in deps[poc][cat]:
                            deps[poc][cat].append(srv)
                        if depserv_deps:
                            walk(depserv_deps)
                walk(td)

            ## Get partition setup records for this service
            separate = service.getSeparate()
            containers = service.getContainer()
            containers.sort(lambda a,b:cmp(
                int(a.getJSCapacity() and a.getJSCapacity().split(" ")[0] or '0'),
                int(b.getJSCapacity() and b.getJSCapacity().split(" ")[0] or '0')
            ))
            preservations = service.getPreservation()
            partsetup = service.getPartitionSetup()

            # Single values become lists here
            for x in range(len(partsetup)):
                if partsetup[x].has_key('container') \
                   and type(partsetup[x]['container']) == str:
                    partsetup[x]['container'] = [partsetup[x]['container'],]
                if partsetup[x].has_key('preservation') \
                   and type(partsetup[x]['preservation']) == str:
                    partsetup[x]['preservation'] = [partsetup[x]['preservation'],]
                minvol = partsetup[x].get('vol', '0 g')
                try:
                    mgminvol = minvol.split(' ', 1)
                    mgminvol = mg(float(mgminvol[0]), mgminvol[1])
                except:
                    mgminvol = mg(0, 'ml')
                try:
                    mgminvol = str(mgminvol.ounit('ml'))
                except:
                    pass
                try:
                    mgminvol = str(mgminvol.ounit('g'))
                except:
                    pass
                partsetup[x]['vol'] = str(mgminvol)

            ## If no dependents, backrefs or partition setup exists
            ## nothing is stored for this service
            if not (backrefs or deps or separate or
                    containers or preservations or partsetup):
                continue

            # store info for this service
            data['services'][uid] = {
                'backrefs':[s.UID() for s in backrefs],
                'deps':deps,
            }

            data['services'][uid]['Separate'] = separate
            data['services'][uid]['Container'] = \
                [container.UID() for container in containers]
            data['services'][uid]['Preservation'] = \
                [pres.UID() for pres in preservations]
            data['services'][uid]['PartitionSetup'] = \
                partsetup

        uc = getToolByName(self.context, 'uid_catalog')

        ## SamplePoint and SampleType autocomplete lookups need a reference
        ## to resolve Title->UID
        data['st_uids'] = {}
        for st_proxy in bsc(portal_type = 'SampleType',
                        inactive_state = 'active'):
            st = st_proxy.getObject()
            data['st_uids'][st.Title()] = {
                'uid':st.UID(),
                'minvol': st.getJSMinimumVolume(),
                'containertype': st.getContainerType() and st.getContainerType().UID() or '',
                'samplepoints': [sp.Title() for sp in st.getSamplePoints()]
            }

        data['sp_uids'] = {}
        for sp_proxy in bsc(portal_type = 'SamplePoint',
                        inactive_state = 'active'):
            sp = sp_proxy.getObject()
            data['sp_uids'][sp.Title()] = {
                'uid':sp.UID(),
                'composite':sp.getComposite(),
                'sampletypes': [st.Title() for st in sp.getSampleTypes()]
            }

        data['containers'] = {}
        for c_proxy in bsc(portal_type = 'Container'):
            c = c_proxy.getObject()
            pres = c.getPreservation()
            data['containers'][c.UID()] = {
                'title':c.Title(),
                'uid':c.UID(),
                'containertype': c.getContainerType() and c.getContainerType().UID() or '',
                'prepreserved':c.getPrePreserved(),
                'preservation':pres and pres.UID() or '',
                'capacity':c.getJSCapacity(),
            }

        data['preservations'] = {}
        for p_proxy in bsc(portal_type = 'Preservation'):
            p = p_proxy.getObject()
            data['preservations'][p.UID()] = {
                'title':p.Title(),
                'uid':p.UID(),
            }

        return json.dumps(data)
예제 #21
0
def convert_to_base(quantity, unit, unit_type):
    # TODO: code base types elsewhere
    base_types = {"volume": "l", "temperature": "degC", "density": "SG(2020)"}
    return float(mg(quantity, unit).ounit(base_types[unit_type]))
예제 #22
0
def convert_to_default(quantity, base_unit, default_unit):
    base_unit_symbol = base_unit.mag_symbol
    default_unit_symbol = default_unit.mag_symbol
    return float(mg(quantity, base_unit_symbol).ounit(default_unit_symbol))
예제 #23
0
def convert_to_default(quantity, base_unit, default_unit):
    base_unit_symbol = base_unit.mag_symbol
    default_unit_symbol = default_unit.mag_symbol
    return float(mg(quantity, base_unit_symbol).ounit(default_unit_symbol))
예제 #24
0
def test_newmag():
    lb = Magnitude(0.45359237, kg=1)
    new_mag('lb', lb)
    assert lb.val - 0.45359237 < 1e-6
    assert lb.unit == [0, 0, 0, 1, 0, 0, 0, 0, 0]
    assert mg(1, 'lb') == lb
예제 #25
0
def test_comp():
    assert mg(1, 'm/s') != mg(2, 'm/s')
    assert mg(1, 'm/s') < mg(2, 'm/s')
    assert not mg(1, 'm/s') > mg(2, 'm/s')
예제 #26
0
파일: test_mg.py 프로젝트: juanre/magnitude
def test_selfmod():
    m = mg(10, 'm/s')
    m += mg(3, 'm/s')
    assert m.val == 13.0
    m -= mg(43, 'm/s')
    assert m.val == -30.0
    m *= mg(2, 's')
    assert m == mg(-60, 'm')

    m = mg(10, 'm2/s')
    m /= (5, 'm')
    assert m == mg(2, 'm/s')

    m = mg(5, 'm/s')
    m //= mg(3, 'm')
    assert m == mg(1, '1/s')

    m = mg(5, 'm/s')
    m **= 2
    assert m == mg(25, 'm2/s2')
예제 #27
0
파일: test_mg.py 프로젝트: juanre/magnitude
def test_comp():
    assert mg(1, 'm/s') != mg(2, 'm/s')
    assert mg(1, 'm/s') < mg(2, 'm/s')
    assert not mg(1, 'm/s') > mg(2, 'm/s')
 def make(self, ndarray, units):
     return magnitude.mg(ndarray, units)
예제 #29
0
def mg(value):
    tokens = value.split(" ") if value else [0, '']
    val = float(tokens[0]) if isinstance(tokens[0], (int, long)) else 0
    unit = tokens[1] if len(tokens) > 1 else ''
    return magnitude.mg(val, unit)
#! /usr/bin/env python
from __future__ import print_function

import os
import math
from magnitude import mg

def deflection_tangent(tangent_length, radius):
    return (tangent_length**2 + radius**2)**(1.0/2.0) - radius
    # Cannot use math.hypot or math.sqrt:
    # magnitude.MagnitudeError: Incompatible units: [1, 0, 0, 0, 0, 0, 0, 0, 0] and [0, 0, 0, 0, 0, 0, 0, 0, 0]
    # Cannot use numpy.hypot:
    # AttributeError: Magnitude instance has no attribute 'hypot'

def deflection_arc(arc_length, radius):
    return radius * (math.cos(arc_length/radius)**-1 - 1)

radius_earth = mg(6371.01, 'km')
length = mg(1, 'km')

deflection_1 = deflection_tangent(length, radius_earth).ounit('cm')
deflection_1.output_prec(10)

deflection_2 = deflection_arc(length, radius_earth).ounit('cm')
deflection_2.output_prec(10)

print(deflection_1)
print(deflection_2)
예제 #31
0
def getContainers(instance,
                  minvol=None,
                  allow_blank=True,
                  show_container_types=True,
                  show_containers=True):
    """ Containers vocabulary

    This is a separate class so that it can be called from ajax to filter
    the container list, as well as being used as the AT field vocabulary.

    Returns a tuple of tuples: ((object_uid, object_title), ())

    If the partition is flagged 'Separate', only containers are displayed.
    If the Separate flag is false, displays container types.

    XXX bsc = self.portal.bika_setup_catalog
    XXX obj = bsc(getKeyword='Moist')[0].getObject()
    XXX u'Container Type: Canvas bag' in obj.getContainers().values()
    XXX True

    """

    bsc = getToolByName(instance, 'bika_setup_catalog')

    items = allow_blank and [['', _('Any')]] or []

    containers = []
    for container in bsc(portal_type='Container', sort_on='sortable_title'):
        container = container.getObject()

        # verify container capacity is large enough for required sample volume.
        if minvol is not None:
            capacity = container.getCapacity()
            try:
                capacity = capacity.split(' ', 1)
                capacity = mg(float(capacity[0]), capacity[1])
                if capacity < minvol:
                    continue
            except:
                # if there's a unit conversion error, allow the container
                # to be displayed.
                pass

        containers.append(container)

    if show_containers:
        # containers with no containertype first
        for container in containers:
            if not container.getContainerType():
                items.append((container.UID(), container.Title()))

    ts = getToolByName(instance, 'translation_service').translate
    cat_str = _c(ts(_('Container Type')))
    containertypes = [c.getContainerType() for c in containers]
    containertypes = dict([(ct.UID(), ct.Title())
                           for ct in containertypes if ct])
    for ctype_uid, ctype_title in containertypes.items():
        ctype_title = _c(ctype_title)
        if show_container_types:
            items.append((ctype_uid, "%s: %s" % (cat_str, ctype_title)))
        if show_containers:
            for container in containers:
                ctype = container.getContainerType()
                if ctype and ctype.UID() == ctype_uid:
                    items.append((container.UID(), container.Title()))

    items = tuple(items)
    return items
예제 #32
0
파일: test_mg.py 프로젝트: juanre/magnitude
def test_newmag():
    lb = Magnitude(0.45359237, kg=1)
    new_mag('lb', lb)
    assert lb.val-0.45359237 < 1e-6
    assert lb.unit == [0, 0, 0, 1, 0, 0, 0, 0, 0]
    assert mg(1, 'lb') == lb
예제 #33
0
def convert_to_base(quantity, unit, unit_type):
    # TODO: code base types elsewhere
    base_types = {"volume": "l", "temperature": "degC", "density": "SG(2020)"}
    return float(mg(quantity, unit).ounit(base_types[unit_type]))
예제 #34
0
def test_arithmetic():
    m = mg(10, 'm/s') * (2, 's')
    n = mg(20, 'm')
    assert m == n
    assert (10, 'm/s') * mg(2, 's') == n
    assert mg(10, 'm/s') / (0.5, 'm') == mg(20, '1/s')
    assert (10, 'm/s') / mg(0.5, 'm') == mg(20, '1/s')
    assert 1 / mg(2, 's') == mg(0.5, '1/s')
    assert mg(5, 'kg/m2') % 3 == mg(2, 'kg/m2')
    assert mg(5, 'm/s') // mg(3, 'm') == mg(1, '1/s')
    assert mg(10, 'm/s')**2 == mg(100, 'm2/s2')
    assert mg(100, 'm2/s2')**0.5 == mg(10, 'm/s')
    assert (-mg(10, 'm/s')).val == -10.0
    assert (+mg(10, 'm/s')).val == 10.0
    assert abs(-mg(10, 'm/s')) == mg(10, 'm/s')
    assert int(mg(10.9, 'm/s')) == 10
    assert float(mg(10.9, 'm/s')) == 10.9
    assert long(mg(10.9, 'm/s')) == 10
예제 #35
0
def getContainers(instance,
                  minvol=None,
                  allow_blank=True,
                  show_container_types=True,
                  show_containers=True):
    """ Containers vocabulary

    This is a separate class so that it can be called from ajax to filter
    the container list, as well as being used as the AT field vocabulary.

    Returns a tuple of tuples: ((object_uid, object_title), ())

    If the partition is flagged 'Separate', only containers are displayed.
    If the Separate flag is false, displays container types.

    XXX bsc = self.portal.bika_setup_catalog
    XXX obj = bsc(getKeyword='Moist')[0].getObject()
    XXX u'Container Type: Canvas bag' in obj.getContainers().values()
    XXX True

    """

    bsc = getToolByName(instance, 'bika_setup_catalog')

    items = allow_blank and [['', _('Any')]] or []

    containers = []
    for container in bsc(portal_type='Container', sort_on='sortable_title'):
        container = container.getObject()

        # verify container capacity is large enough for required sample volume.
        if minvol is not None:
            capacity = container.getCapacity()
            try:
                capacity = capacity.split(' ', 1)
                capacity = mg(float(capacity[0]), capacity[1])
                if capacity < minvol:
                    continue
            except:
                # if there's a unit conversion error, allow the container
                # to be displayed.
                pass

        containers.append(container)

    if show_containers:
        # containers with no containertype first
        for container in containers:
            if not container.getContainerType():
                items.append((container.UID(), container.Title()))

    ts = getToolByName(instance, 'translation_service').translate
    cat_str = _c(ts(_('Container Type')))
    containertypes = [c.getContainerType() for c in containers]
    containertypes = dict([(ct.UID(), ct.Title())
                           for ct in containertypes if ct])
    for ctype_uid, ctype_title in containertypes.items():
        ctype_title = _c(ctype_title)
        if show_container_types:
            items.append((ctype_uid, "%s: %s" % (cat_str, ctype_title)))
        if show_containers:
            for container in containers:
                ctype = container.getContainerType()
                if ctype and ctype.UID() == ctype_uid:
                    items.append((container.UID(), container.Title()))

    items = tuple(items)
    return items
예제 #36
0
def getContainers(instance,
                  preservation=None,
                  minvol=None,
                  allow_blank=True,
                  container_type_entries=False):

    """ Containers vocabulary

    This is a separate class so that it can be called from ajax to
    filter the container list.

    >>> bsc = self.portal.bika_setup_catalog

    >>> obj = bsc(getKeyword='Moist')[0].getObject()
    >>> u'Canvas bag' in obj.getContainers().values()
    True

    >>> obj = bsc(getKeyword='Aflatox')[0].getObject()
    >>> u'20 ml glass vial' in obj.getContainers().values()
    True
    >>> u'Canvas bag' in obj.getContainers().values()
    False

    """
    bsc = getToolByName(instance, 'bika_setup_catalog')
    if allow_blank:
        items = [['','']]
    else:
        items = []

    if not type(preservation) in (list, tuple):
        preservation = [preservation,]
    pres_c_types = []
    for pres in preservation:
        if pres:
            for pres_ct in pres.getContainerType():
                if pres_ct not in pres_c_types:
                    pres_c_types.append(pres_ct)

    containers = {}
    containers_notype = []
    ctype_to_uid = {}
    all_ctypes = [ct.title for ct in bsc(portal_type='ContainerType',
                                         sort_on='sortable_title')]
    for container in bsc(portal_type='Container', sort_on='sortable_title'):
        container = container.getObject()
        if minvol:
            try:
                # If the units match, verify container is large enough.
                # all other containers are considered valid
                cvol = container.getCapacity()
                cvol = cvol.split(" ")
                cvol = mg(float(cvol[0]), " ".join(cvol[1:]).strip())
                if cvol.out_unit == minvol.out_unit and cvol.val < minvol.val:
                    continue
            except MagnitudeError:
                pass

        # This is to sort the container dropdown contents by type
        ctype = container.getContainerType()
        if ctype:
            if ctype.Title() in all_ctypes:
                all_ctypes.remove(ctype.Title())
            # and discard those containers that don't match the preservation
            # requirement
            if pres_c_types and ctype not in pres_c_types:
                continue
            if ctype.Title() in containers:
                containers[ctype.Title()].append((container.UID(), container.Title()))
            else:
                containers[ctype.Title()] = [(container.UID(), container.Title()),]
                ctype_to_uid[ctype.Title()] = ctype.UID()
        else:
            if not pres_c_types:
                containers_notype.append((container.UID(), container.Title()))

    translate = instance.translation_service.translate
    cat_str = translate(_('Container Type'))

    for ctype in containers.keys():
        if container_type_entries:
            items.append([ctype_to_uid[ctype], "%s: %s"%(cat_str, ctype) ])
        for container in containers[ctype]:
            items.append(container)

    # all remaining containers
    for container in containers_notype:
        items.append(list(container))

    items = tuple(items)
    return items
예제 #37
0
    def __call__(self):
        translate = self.context.translate
        bsc = getToolByName(self.context, 'bika_setup_catalog')

        data = {
            'categories': {},  # services keyed by "POC_category"
            'services': {},  # service info, keyed by UID
        }

        ## Loop ALL SERVICES
        services = dict([(b.UID, b.getObject())
                         for b in bsc(portal_type="AnalysisService",
                                      inactive_state="active")])

        for uid, service in services.items():
            ## Store categories
            ## data['categories'][poc_catUID]: [uid, uid]
            key = "%s_%s" % (service.getPointOfCapture(),
                             service.getCategoryUID())
            if key in data['categories']:
                data['categories'][key].append(uid)
            else:
                data['categories'][key] = [
                    uid,
                ]

            ## Get dependants
            ## (this service's Calculation backrefs' dependencies)
            backrefs = []
            # this function follows all backreferences so we need skip to
            # avoid recursion. It should maybe be modified to be more smart...
            skip = []

            def walk(items):
                for item in items:
                    if item.portal_type == 'AnalysisService'\
                       and item.UID() != service.UID():
                        backrefs.append(item)
                    if item not in skip:
                        skip.append(item)
                        brefs = item.getBackReferences()
                        walk(brefs)

            walk([
                service,
            ])

            ## Get dependencies
            ## (services we depend on)
            deps = {}
            calc = service.getCalculation()
            if calc:
                td = calc.getCalculationDependencies()

                def walk(td):
                    for depserv_uid, depserv_deps in td.items():
                        if depserv_uid == uid:
                            continue
                        depserv = services[depserv_uid]
                        category = depserv.getCategory()
                        cat = '%s_%s' % (category.UID(), category.Title())
                        poc = '%s_%s' % \
                            (depserv.getPointOfCapture(),
                             POINTS_OF_CAPTURE.getValue(depserv.getPointOfCapture()))
                        srv = '%s_%s' % (depserv.UID(), depserv.Title())
                        if not deps.has_key(poc): deps[poc] = {}
                        if not deps[poc].has_key(cat): deps[poc][cat] = []
                        if not srv in deps[poc][cat]:
                            deps[poc][cat].append(srv)
                        if depserv_deps:
                            walk(depserv_deps)

                walk(td)

            ## Get partition setup records for this service
            separate = service.getSeparate()
            containers = service.getContainer()
            containers.sort(lambda a, b: cmp(
                int(a.getJSCapacity() and a.getJSCapacity().split(" ")[0] or
                    '0'),
                int(b.getJSCapacity() and b.getJSCapacity().split(" ")[0] or
                    '0')))
            preservations = service.getPreservation()
            partsetup = service.getPartitionSetup()

            # Single values become lists here
            for x in range(len(partsetup)):
                if partsetup[x].has_key('container') \
                   and type(partsetup[x]['container']) == str:
                    partsetup[x]['container'] = [
                        partsetup[x]['container'],
                    ]
                if partsetup[x].has_key('preservation') \
                   and type(partsetup[x]['preservation']) == str:
                    partsetup[x]['preservation'] = [
                        partsetup[x]['preservation'],
                    ]
                minvol = partsetup[x].get('vol', '0 g')
                try:
                    mgminvol = minvol.split(' ', 1)
                    mgminvol = mg(float(mgminvol[0]), mgminvol[1])
                except:
                    mgminvol = mg(0, 'ml')
                try:
                    mgminvol = str(mgminvol.ounit('ml'))
                except:
                    pass
                try:
                    mgminvol = str(mgminvol.ounit('g'))
                except:
                    pass
                partsetup[x]['vol'] = str(mgminvol)

            ## If no dependents, backrefs or partition setup exists
            ## nothing is stored for this service
            if not (backrefs or deps or separate or containers or preservations
                    or partsetup):
                continue

            # store info for this service
            data['services'][uid] = {
                'backrefs': [s.UID() for s in backrefs],
                'deps': deps,
            }

            data['services'][uid]['Separate'] = separate
            data['services'][uid]['Container'] = \
                [container.UID() for container in containers]
            data['services'][uid]['Preservation'] = \
                [pres.UID() for pres in preservations]
            data['services'][uid]['PartitionSetup'] = \
                partsetup

        uc = getToolByName(self.context, 'uid_catalog')

        ## SamplePoint and SampleType autocomplete lookups need a reference
        ## to resolve Title->UID
        data['st_uids'] = {}
        for st_proxy in bsc(portal_type='SampleType', inactive_state='active'):
            st = st_proxy.getObject()
            data['st_uids'][st.Title()] = {
                'uid':
                st.UID(),
                'minvol':
                st.getJSMinimumVolume(),
                'containertype':
                st.getContainerType() and st.getContainerType().UID() or '',
                'samplepoints': [sp.Title() for sp in st.getSamplePoints()]
            }

        data['sp_uids'] = {}
        for sp_proxy in bsc(portal_type='SamplePoint',
                            inactive_state='active'):
            sp = sp_proxy.getObject()
            data['sp_uids'][sp.Title()] = {
                'uid': sp.UID(),
                'composite': sp.getComposite(),
                'sampletypes': [st.Title() for st in sp.getSampleTypes()]
            }

        data['containers'] = {}
        for c_proxy in bsc(portal_type='Container'):
            c = c_proxy.getObject()
            pres = c.getPreservation()
            data['containers'][c.UID()] = {
                'title':
                c.Title(),
                'uid':
                c.UID(),
                'containertype':
                c.getContainerType() and c.getContainerType().UID() or '',
                'prepreserved':
                c.getPrePreserved(),
                'preservation':
                pres and pres.UID() or '',
                'capacity':
                c.getJSCapacity(),
            }

        data['preservations'] = {}
        for p_proxy in bsc(portal_type='Preservation'):
            p = p_proxy.getObject()
            data['preservations'][p.UID()] = {
                'title': p.Title(),
                'uid': p.UID(),
            }

        return json.dumps(data)
예제 #38
0
def mg(value):
    tokens = value.split(" ") if value else [0, '']
    val = float(tokens[0]) if isinstance(tokens[0], (int, long)) else 0
    unit = tokens[1] if len(tokens) > 1 else ''
    return magnitude.mg(val, unit)