Пример #1
0
 def get(self, request, data):
     bounds = data > maybe | X.get('in_polygon')
     return ((data or {}) > as_kwargs(get_car_position_data)
         | where(X['car'] | self.filter)
         | group_by(X['location'] | (grouping_precision, X, bounds))
         | X.iteritems()
         | foreach({
             'location': X[1][0]['location'],
             'cars': X[1] | foreach(X['car']) | self.get_car_data,
           })
         | tuple)
Пример #2
0
 def get(self, request, data):
     bounds = data > maybe | X.get('in_polygon')
     return ((data or {}) > as_kwargs(get_car_position_data)
             | where(X['car'] | self.filter)
             | group_by(X['location'] | (grouping_precision, X, bounds))
             | X.iteritems()
             | foreach({
                 'location': X[1][0]['location'],
                 'cars': X[1] | foreach(X['car']) | self.get_car_data,
             })
             | tuple)
Пример #3
0
def test_pipe_exception():
    "How an exception in a pipe should look like"

    f = pipe | str | foreach(X.upper()) | foreach(~X.lower() | int) | list

    with pytest.raises(ValueError) as excinfo:
        f('adfasfa')

    assert excinfo.value.message == (
        "invalid literal for int() with base 10: 'a'\n"
        "  in pipe | X.lower | X() | int\n"
        "  in pipe | str | foreach(X.upper | X()) | foreach(X.lower | X() | int) | list"
    )
Пример #4
0
    def test_chained(self):

        f = ~X.get("item", "").startswith("Hello")

        assert f({"item": "Hello world"})
        assert not f({"item": "Goodbye world"})
        assert not f({})
Пример #5
0
    def test_chained(self):

        f = ~X.get('item', '').startswith('Hello')

        assert f({'item': 'Hello world'})
        assert not f({'item': 'Goodbye world'})
        assert not f({})
Пример #6
0
    def test_in(self):
        container = "asdf"

        f = ~X._in_(container)

        assert f("a")
        assert not f("b")
Пример #7
0
    def test_in(self):
        container = 'asdf'

        f = ~X._in_(container)

        assert f('a')
        assert not f('b')
Пример #8
0
    def test_chained(self):

        f = ~X.get('item', '').startswith('Hello')

        assert f({'item': 'Hello world'})
        assert not f({'item': 'Goodbye world'})
        assert not f({})
Пример #9
0
    def test_in(self):
        container = 'asdf'

        f = ~X._in_(container)

        assert f('a')
        assert not f('b')
Пример #10
0
def create_units():
    "Creates CarUnits for existing Cars that don't have them"
    cars_with_units = CarUnit.objects.values_list('car_id', flat=True)
    taken_unit_ids = set(CarUnit.objects.values_list('unit_id', flat=True))
    free_unit_ids = count(1) > where_not(X._in_(taken_unit_ids))
    cars_without_units = Car.objects.all() > where_not(X.id._in_(cars_with_units))
    for car, unit_id in izip(cars_without_units, free_unit_ids):
        unit(unit_id, car)
Пример #11
0
def get_car_last_position(car):
    """
    Returns car's last known position.

    First attempts to get it from a CarUnit assigned to `car` and if that fails
    (no CarUnit or it doesn't know the position) it falls back to the car's
    last_position attribute, which might have been filled out manually.
    """
    from metrocar.car_unit_api.models import CarUnit
    from_car_unit = CarUnit.objects.get_for(car) > maybe | X.get_last_position()
    return from_car_unit or car.last_position
Пример #12
0
def split_by_events(journey, entry):
    """
    Returns whether the last two events in `journey` were ENGINE_OFF and LOCKED

    -- where we only care about events: ENGINE_OFF, ENGINE_ON, UNLOCKED, LOCKED
    """
    from metrocar.car_unit_api.models import Events

    events_of_interest = (
        Events.ENGINE_OFF,
        Events.ENGINE_ON,
        Events.UNLOCKED,
        Events.LOCKED,
    )
    events = journey['events'] > where(X._in_(events_of_interest)) | tuple
    return (len(events) >= 2 and
        (events[-2], events[-1]) == (Events.ENGINE_OFF, Events.LOCKED))
Пример #13
0
    def __init__(self, *args, **kwargs):
        super(SmartAdmin, self).__init__(*args, **kwargs)

        if self.list_display == admin.ModelAdmin.list_display:
            self.list_display = ('__str__', ) + (self._get_fields(
                lambda field: type(field) not in self.list_display_exclude))

        self.date_hierarchy = (self.date_hierarchy or self.all_fields > maybe
            | select_first(type | X._in_([DateTimeField, DateField]))
            | X.name)

        self.list_filter = self.list_filter or self._get_list_filter()

        self.search_fields = self.search_fields or self._get_search_fields()
        self.raw_id_fields = self.raw_id_fields or self._get_fields(
            self.should_be_raw_id_field)

        self.filter_horizontal = self.filter_horizontal or self._get_fields(
            type | (X == ManyToManyField))
Пример #14
0
def validate(*rules):
    """
    Creates a validation function that will check if it's input satisfies
    `rules`.

    `rules` should be an (arbitrarily nested) sequence of functions
    that take one argument and return a tuple of:
    ``(valid: bool, error: string or None)``
    where `valid` says if the argument satisfies the rule and `error` says
    why not if it doesn't.

    The rules are checked sequentially and when an error is encountered, it is
    returned immediately from the function, without checking the rest of the
    rules. The returned value is the one returned from the rule, i.e.
    ``(False, "error message")``

    If no error is encountered the function returns ``(True, None)``.

    (Note that the validation function itself is a rule.)
    """
    rules = rules > flatten | tuple
    return lambda val: rules > foreach(X(val)) | select_first(X != OK) or OK
Пример #15
0
    def ready_to_finish(self):
        """
        Returns true if reservation is ready to be finished
        """
        from metrocar.cars.models import Parking
        if self.finished or self.ended is not None: return True
        if self.started is None: return False

        if not self.car.dedicated_parking_only:
            # cars which doesn't have dedicated parking are little trouble
            # as we can't rightfully decide if their reservation can be
            # finished
            # => they are collected by reservation deamon
            return False
        elif settings.GEO_ENABLED:
            # is there a Parking that contains car's last_position?
            return (self.car > maybe
                | get_car_last_position
                | X['location']
                | 'POINT ({0} {1})'
                | xcurry(Parking.objects.filter, polygon__contains=X)
                | X.exists())
Пример #16
0
    def test_call(self):

        f = ~X(42)

        assert f(lambda n: n / 2) == 21
Пример #17
0
"""
The public API
"""
from datetime import datetime
from pipetools import pipe, X
from geotrack.backends import get_backend
from geotrack.queries import get_query
from geotrack.utils import extract_timestamp


def store(unit_id, timestamp, location, **kwargs):
    if isinstance(timestamp, basestring):
        timestamp = extract_timestamp(timestamp)
    backend = get_backend()
    backend.store(
        unit_id=unit_id,
        timestamp=timestamp,
        location=location,
        added=datetime.now(),
        **kwargs)


def query(query_name, **kwargs):
    backend = get_backend()
    query = get_query(query_name, backend=backend)
    return query(**kwargs)


flush = pipe | get_backend | X.flush()
Пример #18
0
 def test_name(self):
     f = ~X.attr(1, 2, three='four')
     assert f.__name__ == "X.attr | X(1, 2, three='four')"
Пример #19
0
    def test_basic(self):

        f = ~X.startswith('Hello')

        assert f('Hello world')
        assert not f('Goodbye world')
Пример #20
0
        TestCommand.finalize_options(self)
        self.test_args = []
        self.test_suite = True

    def run_tests(self):
        # import here, cause outside the eggs aren't loaded
        import pytest
        error_code = pytest.main(self.test_args)
        sys.exit(error_code)


setup(name='pipetools',
      version=pipetools.__versionstr__,
      description=('A library that enables function composition similar to '
                   'using Unix pipes.'),
      long_description='README.rst' > open | X.read(),
      author='Petr Pokorny',
      author_email='*****@*****.**',
      license='MIT',
      url='http://0101.github.com/pipetools/',
      packages=['pipetools'],
      include_package_data=True,
      install_requires=('setuptools>=0.6b1', ),
      tests_require=('pytest', ),
      cmdclass={'test': PyTest},
      classifiers=[
          'Development Status :: 2 - Pre-Alpha',
          'Intended Audience :: Developers',
          'License :: OSI Approved :: MIT License',
          'Operating System :: OS Independent',
          'Programming Language :: Python :: 2',
Пример #21
0
def execute(backend, query, max_items=50, **kwargs):
    return (query(**kwargs)
        > group_by(X['unit_id'])
        | X.iteritems()
        | foreach([KEY, VALUE | prune_to(max_items)])
        | dict)
Пример #22
0
    def test_basic(self):

        f = ~X.startswith('Hello')

        assert f('Hello world')
        assert not f('Goodbye world')
Пример #23
0
def execute(backend, query, max_items=50, **kwargs):
    return (query(**kwargs) > group_by(X['unit_id'])
            | X.iteritems()
            | foreach([KEY, VALUE | prune_to(max_items)])
            | dict)
Пример #24
0
 def test_with_exception(self):
     f = unless(AttributeError, foreach(X.lower()) | list)
     assert f(['A', 'B', 37]) is None
Пример #25
0
 def test_name(self):
     f = ~X.attr(1, 2, three="four")
     assert f.__name__ == "X.attr | X(1, 2, three='four')"
Пример #26
0
 def test_with_exception_in_foreach(self):
     f = foreach(unless(AttributeError, X.lower())) | list
     assert f(['A', 'B', 37]) == ['a', 'b', None]
Пример #27
0
        self.test_args = []
        self.test_suite = True

    def run_tests(self):
        # import here, cause outside the eggs aren't loaded
        import pytest
        error_code = pytest.main(self.test_args)
        sys.exit(error_code)


setup(
    name='pipetools',
    version=pipetools.__versionstr__,
    description=('A library that enables function composition similar to '
        'using Unix pipes.'),
    long_description='README.rst' > xpartial(io.open, X, encoding="utf-8") | X.read(),
    author='Petr Pokorny',
    author_email='*****@*****.**',
    license='MIT',
    url='http://0101.github.com/pipetools/',
    packages=['pipetools'],
    include_package_data=True,
    install_requires=(
         'setuptools>=0.6b1',
    ),
    tests_require=(
        'pytest',
    ),
    cmdclass={'test': PyTest},

    classifiers=[
Пример #28
0
        self.test_args = []
        self.test_suite = True

    def run_tests(self):
        # import here, cause outside the eggs aren't loaded
        import pytest
        error_code = pytest.main(self.test_args)
        sys.exit(error_code)


setup(
    name='pipetools',
    version=pipetools.__versionstr__,
    description=('A library that enables function composition similar to '
        'using Unix pipes.'),
    long_description='README.rst' > open | X.read(),
    author='Petr Pokorny',
    author_email='*****@*****.**',
    license='MIT',
    url='http://0101.github.com/pipetools/',
    packages=['pipetools'],
    include_package_data=True,
    install_requires=(
         'setuptools>=0.6b1',
    ),
    tests_require=(
        'pytest',
    ),
    cmdclass={'test': PyTest},

    classifiers=[
Пример #29
0

commit_readme = """

git add README.rst
git commit -m "(readme update)"

"""

update_gh_pages = """

git checkout gh-pages
git merge master

git rm -rf doc
sphinx-build -b html docs/source/ doc

git add doc
git commit -m "doc update"
git checkout master

"""

runscript = X.split('\n') | where(X) | unless(BuildFailure, foreach_do(sh))

if __name__ == '__main__':

    create_readme()
    runscript(commit_readme)
    runscript(update_gh_pages)
Пример #30
0
 def test_repr(self):
     f = ~X.attr(1, 2, three='four')
     assert repr(f) == "X.attr | X(1, 2, three='four')"
Пример #31
0
    def test_basic(self):

        f = ~X.startswith("Hello")

        assert f("Hello world")
        assert not f("Goodbye world")
Пример #32
0
        self.test_args = []
        self.test_suite = True

    def run_tests(self):
        # import here, cause outside the eggs aren't loaded
        import pytest
        error_code = pytest.main(self.test_args)
        sys.exit(error_code)


setup(name='pipetools',
      version=pipetools.__versionstr__,
      description=('A library that enables function composition similar to '
                   'using Unix pipes.'),
      long_description='README.rst' >
      xpartial(io.open, X, encoding="utf-8") | X.read(),
      author='Petr Pokorny',
      author_email='*****@*****.**',
      license='MIT',
      url='https://0101.github.io/pipetools/',
      packages=['pipetools'],
      include_package_data=True,
      install_requires=('setuptools>=0.6b1', ),
      tests_require=('pytest', ),
      cmdclass={'test': PyTest},
      classifiers=[
          'Development Status :: 5 - Production/Stable',
          'Intended Audience :: Developers',
          'License :: OSI Approved :: MIT License',
          'Operating System :: OS Independent',
          'Programming Language :: Python :: 2',
Пример #33
0
 def test_ok(self):
     f = unless(AttributeError, foreach(X.lower())) | list
     assert f("ABC") == ['a', 'b', 'c']
Пример #34
0
"""
The public API
"""
from datetime import datetime
from pipetools import pipe, X
from geotrack.backends import get_backend
from geotrack.queries import get_query
from geotrack.utils import extract_timestamp


def store(unit_id, timestamp, location, **kwargs):
    if isinstance(timestamp, basestring):
        timestamp = extract_timestamp(timestamp)
    backend = get_backend()
    backend.store(unit_id=unit_id,
                  timestamp=timestamp,
                  location=location,
                  added=datetime.now(),
                  **kwargs)


def query(query_name, **kwargs):
    backend = get_backend()
    query = get_query(query_name, backend=backend)
    return query(**kwargs)


flush = pipe | get_backend | X.flush()
Пример #35
0
 def test_with_exception(self):
     f = unless(AttributeError, foreach(X.lower()) | list)
     assert f(['A', 'B', 37]) is None
Пример #36
0
 def test_repr(self):
     f = ~X.attr(1, 2, three='four')
     assert repr(f) == "X.attr | X(1, 2, three='four')"
Пример #37
0
 def test_with_exception_in_foreach(self):
     f = foreach(unless(AttributeError, X.lower())) | list
     assert f(['A', 'B', 37]) == ['a', 'b', None]
Пример #38
0
 def test_ok(self):
     f = unless(AttributeError, foreach(X.lower())) | list
     assert f("ABC") == ['a', 'b', 'c']
Пример #39
0
commit_readme = """

git add README.rst
git commit -m "(readme update)"

"""


update_gh_pages = """

git checkout gh-pages
git merge master

git rm -rf doc
sphinx-build -b html docs/source/ doc

git add doc
git commit -m "doc update"
git checkout master

"""

runscript = X.split('\n') | where(X) | unless(BuildFailure, foreach_do(sh))


if __name__ == '__main__':

    create_readme()
    runscript(commit_readme)
    runscript(update_gh_pages)