<commit_before>import logging; logger = logging.getLogger("robot." + __name__)
logger.setLevel(logging.DEBUG)

import random

from robots.action import *

from robots.helpers import postures
from robots.helpers.cb import *

from robots.actions import configuration, nav, look_at, speech

used_plan_id = []

@tested("22/02/2012")
@action
def release_gripper(robot, gripper = "RIGHT"):
    """
    Opens the gripper to release something.

    Like gripper_open, except it waits until it senses some effort on the gripper force sensors.

    :see: open_gripper

    :param gripper: "RIGHT" (default) or "LEFT"
    """

    if gripper == "RIGHT":
        return [genom_request("pr2SoftMotion", "GripperGrabRelease", ["RRELEASE"])]
    else:
        return [genom_request("pr2SoftMotion", "GripperGrabRelease", ["LRELEASE"])]

@tested("22/02/2012")
@action
def grab_gripper(robot, gripper = "RIGHT"):
    """
    Closes the gripper to grab something.

    Like gripper_close, except it waits until it senses some effort on the gripper force sensors.

    :see: close_gripper
    :param gripper: "RIGHT" (default) or "LEFT"
    """
    if gripper == "RIGHT":
        return [genom_request("pr2SoftMotion", "GripperGrabRelease", ["RGRAB"])]
    else:
        return [genom_request("pr2SoftMotion", "GripperGrabRelease", ["LGRAB"])]

@tested("22/02/2012")
@action
def open_gripper(robot, gripper = "RIGHT", callback = None):
    """
    Opens a gripper.

    If pr2SoftMotion-genom is available, it tries with it. Else it tries with fingers-genom.
    Parameter 'gripper' is ignored when using fingers-genom.

    :see: release_gripper
    :param gripper: "RIGHT" (default) or "LEFT"
    :param callback: if set, the action is non-blocking and the callback is invoked upon completion
    """

    if robot.hasmodule("pr2SoftMotion"):
        if gripper == "RIGHT":
            return [genom_request("pr2SoftMotion",
                    "GripperGrabRelease",
                    ["ROPEN"],
                    wait_for_completion = False if callback else True,
                    callback = callback)]

        else:
            return [genom_request("pr2SoftMotion",
                    "GripperGrabRelease",
                    ["LOPEN"],
                    wait_for_completion = False if callback else True,
                    callback = callback)]

    if robot.hasmodule("fingers"):
            return [genom_request("fingers",
                    "OpenGrip",
                    [],
                    wait_for_completion = False if callback else True,
                    callback = callback)]

    logger.warning("No module to open the gripper available. Skipping this action.")
    return []

@tested("22/02/2012")
@action
def close_gripper(robot, gripper = "RIGHT", callback = None):
    """ Closes the right gripper.

    If pr2SoftMotion-genom is available, it tries with it. Else it tries with fingers-genom.
    Parameter 'gripper' is ignored when using fingers-genom.

    :see: grab_gripper
    :param gripper: "RIGHT" (default) or "LEFT"
    :param callback: if set, the action is non-blocking and the callback is invoked upon completion
    """
    if robot.hasmodule("pr2SoftMotion"):
        if gripper == "RIGHT":
            return [genom_request("pr2SoftMotion",
                    "GripperGrabRelease",
                    ["RCLOSE"],
                    wait_for_completion = False if callback else True,
                    callback = callback)]
        else:
            return [genom_request("pr2SoftMotion",
                    "GripperGrabRelease",
                    ["LCLOSE"],
                    wait_for_completion = False if callback else True,
                    callback = callback)]

    if robot.hasmodule("fingers"):
            return [genom_request("fingers",
                    "CloseGrip",
                    [],
                    wait_for_completion = False if callback else True,
                    callback = callback)]

    logger.warning("No module to close the gripper available. Skipping this action.")
    return []

@tested("23/02/2012")
@action
def configure_grippers(robot, grab_acc = 8.0, grab_slip = 0.2, release_acc = 4.0, release_slip = 0.05, force = 25):
    """ Sets the grippers thresholds.

    :param grab_acc: threshold for grab detection
    :param grab_slip: threshold for grab detection
    :param release_acc: threshold for release detection
    :param release_slip: threshold for release detection
    :param force: hold force
    """
    return [genom_request("pr2SoftMotion",
            "SetGripperTresholds",
            [grab_acc, grab_slip, release_acc, release_slip, force])]

def getplanid():
    """ Returns a random plan id (for Amit planification routines) which is
    guaranteed to be 'fresh'.
    """
    plan_id = random.randint(1, 1000)
    while plan_id in used_plan_id:
        plan_id = random.randint(1, 1000)
    used_plan_id.append(plan_id)
    return plan_id

@action
def pick(robot, obj, use_cartesian = "GEN_FALSE"):
    """ Picks an object that is reachable by the robot.

    Uses MHP to plan a trajectory.
    The trajectory is executed with by pr2SoftMotion-genom if available,
    else with lwr-genom if available, else oonly exported to the mhpArmTraj poster.

    :param object: the object to pick.
    """

    def haspickedsmthg(robot):

        try:
            gripper_joint = robot.state.getjoint('r_gripper_joint')

            if gripper_joint < 0.01:
                logger.warning("I think I've nothing in my right gripper...")
                return (False, "gripper joint < 0.01")
            else:
                return (True, None)
        except NameError: #no robot.state? consider the pick is successfull
            return (True, None)

    # Open gripper
    actions = open_gripper(robot)

    # Plan trajectory to object and execute it
    actions += [
    genom_request("mhp", "ArmPlanTask",
            [0,
            'GEN_TRUE',
            'MHP_ARM_PICK_GOTO',
            0,
            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            obj,
            'NO_NAME',
            'NO_NAME',
            use_cartesian,
            0,
            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
        genom_request("mhp", "ArmSelectTraj", [0]),
    ]

    if robot.hasmodule("pr2SoftMotion"):
        actions.append(
                genom_request("pr2SoftMotion",
                    "TrackQ",
                    ['mhpArmTraj', 'PR2SM_TRACK_POSTER', 'RARM']))

    elif robot.hasmodule("lwr"):
        actions += [
                genom_request("lwr",
                    "SetMonitorForceParam",
                    [1, 0.5, 0.1, 0.3, 0.005, 0.1]),
                genom_request("lwr",
                    "TrackQ",
                    ["LWR_ARM_RIGHT", "mhpArmTraj", "LWR_TRACK_POSTER"]
                    ]

    else:
        logger.warning("No module for rm trajectory execution. Trajectory only " \
                       "published on the mhpArmTraj poster.")

    # Close gripper
    actions += close_gripper(robot)

    actions += [python_request(haspickedsmthg)]

    return actions

@tested("")
@action
def attachobject(robot, obj, attach = True):
    """ attach or detach the object to the robot hand

    This function should be called after a release or a grab
    :param obj: the object to attach/dettach.
    :param attach: true (default) to attach an object, false to detach it
    """
    i = 0
    if (attach) :
      i = 1
    actions = [
        genom_request("spark","SetGraspedObject", [obj, i, 0]),
        genom_request("spark","SetInferrenceForObject", [obj, i, robot.id, 0,
            "SPARK_PRECISE_ROBOT_HAND", 1.0])
    ]

    return actions

@tested("05/07/2012")
@action
def basictake(robot):
    """ The ultra stupid basic TAKE: simply hand the object in front of the
    robot.
    """

    posture = postures.read()

    actions = configuration.setpose(robot, posture["GIVE"])
    actions += open_gripper(robot)
    actions += [wait(2)]
    actions += grab_gripper(robot)
    actions += configuration.manipose(robot)

    return actions

@action
def take(robot, human, obj):

    actions = look_at.look_at(robot, human)
    actions += configuration.manipose(robot, nop)
    actions += look_at.look_at(robot, [1,0,0.7,"base_link"])

    mobility = 0.0

    res = robot.planning.handover(human, mobility = mobility)

    if not res:
        logger.warning("OTP planning failed. Retrying.")
        robot.sorry()
        res = robot.planning.handover(human, mobility=mobility)
        if not res:
            logger.error("OTP planning failed again. Giving up.")
            return []

    wps, pose = res

    torso = pose["TORSO"]
    del pose["TORSO"]
    actions += configuration.settorso(robot, torso, nop)

    actions += nav.waypoints(robot, wps)
    actions += look_at.look_at(robot, human,nop)

    actions += configuration.setpose(robot, pose)

    actions += speech.say(robot, "Ok, I take it")
    actions += open_gripper(robot)
    actions += grab_gripper(robot)

    return actions

@tested("22/02/2012")
@action
def basicgive(robot):
    """ The ultra stupid basic GIVE: simply hand the object in front of the
    robot.

    After handing the object, the robot waits for someone to take it, and
    stay in this posture.
    """

    posture = postures.read()

    actions = configuration.setpose(robot, posture["GIVE"])
    actions += release_gripper(robot)
    actions += [wait(2)]
    actions += close_gripper(robot, callback = nop)

    return actions

@tested("22/02/2012")
@action
def basicgrab(robot):
    """ The ultra stupid basic GRAB: simply take the object in front of the
    robot.

    After handing its gripper, the robot waits for someone to put an object in
    it, and stay in this posture.
    """

    posture = postures.read()

    actions = open_gripper(nop)
    actions += configuration.setpose(robot, posture["GIVE"])
    actions += grab_gripper(robot)

    return actions

#def chained_handover_feedback_cb(previous_cb = None):
#    def cb(progress):
#        if progress >

@tested("15/06/2012")
@action
def handover(robot, human, mobility = 0.0, feedback = None):
    """ Computes and executes a move for a 'hand-over': given a
    human, the robot finds a trajectory and a pose to go and hand
    the object in its right hand to the human.

    The efforts can be shared between the human and the robot with
    the 'mobility' parameter.

    Note that the object is assumed to be already in the hand.

    :param human: the human (SPARK ID) to hand an object over.
    :param mobility: the level of mobility of the human. 0.0 means
    the human can not move (the robot does all the displacement),
    1.0 means the robot and the human will each roughly move half
    the way.
    :param feedback: (optional) a callback that is invoked as the
    robot moves along. It provides the percentage of the trajectory
    already covered, the distance to go and the distance already
    covered.
    """

    actions = look_at.look_at(robot, human)
    actions += configuration.manipose(robot, nop)
    actions += look_at.look_at(robot, [1,0,0.7,"base_link"])
    res = robot.planning.handover(human, mobility = mobility)

    if not res:
        logger.warning("OTP planning failed. Retrying.")
        robot.sorry()
        res = robot.planning.handover(human, mobility=mobility)
        if not res:
            logger.error("OTP planning failed again. Giving up.")
            return []

    wps, pose = res

    torso = pose["TORSO"]
    del pose["TORSO"]
    actions += configuration.settorso(robot, torso, nop)

    actions += nav.waypoints(robot, wps, feedback = feedback)
    actions += look_at.look_at(robot, human,nop)

    # Collision avoidance
    #pose_rarm = {'RARM':pose['RARM']}
    #actions += configuration.settorso(pose['TORSO'][0], nop)
    #actions += configuration.setpose(robot, pose_rarm, collision_avoidance = True, callback=nop)

    # No collision avoidance
    actions += configuration.setpose(robot, pose)

    actions += speech.say(robot, "Here your object")
    actions += release_gripper(robot)
    actions += [wait(1)]
    actions += close_gripper(robot, callback=nop)

    return actions

@action
def amit_give(robot, performer, obj, receiver):
    """ The 'Amit' GIVE.
    """
    plan_id = getplanid()
    actions = [
        genom_request("mhp",
            "Plan_HRI_Task",
            [plan_id, "GIVE_OBJECT", obj, performer,  receiver, 0, 0, 0]
        ),
        genom_request(	"mhp",
            "Get_SM_Traj_HRI_Task",
            [plan_id]
        ),
        genom_request(	"pr2SoftMotion",
            "GripperGrabRelease",
            ["OPEN"]
        ),
        genom_request(	"mhp",
            "Write_this_SM_Traj_to_Poster",
            [0]
        ),
        genom_request(	"pr2SoftMotion",
            "TrackQ",
            ["mhpArmTraj", "PR2SM_TRACK_POSTER", "RARM"]
        ),
        genom_request(	"mhp",
            "Write_this_SM_Traj_to_Poster",
            [1]
        ),
        genom_request(	"pr2SoftMotion",
            "TrackQ",
            ["mhpArmTraj", "PR2SM_TRACK_POSTER", "RARM"]
        ),
        genom_request(	"pr2SoftMotion",
            "GripperGrabRelease",
            ["CLOSE"]
        ),
        genom_request(	"mhp",
            "Write_this_SM_Traj_to_Poster",
            [3]
        ),
        genom_request(	"pr2SoftMotion",
            "TrackQ",
            ["mhpArmTraj", "PR2SM_TRACK_POSTER", "RARM"]
        ),
        genom_request(	"mhp",
            "Write_this_SM_Traj_to_Poster",
            [4]
        ),
        genom_request(	"pr2SoftMotion",
            "TrackQ",
            ["mhpArmTraj", "PR2SM_TRACK_POSTER", "RARM"]
        ),
        genom_request(	"pr2SoftMotion",
            "GripperGrabRelease",
            ["RELEASE"]
        )
    ]

    return actions

<commit_msg>Tested and fixed the pick on JidoSimu<commit_after>import logging; logger = logging.getLogger("robot." + __name__)
logger.setLevel(logging.DEBUG)

import random

from robots.action import *

from robots.helpers import postures
from robots.helpers.cb import *

from robots.actions import configuration, nav, look_at, speech

used_plan_id = []

@tested("22/02/2012")
@action
def release_gripper(robot, gripper = "RIGHT"):
    """
    Opens the gripper to release something.

    Like gripper_open, except it waits until it senses some effort on the gripper force sensors.

    :see: open_gripper

    :param gripper: "RIGHT" (default) or "LEFT"
    """

    if gripper == "RIGHT":
        return [genom_request("pr2SoftMotion", "GripperGrabRelease", ["RRELEASE"])]
    else:
        return [genom_request("pr2SoftMotion", "GripperGrabRelease", ["LRELEASE"])]

@tested("22/02/2012")
@action
def grab_gripper(robot, gripper = "RIGHT"):
    """
    Closes the gripper to grab something.

    Like gripper_close, except it waits until it senses some effort on the gripper force sensors.

    :see: close_gripper
    :param gripper: "RIGHT" (default) or "LEFT"
    """
    if gripper == "RIGHT":
        return [genom_request("pr2SoftMotion", "GripperGrabRelease", ["RGRAB"])]
    else:
        return [genom_request("pr2SoftMotion", "GripperGrabRelease", ["LGRAB"])]

@tested("22/02/2012")
@action
def open_gripper(robot, gripper = "RIGHT", callback = None):
    """
    Opens a gripper.

    If pr2SoftMotion-genom is available, it tries with it. Else it tries with fingers-genom.
    Parameter 'gripper' is ignored when using fingers-genom.

    :see: release_gripper
    :param gripper: "RIGHT" (default) or "LEFT"
    :param callback: if set, the action is non-blocking and the callback is invoked upon completion
    """

    if robot.hasmodule("pr2SoftMotion"):
        if gripper == "RIGHT":
            return [genom_request("pr2SoftMotion",
                    "GripperGrabRelease",
                    ["ROPEN"],
                    wait_for_completion = False if callback else True,
                    callback = callback)]

        else:
            return [genom_request("pr2SoftMotion",
                    "GripperGrabRelease",
                    ["LOPEN"],
                    wait_for_completion = False if callback else True,
                    callback = callback)]

    if robot.hasmodule("fingers"):
            return [genom_request("fingers",
                    "OpenGrip",
                    [],
                    wait_for_completion = False if callback else True,
                    callback = callback)]

    logger.warning("No module to open the gripper available. Skipping this action.")
    return []

@tested("22/02/2012")
@action
def close_gripper(robot, gripper = "RIGHT", callback = None):
    """ Closes the right gripper.

    If pr2SoftMotion-genom is available, it tries with it. Else it tries with fingers-genom.
    Parameter 'gripper' is ignored when using fingers-genom.

    :see: grab_gripper
    :param gripper: "RIGHT" (default) or "LEFT"
    :param callback: if set, the action is non-blocking and the callback is invoked upon completion
    """
    if robot.hasmodule("pr2SoftMotion"):
        if gripper == "RIGHT":
            return [genom_request("pr2SoftMotion",
                    "GripperGrabRelease",
                    ["RCLOSE"],
                    wait_for_completion = False if callback else True,
                    callback = callback)]
        else:
            return [genom_request("pr2SoftMotion",
                    "GripperGrabRelease",
                    ["LCLOSE"],
                    wait_for_completion = False if callback else True,
                    callback = callback)]

    if robot.hasmodule("fingers"):
            return [genom_request("fingers",
                    "CloseGrip",
                    [],
                    wait_for_completion = False if callback else True,
                    callback = callback)]

    logger.warning("No module to close the gripper available. Skipping this action.")
    return []

@tested("23/02/2012")
@action
def configure_grippers(robot, grab_acc = 8.0, grab_slip = 0.2, release_acc = 4.0, release_slip = 0.05, force = 25):
    """ Sets the grippers thresholds.

    :param grab_acc: threshold for grab detection
    :param grab_slip: threshold for grab detection
    :param release_acc: threshold for release detection
    :param release_slip: threshold for release detection
    :param force: hold force
    """
    return [genom_request("pr2SoftMotion",
            "SetGripperTresholds",
            [grab_acc, grab_slip, release_acc, release_slip, force])]

def getplanid():
    """ Returns a random plan id (for Amit planification routines) which is
    guaranteed to be 'fresh'.
    """
    plan_id = random.randint(1, 1000)
    while plan_id in used_plan_id:
        plan_id = random.randint(1, 1000)
    used_plan_id.append(plan_id)
    return plan_id

@action
def pick(robot, obj, use_cartesian = "GEN_FALSE"):
    """ Picks an object that is reachable by the robot.

    Uses MHP to plan a trajectory.
    The trajectory is executed with by pr2SoftMotion-genom if available,
    else with lwr-genom if available, else oonly exported to the mhpArmTraj poster.

    :param object: the object to pick.
    """

    def haspickedsmthg(robot):

        try:
            gripper_joint = robot.state.getjoint('r_gripper_joint')

            if gripper_joint < 0.01:
                logger.warning("I think I've nothing in my right gripper...")
                return (False, "gripper joint < 0.01")
            else:
                return (True, None)
        except NameError: #no robot.state? consider the pick is successfull
            return (True, None)
        except AttributeError as detail: #no robot.state? consider the pick is successfull
            return (True, None)

    # Open gripper
    actions = open_gripper(robot)

    # Plan trajectory to object and execute it
    actions += [
    genom_request("mhp", "ArmPlanTask",
            [0,
            'GEN_TRUE',
            'MHP_ARM_PICK_GOTO',
            0,
            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            obj,
            'NO_NAME',
            'NO_NAME',
            use_cartesian,
            0,
            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
        genom_request("mhp", "ArmSelectTraj", [0]),
    ]

    if robot.hasmodule("pr2SoftMotion"):
        actions.append(
                genom_request("pr2SoftMotion",
                    "TrackQ",
                    ['mhpArmTraj', 'PR2SM_TRACK_POSTER', 'RARM']))

    elif robot.hasmodule("lwr"):
        actions += [
                         genom_request("lwr",
                             "SetMonitorForceParam",
                             [1, 0.5, 0.1, 0.3, 0.005, 0.1]),
                         genom_request("lwr",
                             "TrackQ",
                             ["LWR_ARM_RIGHT", "mhpArmTraj", "LWR_TRACK_POSTER"]),
                         wait(7)
                             ]

    else:
        logger.warning("No module for rm trajectory execution. Trajectory only " \
                       "published on the mhpArmTraj poster.")

    # Close gripper
    actions += close_gripper(robot)

    actions += [python_request(haspickedsmthg)]

    return actions

@tested("")
@action
def attachobject(robot, obj, attach = True):
    """ attach or detach the object to the robot hand

    This function should be called after a release or a grab
    :param obj: the object to attach/dettach.
    :param attach: true (default) to attach an object, false to detach it
    """
    i = 0
    if (attach) :
      i = 1
    actions = [
        genom_request("spark","SetGraspedObject", [obj, i, 0]),
        genom_request("spark","SetInferrenceForObject", [obj, i, robot.id, 0,
            "SPARK_PRECISE_ROBOT_HAND", 1.0])
    ]

    return actions

@tested("05/07/2012")
@action
def basictake(robot):
    """ The ultra stupid basic TAKE: simply hand the object in front of the
    robot.
    """

    posture = postures.read()

    actions = configuration.setpose(robot, posture["GIVE"])
    actions += open_gripper(robot)
    actions += [wait(2)]
    actions += grab_gripper(robot)
    actions += configuration.manipose(robot)

    return actions

@action
def take(robot, human, obj):

    actions = look_at.look_at(robot, human)
    actions += configuration.manipose(robot, nop)
    actions += look_at.look_at(robot, [1,0,0.7,"base_link"])

    mobility = 0.0

    res = robot.planning.handover(human, mobility = mobility)

    if not res:
        logger.warning("OTP planning failed. Retrying.")
        robot.sorry()
        res = robot.planning.handover(human, mobility=mobility)
        if not res:
            logger.error("OTP planning failed again. Giving up.")
            return []

    wps, pose = res

    torso = pose["TORSO"]
    del pose["TORSO"]
    actions += configuration.settorso(robot, torso, nop)

    actions += nav.waypoints(robot, wps)
    actions += look_at.look_at(robot, human,nop)

    actions += configuration.setpose(robot, pose)

    actions += speech.say(robot, "Ok, I take it")
    actions += open_gripper(robot)
    actions += grab_gripper(robot)

    return actions

@tested("22/02/2012")
@action
def basicgive(robot):
    """ The ultra stupid basic GIVE: simply hand the object in front of the
    robot.

    After handing the object, the robot waits for someone to take it, and
    stay in this posture.
    """

    posture = postures.read()

    actions = configuration.setpose(robot, posture["GIVE"])
    actions += release_gripper(robot)
    actions += [wait(2)]
    actions += close_gripper(robot, callback = nop)

    return actions

@tested("22/02/2012")
@action
def basicgrab(robot):
    """ The ultra stupid basic GRAB: simply take the object in front of the
    robot.

    After handing its gripper, the robot waits for someone to put an object in
    it, and stay in this posture.
    """

    posture = postures.read()

    actions = open_gripper(nop)
    actions += configuration.setpose(robot, posture["GIVE"])
    actions += grab_gripper(robot)

    return actions

#def chained_handover_feedback_cb(previous_cb = None):
#    def cb(progress):
#        if progress >

@tested("15/06/2012")
@action
def handover(robot, human, mobility = 0.0, feedback = None):
    """ Computes and executes a move for a 'hand-over': given a
    human, the robot finds a trajectory and a pose to go and hand
    the object in its right hand to the human.

    The efforts can be shared between the human and the robot with
    the 'mobility' parameter.

    Note that the object is assumed to be already in the hand.

    :param human: the human (SPARK ID) to hand an object over.
    :param mobility: the level of mobility of the human. 0.0 means
    the human can not move (the robot does all the displacement),
    1.0 means the robot and the human will each roughly move half
    the way.
    :param feedback: (optional) a callback that is invoked as the
    robot moves along. It provides the percentage of the trajectory
    already covered, the distance to go and the distance already
    covered.
    """

    actions = look_at.look_at(robot, human)
    actions += configuration.manipose(robot, nop)
    actions += look_at.look_at(robot, [1,0,0.7,"base_link"])
    res = robot.planning.handover(human, mobility = mobility)

    if not res:
        logger.warning("OTP planning failed. Retrying.")
        robot.sorry()
        res = robot.planning.handover(human, mobility=mobility)
        if not res:
            logger.error("OTP planning failed again. Giving up.")
            return []

    wps, pose = res

    torso = pose["TORSO"]
    del pose["TORSO"]
    actions += configuration.settorso(robot, torso, nop)

    actions += nav.waypoints(robot, wps, feedback = feedback)
    actions += look_at.look_at(robot, human,nop)

    # Collision avoidance
    #pose_rarm = {'RARM':pose['RARM']}
    #actions += configuration.settorso(pose['TORSO'][0], nop)
    #actions += configuration.setpose(robot, pose_rarm, collision_avoidance = True, callback=nop)

    # No collision avoidance
    actions += configuration.setpose(robot, pose)

    actions += speech.say(robot, "Here your object")
    actions += release_gripper(robot)
    actions += [wait(1)]
    actions += close_gripper(robot, callback=nop)

    return actions

@action
def amit_give(robot, performer, obj, receiver):
    """ The 'Amit' GIVE.
    """
    plan_id = getplanid()
    actions = [
        genom_request("mhp",
            "Plan_HRI_Task",
            [plan_id, "GIVE_OBJECT", obj, performer,  receiver, 0, 0, 0]
        ),
        genom_request(	"mhp",
            "Get_SM_Traj_HRI_Task",
            [plan_id]
        ),
        genom_request(	"pr2SoftMotion",
            "GripperGrabRelease",
            ["OPEN"]
        ),
        genom_request(	"mhp",
            "Write_this_SM_Traj_to_Poster",
            [0]
        ),
        genom_request(	"pr2SoftMotion",
            "TrackQ",
            ["mhpArmTraj", "PR2SM_TRACK_POSTER", "RARM"]
        ),
        genom_request(	"mhp",
            "Write_this_SM_Traj_to_Poster",
            [1]
        ),
        genom_request(	"pr2SoftMotion",
            "TrackQ",
            ["mhpArmTraj", "PR2SM_TRACK_POSTER", "RARM"]
        ),
        genom_request(	"pr2SoftMotion",
            "GripperGrabRelease",
            ["CLOSE"]
        ),
        genom_request(	"mhp",
            "Write_this_SM_Traj_to_Poster",
            [3]
        ),
        genom_request(	"pr2SoftMotion",
            "TrackQ",
            ["mhpArmTraj", "PR2SM_TRACK_POSTER", "RARM"]
        ),
        genom_request(	"mhp",
            "Write_this_SM_Traj_to_Poster",
            [4]
        ),
        genom_request(	"pr2SoftMotion",
            "TrackQ",
            ["mhpArmTraj", "PR2SM_TRACK_POSTER", "RARM"]
        ),
        genom_request(	"pr2SoftMotion",
            "GripperGrabRelease",
            ["RELEASE"]
        )
    ]

    return actions

<|endoftext|>


<commit_before>from django.conf.urls import patterns, url
from django.views.generic import TemplateView

from repository.api_views import *

# Override handler403 to provide a custom permission denied page.
# Otherwise, a user has no links to get to their resources
# Esp. useful for 'next' redirection after login
handler403 = TemplateView.as_view(template_name='403.html')

# API routes
urlpatterns = patterns('repository.api_views',
    url(r'^api/repository/?$', 'repository_api_root', name='repository-api-root'),
    url(r'^api/repository/specimens/?$', SpecimenList.as_view(), name='specimen-list'),

    url(r'^api/repository/projects/?$', ProjectList.as_view(), name='project-list'),
    url(r'^api/repository/projects/(?P<pk>\d+)/?$', ProjectDetail.as_view(), name='project-detail'),
    url(r'^api/repository/project_panels/?$', ProjectPanelList.as_view(), name='project-panel-list'),
    url(r'^api/repository/project_panels/(?P<pk>\d+)/?$', ProjectPanelDetail.as_view(), name='project-panel-detail'),

    url(r'^api/repository/sites/?$', SiteList.as_view(), name='site-list'),
    url(r'^api/repository/sites/(?P<pk>\d+)/?$', SiteDetail.as_view(), name='site-detail'),
    url(r'^api/repository/site_panels/?$', SitePanelList.as_view(), name='site-panel-list'),
    url(r'^api/repository/site_panels/(?P<pk>\d+)/?$', SitePanelDetail.as_view(), name='site-panel-detail'),
    url(r'^api/repository/cytometers/?$', CytometerList.as_view(), name='cytometer-list'),
    url(r'^api/repository/cytometers/(?P<pk>\d+)/?$', CytometerDetail.as_view(), name='cytometer-detail'),

    url(r'^api/repository/subject_groups/?$', SubjectGroupList.as_view(), name='subject-group-list'),
    url(r'^api/repository/subjects/?$', SubjectList.as_view(), name='subject-list'),
    url(r'^api/repository/subjects/(?P<pk>\d+)/?$', SubjectDetail.as_view(), name='subject-detail'),

    url(r'^api/repository/visit_types/$', VisitTypeList.as_view(), name='visit-type-list'),
    url(r'^api/repository/visit_types/(?P<pk>\d+)/$', VisitTypeDetail.as_view(), name='visittype-detail'),

    url(r'^api/repository/stimulations/?$', StimulationList.as_view(), name='stimulation-list'),
    url(r'^api/repository/stimulations/(?P<pk>\d+)/?$', StimulationDetail.as_view(), name='stimulation-detail'),

    url(r'^api/repository/samples/?$', SampleList.as_view(), name='sample-list'),
    url(r'^api/repository/samples/add/?$', CreateSampleList.as_view(), name='create-sample-list'),
    url(r'^api/repository/samples/(?P<pk>\d+)/?$', SampleDetail.as_view(), name='sample-detail'),
    url(r'^api/repository/samples/(?P<pk>\d+)/fcs_original/?$', retrieve_sample, name='retrieve_sample'),
    url(r'^api/repository/samples/(?P<pk>\d+)/fcs/?$', retrieve_sample_as_pk, name='sample-download-as-pk'),
    url(r'^api/repository/samples/(?P<pk>\d+)/csv/?$', retrieve_subsample_as_csv, name='retrieve_subsample_as_csv'),
    url(r'^api/repository/samples/(?P<pk>\d+)/npy/?$', retrieve_subsample_as_numpy, name='retrieve_subsample_as_numpy'),

    url(r'^api/repository/samplemetadata/?$', SampleMetaDataList.as_view(), name='sample-metadata-list'),

    url(r'^api/repository/compensations/?$', CompensationList.as_view(), name='compensation-list'),
    url(r'^api/repository/compensations/add/?$', CreateCompensation.as_view(), name='create-compensation'),
    url(r'^api/repository/compensations/(?P<pk>\d+)/?$', CompensationDetail.as_view(), name='compensation-detail'),
    url(r'^api/repository/compensations/(?P<pk>\d+)/csv/?$', retrieve_compensation_as_csv, name='retrieve_compensation_as_csv'),
    url(r'^api/repository/compensations/(?P<pk>\d+)/npy/?$', retrieve_compensation_as_numpy, name='retrieve_compensation_as_numpy'),

    url(r'^api/repository/workers/?$', WorkerList.as_view(), name='worker-list'),
    url(r'^api/repository/verify_worker/?$', verify_worker, name='verify-worker'),
    url(r'^api/repository/process_requests/?$', ProcessRequestList.as_view(), name='process-request-list'),
    url(r'^api/repository/viable_process_requests/?$', ViableProcessRequestList.as_view(), name='viable-process-request-list'),
    url(r'^api/repository/assigned_process_requests/?$', AssignedProcessRequestList.as_view(), name='assigned-process-request-list'),
    url(r'^api/repository/process_requests/(?P<pk>\d+)/?$', ProcessRequestDetail.as_view(), name='process-request-detail'),
    url(r'^api/repository/process_requests/(?P<pk>\d+)/request_assignment/?$', ProcessRequestAssignmentUpdate.as_view(), name='process-request-assignment'),
    url(r'^api/repository/process_requests/(?P<pk>\d+)/revoke_assignment/?$', revoke_process_request_assignment, name='revoke-process-request-assignment'),
    url(r'^api/repository/process_requests/(?P<pk>\d+)/verify_assignment/?$', verify_process_request_assignment, name='verify-process-request-assignment'),
    url(r'^api/repository/process_requests/(?P<pk>\d+)/complete_assignment/?$', complete_process_request_assignment, name='complete-process-request-assignment'),
    url(r'^api/repository/process_request_outputs/add/?$', CreateProcessRequestOutput.as_view(), name='create-process-request-output'),
    url(r'^api/repository/process_request_outputs/(?P<pk>\d+)/download/?$', retrieve_process_request_output_value, name='retrieve_process_request_output'),
)

# Angular web routes
urlpatterns += patterns('repository.views',
    url(r'^samples/upload/$', 'fcs_upload_app', name='fcs_upload_app'),
    url(r'^processing/request/$', 'process_request_app', name='process_request_app'),
)

# Regular web routes
urlpatterns += patterns('repository.views',
    url(r'^403$', 'permission_denied', name='permission_denied'),
    url(r'^$', 'home', name='home'),
    url(r'^reflow_admin/$', 'admin', name='admin'),

    url(r'^markers/$', 'view_markers', name='view_markers'),
    url(r'^markers/add/$', 'add_marker', name='add_marker'),
    url(r'^markers/(?P<marker_id>\d+)/edit/$', 'add_marker', name='edit_marker'),

    url(r'^fluorochromes/$', 'view_fluorochromes', name='view_fluorochromes'),
    url(r'^fluorochromes/add/$', 'add_fluorochrome', name='add_fluorochrome'),
    url(r'^fluorochromes/(?P<fluorochrome_id>\d+)/edit/$', 'add_fluorochrome', name='edit_fluorochrome'),

    url(r'^specimens/$', 'view_specimens', name='view_specimens'),
    url(r'^specimens/add/$', 'add_specimen', name='add_specimen'),
    url(r'^specimens/(?P<specimen_id>\d+)/edit/$', 'edit_specimen', name='edit_specimen'),

    url(r'^project/(?P<project_id>\d+)/$', 'view_project', name='view_project'),
    url(r'^project/add/$', 'add_project', name='add_project'),
    url(r'^project/(?P<project_id>\d+)/edit/$', 'add_project', name='edit_project'),

    url(r'^project/(?P<project_id>\d+)/users/$', 'view_project_users', name='view_project_users'),
    url(r'^project/(?P<project_id>\d+)/users/add/$', 'add_user_permissions', name='add_user_permissions'),
    url(r'^project/(?P<project_id>\d+)/users/(?P<user_id>-?\d+)/manage/$', 'manage_project_user', name='manage_project_user'),
    url(r'^site/(?P<site_id>\d+)/users/(?P<user_id>-?\d+)/manage/$', 'manage_site_user', name='manage_site_user'),

    url(r'^project/(?P<project_id>\d+)/stimulations/$', 'view_project_stimulations', name='view_project_stimulations'),
    url(r'^project/(?P<project_id>\d+)/stimulations/add/$', 'add_stimulation', name='add_stimulation'),
    url(r'^project/(?P<project_id>\d+)/stimulations/(?P<stimulation_id>\d+)/edit/$', 'add_stimulation', name='edit_stimulation'),

    url(r'^project/(?P<project_id>\d+)/panels/$', 'view_project_panels', name='view_project_panels'),
    url(r'^project/(?P<project_id>\d+)/panels/add/$', 'add_project_panel', name='add_project_panel'),
    url(r'^project/(?P<project_id>\d+)/panels/(?P<panel_id>\d+)/edit/$', 'add_project_panel', name='edit_project_panel'),
    url(r'^project/(?P<project_id>\d+)/panels/(?P<panel_id>\d+)/copy/$', 'copy_project_panel', name='copy_project_panel'),

    url(r'^project/(?P<project_id>\d+)/sites/$', 'view_project_sites', name='view_project_sites'),
    url(r'^project/(?P<project_id>\d+)/sites/add/$', 'add_site', name='add_site'),
    url(r'^site/(?P<site_id>\d+)/edit/$', 'edit_site', name='edit_site'),

    url(r'^project/(?P<project_id>\d+)/cytometers/$', 'view_project_cytometers', name='view_project_cytometers'),
    url(r'^project/(?P<project_id>\d+)/cytometers/add/$', 'add_cytometer', name='add_cytometer'),
    url(r'^project/(?P<project_id>\d+)/cytometers/(?P<cytometer_id>\d+)/edit/$', 'add_cytometer', name='edit_cytometer'),

    url(r'^project/(?P<project_id>\d+)/compensations/$', 'view_compensations', name='project_compensations'),
    url(r'^project/(?P<project_id>\d+)/compensations/add/$', 'add_compensation', name='add_compensation'),
    url(r'^project/(?P<project_id>\d+)/compensations/(?P<compensation_id>\d+)/edit/$', 'add_compensation', name='edit_compensation'),

    url(r'^project/(?P<project_id>\d+)/visit_types/$', 'view_visit_types', name='project_visit_types'),
    url(r'^project/(?P<project_id>\d+)/visit_types/add/$', 'add_visit_type', name='add_visit_type'),
    url(r'^visit_types/(?P<visit_type_id>\d+)/edit/$', 'edit_visit_type', name='edit_visit_type'),

    url(r'^project/(?P<project_id>\d+)/site_panels/$', 'view_project_site_panels', name='view_project_site_panels'),
    url(r'^project/(?P<project_id>\d+)/site_panels/add/$', 'add_project_site_panel', name='add_project_site_panel'),
    url(r'^project/(?P<project_id>\d+)/site_panels/process_site_panel_post/$', 'process_site_panel_post', name='process_site_panel_post'),
    url(r'^site_panel/(?P<panel_id>\d+)/edit/$', 'edit_site_panel_comments', name='edit_site_panel_comments'),
    url(r'^site_panel/(?P<panel_id>\d+)/parameters/edit/$', 'edit_site_panel_parameters', name='edit_site_panel_parameters'),
    url(r'^parameter/(?P<panel_parameter_id>\d+)/remove/$', 'remove_panel_parameter', name='remove_panel_parameter'),

    url(r'^project/(?P<project_id>\d+)/subject_groups/$', 'view_subject_groups', name='subject_groups'),
    url(r'^project/(?P<project_id>\d+)/subject_groups/add/$', 'add_subject_group', name='add_subject_group'),
    url(r'^project/(?P<project_id>\d+)/subject_groups/(?P<subject_group_id>\d+)/edit/$', 'edit_subject_group', name='edit_subject_group'),

    url(r'^project/(?P<project_id>\d+)/subjects/$', 'view_subjects', name='view_subjects'),
    url(r'^project/(?P<project_id>\d+)/subjects/add/$', 'add_subject', name='add_subject'),
    url(r'^subject/(?P<subject_id>\d+)/edit/$', 'edit_subject', name='edit_subject'),

    url(r'^project/(?P<project_id>\d+)/samples/$', 'view_samples', name='view_project_samples'),
    url(r'^project/(?P<project_id>\d+)/samples/add/$', 'add_sample', name='add_sample'),
    url(r'^sample/(?P<sample_id>\d+)/edit/$', 'edit_sample', name='edit_sample'),
    url(r'^sample/(?P<sample_id>\d+)/parameters/$', 'render_sample_parameters', name='render_sample_parameters'),
    url(r'^sample/(?P<sample_id>\d+)/compensation/$', 'render_sample_compensation', name='render_sample_compensation'),

    url(r'^warning$', TemplateView.as_view(template_name='warning.html'), name='warning_page'),

    url(r'^processing/dashboard/$', 'process_dashboard', name='process_dashboard'),
    url(r'^processing/worker/add/$', 'add_worker', name='add_worker'),
    url(r'^processing/process_requests/(?P<process_request_id>\d+)/$', 'view_process_request', name='view_process_request'),
)<commit_msg>fix trailing slash for visit type API URLs<commit_after>from django.conf.urls import patterns, url
from django.views.generic import TemplateView

from repository.api_views import *

# Override handler403 to provide a custom permission denied page.
# Otherwise, a user has no links to get to their resources
# Esp. useful for 'next' redirection after login
handler403 = TemplateView.as_view(template_name='403.html')

# API routes
urlpatterns = patterns('repository.api_views',
    url(r'^api/repository/?$', 'repository_api_root', name='repository-api-root'),
    url(r'^api/repository/specimens/?$', SpecimenList.as_view(), name='specimen-list'),

    url(r'^api/repository/projects/?$', ProjectList.as_view(), name='project-list'),
    url(r'^api/repository/projects/(?P<pk>\d+)/?$', ProjectDetail.as_view(), name='project-detail'),
    url(r'^api/repository/project_panels/?$', ProjectPanelList.as_view(), name='project-panel-list'),
    url(r'^api/repository/project_panels/(?P<pk>\d+)/?$', ProjectPanelDetail.as_view(), name='project-panel-detail'),

    url(r'^api/repository/sites/?$', SiteList.as_view(), name='site-list'),
    url(r'^api/repository/sites/(?P<pk>\d+)/?$', SiteDetail.as_view(), name='site-detail'),
    url(r'^api/repository/site_panels/?$', SitePanelList.as_view(), name='site-panel-list'),
    url(r'^api/repository/site_panels/(?P<pk>\d+)/?$', SitePanelDetail.as_view(), name='site-panel-detail'),
    url(r'^api/repository/cytometers/?$', CytometerList.as_view(), name='cytometer-list'),
    url(r'^api/repository/cytometers/(?P<pk>\d+)/?$', CytometerDetail.as_view(), name='cytometer-detail'),

    url(r'^api/repository/subject_groups/?$', SubjectGroupList.as_view(), name='subject-group-list'),
    url(r'^api/repository/subjects/?$', SubjectList.as_view(), name='subject-list'),
    url(r'^api/repository/subjects/(?P<pk>\d+)/?$', SubjectDetail.as_view(), name='subject-detail'),

    url(r'^api/repository/visit_types/?$', VisitTypeList.as_view(), name='visit-type-list'),
    url(r'^api/repository/visit_types/(?P<pk>\d+)/?$', VisitTypeDetail.as_view(), name='visittype-detail'),

    url(r'^api/repository/stimulations/?$', StimulationList.as_view(), name='stimulation-list'),
    url(r'^api/repository/stimulations/(?P<pk>\d+)/?$', StimulationDetail.as_view(), name='stimulation-detail'),

    url(r'^api/repository/samples/?$', SampleList.as_view(), name='sample-list'),
    url(r'^api/repository/samples/add/?$', CreateSampleList.as_view(), name='create-sample-list'),
    url(r'^api/repository/samples/(?P<pk>\d+)/?$', SampleDetail.as_view(), name='sample-detail'),
    url(r'^api/repository/samples/(?P<pk>\d+)/fcs_original/?$', retrieve_sample, name='retrieve_sample'),
    url(r'^api/repository/samples/(?P<pk>\d+)/fcs/?$', retrieve_sample_as_pk, name='sample-download-as-pk'),
    url(r'^api/repository/samples/(?P<pk>\d+)/csv/?$', retrieve_subsample_as_csv, name='retrieve_subsample_as_csv'),
    url(r'^api/repository/samples/(?P<pk>\d+)/npy/?$', retrieve_subsample_as_numpy, name='retrieve_subsample_as_numpy'),

    url(r'^api/repository/samplemetadata/?$', SampleMetaDataList.as_view(), name='sample-metadata-list'),

    url(r'^api/repository/compensations/?$', CompensationList.as_view(), name='compensation-list'),
    url(r'^api/repository/compensations/add/?$', CreateCompensation.as_view(), name='create-compensation'),
    url(r'^api/repository/compensations/(?P<pk>\d+)/?$', CompensationDetail.as_view(), name='compensation-detail'),
    url(r'^api/repository/compensations/(?P<pk>\d+)/csv/?$', retrieve_compensation_as_csv, name='retrieve_compensation_as_csv'),
    url(r'^api/repository/compensations/(?P<pk>\d+)/npy/?$', retrieve_compensation_as_numpy, name='retrieve_compensation_as_numpy'),

    url(r'^api/repository/workers/?$', WorkerList.as_view(), name='worker-list'),
    url(r'^api/repository/verify_worker/?$', verify_worker, name='verify-worker'),
    url(r'^api/repository/process_requests/?$', ProcessRequestList.as_view(), name='process-request-list'),
    url(r'^api/repository/viable_process_requests/?$', ViableProcessRequestList.as_view(), name='viable-process-request-list'),
    url(r'^api/repository/assigned_process_requests/?$', AssignedProcessRequestList.as_view(), name='assigned-process-request-list'),
    url(r'^api/repository/process_requests/(?P<pk>\d+)/?$', ProcessRequestDetail.as_view(), name='process-request-detail'),
    url(r'^api/repository/process_requests/(?P<pk>\d+)/request_assignment/?$', ProcessRequestAssignmentUpdate.as_view(), name='process-request-assignment'),
    url(r'^api/repository/process_requests/(?P<pk>\d+)/revoke_assignment/?$', revoke_process_request_assignment, name='revoke-process-request-assignment'),
    url(r'^api/repository/process_requests/(?P<pk>\d+)/verify_assignment/?$', verify_process_request_assignment, name='verify-process-request-assignment'),
    url(r'^api/repository/process_requests/(?P<pk>\d+)/complete_assignment/?$', complete_process_request_assignment, name='complete-process-request-assignment'),
    url(r'^api/repository/process_request_outputs/add/?$', CreateProcessRequestOutput.as_view(), name='create-process-request-output'),
    url(r'^api/repository/process_request_outputs/(?P<pk>\d+)/download/?$', retrieve_process_request_output_value, name='retrieve_process_request_output'),
)

# Angular web routes
urlpatterns += patterns('repository.views',
    url(r'^samples/upload/$', 'fcs_upload_app', name='fcs_upload_app'),
    url(r'^processing/request/$', 'process_request_app', name='process_request_app'),
)

# Regular web routes
urlpatterns += patterns('repository.views',
    url(r'^403$', 'permission_denied', name='permission_denied'),
    url(r'^$', 'home', name='home'),
    url(r'^reflow_admin/$', 'admin', name='admin'),

    url(r'^markers/$', 'view_markers', name='view_markers'),
    url(r'^markers/add/$', 'add_marker', name='add_marker'),
    url(r'^markers/(?P<marker_id>\d+)/edit/$', 'add_marker', name='edit_marker'),

    url(r'^fluorochromes/$', 'view_fluorochromes', name='view_fluorochromes'),
    url(r'^fluorochromes/add/$', 'add_fluorochrome', name='add_fluorochrome'),
    url(r'^fluorochromes/(?P<fluorochrome_id>\d+)/edit/$', 'add_fluorochrome', name='edit_fluorochrome'),

    url(r'^specimens/$', 'view_specimens', name='view_specimens'),
    url(r'^specimens/add/$', 'add_specimen', name='add_specimen'),
    url(r'^specimens/(?P<specimen_id>\d+)/edit/$', 'edit_specimen', name='edit_specimen'),

    url(r'^project/(?P<project_id>\d+)/$', 'view_project', name='view_project'),
    url(r'^project/add/$', 'add_project', name='add_project'),
    url(r'^project/(?P<project_id>\d+)/edit/$', 'add_project', name='edit_project'),

    url(r'^project/(?P<project_id>\d+)/users/$', 'view_project_users', name='view_project_users'),
    url(r'^project/(?P<project_id>\d+)/users/add/$', 'add_user_permissions', name='add_user_permissions'),
    url(r'^project/(?P<project_id>\d+)/users/(?P<user_id>-?\d+)/manage/$', 'manage_project_user', name='manage_project_user'),
    url(r'^site/(?P<site_id>\d+)/users/(?P<user_id>-?\d+)/manage/$', 'manage_site_user', name='manage_site_user'),

    url(r'^project/(?P<project_id>\d+)/stimulations/$', 'view_project_stimulations', name='view_project_stimulations'),
    url(r'^project/(?P<project_id>\d+)/stimulations/add/$', 'add_stimulation', name='add_stimulation'),
    url(r'^project/(?P<project_id>\d+)/stimulations/(?P<stimulation_id>\d+)/edit/$', 'add_stimulation', name='edit_stimulation'),

    url(r'^project/(?P<project_id>\d+)/panels/$', 'view_project_panels', name='view_project_panels'),
    url(r'^project/(?P<project_id>\d+)/panels/add/$', 'add_project_panel', name='add_project_panel'),
    url(r'^project/(?P<project_id>\d+)/panels/(?P<panel_id>\d+)/edit/$', 'add_project_panel', name='edit_project_panel'),
    url(r'^project/(?P<project_id>\d+)/panels/(?P<panel_id>\d+)/copy/$', 'copy_project_panel', name='copy_project_panel'),

    url(r'^project/(?P<project_id>\d+)/sites/$', 'view_project_sites', name='view_project_sites'),
    url(r'^project/(?P<project_id>\d+)/sites/add/$', 'add_site', name='add_site'),
    url(r'^site/(?P<site_id>\d+)/edit/$', 'edit_site', name='edit_site'),

    url(r'^project/(?P<project_id>\d+)/cytometers/$', 'view_project_cytometers', name='view_project_cytometers'),
    url(r'^project/(?P<project_id>\d+)/cytometers/add/$', 'add_cytometer', name='add_cytometer'),
    url(r'^project/(?P<project_id>\d+)/cytometers/(?P<cytometer_id>\d+)/edit/$', 'add_cytometer', name='edit_cytometer'),

    url(r'^project/(?P<project_id>\d+)/compensations/$', 'view_compensations', name='project_compensations'),
    url(r'^project/(?P<project_id>\d+)/compensations/add/$', 'add_compensation', name='add_compensation'),
    url(r'^project/(?P<project_id>\d+)/compensations/(?P<compensation_id>\d+)/edit/$', 'add_compensation', name='edit_compensation'),

    url(r'^project/(?P<project_id>\d+)/visit_types/$', 'view_visit_types', name='project_visit_types'),
    url(r'^project/(?P<project_id>\d+)/visit_types/add/$', 'add_visit_type', name='add_visit_type'),
    url(r'^visit_types/(?P<visit_type_id>\d+)/edit/$', 'edit_visit_type', name='edit_visit_type'),

    url(r'^project/(?P<project_id>\d+)/site_panels/$', 'view_project_site_panels', name='view_project_site_panels'),
    url(r'^project/(?P<project_id>\d+)/site_panels/add/$', 'add_project_site_panel', name='add_project_site_panel'),
    url(r'^project/(?P<project_id>\d+)/site_panels/process_site_panel_post/$', 'process_site_panel_post', name='process_site_panel_post'),
    url(r'^site_panel/(?P<panel_id>\d+)/edit/$', 'edit_site_panel_comments', name='edit_site_panel_comments'),
    url(r'^site_panel/(?P<panel_id>\d+)/parameters/edit/$', 'edit_site_panel_parameters', name='edit_site_panel_parameters'),
    url(r'^parameter/(?P<panel_parameter_id>\d+)/remove/$', 'remove_panel_parameter', name='remove_panel_parameter'),

    url(r'^project/(?P<project_id>\d+)/subject_groups/$', 'view_subject_groups', name='subject_groups'),
    url(r'^project/(?P<project_id>\d+)/subject_groups/add/$', 'add_subject_group', name='add_subject_group'),
    url(r'^project/(?P<project_id>\d+)/subject_groups/(?P<subject_group_id>\d+)/edit/$', 'edit_subject_group', name='edit_subject_group'),

    url(r'^project/(?P<project_id>\d+)/subjects/$', 'view_subjects', name='view_subjects'),
    url(r'^project/(?P<project_id>\d+)/subjects/add/$', 'add_subject', name='add_subject'),
    url(r'^subject/(?P<subject_id>\d+)/edit/$', 'edit_subject', name='edit_subject'),

    url(r'^project/(?P<project_id>\d+)/samples/$', 'view_samples', name='view_project_samples'),
    url(r'^project/(?P<project_id>\d+)/samples/add/$', 'add_sample', name='add_sample'),
    url(r'^sample/(?P<sample_id>\d+)/edit/$', 'edit_sample', name='edit_sample'),
    url(r'^sample/(?P<sample_id>\d+)/parameters/$', 'render_sample_parameters', name='render_sample_parameters'),
    url(r'^sample/(?P<sample_id>\d+)/compensation/$', 'render_sample_compensation', name='render_sample_compensation'),

    url(r'^warning$', TemplateView.as_view(template_name='warning.html'), name='warning_page'),

    url(r'^processing/dashboard/$', 'process_dashboard', name='process_dashboard'),
    url(r'^processing/worker/add/$', 'add_worker', name='add_worker'),
    url(r'^processing/process_requests/(?P<process_request_id>\d+)/$', 'view_process_request', name='view_process_request'),
)<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab

"""
csv2ofx
~~~~~~~

Converts a csv file to ofx and qif

Examples:
    literal blocks::

        python example_google.py

Attributes:
    ENCODING (str): Default file encoding.
"""

from __future__ import (
    absolute_import, division, print_function, with_statement,
    unicode_literals)

import hashlib

from datetime import datetime as dt
from operator import itemgetter
from dateutil.parser import parse
from . import utils

__title__ = 'csv2ofx'
__package_name__ = 'csv2ofx'
__author__ = 'Reuben Cummings'
__description__ = 'converts a csv file of transactions to an ofx or qif file'
__email__ = 'reubano@gmail.com'
__version__ = '0.16.0'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015 Reuben Cummings'

md5 = lambda content: hashlib.md5(content.encode('utf-8')).hexdigest()

class Content(object):
    def __init__(self, mapping=None, **kwargs):
        """ Base content constructor
        Args:
            mapping (dict): bank mapper (see csv2ofx.mappings)
            kwargs (dict): Keyword arguments

        Kwargs:
            split_header (str): Transaction field to use for the split account.
            start (date): Date from which to begin including transactions.
            end (date): Date from which to exclude transactions.

        Examples:
            >>> from mappings.mint import mapping
            >>> Content(mapping)  #doctest: +ELLIPSIS
            <csv2ofx.Content object at 0x...>
        """
        mapping = mapping or {}
        [self.__setattr__(k, v) for k, v in mapping.items()]

        if not hasattr(self, 'is_split'):
            self.is_split = False

        if kwargs.get('split_header'):
            self.split_account = itemgetter(kwargs['split_header'])
        else:
            self.split_account = None

        self.start = kwargs.get('start', dt.now())
        self.end = kwargs.get('end', dt.now())

    def get(self, name, tr=None, default=None):
        """ Gets an attribute which could be either a normal attribute,
        a mapping function, or a mapping attribute

        Args:
            name (str): The attribute.
            tr (dict): The transaction. Require if `name` is a mapping function
                (default: None).

            default (str): Value to use if `name` isn't found (default: None).

        Returns:
            (mixed): Either the value of the attribute function applied to the
                transaction, or the value of the attribute.

        Examples:
            >>> from mappings.mint import mapping
            >>> tr = {'Transaction Type': 'debit', 'Amount': 1000.00}
            >>> start = dt(2015, 1, 1)
            >>> Content(mapping, start=start).get('start')  # normal attribute
            datetime.datetime(2015, 1, 1, 0, 0)
            >>> Content(mapping).get('amount', tr)  # mapping function
            1000.0
            >>> Content(mapping).get('has_header')  # mapping attribute
            True
        """
        try:
            attr = getattr(self, name)
        except AttributeError:
            attr = None
            value = None
        else:
            value = None

        try:
            value = value or attr(tr) if attr else default
        except TypeError:
            value = attr
        except KeyError:
            value = default

        return value

    def skip_transaction(self, tr):
        """ Determines whether a transaction should be skipped (isn't in the
        specified date range)

        Args:
            tr (dict): The transaction.

        Returns:
            (bool): Whether or not to skip the transaction.

        Examples:
            >>> from mappings.mint import mapping
            >>> tr = {'Date': '06/12/10', 'Amount': 1000.00}
            >>> Content(mapping, start=dt(2010, 1, 1)).skip_transaction(tr)
            False
            >>> Content(mapping, start=dt(2013, 1, 1)).skip_transaction(tr)
            True
        """
        return not (self.end >= parse(self.get('date', tr)) >= self.start)

    def convert_amount(self, tr):
        """ Converts a string amount into a number

        Args:
            tr (dict): The transaction.

        Returns:
            (decimal): The converted amount.

        Examples:
            >>> from mappings.mint import mapping
            >>> tr = {'Date': '06/12/10', 'Amount': '$1,000'}
            >>> Content(mapping, start=dt(2010, 1, 1)).convert_amount(tr)
            Decimal('1000.00')
        """
        return utils.convert_amount(self.get('amount', tr))

    def transaction_data(self, tr):
        """ gets transaction data

        Args:
            tr (dict): the transaction

        Returns:
            (dict): the QIF content

        Examples:
            >>> from mappings.mint import mapping
            >>> tr = {'Transaction Type': 'debit', 'Amount': 1000.00, \
'Date': '06/12/10', 'Description': 'payee', 'Original Description': \
'description', 'Notes': 'notes', 'Category': 'Checking', 'Account Name': \
'account'}
            >>> Content(mapping).transaction_data(tr)
            {u'account_id': 'e268443e43d93dab7ebef303bbe9642f', u'memo': \
u'description notes', u'split_account_id': None, u'currency': u'USD', \
u'date': datetime.datetime(2010, 6, 12, 0, 0), u'class': None, u'bank': \
u'account', u'account': u'account', u'split_account': None, u'bank_id': \
'e268443e43d93dab7ebef303bbe9642f', u'id': \
'ee86450a47899254e2faa82dca3c2cf2', u'payee': u'payee', u'amount': \
Decimal('-1000.00'), u'check_num': None, u'type': u'debit'}
        """
        account = self.get('account', tr)
        split_account = self.get('split_account', tr)
        bank = self.get('bank', tr, account)

        raw_amount = str(self.get('amount', tr))
        amount = self.convert_amount(tr)
        _type = self.get('type', tr)

        if _type:
            amount = -1 * amount if _type.lower() == 'debit' else amount
        else:
            _type = 'CREDIT' if amount > 0 else 'DEBIT'

        date = self.get('date', tr)
        payee = self.get('payee', tr)
        desc = self.get('desc', tr)
        notes = self.get('notes', tr)

        if desc and notes:
            memo = '%s %s' % (desc, notes)
        else:
            memo = desc or notes

        check_num = self.get('check_num', tr)
        details = utils.filter_join([date, raw_amount, payee, memo])

        return {
            'date': parse(date),
            'currency': self.get('currency', tr, 'USD'),
            'bank': bank,
            'bank_id': self.get('bank_id', tr, md5(bank)),
            'account': account,
            'account_id': self.get('account_id', tr, md5(account)),
            'split_account': split_account,
            'split_account_id': md5(split_account) if split_account else None,
            'amount': amount,
            'payee': payee,
            'memo': memo,
            'class': self.get('class', tr),
            'id': self.get('id', tr, check_num) or md5(details),
            'check_num': check_num,
            'type': _type,
        }
<commit_msg>Bump to version 0.16.1<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab

"""
csv2ofx
~~~~~~~

Converts a csv file to ofx and qif

Examples:
    literal blocks::

        python example_google.py

Attributes:
    ENCODING (str): Default file encoding.
"""

from __future__ import (
    absolute_import, division, print_function, with_statement,
    unicode_literals)

import hashlib

from datetime import datetime as dt
from operator import itemgetter
from dateutil.parser import parse
from . import utils

__title__ = 'csv2ofx'
__package_name__ = 'csv2ofx'
__author__ = 'Reuben Cummings'
__description__ = 'converts a csv file of transactions to an ofx or qif file'
__email__ = 'reubano@gmail.com'
__version__ = '0.16.1'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015 Reuben Cummings'

md5 = lambda content: hashlib.md5(content.encode('utf-8')).hexdigest()

class Content(object):
    def __init__(self, mapping=None, **kwargs):
        """ Base content constructor
        Args:
            mapping (dict): bank mapper (see csv2ofx.mappings)
            kwargs (dict): Keyword arguments

        Kwargs:
            split_header (str): Transaction field to use for the split account.
            start (date): Date from which to begin including transactions.
            end (date): Date from which to exclude transactions.

        Examples:
            >>> from mappings.mint import mapping
            >>> Content(mapping)  #doctest: +ELLIPSIS
            <csv2ofx.Content object at 0x...>
        """
        mapping = mapping or {}
        [self.__setattr__(k, v) for k, v in mapping.items()]

        if not hasattr(self, 'is_split'):
            self.is_split = False

        if kwargs.get('split_header'):
            self.split_account = itemgetter(kwargs['split_header'])
        else:
            self.split_account = None

        self.start = kwargs.get('start', dt.now())
        self.end = kwargs.get('end', dt.now())

    def get(self, name, tr=None, default=None):
        """ Gets an attribute which could be either a normal attribute,
        a mapping function, or a mapping attribute

        Args:
            name (str): The attribute.
            tr (dict): The transaction. Require if `name` is a mapping function
                (default: None).

            default (str): Value to use if `name` isn't found (default: None).

        Returns:
            (mixed): Either the value of the attribute function applied to the
                transaction, or the value of the attribute.

        Examples:
            >>> from mappings.mint import mapping
            >>> tr = {'Transaction Type': 'debit', 'Amount': 1000.00}
            >>> start = dt(2015, 1, 1)
            >>> Content(mapping, start=start).get('start')  # normal attribute
            datetime.datetime(2015, 1, 1, 0, 0)
            >>> Content(mapping).get('amount', tr)  # mapping function
            1000.0
            >>> Content(mapping).get('has_header')  # mapping attribute
            True
        """
        try:
            attr = getattr(self, name)
        except AttributeError:
            attr = None
            value = None
        else:
            value = None

        try:
            value = value or attr(tr) if attr else default
        except TypeError:
            value = attr
        except KeyError:
            value = default

        return value

    def skip_transaction(self, tr):
        """ Determines whether a transaction should be skipped (isn't in the
        specified date range)

        Args:
            tr (dict): The transaction.

        Returns:
            (bool): Whether or not to skip the transaction.

        Examples:
            >>> from mappings.mint import mapping
            >>> tr = {'Date': '06/12/10', 'Amount': 1000.00}
            >>> Content(mapping, start=dt(2010, 1, 1)).skip_transaction(tr)
            False
            >>> Content(mapping, start=dt(2013, 1, 1)).skip_transaction(tr)
            True
        """
        return not (self.end >= parse(self.get('date', tr)) >= self.start)

    def convert_amount(self, tr):
        """ Converts a string amount into a number

        Args:
            tr (dict): The transaction.

        Returns:
            (decimal): The converted amount.

        Examples:
            >>> from mappings.mint import mapping
            >>> tr = {'Date': '06/12/10', 'Amount': '$1,000'}
            >>> Content(mapping, start=dt(2010, 1, 1)).convert_amount(tr)
            Decimal('1000.00')
        """
        return utils.convert_amount(self.get('amount', tr))

    def transaction_data(self, tr):
        """ gets transaction data

        Args:
            tr (dict): the transaction

        Returns:
            (dict): the QIF content

        Examples:
            >>> from mappings.mint import mapping
            >>> tr = {'Transaction Type': 'debit', 'Amount': 1000.00, \
'Date': '06/12/10', 'Description': 'payee', 'Original Description': \
'description', 'Notes': 'notes', 'Category': 'Checking', 'Account Name': \
'account'}
            >>> Content(mapping).transaction_data(tr)
            {u'account_id': 'e268443e43d93dab7ebef303bbe9642f', u'memo': \
u'description notes', u'split_account_id': None, u'currency': u'USD', \
u'date': datetime.datetime(2010, 6, 12, 0, 0), u'class': None, u'bank': \
u'account', u'account': u'account', u'split_account': None, u'bank_id': \
'e268443e43d93dab7ebef303bbe9642f', u'id': \
'ee86450a47899254e2faa82dca3c2cf2', u'payee': u'payee', u'amount': \
Decimal('-1000.00'), u'check_num': None, u'type': u'debit'}
        """
        account = self.get('account', tr)
        split_account = self.get('split_account', tr)
        bank = self.get('bank', tr, account)

        raw_amount = str(self.get('amount', tr))
        amount = self.convert_amount(tr)
        _type = self.get('type', tr)

        if _type:
            amount = -1 * amount if _type.lower() == 'debit' else amount
        else:
            _type = 'CREDIT' if amount > 0 else 'DEBIT'

        date = self.get('date', tr)
        payee = self.get('payee', tr)
        desc = self.get('desc', tr)
        notes = self.get('notes', tr)

        if desc and notes:
            memo = '%s %s' % (desc, notes)
        else:
            memo = desc or notes

        check_num = self.get('check_num', tr)
        details = utils.filter_join([date, raw_amount, payee, memo])

        return {
            'date': parse(date),
            'currency': self.get('currency', tr, 'USD'),
            'bank': bank,
            'bank_id': self.get('bank_id', tr, md5(bank)),
            'account': account,
            'account_id': self.get('account_id', tr, md5(account)),
            'split_account': split_account,
            'split_account_id': md5(split_account) if split_account else None,
            'amount': amount,
            'payee': payee,
            'memo': memo,
            'class': self.get('class', tr),
            'id': self.get('id', tr, check_num) or md5(details),
            'check_num': check_num,
            'type': _type,
        }
<|endoftext|>


<commit_before>import psycopg2
import numpy as np
from pyiem.network import Table as NetworkTable
import datetime
from scipy import stats
import pandas as pd
from pyiem import meteorology
from pyiem.datatypes import temperature, mixingratio, pressure

PDICT2 = {'winter': 'Winter (Dec, Jan, Feb)',
          'spring': 'Spring (Mar, Apr, May)',
          'summer': 'Summer (Jun, Jul, Aug)',
          'fall': 'Fall (Sep, Oct, Nov)',
          'all': 'Entire Year'}

def get_description():
    """ Return a dict describing how to call this plotter """
    d = dict()
    d['data'] = True
    d['description'] = """Simple plot of seasonal or yearly average dew points.
    This calculation was done by computing the mixing ratio, then averaging
    the mixing ratios by year, and then converting that average to a dew point.
    This was done due to the non-linear nature of dew point.
    """
    d['arguments'] = [
        dict(type='zstation', name='station', default='DSM',
             label='Select Station'),
        dict(type='select', name='season', default='winter',
             label='Select Season:', options=PDICT2),
        dict(type="year", name="year", default=1893,
             label="Start Year of Plot"),
    ]
    return d

def plotter(fdict):
    """ Go """
    import matplotlib
    matplotlib.use('agg')
    import matplotlib.pyplot as plt
    pgconn = psycopg2.connect(database='asos', host='iemdb', user='nobody')
    cursor = pgconn.cursor()

    station = fdict.get('station', 'DSM')
    network = fdict.get('network', 'IA_ASOS')
    season = fdict.get('season', 'winter')
    _ = PDICT2[season]
    startyear = int(fdict.get('year', 1893))

    nt = NetworkTable(network)

    cursor.execute("""
      SELECT valid, dwpf from alldata where station = %s and dwpf > -90 and
      dwpf < 100
    """, (station, ))

    months = range(1, 13)
    today = datetime.datetime.now()
    lastyear = today.year
    if season == 'spring':
        months = [3, 4, 5]
        if today.month > 5:
            lastyear += 1
    if season == 'fall':
        months = [9, 10, 11]
        if today.month > 11:
            lastyear += 1
    if season == 'summer':
        months = [6, 7, 8]
        if today.month > 8:
            lastyear += 1
    if season == 'winter':
        months = [12, 1, 2]
        if today.month > 2:
            lastyear += 1

    rows = []
    for row in cursor:
        if (row[0].month not in months or row[0].year < startyear or
                row[0].year >= lastyear):
            continue
        yr = (row[0] + datetime.timedelta(days=31)).year
        r = meteorology.mixing_ratio(temperature(row[1], 'F')).value('KG/KG')
        rows.append(dict(year=yr, r=r))
    df = pd.DataFrame(rows)
    group = df.groupby('year')
    df = group.aggregate(np.average)

    def to_dwpf(val):
        return meteorology.dewpoint_from_pq(pressure(1000, 'MB'),
                                            mixingratio(val, 'KG/KG')
                                            ).value('F')
    df['r'] = df['r'].apply(to_dwpf)
    data = np.array(df['r'])
    years = np.array(df.index.astype('i'))

    (fig, ax) = plt.subplots(1, 1)
    avgv = np.average(data)

    colorabove = 'seagreen'
    colorbelow = 'lightsalmon'
    bars = ax.bar(years - 0.4, data, fc=colorabove, ec=colorabove)
    for i, bar in enumerate(bars):
        if data[i] < avgv:
            bar.set_facecolor(colorbelow)
            bar.set_edgecolor(colorbelow)
    ax.axhline(avgv, lw=2, color='k', zorder=2, label='Average')
    h_slope, intercept, r_value, _, _ = stats.linregress(years, data)
    ax.plot(years, h_slope * np.array(years) + intercept, '--',
            lw=2, color='k', label='Trend')
    ax.text(0.01, 0.99, "Avg: %.1f, slope: %.2f F/century, R$^2$=%.2f" % (
            avgv, h_slope * 100., r_value ** 2),
            transform=ax.transAxes, va='top', bbox=dict(color='white'))
    ax.set_xlabel("Year")
    ax.set_xlim(min(years)-1, max(years)+1)
    ax.set_ylim(min(data)-5, max(data) + max(data)/10.)
    ax.set_ylabel("Average Dew Point [F]")
    ax.grid(True)
    msg = ("[%s] %s %.0f-%.0f Average Dew Point [%s] "
           ) % (station, nt.sts[station]['name'],
                min(years), max(years),  PDICT2[season])
    tokens = msg.split()
    sz = len(tokens) / 2
    ax.set_title(" ".join(tokens[:sz]) + "\n" + " ".join(tokens[sz:]))
    ax.legend(ncol=1)

    return fig, df
<commit_msg>allow for monthly avg dewpoints<commit_after>import psycopg2
import numpy as np
from pyiem.network import Table as NetworkTable
import datetime
from scipy import stats
import pandas as pd
from pyiem import meteorology
from collections import OrderedDict
from pyiem.datatypes import temperature, mixingratio, pressure

MDICT = OrderedDict([
         ('all', 'No Month/Time Limit'),
         ('spring', 'Spring (MAM)'),
         ('fall', 'Fall (SON)'),
         ('winter', 'Winter (DJF)'),
         ('summer', 'Summer (JJA)'),
         ('jan', 'January'),
         ('feb', 'February'),
         ('mar', 'March'),
         ('apr', 'April'),
         ('may', 'May'),
         ('jun', 'June'),
         ('jul', 'July'),
         ('aug', 'August'),
         ('sep', 'September'),
         ('oct', 'October'),
         ('nov', 'November'),
         ('dec', 'December')])

def get_description():
    """ Return a dict describing how to call this plotter """
    d = dict()
    d['data'] = True
    d['description'] = """Simple plot of yearly average dew points by year,
    season, or month.
    This calculation was done by computing the mixing ratio, then averaging
    the mixing ratios by year, and then converting that average to a dew point.
    This was done due to the non-linear nature of dew point when expressed in
    units of temperature.
    """
    d['arguments'] = [
        dict(type='zstation', name='station', default='DSM',
             label='Select Station'),
        dict(type='select', name='season', default='winter',
             label='Select Time Period:', options=MDICT),
        dict(type="year", name="year", default=1893,
             label="Start Year of Plot"),
    ]
    return d

def plotter(fdict):
    """ Go """
    import matplotlib
    matplotlib.use('agg')
    import matplotlib.pyplot as plt
    pgconn = psycopg2.connect(database='asos', host='iemdb', user='nobody')
    cursor = pgconn.cursor()

    station = fdict.get('station', 'DSM')
    network = fdict.get('network', 'IA_ASOS')
    season = fdict.get('season', 'winter')
    _ = MDICT[season]
    startyear = int(fdict.get('year', 1893))

    nt = NetworkTable(network)

    today = datetime.datetime.now()
    lastyear = today.year
    if season == 'all':
        months = range(1, 13)
    elif season == 'spring':
        months = [3, 4, 5]
        if today.month > 5:
            lastyear += 1
    elif season == 'fall':
        months = [9, 10, 11]
        if today.month > 11:
            lastyear += 1
    elif season == 'summer':
        months = [6, 7, 8]
        if today.month > 8:
            lastyear += 1
    elif season == 'winter':
        months = [12, 1, 2]
        if today.month > 2:
            lastyear += 1
    else:
        ts = datetime.datetime.strptime("2000-"+season+"-01", '%Y-%b-%d')
        # make sure it is length two for the trick below in SQL
        months = [ts.month, 999]
        lastyear += 1

    cursor.execute("""
      SELECT valid, dwpf from alldata where station = %s and dwpf > -90 and
      dwpf < 100 and extract(month from valid) in %s
    """, (station,  tuple(months)))

    rows = []
    for row in cursor:
        if (row[0].month not in months or row[0].year < startyear or
                row[0].year >= lastyear):
            continue
        yr = (row[0] + datetime.timedelta(days=31)).year
        r = meteorology.mixing_ratio(temperature(row[1], 'F')).value('KG/KG')
        rows.append(dict(year=yr, r=r))
    df = pd.DataFrame(rows)
    group = df.groupby('year')
    df = group.aggregate(np.average)

    def to_dwpf(val):
        return meteorology.dewpoint_from_pq(pressure(1000, 'MB'),
                                            mixingratio(val, 'KG/KG')
                                            ).value('F')
    df['r'] = df['r'].apply(to_dwpf)
    data = np.array(df['r'])
    years = np.array(df.index.astype('i'))

    (fig, ax) = plt.subplots(1, 1)
    avgv = np.average(data)

    colorabove = 'seagreen'
    colorbelow = 'lightsalmon'
    bars = ax.bar(years - 0.4, data, fc=colorabove, ec=colorabove)
    for i, bar in enumerate(bars):
        if data[i] < avgv:
            bar.set_facecolor(colorbelow)
            bar.set_edgecolor(colorbelow)
    ax.axhline(avgv, lw=2, color='k', zorder=2, label='Average')
    h_slope, intercept, r_value, _, _ = stats.linregress(years, data)
    ax.plot(years, h_slope * np.array(years) + intercept, '--',
            lw=2, color='k', label='Trend')
    ax.text(0.01, 0.99, "Avg: %.1f, slope: %.2f F/century, R$^2$=%.2f" % (
            avgv, h_slope * 100., r_value ** 2),
            transform=ax.transAxes, va='top', bbox=dict(color='white'))
    ax.set_xlabel("Year")
    ax.set_xlim(min(years)-1, max(years)+1)
    ax.set_ylim(min(data)-5, max(data) + max(data)/10.)
    ax.set_ylabel("Average Dew Point [F]")
    ax.grid(True)
    msg = ("[%s] %s %.0f-%.0f Average Dew Point [%s] "
           ) % (station, nt.sts[station]['name'],
                min(years), max(years),  MDICT[season])
    tokens = msg.split()
    sz = len(tokens) / 2
    ax.set_title(" ".join(tokens[:sz]) + "\n" + " ".join(tokens[sz:]))
    ax.legend(ncol=1)

    return fig, df
<|endoftext|>


<commit_before>"""
calculatepi.py
Author: Glen Passow
Credit: Hagin
Assignment:

Write and submit a Python program that computes an approximate value of π by calculating the following sum:

(see: https://github.com/HHS-IntroProgramming/Calculate-Pi/blob/master/README.md)

This sum approaches the true value of π as n approaches ∞.

Your program must ask the user how many terms to use in the estimate of π, how many decimal places,
then print the estimate using that many decimal places. Exactly like this:

I will estimate pi. How many terms should I use? 100
How many decimal places should I use in the result? 7
The approximate value of pi is 3.1315929

Note: remember that the printed value of pi will be an estimate!

"""
import math
pi = int(input("I will estimate pi. How many terms should I use? "))
decimals = int(input("How many decimal places should I use in the result? "))
pi = 4*sum([((-1.0)**k)/math.factorial(2*k+1) for k in range(0,n)])
print("The approximate value of pi is {0}".format(round(pi, decimals)))
print("(The true value of pi is {0})".format(round(math.pi, decimals)))

print("Note: remember that the printed value of pi will be an estimate!")<commit_msg>Updated from Brython Server: February 3, 2016 1:24:23 PM EST<commit_after>"""
calculatepi.py
Author: Glen Passow
Credit: Hagin
Assignment:

Write and submit a Python program that computes an approximate value of π by calculating the following sum:

(see: https://github.com/HHS-IntroProgramming/Calculate-Pi/blob/master/README.md)

This sum approaches the true value of π as n approaches ∞.

Your program must ask the user how many terms to use in the estimate of π, how many decimal places,
then print the estimate using that many decimal places. Exactly like this:

I will estimate pi. How many terms should I use? 100
How many decimal places should I use in the result? 7
The approximate value of pi is 3.1315929

Note: remember that the printed value of pi will be an estimate!

"""
import math
n = int(input("I will estimate pi. How many terms should I use? "))
decimals = int(input("How many decimal places should I use in the result? "))
pi = 4*sum([((-1.0)**k)/math.factorial(2*k+1) for k in range(0,n)])
print("The approximate value of pi is {0}".format(round(pi, decimals)))
print("(The true value of pi is {0})".format(round(math.pi, decimals)))

print("Note: remember that the printed value of pi will be an estimate!")<|endoftext|>


<commit_before>import logging
from pymongo import MongoClient, database, collection

# from pymongo.errors import DuplicateKeyError
# from pymongo.errors import OperationFailure

class MongoInterface:
    def __init__(self):
        self._logger = logging.getLogger('spud')
        self._db = database.Database(MongoClient(), 'spud')

        self.print_collections()
        # self.duplicate_error = DuplicateKeyError
        # self.index_error = OperationFailure

    # print all collections
    def print_collections(self):
        self._logger.debug(self._db.collection_names())

    # return all documents in a collection
    def fetch_all(self, _collection):
        return self.query(_collection)

    # return specific documents in a collection
    def query(self, _collection, **kwargs):
        query = kwargs.get('query', None)
        per_page = kwargs.get('per_page', 20)
        page = kwargs.get('page', 1)
        # figure out how many records to skip
        offset = per_page * (page-1)

        q = collection.Collection(self._db, _collection)
        if query is not None:
            q = q.find(query)
        else:
            q = q.find()
        q = q.limit(per_page)
        q = q.skip(offset)

        total =q.count()
        has_more = offset + per_page < total
        meta = {
            'total': total,
            'page': page,
            'per_page': per_page,
            'has_more': has_more,
        }
        return list(q), meta

    # save document to a collection
    def save(self, _collection, document):
        collection.Collection(self._db, _collection).save(document)
<commit_msg>Rename _db in mongo, for backwards compatibility<commit_after>import logging
from pymongo import MongoClient, database, collection

# from pymongo.errors import DuplicateKeyError
# from pymongo.errors import OperationFailure

class MongoInterface:
    def __init__(self):
        self._logger = logging.getLogger('spud')
        self.db = database.Database(MongoClient(), 'spud')

        self.print_collections()
        # self.duplicate_error = DuplicateKeyError
        # self.index_error = OperationFailure

    # print all collections
    def print_collections(self):
        self._logger.debug(self.db.collection_names())

    # return all documents in a collection
    def fetch_all(self, _collection):
        return self.query(_collection)

    # return specific documents in a collection
    def query(self, _collection, **kwargs):
        query = kwargs.get('query', None)
        per_page = kwargs.get('per_page', 20)
        page = kwargs.get('page', 1)
        # figure out how many records to skip
        offset = per_page * (page-1)

        q = collection.Collection(self.db, _collection)
        if query is not None:
            q = q.find(query)
        else:
            q = q.find()
        q = q.limit(per_page)
        q = q.skip(offset)

        total =q.count()
        has_more = offset + per_page < total
        meta = {
            'total': total,
            'page': page,
            'per_page': per_page,
            'has_more': has_more,
        }
        return list(q), meta

    # save document to a collection
    def save(self, _collection, document):
        collection.Collection(self.db, _collection).save(document)
<|endoftext|>