<commit_before>#!/usr/bin/env python3
import pytest

from cozify import hub, multisensor
from cozify.test import debug
from cozify.test.fixtures import *
from cozify.Error import APIError

@pytest.mark.logic
def test_hub_tmp_hub(tmp_hub):
    assert config.state['Cloud']['email'] == 'example@example.com'
    assert config.state['Hubs']['default'] == 'deadbeef-aaaa-bbbb-cccc-tmphubdddddd'

@pytest.mark.live
def test_hub_tz(live_hub):
    assert hub.ping()
    assert hub.tz()

@pytest.mark.live
def test_hub_remote_naive(live_hub):
    assert hub.tz()

@pytest.mark.logic
def test_hub_remote_set(tmp_hub):
    assert hub.remote(tmp_hub.id, True) == True
    assert hub.remote(tmp_hub.id) == True
    assert hub.remote(tmp_hub.id, False) == False
    assert hub.remote(tmp_hub.id) == False

@pytest.mark.logic
def test_hub_autoremote_set(tmp_hub):
    assert hub.autoremote(tmp_hub.id, True) == True
    assert hub.autoremote(tmp_hub.id) == True
    assert hub.autoremote(tmp_hub.id, False) == False
    assert hub.autoremote(tmp_hub.id) == False

@pytest.mark.logic
def test_hub_id_to_name(tmp_hub):
    assert hub.name(tmp_hub.id) == tmp_hub.name

@pytest.mark.logic
def test_hub_name_to_id(tmp_hub):
    assert hub.hub_id(tmp_hub.name) == tmp_hub.id

@pytest.mark.live
def test_multisensor(live_hub):
    assert hub.ping()
    data = hub.devices()
    print(multisensor.getMultisensorData(data))

@pytest.mark.logic
def test_hub_get_id(tmp_hub):
    assert hub._get_id(hub_id=tmp_hub.id) == tmp_hub.id
    assert hub._get_id(hub_name=tmp_hub.name) == tmp_hub.id
    assert hub._get_id(hub_name=tmp_hub.name, hub_id=tmp_hub.id) == tmp_hub.id
    assert hub._get_id(hubName=tmp_hub.name) == tmp_hub.id
    assert hub._get_id(hubId=tmp_hub.id) == tmp_hub.id
    assert hub._get_id() == tmp_hub.id
    assert not hub._get_id(hub_id='foo') == tmp_hub.id

@pytest.mark.destructive
def test_hub_ping_autorefresh(live_hub):
    assert hub.ping()
    hub_id = live_hub.default()
    live_hub.token(hub_id=hub_id, new_token='destroyed-on-purpose-by-destructive-test')

    assert not live_hub.ping(autorefresh=False)
    with pytest.raises(APIError):
        hub.tz()
    assert live_hub.ping(autorefresh=True)

@pytest.mark.live
def test_hub_fill_kwargs(live_hub):
    assert hub.ping()
    kwargs = {}
    hub._fill_kwargs(kwargs)
    for key in ['hub_id', 'remote', 'autoremote', 'hub_token', 'cloud_token', 'host']:
        assert key in kwargs, 'key {0} did not get set.'.format(key)
        if key != 'host' or (key == 'host' and not live_hub.remote(hub.default())):
            assert kwargs[key] is not None, 'key {0} was set to None'.format(key)

@pytest.mark.logic
def test_hub_clean_state(tmp_hub):
    states = tmp_hub.states()
    assert states['clean'] == hub._clean_state(states['dirty'])

@pytest.mark.logic
def test_hub_in_range():
    assert hub._in_range(0.5, low=0.0, high=1.0)
    assert hub._in_range(0.0, low=0.0, high=1.0)
    assert hub._in_range(1.0, low=0.0, high=1.0)
    assert hub._in_range(None, low=0.0, high=1.0)
    with pytest.raises(ValueError):
        hub._in_range(1.5, low=0.0, high=1.0)
    with pytest.raises(ValueError):
        hub._in_range(-0.5, low=0.0, high=1.0)
<commit_msg>Revert "Merge branch 'devel'"<commit_after>#!/usr/bin/env python3
import pytest

from cozify import hub, multisensor
from cozify.test import debug
from cozify.test.fixtures import *
from cozify.Error import APIError

@pytest.mark.logic
def test_hub_tmp_hub(tmp_hub):
    assert config.state['Cloud']['email'] == 'example@example.com'
    assert config.state['Hubs']['default'] == 'deadbeef-aaaa-bbbb-cccc-tmphubdddddd'

@pytest.mark.live
def test_hub_tz(live_hub):
    assert hub.ping()
    assert hub.tz()

@pytest.mark.live
def test_hub_remote_naive(live_hub):
    assert hub.tz()

@pytest.mark.logic
def test_hub_remote_set(tmp_hub):
    assert hub.remote(tmp_hub.id, True) == True
    assert hub.remote(tmp_hub.id) == True
    assert hub.remote(tmp_hub.id, False) == False
    assert hub.remote(tmp_hub.id) == False

@pytest.mark.logic
def test_hub_autoremote_set(tmp_hub):
    assert hub.autoremote(tmp_hub.id, True) == True
    assert hub.autoremote(tmp_hub.id) == True
    assert hub.autoremote(tmp_hub.id, False) == False
    assert hub.autoremote(tmp_hub.id) == False

@pytest.mark.logic
def test_hub_id_to_name(tmp_hub):
    assert hub.name(tmp_hub.id) == tmp_hub.name

@pytest.mark.logic
def test_hub_name_to_id(tmp_hub):
    assert hub.hub_id(tmp_hub.name) == tmp_hub.id

@pytest.mark.live
def test_multisensor(live_hub):
    assert hub.ping()
    data = hub.devices()
    print(multisensor.getMultisensorData(data))

@pytest.mark.logic
def test_hub_get_id(tmp_hub):
    assert hub._get_id(hub_id=tmp_hub.id) == tmp_hub.id
    assert hub._get_id(hub_name=tmp_hub.name) == tmp_hub.id
    assert hub._get_id(hub_name=tmp_hub.name, hub_id=tmp_hub.id) == tmp_hub.id
    assert hub._get_id(hubName=tmp_hub.name) == tmp_hub.id
    assert hub._get_id(hubId=tmp_hub.id) == tmp_hub.id
    assert hub._get_id() == tmp_hub.id
    assert not hub._get_id(hub_id='foo') == tmp_hub.id

@pytest.mark.destructive
def test_hub_ping_autorefresh(live_hub):
    hub_id = live_hub.default()
    live_hub.token(hub_id=hub_id, new_token='destroyed-on-purpose-by-destructive-test')

    assert not live_hub.ping(autorefresh=False)
    with pytest.raises(APIError):
        hub.tz()
    assert live_hub.ping(autorefresh=True)

@pytest.mark.live
def test_hub_fill_kwargs(live_hub):
    kwargs = {}
    hub._fill_kwargs(kwargs)
    for key in ['hub_id', 'remote', 'autoremote', 'hub_token', 'cloud_token', 'host']:
        assert key in kwargs, 'key {0} did not get set.'.format(key)
        if key != 'host' or (key == 'host' and not live_hub.remote(hub.default())):
            assert kwargs[key] is not None, 'key {0} was set to None'.format(key)

@pytest.mark.logic
def test_hub_clean_state(tmp_hub):
    states = tmp_hub.states()
    assert states['clean'] == hub._clean_state(states['dirty'])

@pytest.mark.logic
def test_hub_in_range():
    assert hub._in_range(0.5, low=0.0, high=1.0)
    assert hub._in_range(0.0, low=0.0, high=1.0)
    assert hub._in_range(1.0, low=0.0, high=1.0)
    assert hub._in_range(None, low=0.0, high=1.0)
    with pytest.raises(ValueError):
        hub._in_range(1.5, low=0.0, high=1.0)
    with pytest.raises(ValueError):
        hub._in_range(-0.5, low=0.0, high=1.0)
<|endoftext|>


<commit_before>import requests

from util import init_logging

from alppaca.compat import OrderedDict

class NoRolesFoundException(Exception):
    pass

class NoCredentialsFoundException(Exception):
    pass

class IMSInterface(object):

    def __init__(self, ims_url, debug=False):
        self.ims_host = ims_url
        self.logger = init_logging(debug)

    def get_roles(self):
        try:
            response = requests.get("http://{0}/latest/meta-data/iam/security-credentials/".format(self.ims_host))

            if response.status_code == 200:
                if not response.content:
                    raise NoRolesFoundException("Server response was empty; host has no roles?")

                roles_list = [line.strip() for line in response.content.split("\n")] if response.content else []
                self.logger.debug("Loaded roles: {0}".format(roles_list))
                return roles_list
            else:
                response.raise_for_status()
        except Exception as e:
            self.logger.exception("Due to following cause:")
            raise NoRolesFoundException(e.message)

    def get_credentials(self, role):
        try:
            response = requests.get("http://{0}/latest/meta-data/iam/security-credentials/{1}".format(self.ims_host, role))
            if response.status_code == 200:
                if not response.content:
                    raise NoCredentialsFoundException("Server response was empty; no credentials for role?")
                return response.content
            else:
                response.raise_for_status()
        except Exception as e:
            self.logger.exception("Due to following cause:")
            raise NoCredentialsFoundException(e.message)

    def get_credentials_for_all_roles(self):
        results = OrderedDict()
        for role in self.get_roles():
            try:
                results[role] = self.get_credentials(role)
            except NoCredentialsFoundException:
                self.logger.exception("Role {0} didn't have any credentials.".format(role))
        return results
<commit_msg>clean more imports<commit_after>import requests

from util import init_logging
from compat import OrderedDict

class NoRolesFoundException(Exception):
    pass

class NoCredentialsFoundException(Exception):
    pass

class IMSInterface(object):

    def __init__(self, ims_url, debug=False):
        self.ims_host = ims_url
        self.logger = init_logging(debug)

    def get_roles(self):
        try:
            response = requests.get("http://{0}/latest/meta-data/iam/security-credentials/".format(self.ims_host))

            if response.status_code == 200:
                if not response.content:
                    raise NoRolesFoundException("Server response was empty; host has no roles?")

                roles_list = [line.strip() for line in response.content.split("\n")] if response.content else []
                self.logger.debug("Loaded roles: {0}".format(roles_list))
                return roles_list
            else:
                response.raise_for_status()
        except Exception as e:
            self.logger.exception("Due to following cause:")
            raise NoRolesFoundException(e.message)

    def get_credentials(self, role):
        try:
            response = requests.get("http://{0}/latest/meta-data/iam/security-credentials/{1}".format(self.ims_host, role))
            if response.status_code == 200:
                if not response.content:
                    raise NoCredentialsFoundException("Server response was empty; no credentials for role?")
                return response.content
            else:
                response.raise_for_status()
        except Exception as e:
            self.logger.exception("Due to following cause:")
            raise NoCredentialsFoundException(e.message)

    def get_credentials_for_all_roles(self):
        results = OrderedDict()
        for role in self.get_roles():
            try:
                results[role] = self.get_credentials(role)
            except NoCredentialsFoundException:
                self.logger.exception("Role {0} didn't have any credentials.".format(role))
        return results
<|endoftext|>


<commit_before>#!/usr/bin/env python

import sys; sys.path.append("..")

from lilypond.interp import parse
from midi.write_midi import SMF

patterns = [
    r"\relative c' { \acciaccatura c8 e4 \acciaccatura c8 e4 \acciaccatura c8 e4 }", #1
    r"\relative c' { \acciaccatura c8 e8 f8 e4 }",
    r"\relative c' { r8 e8 f8 e8 }",
    r"\relative c' { r8 e8 f8 g8 }",
    r"\relative c' { e8 f8 g8 r8 }", #5
    r"\relative c'' { c1~ c1 }",
    r"\relative c' { r4 r4 r4 r8 c16 c16 c8 r8 r4 r4 r4 r4 }",
    r"\relative c'' { g1. f1~ f1 }",
    r"\relative c'' { b16 g16 r8 r4 r4 r4 }",
    r"\relative c'' { b16 g16 }", #10
    r"\relative c' { f16 g16 b16 g16 b16 g16 }",
    r"\relative c' { f8 g8 b1 c4}",
    r"\relative c'' { b16 g8. g16 f16 g8 r8. g16~ g2. }",
    r"\relative c'' { c1 b1 g1 fis1 }",
    r"\relative c'' { g16 r8. r4 r4 r4 }",#15
    r"\relative c'' { g16 b16 c16 b16 }",
    r"\relative c'' { b16 c16 b16 c16 b16 r16 }",
    r"\relative c' { e16 fis16 e16 fis16 e8. e16 }",
    r"\relative c'' { r4. g'4. }",
    r"\relative c' { e16 fis16 e16 fis16 g,8. e'16 fis16 e16 fis16 e16 }",#20
    r"\relative c' { fis2.}",
    r"\relative c' { e4. e4. e4. e4. e4. fis4. g4. a4. b8 }",
    r"\relative c' { e8 fis4. fis4. fis4. fis4. fis4. g4. a4. b4 }",
    r"\relative c' { e8 fis8 g4. g4. g4. g4. g4. a4. b8 }",
    r"\relative c' { e8 fis8 g8 a4. a4. a4. a4. a4. b4. }",#25
    r"\relative c' { e8 fis8 g8 a8 b4. b4. b4. b4. b4. }",
    r"\relative c' { e16 fis16 e16 fis16 g8 e16 g16 fis16 e16 fis16 e16}",
    r"\relative c' { e16 fis16 e16 fis16 e8. e16 }",
    r"\relative c' { e2. g2. c2. }",
    r"\relative c' { c'1. }",#30
    r"\relative c'' { g16 f16 g16 b16 g16 b16 }",
    r"\relative c' { f16 g16 f16 g16 b16 f16~ f2. g4. }",
    r"\relative c'' { g16 f16 r8 }",
    r"\relative c'' { g16 f16 }",
    r"\relative c' { f16 g16 b16 g16 b16 g16 b16 g16 b16 g16 r8 r4 r4 r4 bes4 g'2. a8 g8~ g8 b8 a4. g8 e2. g8 fis8~ fis2. r4 r4 r8 e8~ e2 f1. }",#35
    r"\relative c' { f16 g16 b16 g16 b16 g16 }",
    r"\relative c' { f16 g16 }",
    r"\relative c' { f16 g16 b16 }",
    r"\relative c'' { b16 g16 f16 g16 b16 c16 }",
    r"\relative c'' { b16 f16 }",#40
    r"\relative c'' { b16 g16 }",
    r"\relative c'' { c1 b1 a1 c1 }",
    r"\relative c'' { f16 e16 f16 e16 e8 e8 e8 f16 e16 }",
    r"\relative c'' { f8 e8~ e8 e8 c4 }",
    r"\relative c'' { d4 d4 g='4 }",#45
    r"\relative c'' { g16 d=''16 e16 d16 r8 g='8 r8 g8 r8 g8 g16 d=''16 e16 d16 }",
    r"\relative c'' { d16 e16 d8 }",
    r"\relative c'' { g1. g1 f1~ f4 }",
    r"\relative c' { f16 g16 bes16 g16 bes16 g16 }",
    r"\relative c' { f16 g16 }",#50
    r"\relative c' { f16 g16 bes16 }",
    r"\relative c'' { g16 bes16 }",
    r"\relative c'' { bes16 g16 }",
]

# make a separate MIDI file for each pattern

def separate_files():
    for num, pattern in enumerate(patterns):
        p = parse(pattern)
        print num + 1, list(p)
        f = open("in_c_%s.mid" % (num + 1), "w")
        s = SMF(parse(pattern))
        s.write(f)
        f.close()

# make a single MIDI file with all the patterns in a row

def one_file():
    big_pattern = []
    offset = 0
    for num, pattern in enumerate(patterns):
        for ev in parse(pattern, offset):
            if ev[1] != -1: # -1 means a offset check with no sound
                big_pattern.append(ev)
            offset = ev[0] # remember the last offset so the next pattern can use it
        f = open("in_c_all.mid", "w")
        s = SMF(big_pattern)
        s.write(f)
        f.close()

one_file()
<commit_msg>Fixed lilypond tests so the octave check bug is obvious and corrected related errors in the Lilypond definitions of fragments 45 and 46<commit_after>#!/usr/bin/env python

import sys; sys.path.append("..")

from lilypond.interp import parse
from midi.write_midi import SMF

patterns = [
    r"\relative c' { \acciaccatura c8 e4 \acciaccatura c8 e4 \acciaccatura c8 e4 }", #1
    r"\relative c' { \acciaccatura c8 e8 f8 e4 }",
    r"\relative c' { r8 e8 f8 e8 }",
    r"\relative c' { r8 e8 f8 g8 }",
    r"\relative c' { e8 f8 g8 r8 }", #5
    r"\relative c'' { c1~ c1 }",
    r"\relative c' { r4 r4 r4 r8 c16 c16 c8 r8 r4 r4 r4 r4 }",
    r"\relative c'' { g1. f1~ f1 }",
    r"\relative c'' { b16 g16 r8 r4 r4 r4 }",
    r"\relative c'' { b16 g16 }", #10
    r"\relative c' { f16 g16 b16 g16 b16 g16 }",
    r"\relative c' { f8 g8 b1 c4}",
    r"\relative c'' { b16 g8. g16 f16 g8 r8. g16~ g2. }",
    r"\relative c'' { c1 b1 g1 fis1 }",
    r"\relative c'' { g16 r8. r4 r4 r4 }",#15
    r"\relative c'' { g16 b16 c16 b16 }",
    r"\relative c'' { b16 c16 b16 c16 b16 r16 }",
    r"\relative c' { e16 fis16 e16 fis16 e8. e16 }",
    r"\relative c'' { r4. g'4. }",
    r"\relative c' { e16 fis16 e16 fis16 g,8. e'16 fis16 e16 fis16 e16 }",#20
    r"\relative c' { fis2.}",
    r"\relative c' { e4. e4. e4. e4. e4. fis4. g4. a4. b8 }",
    r"\relative c' { e8 fis4. fis4. fis4. fis4. fis4. g4. a4. b4 }",
    r"\relative c' { e8 fis8 g4. g4. g4. g4. g4. a4. b8 }",
    r"\relative c' { e8 fis8 g8 a4. a4. a4. a4. a4. b4. }",#25
    r"\relative c' { e8 fis8 g8 a8 b4. b4. b4. b4. b4. }",
    r"\relative c' { e16 fis16 e16 fis16 g8 e16 g16 fis16 e16 fis16 e16}",
    r"\relative c' { e16 fis16 e16 fis16 e8. e16 }",
    r"\relative c' { e2. g2. c2. }",
    r"\relative c' { c'1. }",#30
    r"\relative c'' { g16 f16 g16 b16 g16 b16 }",
    r"\relative c' { f16 g16 f16 g16 b16 f16~ f2. g4. }",
    r"\relative c'' { g16 f16 r8 }",
    r"\relative c'' { g16 f16 }",
    r"\relative c' { f16 g16 b16 g16 b16 g16 b16 g16 b16 g16 r8 r4 r4 r4 bes4 g'2. a8 g8~ g8 b8 a4. g8 e2. g8 fis8~ fis2. r4 r4 r8 e8~ e2 f1. }",#35
    r"\relative c' { f16 g16 b16 g16 b16 g16 }",
    r"\relative c' { f16 g16 }",
    r"\relative c' { f16 g16 b16 }",
    r"\relative c'' { b16 g16 f16 g16 b16 c16 }",
    r"\relative c'' { b16 f16 }",#40
    r"\relative c'' { b16 g16 }",
    r"\relative c'' { c1 b1 a1 c1 }",
    r"\relative c'' { f16 e16 f16 e16 e8 e8 e8 f16 e16 }",
    r"\relative c'' { f8 e8~ e8 e8 c4 }",
    r"\relative c'' { d4 d4 g,4 }",#45
    r"\relative c'' { g16 d'16 e16 d16 r8 g,8 r8 g8 r8 g8 g16 d'16 e16 d16 }",
    r"\relative c'' { d16 e16 d8 }",
    r"\relative c'' { g1. g1 f1~ f4 }",
    r"\relative c' { f16 g16 bes16 g16 bes16 g16 }",
    r"\relative c' { f16 g16 }",#50
    r"\relative c' { f16 g16 bes16 }",
    r"\relative c'' { g16 bes16 }",
    r"\relative c'' { bes16 g16 }",
]

# make a separate MIDI file for each pattern

def separate_files():
    for num, pattern in enumerate(patterns):
        p = parse(pattern)
        f = open("in_c_%s.mid" % (num + 1), "w")
        s = SMF(parse(pattern))
        s.write(f)
        f.close()

# make a single MIDI file with all the patterns in a row

def one_file():
    big_pattern = []
    offset = 0
    for num, pattern in enumerate(patterns):
        for ev in parse(pattern, offset):
            if ev[1] != -1: # -1 means a offset check with no sound
                big_pattern.append(ev)
            offset = ev[0] # remember the last offset so the next pattern can use it
        f = open("in_c_all.mid", "w")
        s = SMF(big_pattern)
        s.write(f)
        f.close()

one_file()
<|endoftext|>


<commit_before>#
# Copyright (c) 2012 Lifted Studios.  All Rights Reserved.
#

import constants
import datetime
import os
import shutil
import sublime
import sublime_plugin

class MissingOwnerException(Exception):
  """
  Exception signifying that the copyright owner information has not been entered into the settings.
  """
  pass

class InsertCopyrightCommand(sublime_plugin.TextCommand):
  """
  Inserts the copyright text.
  """
  def __init__(self, view):
    """
    Initializes the InsertCopyrightCommand class.
    """
    self.settings = sublime.load_settings(constants.SETTINGS_FILE)
    self.__get_block_comment_settings()
    self.view = view

  def run(self, edit):
    """
    Executes the copyright command by inserting the appropriate copyright text at the current selection point.
    """
    try:
      year = datetime.date.today().year

      owner = self.settings.get("owner")
      if not owner:
        raise MissingOwnerException()

      copyrightText = self.__build_block_comment("Copyright (c) {0!s} {1}.  All Rights Reserved.".format(year, owner))
      self.view.replace(edit, self.view.sel()[0], copyrightText)

    except MissingOwnerException:
      sublime.error_message("SublimeCopyright: Copyright owner not set")
      user_settings_path = os.path.join(sublime.packages_path(), 'User', constants.SETTINGS_FILE)

      if not os.path.exists(user_settings_path):
        default_settings_path = os.path.join(sublime.packages_path(), 'SublimeCopyright', constants.SETTINGS_FILE)
        shutil.copy(default_settings_path, user_settings_path)

      sublime.active_window().open_file(user_settings_path)

  def __build_block_comment(self, text):
    """
    Builds a block comment and puts the given text into it.
    """
    def make_comment(line): return self.middleLine + line + "\n"
    def concatenate(x, y): return x + y

    comment = self.firstLine + "\n"
    lines = map(make_comment, text.split("\n"))
    comment += reduce(concatenate, lines)
    comment += self.lastLine + "\n"
    return comment

  def __get_block_comment_settings(self):
    """
    Determines the appropriate block comment characters for the currently selected syntax.
    """
    comments = self.settings.get('comments')['Default']
    self.firstLine = comments[0]
    self.middleLine = comments[1]
    self.lastLine = comments[2]
<commit_msg>Comments.<commit_after>#
# Copyright (c) 2012 Lifted Studios.  All Rights Reserved.
#

import constants
import datetime
import os
import shutil
import sublime
import sublime_plugin

class MissingOwnerException(Exception):
  """
  Exception signifying that the copyright owner information has not been entered into the settings.
  """
  pass

class InsertCopyrightCommand(sublime_plugin.TextCommand):
  """
  Inserts the copyright text at the location of the current selection.
  """
  def __init__(self, view):
    """
    Initializes the InsertCopyrightCommand class.
    """
    self.settings = sublime.load_settings(constants.SETTINGS_FILE)
    self.__get_block_comment_settings()
    self.view = view

  def description(self, *args):
    """
    Describes the command.
    """
    return "Inserts the copyright text at the location of the current selection."

  def run(self, edit):
    """
    Executes the copyright command by inserting the appropriate copyright text at the current selection point.
    """
    try:
      year = datetime.date.today().year

      owner = self.settings.get("owner")
      if not owner:
        raise MissingOwnerException()

      copyrightText = self.__build_block_comment("Copyright (c) {0!s} {1}.  All Rights Reserved.".format(year, owner))
      self.view.replace(edit, self.view.sel()[0], copyrightText)

    except MissingOwnerException:
      sublime.error_message("SublimeCopyright: Copyright owner not set")
      user_settings_path = os.path.join(sublime.packages_path(), 'User', constants.SETTINGS_FILE)

      if not os.path.exists(user_settings_path):
        default_settings_path = os.path.join(sublime.packages_path(), 'SublimeCopyright', constants.SETTINGS_FILE)
        shutil.copy(default_settings_path, user_settings_path)

      sublime.active_window().open_file(user_settings_path)

  def __build_block_comment(self, text):
    """
    Builds a block comment and puts the given text into it.
    """
    def make_comment(line): return self.middleLine + line + "\n"
    def concatenate(x, y): return x + y

    comment = self.firstLine + "\n"
    lines = map(make_comment, text.split("\n"))
    comment += reduce(concatenate, lines)
    comment += self.lastLine + "\n"
    return comment

  def __get_block_comment_settings(self):
    """
    Determines the appropriate block comment characters for the currently selected syntax.
    """
    comments = self.settings.get('comments')['Default']
    self.firstLine = comments[0]
    self.middleLine = comments[1]
    self.lastLine = comments[2]
<|endoftext|>


<commit_before>from lib.config import Config
from slackclient import SlackClient
from flask import abort
from youtube import Youtube
from random import randint
from datetime import datetime

class Tubey():

    buttons = [{
                    "name": "send",
                    "text": "Send",
                    "type": "button",
                    "style": "primary",
                    "value": "Send that pineapple"
                },
                {
                    "name": "shuffle",
                    "text": "Shuffle",
                    "type": "button",
                    "value": "Shuffle it up!"
                },
                {
                    "name": "cancel",
                    "text": "Cancel",
                    "type": "button",
                    "style": "danger",
                    "value": "Cancel dis plz"
                 }]

    def __init__(self):
        # Cache the client in memory
        self._client = None

    def send_message(self, params, type="Message"):
        # Sends message to the user/channel
        # Type should either be Message or Ephemeral
        if 'as_user' in params.keys():
            client = self.get_client(type='client')
        else:
            client = self.get_client(type='bot')

        client.api_call("chat.post" + type, **params)

    def get_client(self, type='bot'):
        # Fetch a cached slack client or create one and return it
        # type is either 'bot' or 'client'
        if self._client is not None:
            return self._client

        token = Config.get_variable('tubey', type + '_oauth_token')
        sc = SlackClient(token)
        self._client = sc
        return self._client

    def suggest_video(self, query, channel, user, is_shuffle):
        # Sends a video suggestion in an ephemeral message
        videos = self.search(query)
        num_vids = len(videos)
        suggested_video = videos[randint(0, num_vids) % num_vids]

        published_date = datetime.strptime(suggested_video['snippet']['publishedAt'][0:10], "%Y-%m-%d").date().strftime(
            '%B %d, %Y')
        channel_name = suggested_video['snippet']['channelTitle']
        video_title = suggested_video['snippet']['title']
        description = suggested_video['snippet']['description']
        thumbnail = suggested_video['snippet']['thumbnails']['high']['url']
        id = suggested_video['id']['videoId']

        self.buttons[0]['value'] = id
        self.buttons[1]['value'] = query

        params = {
            'unfurl_links': False,
            'channel': channel,
            'user': user,
            "attachments": [{
                "title": "Video title: {}".format(video_title),
                "text": "Channel name: {}\nPublished date: {}\nVideo description: {}".format(channel_name, published_date, description),
                "title_link": "https://www.youtube.com/watch?v=".format(id),
                "image_url": thumbnail,
                "fallback": "You need to upgrade your Slack client to use this command!",
                "color": "#CD201F",
                "attachment_type": "default",
                "actions": self.buttons,
                "callback_id": "primary_menu"
            }]
        }

        if is_shuffle:
            params['replace_original'] = True
            return params
        else:
            response = self.send_message(params, type="Ephemeral")
            print(response)

    def send_video(self, video_id, channel):
        # Sends a chosen video to the channel
        params =  {
            "channel": channel,
            "text": "https://www.youtube.com/watch?v={}".format(video_id),
            "as_user": True
        }

        response = self.send_message(params)
        print(response)

        return {"delete_original": True}

    def send_channel(self, channel_id, channel_name, thumbnail_url):
        # Sends the youtube channel to the active user/slack channel
        channel_url = "https://www.youtube.com/channel/{}".format(channel_id)
        params = {'channel': 'tubeydev',
                  'text': "Here's the channel:",
                  'attachments': [
                      {'fallback': channel_name + ' thumbnail',
                       'title': channel_name,
                       "title_link": channel_url,
                       "image_url": thumbnail_url
                       }]
                  }
        self.send_message(params)

    def search(self, search_query):
        youtube = Youtube()
        results = youtube.query(search_query)

        return results['videos']

    def verify_token(self, token):
        verif_token = Config.get_variable('tubey', 'verif_token')

        # Validate the request parameters
        if token != verif_token:
            abort(401)  # Unauthorized request. If you're not Slack, go away

if __name__ == "__main__":
    # Should probably put a legitimate sample run here...I'll start it off
    pass
<commit_msg>multiple clients for multiple posters<commit_after>from lib.config import Config
from slackclient import SlackClient
from flask import abort
from youtube import Youtube
from random import randint
from datetime import datetime

class Tubey():

    buttons = [{
                    "name": "send",
                    "text": "Send",
                    "type": "button",
                    "style": "primary",
                    "value": "Send that pineapple"
                },
                {
                    "name": "shuffle",
                    "text": "Shuffle",
                    "type": "button",
                    "value": "Shuffle it up!"
                },
                {
                    "name": "cancel",
                    "text": "Cancel",
                    "type": "button",
                    "style": "danger",
                    "value": "Cancel dis plz"
                 }]

    def __init__(self):
        # Cache the client in memory
        self._bot_client = None
        self._user_client = None
        self.clients = {'bot': self._bot_client, 'user': self._user_client}

    def send_message(self, params, type="Message"):
        # Sends message to the user/channel
        # Type should either be Message or Ephemeral
        if 'as_user' in params.keys() and params['as_user']:
            client = self.get_client(type='user')
        else:
            client = self.get_client(type='bot')

        client.api_call("chat.post" + type, **params)

    def get_client(self, type='bot'):
        # Fetch a cached slack client or create one and return it
        # type is either 'bot' or 'user'
        if self.clients[type] is not None:
            return self.clients[type]

        print("NEW CLIENT ALERT FOR: ", type)

        token = Config.get_variable('tubey', type + '_oauth_token')
        sc = SlackClient(token)
        self.clients[type] = sc
        return sc

    def suggest_video(self, query, channel, user, is_shuffle):
        # Sends a video suggestion in an ephemeral message
        videos = self.search(query)
        num_vids = len(videos)
        suggested_video = videos[randint(0, num_vids) % num_vids]

        published_date = datetime.strptime(suggested_video['snippet']['publishedAt'][0:10], "%Y-%m-%d").date().strftime(
            '%B %d, %Y')
        channel_name = suggested_video['snippet']['channelTitle']
        video_title = suggested_video['snippet']['title']
        description = suggested_video['snippet']['description']
        thumbnail = suggested_video['snippet']['thumbnails']['high']['url']
        id = suggested_video['id']['videoId']

        self.buttons[0]['value'] = id
        self.buttons[1]['value'] = query

        params = {
            'unfurl_links': False,
            'channel': channel,
            'user': user,
            "attachments": [{
                "title": "Video title: {}".format(video_title),
                "text": "Channel name: {}\nPublished date: {}\nVideo description: {}".format(channel_name, published_date, description),
                "title_link": "https://www.youtube.com/watch?v=".format(id),
                "image_url": thumbnail,
                "fallback": "You need to upgrade your Slack client to use this command!",
                "color": "#CD201F",
                "attachment_type": "default",
                "actions": self.buttons,
                "callback_id": "primary_menu"
            }]
        }

        if is_shuffle:
            params['replace_original'] = True
            return params
        else:
            response = self.send_message(params, type="Ephemeral")
            print(response)

    def send_video(self, video_id, channel):
        # Sends a chosen video to the channel
        params =  {
            "channel": channel,
            "text": "https://www.youtube.com/watch?v={}".format(video_id),
            "as_user": True
        }

        response = self.send_message(params)

        return {"delete_original": True}

    def send_channel(self, channel_id, channel_name, thumbnail_url):
        # Sends the youtube channel to the active user/slack channel
        channel_url = "https://www.youtube.com/channel/{}".format(channel_id)
        params = {'channel': 'tubeydev',
                  'text': "Here's the channel:",
                  'attachments': [
                      {'fallback': channel_name + ' thumbnail',
                       'title': channel_name,
                       "title_link": channel_url,
                       "image_url": thumbnail_url
                       }]
                  }
        self.send_message(params)

    def search(self, search_query):
        youtube = Youtube()
        results = youtube.query(search_query)

        return results['videos']

    def verify_token(self, token):
        verif_token = Config.get_variable('tubey', 'verif_token')

        # Validate the request parameters
        if token != verif_token:
            abort(401)  # Unauthorized request. If you're not Slack, go away

if __name__ == "__main__":
    # Should probably put a legitimate sample run here...I'll start it off
    pass
<|endoftext|>


<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Utilities for computing different aspects and complexities of voltage dividers
"""
from UliEngineering.EngineerIO import normalize_numeric, format_value
from .Resistors import *
import numpy as np
from collections import namedtuple
from UliEngineering.Units import Unit

__all__ = ["voltage_divider_ratio", "top_resistor_by_ratio",
           "voltage_divider_voltage", "voltage_divider_current",
           "bottom_resistor_by_ratio", "feedback_top_resistor",
           "feedback_bottom_resistor", "feedback_actual_voltage",
           "voltage_divider_power"]

def voltage_divider_ratio(rtop, rbot, rload=np.inf) -> Unit(""):
    """
    Compute the division ratio of a voltage divider.

    If rload is supplied, additional load (in parallel to R2) is taken into account.
    """
    rtop = normalize_numeric(rtop)
    rbot = normalize_numeric(rbot)
    return rbot / (rtop + parallel_resistors(rbot, rload))

def voltage_divider_voltage(rtop, rbot, vin, rload=np.inf) -> Unit("V"):
    """
    Compute the voltage output of a voltage divider

    If rload is supplied, additional load (in parallel to R2) is taken into account.
    """
    vin = normalize_numeric(vin)
    return voltage_divider_ratio(rtop, rbot, rload=rload) * vin

def voltage_divider_current(rtop, rbot, vin, rload=np.inf) -> Unit("V"):
    """
    Compute the current through the top resistor of a voltage divider.

    If rload is supplied, additional load (in parallel to R2) is taken into account.
    """
    vin = normalize_numeric(vin)
    rtop = normalize_numeric(rtop)
    vout = voltage_divider_voltage(rtop, rbot, vin, rload=rload)
    # Compute voltage delta across resistor
    vdelta = vout - vin
    # Compute current through resisotr
    return current_through_resistor(rtop, vdelta);

class VoltageDividerPower(namedtuple("VoltageDividerPower", [
        "top", "bottom", "load", "total"
    ])):
    """
    Represents the power dissipated in different parts of a voltage
    """
    def __repr__(self):
        """Better formatting"""
        return "VoltageDividerPower(top={}, bottom={}, {}total={})".format(
            format_value(self.top, "W"),
            format_value(self.bottom, "W"),
            format_value(self.load, "W") if self.load != 0 else "",
            format_value(self.total, "W")
        )

def voltage_divider_power(rtop, rbot, vin, rload=np.inf):
    """
    Compute the power dissipated in a voltage divider.

    Returns a VoltageDividerPower object.

    Usage example:
    >>> voltage_divider_power("250k", "1k", "230V")
    VoltageDividerPower(top=210 mW, bottom=840 µW, total=211 mW
    >>> voltage_divider_power("250k", "1k", "230V").total
    0.2107569721115538

    If rload is supplied, additional load (in parallel to R2) is taken into account.
    """
    vin = normalize_numeric(vin)
    rtop = normalize_numeric(rtop)
    vout = voltage_divider_voltage(rtop, rbot, vin, rload=rload)
    # Compute voltage delta across resistor
    ptop = power_dissipated_in_resistor_by_voltage(rtop, vout - vin)
    pbot = power_dissipated_in_resistor_by_voltage(rbot, vout)
    pload = power_dissipated_in_resistor_by_voltage(rload, vout)
    return VoltageDividerPower(
        ptop, pbot, pload, ptop + pbot + pload
    )

def top_resistor_by_ratio(rbottom, ratio) -> Unit("Ω"):
    """
    Compute the bottom resistor of a voltage divider given the top resistor value
    and the division ration
    """
    rbottom = normalize_numeric(rbottom)
    ratio = normalize_numeric(ratio)
    return rbottom * (1.0 / ratio - 1.0)

def bottom_resistor_by_ratio(rtop, ratio) -> Unit("Ω"):
    """
    Compute the bottom resistor of a voltage divider given the top resistor value
    and the division ration
    """
    rtop = normalize_numeric(rtop)
    ratio = normalize_numeric(ratio)
    return -(rtop * ratio) / (ratio - 1.0)

def feedback_top_resistor(vexp, rbot, vfb) -> Unit("Ω"):
    """
    Utility to compute the top feedback resistor
    in a voltage feedback network (e.g. for a DC/DC converter)

    Parameters
    ----------
    vexp : float
        The voltage at between top and bottom of the voltage divider
    rbot : float
        The known bottom resistor
    vfb : float
        The feedback voltage that is servoed by the regulator
    """
    vexp = normalize_numeric(vexp)
    rbot = normalize_numeric(rbot)
    vfb = normalize_numeric(vfb)
    # Vo = Vfb * (R1/R2 + 1)
    # solve A = B*((C/D) + 1) for C
    return rbot * (vexp - vfb) / vfb

def feedback_bottom_resistor(vexp, rtop, vfb) -> Unit("Ω"):
    """
    Utility to compute the bottom feedback resistor
    in a voltage feedback network (e.g. for a DC/DC converter)

    Parameters
    ----------
    vexp : float
        The voltage at between top and bottom of the voltage divider
    rtop : float
        The known top resistor
    vfb : float
        The feedback voltage that is servoed by the regulator
    """
    vexp = normalize_numeric(vexp)
    rtop = normalize_numeric(rtop)
    vfb = normalize_numeric(vfb)
    # Vo = Vfb * (R1/R2 + 1)
    # solve A = B*((C/D) + 1) for D
    return (vfb * rtop) / (vexp - vfb)

def feedback_actual_voltage(rtop, rbot, vfb) -> Unit("V"):
    """
    Compute the actual voltage regulator output in a feedback
    servo setup. Returns the Vout voltage.

    Parameters
    ----------
    rtop : float
        The top resistor of the voltage divider
    rbot : float
        The bottom resistor of the voltage divider
    vfb : float
        The feedback voltage
    """
    # Equation: Vout * ratio = vfb
    ratio = voltage_divider_ratio(rtop, rbot)
    return normalize_numeric(vfb) / ratio
<commit_msg>Added rload parameter to VoltageDivider<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Utilities for computing different aspects and complexities of voltage dividers
"""
from UliEngineering.EngineerIO import normalize_numeric, format_value
from .Resistors import *
import numpy as np
from collections import namedtuple
from UliEngineering.Units import Unit

__all__ = ["voltage_divider_ratio", "top_resistor_by_ratio",
           "voltage_divider_voltage", "voltage_divider_current",
           "bottom_resistor_by_ratio", "feedback_top_resistor",
           "feedback_bottom_resistor", "feedback_actual_voltage",
           "voltage_divider_power"]

def voltage_divider_ratio(rtop, rbot, rload=np.inf) -> Unit(""):
    """
    Compute the division ratio of a voltage divider.

    If rload is supplied, additional load (in parallel to R2) is taken into account.
    """
    rtop = normalize_numeric(rtop)
    rbot = normalize_numeric(rbot)
    return rbot / (rtop + parallel_resistors(rbot, rload))

def voltage_divider_voltage(rtop, rbot, vin, rload=np.inf) -> Unit("V"):
    """
    Compute the voltage output of a voltage divider

    If rload is supplied, additional load (in parallel to R2) is taken into account.
    """
    vin = normalize_numeric(vin)
    return voltage_divider_ratio(rtop, rbot, rload=rload) * vin

def voltage_divider_current(rtop, rbot, vin, rload=np.inf) -> Unit("V"):
    """
    Compute the current through the top resistor of a voltage divider.

    If rload is supplied, additional load (in parallel to R2) is taken into account.
    """
    vin = normalize_numeric(vin)
    rtop = normalize_numeric(rtop)
    vout = voltage_divider_voltage(rtop, rbot, vin, rload=rload)
    # Compute voltage delta across resistor
    vdelta = vout - vin
    # Compute current through resisotr
    return current_through_resistor(rtop, vdelta);

class VoltageDividerPower(namedtuple("VoltageDividerPower", [
        "top", "bottom", "load", "total"
    ])):
    """
    Represents the power dissipated in different parts of a voltage
    """
    def __repr__(self):
        """Better formatting"""
        return "VoltageDividerPower(top={}, bottom={}, {}total={})".format(
            format_value(self.top, "W"),
            format_value(self.bottom, "W"),
            format_value(self.load, "W") if self.load != 0 else "",
            format_value(self.total, "W")
        )

def voltage_divider_power(rtop, rbot, vin, rload=np.inf):
    """
    Compute the power dissipated in a voltage divider.

    Returns a VoltageDividerPower object.

    Usage example:
    >>> voltage_divider_power("250k", "1k", "230V")
    VoltageDividerPower(top=210 mW, bottom=840 µW, total=211 mW
    >>> voltage_divider_power("250k", "1k", "230V").total
    0.2107569721115538

    If rload is supplied, additional load (in parallel to R2) is taken into account.
    """
    vin = normalize_numeric(vin)
    rtop = normalize_numeric(rtop)
    vout = voltage_divider_voltage(rtop, rbot, vin, rload=rload)
    # Compute voltage delta across resistor
    ptop = power_dissipated_in_resistor_by_voltage(rtop, vout - vin)
    pbot = power_dissipated_in_resistor_by_voltage(rbot, vout)
    pload = power_dissipated_in_resistor_by_voltage(rload, vout)
    return VoltageDividerPower(
        ptop, pbot, pload, ptop + pbot + pload
    )

def top_resistor_by_ratio(rbottom, ratio) -> Unit("Ω"):
    """
    Compute the bottom resistor of a voltage divider given the top resistor value
    and the division ration
    """
    rbottom = normalize_numeric(rbottom)
    ratio = normalize_numeric(ratio)
    return rbottom * (1.0 / ratio - 1.0)

def bottom_resistor_by_ratio(rtop, ratio) -> Unit("Ω"):
    """
    Compute the bottom resistor of a voltage divider given the top resistor value
    and the division ration
    """
    rtop = normalize_numeric(rtop)
    ratio = normalize_numeric(ratio)
    return -(rtop * ratio) / (ratio - 1.0)

def feedback_top_resistor(vexp, rbot, vfb, rload=np.inf) -> Unit("Ω"):
    """
    Utility to compute the top feedback resistor
    in a voltage feedback network (e.g. for a DC/DC converter)

    Parameters
    ----------
    vexp : float
        The voltage at between top and bottom of the voltage divider
    rbot : float
        The known bottom resistor
    vfb : float
        The feedback voltage that is servoed by the regulator
    rload : float
        A load resistor in parallel to the bottom resistor
    """
    vexp = normalize_numeric(vexp)
    rbot = normalize_numeric(rbot)
    vfb = normalize_numeric(vfb)
    rload = normalize_numeric(rload)
    # Vo = Vfb * (R1/R2 + 1)
    # solve A = B*((C/D) + 1) for C
    return (parallel_resistors(rbot, rload)) * (vexp - vfb) / vfb

def feedback_bottom_resistor(vexp, rtop, vfb) -> Unit("Ω"):
    """
    Utility to compute the bottom feedback resistor
    in a voltage feedback network (e.g. for a DC/DC converter)

    Parameters
    ----------
    vexp : float
        The voltage at between top and bottom of the voltage divider
    rtop : float
        The known top resistor
    vfb : float
        The feedback voltage that is servoed by the regulator
    """
    vexp = normalize_numeric(vexp)
    rtop = normalize_numeric(rtop)
    vfb = normalize_numeric(vfb)
    # Vo = Vfb * (R1/R2 + 1)
    # solve A = B*((C/D) + 1) for D
    return (vfb * rtop) / (vexp - vfb)

def feedback_actual_voltage(rtop, rbot, vfb, rload=np.inf) -> Unit("V"):
    """
    Compute the actual voltage regulator output in a feedback
    servo setup. Returns the Vout voltage.

    Parameters
    ----------
    rtop : float
        The top resistor of the voltage divider
    rbot : float
        The bottom resistor of the voltage divider
    vfb : float
        The feedback voltage
    """
    rload = normalize_numeric(rload)
    # Equation: Vout * ratio = vfb
    ratio = voltage_divider_ratio(rtop, parallel_resistors(rbot, rload))
    return normalize_numeric(vfb) / ratio
<|endoftext|>


<commit_before>#!/usr/bin/env python
# encoding: utf-8
"""
GPX.py

Created by Joel Carranza on 2011-02-06.
"""

import xml.etree.cElementTree as ElementTree
from xml.etree.cElementTree import Element,SubElement
import sys
import os
import pytz
# this is going to fail on 2.5???
import isodate
import math
import bisect
from xmlutil import XAttr as xa
import xmlutil

# TODO: these should be class attributes
_route_scheme = _track_scheme = dict(name="s",
  cmt="s",
  desc="s",
  src="s",
  link="s")

NS_1_0 = 'http://www.topografix.com/GPX/1/0'
NS = NS_1_1 = 'http://www.topografix.com/GPX/1/1'
VERSION = "0.1"

def parse(source):
  "Construct a new GPX instance based on a file"
  gpx = GPX()
  gpx.load(source)
  return gpx

def wptdistance(pts):
  # does there exist some pairwise function?
  d = 0
  for ix in xrange(1,len(pts)):
    d += pts[ix].dist(pts[ix-1])
  return d

def wptbounds(pts):
  "return a bounding box which contains all waypoints on this path"
  # TODO: this requires a list and it would be better if we just did it in one loop
  if not pts:
    return None
  lat = [p.lat for p in pts]
  lon = [p.lon for p in pts]
  return (min(lat),min(lon),max(lat),max(lon))

def wpttimespan(pts):
  "return upper and lower bounds on the time"
  t = [p.time for p in pts if p.time is not None]
  return (min(t),max(t)) if t else None

# TODO: math!
# http://www.movable-type.co.uk/scripts/latlong.html
# dist2d
# dist3d
# See also: http://megocode3.wordpress.com/2008/02/05/haversine-formula-in-c/
# "When a difference in altitude is smallish relative to the great circle distance, a quick approximation is to add the two. This is essentially the approximation of a right triangle’s hypotenuse by adding the lengths of the two legs, reliable when one leg is much longer than the other. If the two distances were similar in magnitude, the Pythagorean formula would be more accurate, i.e. the square root of the square of altitude difference plus the square of the great circle distance."
# http://www.gps-forums.net/distance-between-two-points-t34357.html
# interpolate! Possibly not that, instead its give me n points ever mile along line
# distance from line (Cross-track distance?)
# containment within polygon
# UTM - to - LatLon (HARD!!!!)

# TODO: copy() method for all classes

class GPX:
  """
  Model of a GPX file. Gpx file contains one or more of
  the following types
  tracks
  waypoints
  routes
  metadata see http://www.topografix.com/GPX/1/1/#type_metadataType
  """

  def __init__(self):
    self.tracks = []
    self.waypoints = []
    self.routes = []

  def load(self,src):
    parser = GPXParser(self)
    parser.parse(src)

  def newTrack(self,**kwargs):
    t = Track(**kwargs)
    self.tracks.append(t)
    return t

  def newWaypoint(self,lat,lon,**kwargs):
    w = Waypoint(lat,lon,**kwargs)
    self.waypoints.append(w)
    return w

  def newRoute(self,**kwargs):
    r = Route(**kwargs)
    self.routes.append(w)
    return r

  def allpoints(self):
    for w in self.waypoints:
      yield w
    for r in self.routes:
      for w in r:
        yield w
    for t in self.tracks:
      for w in t.points():
        yield w

  def ptAtTime(self,dt):
    for t in self.tracks:
      for s in t:
        (mints,maxts) = s.timespan()
        if mints < dt and dt < maxts:
          return s.ptAtTime(dt)

  def filter(self,pred):
    self.waypoints[:] = filter(pred,self.waypoints)
    for trk in self.tracks:
      trk.filter(pred)
    for r in self.routes:
      t.filter(pred)
    self.tracks[:] = filter(lambda t:len(t.segments()) > 0,self.tracks)
    self.routes[:] = filter(lambda t:len(r) > 0,self.routes)

  def bounds(self):
    "return a bounding box which contains all waypoints on this path"
    return wptbounds(list(self.allpoints()))

  def timespan(self):
    "return a bounding box which contains all waypoints on this path"
    return wpttimespan(list(self.allpoints()))

  def write(self,file):
    # note that we would like for this pretty-print possibly
    GPXWriter().write(self,file)

  def __str__(self):
    return "GPX{waypoints=%d,tracks=%d,routes=%d}" % (len(self.waypoints),len(self.tracks),len(self.routes))

class Path:
  """
  Ordered list of points. Used directly as a track segment
  and by extension for Route
  """

  _wpt = None

  def __init__(self, points=None):
    self._wpt = points if points is not None else []

  def points(self):
    "Return a list of waypoints in the path"
    return self._wpt

  def newWaypoint(self,**kwargs):
    w = Waypoint(**kwargs)
    self._wpt.append(w)
    return w

  def append(self,wpt):
    "Add a new waypoint to the end of the path"
    self._wpt.append(wpt)

  def extend(self,pts):
    "Add new waypoints to the end of the path"
    self._wpt.extend(pts)

  def filter(self,pred):
    "Remove point from this path based on predicate"
    self._wpt = filter(pred,self._wpt)

  # TODO: pt?
  def ptAtTime(self,date):
    dts = [p.time for p in self]
    ix = bisect.bisect_left(dts,date)
    return self[ix]

  # TODO: this is deceptively named
  def simplify(self,pred):
    """Remove points form path based on predicate. Predicate
    is passed two points, the current point and the last point
    that passed the test. Only points that pass the test are returned"""
    np = self._wpt[0:1]
    for p in self._wpt[1:]:
      if pred(p,np[-1]):
        np.append(p)
    self._wpt = np

  def __iter__(self):
    return self._wpt.__iter__()

  def __len__(self):
    return len(self._wpt)

  def __getitem__(self,k):
    return self._wpt[k]

  def bounds(self):
    "return a bounding box which contains all waypoints on this path"
    return wptbounds(self._wpt)

  def timespan(self):
    "return min max bounds of path"
    return wpttimespan(self._wpt)

  def length(self):
    return wptdistance(self._wpt)

  def __str__(self):
    return "Path{points=%d}" % len(self._wpt)

class Route(Path):
  """
  n ordered list of waypoints representing a series of turn points leading to a destination.
  """

  _scheme = [xa('name',type="s"),
    xa('cmt',type="s"),
    xa('desc',type="s"),
    xa('src',type="s"),
    xa('link',type="s")]

  def __init__(self,**kwargs):
    Path.__init__(self,**kwargs)
    xmlutil.init(self,kwargs,self._scheme)

class Track:
  """
  Represents an ordered list of track segments (paths) which
  taken together represent a (potentially complex) path
  """

  _scheme = [xa('name',type="s"),
    xa('cmt',type="s"),
    xa('desc',type="s"),
    xa('src',type="s"),
    xa('link',type="s")]

  _s = None

  def __init__(self,segments = None, points=None,**kwargs):
    self._s = segments if segments is not None else []
    if points is not None:
      self.extendpt(points)
    xmlutil.init(self,kwargs,self._scheme)

  def points(self):
    "Returns an interator over all waypoints in track"
    # TODO: can you itertools.chain here!
    for s in self._s:
      for p in s:
        yield p

  def newSegment(self,**kwargs):
    p = Path(**kwargs)
    self._s.append(p)
    return p

  def join(self):
    "Join all segments together into a single segment"
    for s in self._s[1:]:
      self._s[0].extend(s.points)
    self._s[1:] = []

  def filter(self,pred):
    for s in self._s:
      s.filter(pred)
    # drop empty segments
    self._s[:] = filter(lambda s:len(s),self._s)

  def ptAtTime(self,date):
    return min(self.points(),key=lambda p:abs(p.time-date))

  def segments(self):
    return self._s

  def append(self,trk):
    "Add a new waypoint to the end of the path"
    self._s.append(trk)

  def extend(self,trk):
    "Add new waypoints to the end of the path"
    self._s.extend(trk)

  def appendpt(self,wpt):
    if not self._s:
      self.newSegment();
    self._s[-1].append(wpt)

  def extendpt(self,wpt):
    if not self._s:
      self.newSegment();
    self._s[-1].extend(wpt)

  def __iter__(self):
    return self._s.__iter__()

  def __len__(self):
    return len(self._s)

  def __getitem__(self,k):
    return self._s[k]

  def __str__(self):
    return "Track{segments=%d}" % len(self._s)

class Waypoint:
  """
  Represents a waypoint, point of interest, or named feature on a map.
  See: http://www.topografix.com/GPX/1/1/#type_wptType
  """

  _scheme = [
    xa('lat',type="n",attr=True),
    xa('lon',type="n",attr=True),
    xa('ele',type="n"),
    xa('time',type="d"),
    xa('magvar',type="n"),
    xa('geoidheight',type="n"),
    xa('name',type="s"),
    xa('cmt',type="s"),
    xa('desc',type="s"),
    xa('src',type="s"),
    xa('link',type="s"),
    xa('sym',type="s"),
    xa('type',type="s"),
    xa('fix',type="s"),
    xa('sat',type="i"),
    xa('hdop',type="n"),
    xa('vdop',type="n"),
    xa('pdop',type="n")]

  def __init__(self,lat,lon,**kwargs):
    self.lat = lat
    self.lon = lon
    xmlutil.init(self,kwargs,self._scheme[2:])

  def __str__(self):
    return "Waypoint{%f,%f}" % (self.lat,self.lon)

  def tuple2d(self):
    return (self.lon,self.lat)

  def tuple3d(self):
    return (self.lon,self.lat,self.ele)

  def dist(self,p,includeEle=False):
    "Distance between two waypoints using haversine"
    # TODO: take into account of elevation!
    R = 6372800 # Radius of earth in meters
    lat1 = math.radians(self.lat)
    lon1 = math.radians(self.lon)
    lat2 = math.radians(p.lat)
    lon2 = math.radians(p.lon)
    dLat = lat2-lat1
    dLon = lon2-lon1
    a = math.sin(dLat/2) * math.sin(dLat/2) + math.cos(lat1) * math.cos(lat2) * math.sin(dLon/2) * math.sin(dLon/2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    d = R * c
    # approximate distance in 3d by adding elevation distance
    if includeEle and self.ele is not None and p.ele is not None:
      d += abs(self.ele-p.ele)
    return d

class GPXWriter:
  """
  Writes a GPX file to
  """
  creator = "GPX.py "+VERSION

  # Taken from: http://infix.se/2007/02/06/gentlemen-indent-your-xml

  def gpx(self,gpx):
    root = Element("gpx",xmlns=NS,version="1.1",creator=self.creator)
    for wpt in gpx.waypoints:
      root.append(self.wpt(wpt,"wpt"))
    for route in gpx.routes:
      el = self.path(route,"rte","rtept")
      xmlutil.write(el,route,Route._scheme)
      root.append(el)
    for track in gpx.tracks:
      el = SubElement(root,"trk")
      xmlutil.write(el,track,Track._scheme)
      for seg in track:
        el.append(self.path(seg,"trkseg","trkpt"))
    return root

  def wpt(self,wpt,name):
   "Creates an XML element with specified name which represents this Waypoint"
   e = Element(name)
   xmlutil.write(e,wpt,Waypoint._scheme)
   return e

  def path(self,p,name,ptname):
    e = Element(name)
    for p in p._wpt:
      e.append(self.wpt(p,ptname))
    return e

  def write(self,gpx,file):
    root = self.gpx(gpx)
    xmlutil.indent(root)
    ElementTree.ElementTree(root).write(file)

class GPXParser:
  """
  DOM Parsing tool which constructs a
  """
  def __init__(self,gpx):
    self.gpx = gpx

  def parse(self,src):
    root = ElementTree.parse(src).getroot()
    # namespace should be either gpx1/0 or gpx1/1
    self.NS = root.tag[1:-4]
    for wptEl in root.findall("{%s}wpt" % self.NS):
      self.gpx.waypoints.append(self.parseWaypoint(wptEl))
    for rteEl in root.findall("{%s}rte" % self.NS):
      self.gpx.routes.append(self.parseRoute(rteEl))
    for trkEl in root.findall("{%s}trk" % self.NS):
      self.gpx.tracks.append(self.parseTrack(trkEl))

  def parseTrack(self,el):
    trk = Track(**xmlutil.parse(self.NS,el,Track._scheme))
    for seg in el.findall("{%s}trkseg" % self.NS):
      p = Path()
      for wpel in seg.findall("{%s}trkpt" % self.NS):
        p.append(self.parseWaypoint(wpel))
      trk.append(p)
    return trk

  def parseRoute(self,el):
    r = Route(**xmlutil.parse(self.NS,el,Route._scheme))
    for wpel in el.findall("{%s}rtept" % self.NS):
      r.append(self.parseWaypoint(wpel))
    return r

  def parseWaypoint(self,e):
    return Waypoint(**xmlutil.parse(self.NS,e,Waypoint._scheme))

# TODO: this does not need a main!
if __name__ == '__main__':
  import sys
  for fn in sys.argv[1:]:
    gpx = GPX()
    gpx.load(fn)
    print fn
    print "------------"
    print "%d waypoints" % len(gpx.waypoints)
    print "%d tracks" % len(gpx.tracks)
    for t in gpx.tracks:
      print t.name
      for s in t:
        print "Pt count: %d" % len(s)
        print s.timespan()
        print s.bounds()
        print s.length()

<commit_msg>move main out of gpxpy<commit_after>#!/usr/bin/env python
# encoding: utf-8
"""
GPX.py

Created by Joel Carranza on 2011-02-06.
"""

import xml.etree.cElementTree as ElementTree
from xml.etree.cElementTree import Element,SubElement
import sys
import os
import pytz
# this is going to fail on 2.5???
import isodate
import math
import bisect
from xmlutil import XAttr as xa
import xmlutil

# TODO: these should be class attributes
_route_scheme = _track_scheme = dict(name="s",
  cmt="s",
  desc="s",
  src="s",
  link="s")

NS_1_0 = 'http://www.topografix.com/GPX/1/0'
NS = NS_1_1 = 'http://www.topografix.com/GPX/1/1'
VERSION = "0.1"

def parse(source):
  "Construct a new GPX instance based on a file"
  gpx = GPX()
  gpx.load(source)
  return gpx

def wptdistance(pts):
  # does there exist some pairwise function?
  d = 0
  for ix in xrange(1,len(pts)):
    d += pts[ix].dist(pts[ix-1])
  return d

def wptbounds(pts):
  "return a bounding box which contains all waypoints on this path"
  # TODO: this requires a list and it would be better if we just did it in one loop
  if not pts:
    return None
  lat = [p.lat for p in pts]
  lon = [p.lon for p in pts]
  return (min(lat),min(lon),max(lat),max(lon))

def wpttimespan(pts):
  "return upper and lower bounds on the time"
  t = [p.time for p in pts if p.time is not None]
  return (min(t),max(t)) if t else None

# TODO: math!
# http://www.movable-type.co.uk/scripts/latlong.html
# dist2d
# dist3d
# See also: http://megocode3.wordpress.com/2008/02/05/haversine-formula-in-c/
# "When a difference in altitude is smallish relative to the great circle distance, a quick approximation is to add the two. This is essentially the approximation of a right triangle’s hypotenuse by adding the lengths of the two legs, reliable when one leg is much longer than the other. If the two distances were similar in magnitude, the Pythagorean formula would be more accurate, i.e. the square root of the square of altitude difference plus the square of the great circle distance."
# http://www.gps-forums.net/distance-between-two-points-t34357.html
# interpolate! Possibly not that, instead its give me n points ever mile along line
# distance from line (Cross-track distance?)
# containment within polygon
# UTM - to - LatLon (HARD!!!!)

# TODO: copy() method for all classes

class GPX:
  """
  Model of a GPX file. Gpx file contains one or more of
  the following types
  tracks
  waypoints
  routes
  metadata see http://www.topografix.com/GPX/1/1/#type_metadataType
  """

  def __init__(self):
    self.tracks = []
    self.waypoints = []
    self.routes = []

  def load(self,src):
    parser = GPXParser(self)
    parser.parse(src)

  def newTrack(self,**kwargs):
    t = Track(**kwargs)
    self.tracks.append(t)
    return t

  def newWaypoint(self,lat,lon,**kwargs):
    w = Waypoint(lat,lon,**kwargs)
    self.waypoints.append(w)
    return w

  def newRoute(self,**kwargs):
    r = Route(**kwargs)
    self.routes.append(w)
    return r

  def allpoints(self):
    for w in self.waypoints:
      yield w
    for r in self.routes:
      for w in r:
        yield w
    for t in self.tracks:
      for w in t.points():
        yield w

  def ptAtTime(self,dt):
    for t in self.tracks:
      for s in t:
        (mints,maxts) = s.timespan()
        if mints < dt and dt < maxts:
          return s.ptAtTime(dt)

  def filter(self,pred):
    self.waypoints[:] = filter(pred,self.waypoints)
    for trk in self.tracks:
      trk.filter(pred)
    for r in self.routes:
      t.filter(pred)
    self.tracks[:] = filter(lambda t:len(t.segments()) > 0,self.tracks)
    self.routes[:] = filter(lambda t:len(r) > 0,self.routes)

  def bounds(self):
    "return a bounding box which contains all waypoints on this path"
    return wptbounds(list(self.allpoints()))

  def timespan(self):
    "return a bounding box which contains all waypoints on this path"
    return wpttimespan(list(self.allpoints()))

  def write(self,file):
    # note that we would like for this pretty-print possibly
    GPXWriter().write(self,file)

  def __str__(self):
    return "GPX{waypoints=%d,tracks=%d,routes=%d}" % (len(self.waypoints),len(self.tracks),len(self.routes))

class Path:
  """
  Ordered list of points. Used directly as a track segment
  and by extension for Route
  """

  _wpt = None

  def __init__(self, points=None):
    self._wpt = points if points is not None else []

  def points(self):
    "Return a list of waypoints in the path"
    return self._wpt

  def newWaypoint(self,**kwargs):
    w = Waypoint(**kwargs)
    self._wpt.append(w)
    return w

  def append(self,wpt):
    "Add a new waypoint to the end of the path"
    self._wpt.append(wpt)

  def extend(self,pts):
    "Add new waypoints to the end of the path"
    self._wpt.extend(pts)

  def filter(self,pred):
    "Remove point from this path based on predicate"
    self._wpt = filter(pred,self._wpt)

  # TODO: pt?
  def ptAtTime(self,date):
    dts = [p.time for p in self]
    ix = bisect.bisect_left(dts,date)
    return self[ix]

  # TODO: this is deceptively named
  def simplify(self,pred):
    """Remove points form path based on predicate. Predicate
    is passed two points, the current point and the last point
    that passed the test. Only points that pass the test are returned"""
    np = self._wpt[0:1]
    for p in self._wpt[1:]:
      if pred(p,np[-1]):
        np.append(p)
    self._wpt = np

  def __iter__(self):
    return self._wpt.__iter__()

  def __len__(self):
    return len(self._wpt)

  def __getitem__(self,k):
    return self._wpt[k]

  def bounds(self):
    "return a bounding box which contains all waypoints on this path"
    return wptbounds(self._wpt)

  def timespan(self):
    "return min max bounds of path"
    return wpttimespan(self._wpt)

  def length(self):
    return wptdistance(self._wpt)

  def __str__(self):
    return "Path{points=%d}" % len(self._wpt)

class Route(Path):
  """
  n ordered list of waypoints representing a series of turn points leading to a destination.
  """

  _scheme = [xa('name',type="s"),
    xa('cmt',type="s"),
    xa('desc',type="s"),
    xa('src',type="s"),
    xa('link',type="s")]

  def __init__(self,**kwargs):
    Path.__init__(self,**kwargs)
    xmlutil.init(self,kwargs,self._scheme)

class Track:
  """
  Represents an ordered list of track segments (paths) which
  taken together represent a (potentially complex) path
  """

  _scheme = [xa('name',type="s"),
    xa('cmt',type="s"),
    xa('desc',type="s"),
    xa('src',type="s"),
    xa('link',type="s")]

  _s = None

  def __init__(self,segments = None, points=None,**kwargs):
    self._s = segments if segments is not None else []
    if points is not None:
      self.extendpt(points)
    xmlutil.init(self,kwargs,self._scheme)

  def points(self):
    "Returns an interator over all waypoints in track"
    # TODO: can you itertools.chain here!
    for s in self._s:
      for p in s:
        yield p

  def newSegment(self,**kwargs):
    p = Path(**kwargs)
    self._s.append(p)
    return p

  def join(self):
    "Join all segments together into a single segment"
    for s in self._s[1:]:
      self._s[0].extend(s.points)
    self._s[1:] = []

  def filter(self,pred):
    for s in self._s:
      s.filter(pred)
    # drop empty segments
    self._s[:] = filter(lambda s:len(s),self._s)

  def ptAtTime(self,date):
    return min(self.points(),key=lambda p:abs(p.time-date))

  def segments(self):
    return self._s

  def append(self,trk):
    "Add a new waypoint to the end of the path"
    self._s.append(trk)

  def extend(self,trk):
    "Add new waypoints to the end of the path"
    self._s.extend(trk)

  def appendpt(self,wpt):
    if not self._s:
      self.newSegment();
    self._s[-1].append(wpt)

  def extendpt(self,wpt):
    if not self._s:
      self.newSegment();
    self._s[-1].extend(wpt)

  def __iter__(self):
    return self._s.__iter__()

  def __len__(self):
    return len(self._s)

  def __getitem__(self,k):
    return self._s[k]

  def __str__(self):
    return "Track{segments=%d}" % len(self._s)

class Waypoint:
  """
  Represents a waypoint, point of interest, or named feature on a map.
  See: http://www.topografix.com/GPX/1/1/#type_wptType
  """

  _scheme = [
    xa('lat',type="n",attr=True),
    xa('lon',type="n",attr=True),
    xa('ele',type="n"),
    xa('time',type="d"),
    xa('magvar',type="n"),
    xa('geoidheight',type="n"),
    xa('name',type="s"),
    xa('cmt',type="s"),
    xa('desc',type="s"),
    xa('src',type="s"),
    xa('link',type="s"),
    xa('sym',type="s"),
    xa('type',type="s"),
    xa('fix',type="s"),
    xa('sat',type="i"),
    xa('hdop',type="n"),
    xa('vdop',type="n"),
    xa('pdop',type="n")]

  def __init__(self,lat,lon,**kwargs):
    self.lat = lat
    self.lon = lon
    xmlutil.init(self,kwargs,self._scheme[2:])

  def __str__(self):
    return "Waypoint{%f,%f}" % (self.lat,self.lon)

  def tuple2d(self):
    return (self.lon,self.lat)

  def tuple3d(self):
    return (self.lon,self.lat,self.ele)

  def dist(self,p,includeEle=False):
    "Distance between two waypoints using haversine"
    # TODO: take into account of elevation!
    R = 6372800 # Radius of earth in meters
    lat1 = math.radians(self.lat)
    lon1 = math.radians(self.lon)
    lat2 = math.radians(p.lat)
    lon2 = math.radians(p.lon)
    dLat = lat2-lat1
    dLon = lon2-lon1
    a = math.sin(dLat/2) * math.sin(dLat/2) + math.cos(lat1) * math.cos(lat2) * math.sin(dLon/2) * math.sin(dLon/2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    d = R * c
    # approximate distance in 3d by adding elevation distance
    if includeEle and self.ele is not None and p.ele is not None:
      d += abs(self.ele-p.ele)
    return d

class GPXWriter:
  """
  Writes a GPX file to
  """
  creator = "GPX.py "+VERSION

  # Taken from: http://infix.se/2007/02/06/gentlemen-indent-your-xml

  def gpx(self,gpx):
    root = Element("gpx",xmlns=NS,version="1.1",creator=self.creator)
    for wpt in gpx.waypoints:
      root.append(self.wpt(wpt,"wpt"))
    for route in gpx.routes:
      el = self.path(route,"rte","rtept")
      xmlutil.write(el,route,Route._scheme)
      root.append(el)
    for track in gpx.tracks:
      el = SubElement(root,"trk")
      xmlutil.write(el,track,Track._scheme)
      for seg in track:
        el.append(self.path(seg,"trkseg","trkpt"))
    return root

  def wpt(self,wpt,name):
   "Creates an XML element with specified name which represents this Waypoint"
   e = Element(name)
   xmlutil.write(e,wpt,Waypoint._scheme)
   return e

  def path(self,p,name,ptname):
    e = Element(name)
    for p in p._wpt:
      e.append(self.wpt(p,ptname))
    return e

  def write(self,gpx,file):
    root = self.gpx(gpx)
    xmlutil.indent(root)
    ElementTree.ElementTree(root).write(file)

class GPXParser:
  """
  DOM Parsing tool which constructs a
  """
  def __init__(self,gpx):
    self.gpx = gpx

  def parse(self,src):
    root = ElementTree.parse(src).getroot()
    # namespace should be either gpx1/0 or gpx1/1
    self.NS = root.tag[1:-4]
    for wptEl in root.findall("{%s}wpt" % self.NS):
      self.gpx.waypoints.append(self.parseWaypoint(wptEl))
    for rteEl in root.findall("{%s}rte" % self.NS):
      self.gpx.routes.append(self.parseRoute(rteEl))
    for trkEl in root.findall("{%s}trk" % self.NS):
      self.gpx.tracks.append(self.parseTrack(trkEl))

  def parseTrack(self,el):
    trk = Track(**xmlutil.parse(self.NS,el,Track._scheme))
    for seg in el.findall("{%s}trkseg" % self.NS):
      p = Path()
      for wpel in seg.findall("{%s}trkpt" % self.NS):
        p.append(self.parseWaypoint(wpel))
      trk.append(p)
    return trk

  def parseRoute(self,el):
    r = Route(**xmlutil.parse(self.NS,el,Route._scheme))
    for wpel in el.findall("{%s}rtept" % self.NS):
      r.append(self.parseWaypoint(wpel))
    return r

  def parseWaypoint(self,e):
    return Waypoint(**xmlutil.parse(self.NS,e,Waypoint._scheme))

<|endoftext|>


<commit_before>import time
from monosat.bvtheory import BitVector
from monosat.logic import *
from monosat.monosat_c import Monosat
from monosat.pbtheory import PBManager

def FoundOptimal():
    return Monosat().lastSolutionWasOptimal();
class SolveException(Exception):
    pass
def Solve(assumptions=None, preprocessing=True,bvs_to_minimize=None,time_limit_seconds=None, memory_limit_mb=None,conflict_limit=None):
    WriteConstraints()
    if time_limit_seconds is None or time_limit_seconds <=0:
        time_limit_seconds=-1
    if memory_limit_mb is None or memory_limit_mb <=0:
        memory_limit_mb=-1
    if conflict_limit is None or conflict_limit <=0:
        conflict_limit=-1

    Monosat().setTimeLimit(time_limit_seconds)
    Monosat().setMemoryLimit(memory_limit_mb)
    Monosat().setConflictLimit(conflict_limit)

    #if preprocessing:
    #    Monosat().preprocess();
    print("Solving in Monosat...")
    t = time.clock()

    if isinstance(assumptions,Var):
        assumptions=[assumptions]
    elif assumptions is None:
        assumptions = []

    if isinstance(bvs_to_minimize,BitVector):
        bvs_to_minimize=[bvs_to_minimize]
    elif bvs_to_minimize is None:
        bvs_to_minimize=[]

    for bv in bvs_to_minimize:
        bvID = bv.getID()
        Monosat().minimizeBV(bvID)

    r= Monosat().solveLimited([x.getLit() for x in assumptions])
    if r is None:
        raise SolveException("MonoSAT aborted before solving (possibly do to a time or memory limit)")
    Monosat().elapsed_time +=  time.clock()-t
    found_optimal = Monosat().lastSolutionWasOptimal();
    if r is None:
        raise SolveException("MonoSAT aborted before solving (possibly due to a time or memory limit)")
    elif r and not found_optimal:
        print("MonoSAT found a satisfying solution, but it might not be optimal (due to a time or memory limit)")

    return r
#If the most recent solve() call was UNSAT, returns a
def getConflictClause():
    conf_clause = Monosat().getConflictClause()
    if conf_clause is None:
        return None
    else:
        vars = []
        for v in conf_clause:
            vars.append(Var(v))
        return vars

#optimization support
def clearOptimizationObjectives():
    Monosat().clearOptimizationObjectives()

def maximize(bitvector_or_literals,weights=None):
    if isinstance(bitvector_or_literals,Var):
        arg = [bitvector_or_literals]
    if isinstance(weights,int):
        weights = [weights]

    if isinstance(bitvector_or_literals,BitVector):
        Monosat().maximizeBV(bitvector_or_literals.getID())
    else:
        lit_ints = [l.getLit() for l in bitvector_or_literals]
        if weights is None:
            Monosat().maximizeLits(lit_ints)
        else:
            Monosat().maximizeWeightedLits(lit_ints,weights)

def minimize(bitvector_or_literals,weights=None):
    if isinstance(bitvector_or_literals,Var):
        bitvector_or_literals = [bitvector_or_literals]
    if isinstance(weights,int):
        weights = [weights]

    if isinstance(bitvector_or_literals,BitVector):
        Monosat().minimizeBV(bitvector_or_literals)
    else:
        lit_ints = [l.getLit() for l in bitvector_or_literals]
        if weights is None:
            Monosat().minimizeLits(lit_ints)
        else:
            Monosat().minimizeWeightedLits(lit_ints,weights)

def WriteConstraints():
    _writePBCosntraints()

def _writePBCosntraints():
    #write any pseudoboolean constraints
    if not PBManager().hasConstraints():
        return

    t = time.clock()
    pbmgr = PBManager()
    pbmgr.flush();
    d = time.clock()
    PBManager().elapsed_time += d-t<commit_msg>further fixes to bv minimize<commit_after>import time
from monosat.bvtheory import BitVector
from monosat.logic import *
from monosat.monosat_c import Monosat
from monosat.pbtheory import PBManager

def FoundOptimal():
    return Monosat().lastSolutionWasOptimal();
class SolveException(Exception):
    pass
def Solve(assumptions=None, preprocessing=True,bvs_to_minimize=None,time_limit_seconds=None, memory_limit_mb=None,conflict_limit=None):
    WriteConstraints()
    if time_limit_seconds is None or time_limit_seconds <=0:
        time_limit_seconds=-1
    if memory_limit_mb is None or memory_limit_mb <=0:
        memory_limit_mb=-1
    if conflict_limit is None or conflict_limit <=0:
        conflict_limit=-1

    Monosat().setTimeLimit(time_limit_seconds)
    Monosat().setMemoryLimit(memory_limit_mb)
    Monosat().setConflictLimit(conflict_limit)

    #if preprocessing:
    #    Monosat().preprocess();
    print("Solving in Monosat...")
    t = time.clock()

    if isinstance(assumptions,Var):
        assumptions=[assumptions]
    elif assumptions is None:
        assumptions = []

    if isinstance(bvs_to_minimize,BitVector):
        bvs_to_minimize=[bvs_to_minimize]
    elif bvs_to_minimize is None:
        bvs_to_minimize=[]

    for bv in bvs_to_minimize:
        bvID = bv.getID()
        Monosat().minimizeBV(bvID)

    r= Monosat().solveLimited([x.getLit() for x in assumptions])
    if r is None:
        raise SolveException("MonoSAT aborted before solving (possibly do to a time or memory limit)")
    Monosat().elapsed_time +=  time.clock()-t
    found_optimal = Monosat().lastSolutionWasOptimal();
    if r is None:
        raise SolveException("MonoSAT aborted before solving (possibly due to a time or memory limit)")
    elif r and not found_optimal:
        print("MonoSAT found a satisfying solution, but it might not be optimal (due to a time or memory limit)")

    return r
#If the most recent solve() call was UNSAT, returns a
def getConflictClause():
    conf_clause = Monosat().getConflictClause()
    if conf_clause is None:
        return None
    else:
        vars = []
        for v in conf_clause:
            vars.append(Var(v))
        return vars

#optimization support
def clearOptimizationObjectives():
    Monosat().clearOptimizationObjectives()

def maximize(bitvector_or_literals,weights=None):
    if isinstance(bitvector_or_literals,Var):
        arg = [bitvector_or_literals]
    if isinstance(weights,int):
        weights = [weights]

    if isinstance(bitvector_or_literals,BitVector):
        Monosat().maximizeBV(bitvector_or_literals.getID())
    else:
        lit_ints = [l.getLit() for l in bitvector_or_literals]
        if weights is None:
            Monosat().maximizeLits(lit_ints)
        else:
            Monosat().maximizeWeightedLits(lit_ints,weights)

def minimize(bitvector_or_literals,weights=None):
    if isinstance(bitvector_or_literals,Var):
        bitvector_or_literals = [bitvector_or_literals]
    if isinstance(weights,int):
        weights = [weights]

    if isinstance(bitvector_or_literals,BitVector.getID()):
        Monosat().minimizeBV(bitvector_or_literals)
    else:
        lit_ints = [l.getLit() for l in bitvector_or_literals]
        if weights is None:
            Monosat().minimizeLits(lit_ints)
        else:
            Monosat().minimizeWeightedLits(lit_ints,weights)

def WriteConstraints():
    _writePBCosntraints()

def _writePBCosntraints():
    #write any pseudoboolean constraints
    if not PBManager().hasConstraints():
        return

    t = time.clock()
    pbmgr = PBManager()
    pbmgr.flush();
    d = time.clock()
    PBManager().elapsed_time += d-t<|endoftext|>


<commit_before>from time import sleep

import arkInit
arkInit.init()

import coren

class Database(object):
	def __init__(self, apiRoot, keepTrying=False):
		self.apiRoot = apiRoot
		self.keepTrying = keepTrying
		try:
			self.coren = coren.Coren(apiRoot)
		except:
			if self.keepTrying:
				self.coren = None
				while not self.coren:
					print('no connection made yet, trying again.')
					sleep(0.5)
					try:
						self.coren = coren.Coren(apiRoot)
					except:
						pass
			else:
				raise Exception('The database could not be initialized at %s, please check the connection' % self.apiRoot)

	def create(self, entityType, data):
		return self.coren.create(entityType, data, self.execute)

	def find(self, entityType):
		return self.coren.find(entityType, self.execute)

	def update(self, entityType, data=None):
		return self.coren.update(entityType, data, self.execute)

	def remove(self, entityType):
		return self.coren.remove(entityType, self.execute)

	def empty(self, entityType):
		return self.coren.empty(entityType)

	def findOne(self, entityType):
		return self.coren.findOne(entityType)

	def getID(self, entityType):
		return self.coren.getID(entityType, self.execute)

	def getIDByName(self, entityType, name):
		return self.coren.getIDByName(self, entityType, name)

	def execute(self, queryParams, queryOptions, keepTrying=None):
		if keepTrying is None:
			keepTrying = self.keepTrying
		try:
			response = self.coren.execute(queryParams, queryOptions)
			return response
		except:
			if keepTrying:
				response = None
				while response == None:
					try:
						print('Database hasn\'t responded yet, retrying')
						sleep(0.5)
						response = self.coren.execute(queryParams, queryOptions)
					except NotImplementedError:
						raise
					except:
						pass
			else:
				raise

<commit_msg>database now has a "connect" method<commit_after>from time import sleep

import arkInit
arkInit.init()

import coren

class Database(object):
	def __init__(self, apiRoot, keepTrying=False):
		self.apiRoot = apiRoot
		self.keepTrying = keepTrying

	def connect(self, keepTrying=False):
		self.keepTrying = keepTrying
		try:
			self.coren = coren.Coren(apiRoot)
			return self
		except:
			if self.keepTrying:
				self.coren = None
				while not self.coren:
					print('no connection made yet, trying again.')
					sleep(0.5)
					try:
						self.coren = coren.Coren(apiRoot)
					except:
						pass
				return self
			else:
				return None
				# return False
				#raise Exception('The database could not be initialized at %s, please check the connection' % self.apiRoot)

	def create(self, entityType, data):
		return self.coren.create(entityType, data, self.execute)

	def find(self, entityType):
		return self.coren.find(entityType, self.execute)

	def update(self, entityType, data=None):
		return self.coren.update(entityType, data, self.execute)

	def remove(self, entityType):
		return self.coren.remove(entityType, self.execute)

	def empty(self, entityType):
		return self.coren.empty(entityType)

	def findOne(self, entityType):
		return self.coren.findOne(entityType)

	def getID(self, entityType):
		return self.coren.getID(entityType, self.execute)

	def getIDByName(self, entityType, name):
		return self.coren.getIDByName(self, entityType, name)

	def execute(self, queryParams, queryOptions, keepTrying=None):
		if keepTrying is None:
			keepTrying = self.keepTrying
		try:
			response = self.coren.execute(queryParams, queryOptions)
			return response
		except:
			if keepTrying:
				response = None
				while response == None:
					try:
						print('Database hasn\'t responded yet, retrying')
						sleep(0.5)
						response = self.coren.execute(queryParams, queryOptions)
					except NotImplementedError:
						raise
					except:
						pass
			else:
				raise

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo.tests import common
from datetime import datetime

class TestSaleMargin(common.TransactionCase):

    def setUp(self):
        super(TestSaleMargin, self).setUp()
        self.SaleOrder = self.env['sale.order']

        self.product_uom_id = self.ref('uom.product_uom_unit')
        self.product_id = self.ref('product.product_product_24')
        self.partner_id = self.ref('base.res_partner_4')
        self.partner_invoice_address_id = self.ref('base.res_partner_address_7')
        self.pricelist_id = self.ref('product.list0')

    def test_sale_margin(self):
        """ Test the sale_margin module in Odoo. """
        sale_order_so11 = self.SaleOrder.create({
            'date_order': datetime.today(),
            'name': 'Test_SO011',
            'order_line': [
                (0, 0, {
                    'name': '[CARD] Individual Workplace',
                    'purchase_price': 700.0,
                    'price_unit': 1000.0,
                    'product_uom': self.product_uom_id,
                    'product_uom_qty': 10.0,
                    'state': 'draft',
                    'product_id': self.product_id}),
                (0, 0, {
                    'name': 'Line without product_uom',
                    'price_unit': 1000.0,
                    'purchase_price': 700.0,
                    'product_uom_qty': 10.0,
                    'state': 'draft',
                    'product_id': self.product_id})],
            'partner_id': self.partner_id,
            'partner_invoice_id': self.partner_invoice_address_id,
            'partner_shipping_id': self.partner_invoice_address_id,
            'pricelist_id': self.pricelist_id})
        # Confirm the sales order.
        sale_order_so11.action_confirm()
        # Verify that margin field gets bind with the value.
        self.assertEqual(sale_order_so11.margin, 6000.00, "Sales order margin should be 6000.00")
<commit_msg>[IMP] sale_margin: Adapt tests to work with/without demo data<commit_after># -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo.tests import common
from datetime import datetime

class TestSaleMargin(common.TransactionCase):

    def setUp(self):
        super(TestSaleMargin, self).setUp()
        self.SaleOrder = self.env['sale.order']

        self.product_uom_id = self.ref('uom.product_uom_unit')
        self.product_id = self.env['product.product'].create({'name': 'Individual Workplace'}).id
        self.partner_id = self.env['res.partner'].create({'name': 'A test partner'}).id
        self.partner_invoice_address_id = self.env['res.partner'].create({
            'name': 'A test partner address',
            'parent_id': self.partner_id,
        }).id
        self.pricelist_id = self.ref('product.list0')

    def test_sale_margin(self):
        """ Test the sale_margin module in Odoo. """
        sale_order_so11 = self.SaleOrder.create({
            'date_order': datetime.today(),
            'name': 'Test_SO011',
            'order_line': [
                (0, 0, {
                    'name': '[CARD] Individual Workplace',
                    'purchase_price': 700.0,
                    'price_unit': 1000.0,
                    'product_uom': self.product_uom_id,
                    'product_uom_qty': 10.0,
                    'state': 'draft',
                    'product_id': self.product_id}),
                (0, 0, {
                    'name': 'Line without product_uom',
                    'price_unit': 1000.0,
                    'purchase_price': 700.0,
                    'product_uom_qty': 10.0,
                    'state': 'draft',
                    'product_id': self.product_id})],
            'partner_id': self.partner_id,
            'partner_invoice_id': self.partner_invoice_address_id,
            'partner_shipping_id': self.partner_invoice_address_id,
            'pricelist_id': self.pricelist_id})
        # Confirm the sales order.
        sale_order_so11.action_confirm()
        # Verify that margin field gets bind with the value.
        self.assertEqual(sale_order_so11.margin, 6000.00, "Sales order margin should be 6000.00")
<|endoftext|>