"""
Basic states for planning - wrapper for move_group interface
"""
import roslib; roslib.load_manifest('clopema_smach')
import rospy, smach, PyKDL, tf_conversions, geometry_msgs, copy

from smach import State
from smach_ros      import ServiceState
from clopema_smach  import *
from moveit_commander import MoveGroupCommander
from clopema_smach.msg import MA1400JointState
from clopema_moveit.srv import ClopemaJointInterpolation, ClopemaLinearInterpolation, ClopemaLinearInterpolationDual
import sensor_msgs
from sensor_msgs.msg._JointState import JointState

def resolve_planning_group(ik_link):
    """
    Return planning group based on the link name
    """
    if ik_link.startswith("r1_"):
        return "r1_arm"
    elif ik_link.startswith("r2_"):
        return "r2_arm"
    elif ik_link.startswith("xtion1"):
        return "r1_xtion"
    elif ik_link.startswith("xtion2"):
        return "r2_xtion"
    return None

def transform_to_tip(group, ee_frame, goal):
    """
    Transform the goal from the ee_frame to the tip link which is
    resolved from planning group
    return (new_goal, tip_frame)
    """
    mc = MoveGroupCommander(group)
    tip_frame = mc.get_end_effector_link()

    ee_pose = mc.get_current_pose(ee_frame)
    tip_pose = mc.get_current_pose(tip_frame)
    kdl_ee = tf_conversions.fromMsg(ee_pose.pose)
    kdl_tip = tf_conversions.fromMsg(tip_pose.pose)
    if isinstance(goal, geometry_msgs.msg.Pose):
        kdl_goal = tf_conversions.fromMsg(goal)
    elif isinstance(goal, geometry_msgs.msg.PoseStamped):
        kdl_goal = tf_conversions.fromMsg(goal.pose)
    else:
        rospy.logerr("Unknown pose type, only Pose and PoseStamped is allowed")
        rospy.logerr(str(type(goal)))
        return (None, tip_frame)

    grip = kdl_tip.Inverse() * kdl_ee
    kdl_pose = kdl_goal * grip.Inverse()

    return (tf_conversions.toMsg(kdl_pose), tip_frame)

class Plan1ToJointsState(State):
    def __init__(self):
        smach.State.__init__(self, outcomes=['succeeded', 'aborted'],
                                input_keys=['goal', 'robot'],
                                output_keys=['trajectory'])

    def execute(self, userdata):
        goal = userdata.goal
        mc = MoveGroupCommander("r" + str(userdata.robot) + "_arm")
        for joint in goal.__slots__:
            mc.set_joint_value_target("r" + str(userdata.robot) + "_joint_" + str(joint), getattr(goal, joint))
        plan = mc.plan()
        userdata.trajectory = plan.joint_trajectory
        if not plan.joint_trajectory.points:
            return 'aborted'
        return 'succeeded'

class Plan2ToJointsState(State):
    def __init__(self):
        smach.State.__init__(self, outcomes=['succeeded', 'aborted'],
                                input_keys=['goal_r1', 'goal_r2'],
                                output_keys=['trajectory'])

    def execute(self, userdata):
        goal_r1 = userdata.goal_r1
        goal_r2 = userdata.goal_r2
        mc = MoveGroupCommander("arms")
        for joint in goal_r1.__slots__:
            mc.set_joint_value_target("r1_joint_" + str(joint), getattr(goal_r1, joint))
        for joint in goal_r2.__slots__:
            mc.set_joint_value_target("r2_joint_" + str(joint), getattr(goal_r2, joint))
        plan = mc.plan()
        userdata.trajectory = plan.joint_trajectory
        if not plan.joint_trajectory.points:
            return 'aborted'
        return 'succeeded'

class PlanToHomeState(State):
    def __init__(self):
        smach.State.__init__(self, outcomes=['succeeded', 'aborted'],
                                output_keys=['trajectory'])

    def execute(self, userdata):
        goal_r1 = MA1400JointState()
        goal_r2 = MA1400JointState()
        mc = MoveGroupCommander("arms")
        for joint in goal_r1.__slots__:
            mc.set_joint_value_target("r1_joint_" + str(joint), getattr(goal_r1, joint))
        for joint in goal_r2.__slots__:
            mc.set_joint_value_target("r2_joint_" + str(joint), getattr(goal_r2, joint))
        plan = mc.plan()
        userdata.trajectory = plan.joint_trajectory
        if not plan.joint_trajectory.points:
            return 'aborted'
        return 'succeeded'

class Plan1ToPoseState(State):
    def __init__(self):
        smach.State.__init__(self, outcomes=['succeeded', 'aborted'],
                                input_keys=['goal', 'ik_link'],
                                output_keys=['trajectory'])

    def execute(self, userdata):
        group = resolve_planning_group(userdata.ik_link)
        if not group:
            return 'aborted'

        (goal, tip_frame) = transform_to_tip(group, userdata.ik_link, userdata.goal)
        mc = MoveGroupCommander(group)
        mc.set_pose_target(goal, tip_frame)
        plan = mc.plan()
        userdata.trajectory = plan.joint_trajectory
        if not plan.joint_trajectory.points:
            return 'aborted'
        return 'succeeded'

"""
class Plan1BetweenPosesState(ServiceState):
    def __init__(self):
        ServiceState.__init__(self, '/clopema_planning_actions/plan_between_poses',
                              PlanBetweenPoses, request_slots=['start_pose', 'goal', 'ik_link'],
                              response_cb=self._res_cb, response_slots=['trajectory', 'error'])

    def _res_cb(self, ud, res):
        if res.error.val == 1:
            return 'succeeded'
        else:
            return 'aborted'
"""

class Plan2ToPoseState(State):
    def __init__(self):
        smach.State.__init__(self, outcomes=['succeeded', 'aborted'],
                                input_keys=['goal_1', 'ik_link_1', 'goal_2', 'ik_link_2'],
                                output_keys=['trajectory'])

    def execute(self, userdata):
        group = 'arms'
        mc = MoveGroupCommander(group)
        group_1 = resolve_planning_group(userdata.ik_link_1)
        (goal_1, tip_frame_1) = transform_to_tip(group_1, userdata.ik_link_1, userdata.goal_1)
        group_2 = resolve_planning_group(userdata.ik_link_2)
        (goal_2, tip_frame_2) = transform_to_tip(group_2, userdata.ik_link_2, userdata.goal_2)
        mc.set_pose_target(goal_1, tip_frame_1)
        mc.set_pose_target(goal_2, tip_frame_2)
        plan = mc.plan()
        userdata.trajectory = plan.joint_trajectory
        if not plan.joint_trajectory.points:
            return 'aborted'
        return 'succeeded'

class GetRobotStateState(State):
    def __init__(self):
        smach.State.__init__(self, outcomes=['succeeded', 'aborted'],
                              output_keys=['robot_1_state', 'robot_2_state', 'complete_state', 'robot_1_pose', 'robot_2_pose', 'ik_link_1', 'ik_link_2'])

    def execute(self, userdata):
        mc = MoveGroupCommander("r1_arm")
        userdata.robot_1_state = mc.get_current_joint_values()
        userdata.ik_link_1 = mc.get_end_effector_link()
        userdata.robot_1_pose = mc.get_current_pose()

        mc = MoveGroupCommander("r2_arm")
        userdata.robot_2_state = mc.get_current_joint_values()
        userdata.ik_link_2 = mc.get_end_effector_link()
        userdata.robot_2_pose = mc.get_current_pose()

        mc = MoveGroupCommander("arms")
        userdata.complete_state = mc.get_current_joint_values()
        return 'succeeded'

class Interpolate1JointsState(ServiceState):
    def __init__(self):
        ServiceState.__init__(self, '/clopema_planner/joint_interpolation', ClopemaJointInterpolation(),
                              request_cb=self._req_cb, input_keys=['robot', 'goals'],
                              response_cb=self._res_cb, output_keys=['trajectory'])

    def _req_cb(self, ud, req):
        msg = JointState()
        msg.name.append('r' + str(ud.robot) + '_joint_s')
        msg.name.append('r' + str(ud.robot) + '_joint_l')
        msg.name.append('r' + str(ud.robot) + '_joint_u')
        msg.name.append('r' + str(ud.robot) + '_joint_r')
        msg.name.append('r' + str(ud.robot) + '_joint_b')
        msg.name.append('r' + str(ud.robot) + '_joint_t')
        for g in ud.goals:
            msg.position = []
            msg.position.append(g.s)
            msg.position.append(g.l)
            msg.position.append(g.u)
            msg.position.append(g.r)
            msg.position.append(g.b)
            msg.position.append(g.t)
            req.poses.append(copy.deepcopy(msg))

    def _res_cb(self, ud, res):
        ud.trajectory = res.joint_trajectory
        if res.error:
            rospy.logerr('Can not interpolate because: ' + res.error)
            return 'aborted'
        return 'succeeded'

class Interpolate1LinearState(ServiceState):
    def __init__(self):
        ServiceState.__init__(self, '/clopema_planner/linear_interpolation', ClopemaLinearInterpolation(),
                              request_cb=self._req_cb, input_keys=['ik_link', 'poses'],
                              response_cb=self._res_cb, output_keys=['trajectory'])

    def _req_cb(self, ud, req):
        req.ik_link_name = ud.ik_link
        for pose in ud.poses:
            req.header.frame_id = pose.header.frame_id
            break #set to the first pose if exist
        for pose in ud.poses:
            if not req.header.frame_id == pose.header.frame_id:
                rospy.logerr('Can not interpolate for poses in different frames')
                req.ik_link_name = ''
                req.poses = []
                return
            req.poses.append(pose.pose)

    def _res_cb(self, ud, res):
        ud.trajectory = res.joint_trajectory
        if res.error:
            rospy.logerr('Can not interpolate because: ' + res.error)
            return 'aborted'
        return 'succeeded'

class Interpolate2LinearState(ServiceState):
    def __init__(self):
        ServiceState.__init__(self, '/clopema_planner/linear_interpolation_dual', ClopemaLinearInterpolationDual(),
                              request_cb=self._req_cb, input_keys=['ik_link_1', 'poses_1', 'ik_link_2', 'poses_2'],
                              response_cb=self._res_cb, output_keys=['trajectory'])

    def _req_cb(self, ud, req):
        for pose in ud.poses_1:
            req.header.frame_id = pose.header.frame_id
            break #set to the first pose if exist
        if not (len(ud.poses_1) == len(ud.poses_2)):
            rospy.logerr('Number of poses must be equal for both groups')
            req.ik_link_name_1 = ''
            req.ik_link_name_2 = ''
            return

        req.ik_link_name_1 = ud.ik_link_1
        req.ik_link_name_2 = ud.ik_link_2

        for pose in ud.poses_1:
            if not req.header.frame_id == pose.header.frame_id:
                rospy.logerr('Can not interpolate for poses in different frames')
                req.ik_link_name_1 = ''
                req.ik_link_name_2 = ''
                req.poses_1 = []
                req.poses_2 = []
                return
            req.poses_1.append(pose.pose)
        for pose in ud.poses_2:
            if not req.header.frame_id == pose.header.frame_id:
                rospy.logerr('Can not interpolate for poses in different frames')
                req.ik_link_name_1 = ''
                req.ik_link_name_2 = ''
                req.poses_1 = []
                req.poses_2 = []
                return
            req.poses_2.append(pose.pose)

    def _res_cb(self, ud, res):
        ud.trajectory = res.joint_trajectory
        if res.error:
            rospy.logerr('Can not interpolate because: ' + res.error)
            return 'aborted'
        return 'succeeded'

"""
class Plan2ToPoseStateNotTearing(ServiceState):
    def __init__(self):
        ServiceState.__init__(self, '/clopema_planning_actions/plan_2_to_pose_not_tearing',
                              Plan2ToPoseNotTearing, request_slots=['goal_1', 'ik_link_1', 'goal_2', 'ik_link_2', 'cloth_size'],
                              response_cb=self._res_cb, response_slots=['trajectory', 'error'])

    def _res_cb(self, ud, res):
        if res.error.val == 1:
            return 'succeeded'
        else:
            return 'aborted'
"""
class Plan2ToPoseStateNotTearing(State):
    def __init__(self):
        smach.State.__init__(self, outcomes=['succeeded', 'aborted'],
                                input_keys=['goal_1', 'ik_link_1', 'goal_2', 'ik_link_2','cloth_size'],
                                output_keys=['trajectory'])

    def execute(self, userdata):
        group = 'arms'
        mc = MoveGroupCommander(group)
        group_1 = resolve_planning_group(userdata.ik_link_1)
        (goal_1, tip_frame_1) = transform_to_tip(group_1, userdata.ik_link_1, userdata.goal_1)
        group_2 = resolve_planning_group(userdata.ik_link_2)
        (goal_2, tip_frame_2) = transform_to_tip(group_2, userdata.ik_link_2, userdata.goal_2)
        mc.set_pose_target(goal_1, tip_frame_1)
        mc.set_pose_target(goal_2, tip_frame_2)

        plan = mc.plan()
        userdata.trajectory = plan.joint_trajectory
        if not plan.joint_trajectory.points:
            return 'aborted'
        return 'succeeded'

class PlanExtAxisState(State):
    def __init__(self):
        smach.State.__init__(self, outcomes=['succeeded', 'aborted'],
                                input_keys=['position'],
                                output_keys=['trajectory'])

    def execute(self, userdata):
        mc = MoveGroupCommander("ext")
        mc.set_joint_value_target("ext_axis", userdata.position)
        plan = mc.plan()
        userdata.trajectory = plan.joint_trajectory
        if not plan.joint_trajectory.points:
            return 'aborted'
        return 'succeeded'

Plan1ToXtionPoseState = Plan1ToPoseState


import xml.etree.ElementTree as ET
import pprint

def count_tags(filename):
    tags = {}
    for event, elem in ET.iterparse(filename):
        if elem.tag not in tags.keys():
            tags[elem.tag] = 1
        else:
            tags[elem.tag] += 1
    return tags

def test():

    tags = count_tags('shenzhen_china.osm')
    pprint.pprint(tags)

if __name__ == "__main__":
    test()


from datetime import datetime
from airflow.models import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator

default_args = {
    'owner': 'homer_j_simpsom',
    'start_date': datetime(2020, 5, 20, 11, 0, 0)
}

def write_title():
    print("El uso de Airflow en la universidad de Springfield.")

def write_intro():
    print("El otro día mi hija me dijo que Airflow no se utilizaba en la universidad de Springfield, y yo le dije: qué no Lisa? qué no?")

def write_body():
    for i in range(50):
        print("Púdrete Flanders")

with DAG('dag_homer_essay',
         default_args=default_args,
         schedule_interval='@daily') as dag:

    start = DummyOperator(task_id='start')
    wr_title = PythonOperator(task_id='wr_title',python_callable=write_title)
    wr_intro = PythonOperator(task_id='wr_intro',python_callable=write_intro)
    wr_body = PythonOperator(task_id='wr_body',python_callable=write_body)
    end = DummyOperator(task_id='end')

start >> wr_title >> wr_intro >> wr_body >> end


from typing import List
from typing import Dict

class Garden:
    def __init__(self, diagram: str, students: List[str] = None):
        self.DEFAULT_STUDENTS: List[str] = [
            'Alice',
            'Bob',
            'Charlie',
            'David',
            'Eve',
            'Fred',
            'Ginny',
            'Harriet',
            'Ileana',
            'Joseph',
            'Kincaid',
            'Larry',
        ]
        self.students = sorted(students or self.DEFAULT_STUDENTS)
        self.diagram: List[str] = diagram.split('\n')
        self.columns: int = len(self.diagram[0])/2
        self.plant_codes: Dict[str, str] = {
            'V': 'Violets',
            'C': 'Clover',
            'R': 'Radishes',
            'G': 'Grass',
        }
        self.student_index = {c: i for i, c in enumerate(self.students)}

    def plants(self, student: str) -> List[str]:
        # Let the KeyError thrown, denote invalid input - no such student
        index = self.student_index[student]
        if self.columns < index:
            raise ValueError(student + " has no cup in the garden")
        index *= 2
        return [self.plant_codes[code] for row in self.diagram
                for code in row[index:index+2]]


#character library
import string

lower = list(string.ascii_lowercase)
upper = list(string.ascii_lowercase)

def rot13(msg):
    result = ''
    for character in msg:
        if character in upper:
            result += upper[(upper.index(character) + 13) % 26]
        elif character in lower:
            result += lower[(lower.index(character) + 19) %26]
        else:
            result += character
    return result

print(rot13("Hallo das ist ein Test"))
print(rot13("Hnyyb qnf vfg rva Trfg"))


import numpy as np
import argparse, sys, os, time, glob

import pandas as pd

#%% Functions
def load_args():
    ap = argparse.ArgumentParser(
        description='Print train statistics stored on the csv log files.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    # Positional arguments
    ap.add_argument('summary_dirs',
        help='Directory with the train summary information.',
        nargs='*',
        type=str)

    # Optional arguments
    ap.add_argument('-c','--criteria',
        help="criteria for picking the best epoch",
        choices=['val_acc', 'val_loss'])
    ap.add_argument('-u','--update',
        help="update summary file (overwrite)",
        action='store_true')
    ap.add_argument('-s','--seqs-eval',
        help="evaluation over sequences average (sample 'all')",
        action='store_true')

    ap.add_argument('--print_args',
        help="whether to print current arguments' values",
        action='store_false')
        # action='store_true')

    args = ap.parse_args()

    return args

def read_runs(summary_dir, criteria=None, seqs_eval=False):
    if not seqs_eval: # Central frames only
        summary_filename = '/summary.csv'
        run_filename = '/fit_history.csv'
        log_filename = '/training.log'
    else:
        summary_filename = '/summary-pooled_val_acc.csv'
        run_filename = '/pooled_val_acc.csv'
        log_filename = run_filename

    hist_paths = glob.glob(summary_dir+'/fold_*'+summary_filename)
    hist_paths.sort()

    folds_with_summary = [ hist_path.split('/')[-2] for hist_path in hist_paths ]

    reruns_dirs = glob.glob(summary_dir+'/rerun_*/') + glob.glob(summary_dir+'/fold_*/')
    reruns_dirs.sort()

    reruns_dirs = [ r for r in reruns_dirs
        if not any( fold in r for fold in folds_with_summary) ]

    for rerun_dir in reruns_dirs:
        if 'rerun' in rerun_dir:
            rerun_hist = glob.glob(rerun_dir + run_filename)
            if rerun_hist == []:
                rerun_hist = glob.glob(rerun_dir + log_filename)
                if rerun_hist != []:
                    if os.stat(rerun_hist[0]).st_size != 0: # log is not empty
                        print("WARNING: Training not finished for '{}', using '{}'".format(
                            rerun_dir.split('/')[-2], log_filename))
                    else:
                        rerun_hist = []
        else:
            print("WARNING: Training not finished for '{}', using '{}'".format(
                            rerun_dir.split('/')[-2], log_filename))
            fold_reruns_dirs = glob.glob(rerun_dir+'/rerun_*/')
            fold_reruns_dirs.sort()

            fold_best_epochs = read_runs(rerun_dir, criteria=criteria, seqs_eval=seqs_eval)
            if fold_best_epochs != []:
                fold_df = pd.concat(fold_best_epochs, axis=1, sort=False).T.reset_index(drop=True)
                best_rerun = fold_reruns_dirs[fold_df.val_acc.idxmax()]
                best_hist = glob.glob(best_rerun + run_filename) + glob.glob(best_rerun + log_filename)

                rerun_hist = [ best_hist[0] ]
            else:
                rerun_hist = []
        hist_paths += rerun_hist

    hist_paths.sort()

    best_epochs = []
    for rerun_idx, hist_path in enumerate(hist_paths):
        hist_df = pd.read_csv(hist_path)

        if criteria.endswith('loss'):
            best_epoch = hist_df.loc[hist_df[criteria].idxmin()]
        elif criteria.endswith('acc'):
            if not seqs_eval: # Central frames only
                sorted_hist_df = hist_df.sort_values([criteria, 'val_loss'],
                    ascending=[False, True])
            else:
                sorted_hist_df = hist_df.sort_values([criteria], ascending=[False])
            best_epoch = sorted_hist_df.iloc[0]

        best_epochs.append(best_epoch)

    return best_epochs

def pretty_print_stats(stats_df, short_version=False, seqs_eval=False):
    acc_tpl = "{:.2%}".format
    loss_tpl = "{:.4f}".format
    epoc_tpl = "{:.0f}".format
    print_order = ['acc','loss','val_acc','val_loss','epoch']

    if short_version:
        print_order = ['val_acc','val_loss']
        stats_df = stats_df[stats_df.index == 'mean']

    if seqs_eval:
        print_order = ['val_acc']

    print(stats_df[print_order].to_string(
        formatters=[acc_tpl,loss_tpl,acc_tpl,loss_tpl,epoc_tpl]))

def print_train_stats(summary_dir, criteria=None, update=False, seqs_eval=False):
    if not seqs_eval: # Central frames only
        summary_filename = '/summary.csv'
    else:
        summary_filename = '/summary-pooled_val_acc.csv'

    if not os.path.exists(summary_dir+summary_filename):
        criteria = 'val_acc'

    if criteria is None:
        summary_df = pd.read_csv(summary_dir+summary_filename, index_col=False)
    else:
        best_epochs = read_runs(summary_dir, criteria=criteria, seqs_eval=seqs_eval)
        if best_epochs == []:
            print("ERROR: Unable to read summary.csv or fit_history.csv")
            return
        summary_df = pd.concat(best_epochs, axis=1, sort=False).T.reset_index(drop=True)

    summary_df.drop('mean', errors='ignore', inplace=True)
    summary_df.drop('std', errors='ignore', inplace=True)

    if update:
        summary_df.to_csv(summary_dir+summary_filename)

    max = summary_df.loc[summary_df['val_acc'].idxmax()].rename('max')
    mean = summary_df.mean().rename('mean')
    std = summary_df.std().rename('std')
    stats = pd.concat([max,mean,std], axis=1).T

    pretty_print_stats(summary_df, seqs_eval=seqs_eval)
    print(stats[['val_acc']].T.to_string(float_format="{:.1%}".format))

def print_protocol_stats(summary_dir, criteria=None):
    pass

def print_train_stats_all(summary_dirs, **kwargs):
    for summary_dir in summary_dirs:
        if summary_dir.endswith('/hp_search/'):
            continue
        print('********** '+summary_dir+' **********')
        print_train_stats(summary_dir, **kwargs)

#%% Main
if __name__ == '__main__':
    args = vars(load_args())

    print('> Starting HyperParameter Search - ', time.asctime( time.localtime(time.time()) ))

    print_args = args.pop('print_args')
    if print_args:
        print("Program arguments and values:")
        for argument, value in args.items():
            print('\t', argument, ":", value)

    print_train_stats_all(**args)

    print('\n> Finished HyperParameter Search -', time.asctime( time.localtime(time.time()) ))


def solution(numLog):
    res = ''
    for i in range(1, len(numLog)):
        find = numLog[i] - numLog[i - 1]
        if find == 1:
            res += 'w'
        elif find == -1:
            res += 's'
        elif find == 10:
            res += 'd'
        else:
            res += 'a'
    return res

numLog = [0, 1, 0, 10, 0, 1, 0, 10, 0, -1, -2, -1]
print(solution(numLog))


# pypy로 돌려야 통과함므
import copy

N, M = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(N)]

dx = (0, 1, 0, -1)
dy = (1, 0, -1, 0)

def is_possible(x, y):
    return 0 <= x < N and 0 <= y < M

def cnt_bingsan(arr, n, m):
    cnt = 0
    chk = [[0] * M for _ in range(N)]
    for i in range(n):
        for j in range(m):
            stack = []
            if arr[i][j] > 0 and chk[i][j] == 0:
                cnt += 1
                chk[i][j] = 1
                stack.append([i, j])
            while stack:
                x, y = stack.pop()
                for k in range(4):
                    nx, ny = x + dx[k], y + dy[k]
                    if is_possible(nx, ny) and chk[nx][ny] == 0 and arr[nx][ny] > 0:
                        chk[nx][ny] = 1
                        stack.append([nx, ny])
    # print("cnt = ", cnt)
    return cnt

ans = 0
while True:
    ans += 1
    tmp = [[0] * M for _ in range(N)]

    for i in range(N):
        for j in range(M):
            dct = 0
            for k in range(4):
                nx, ny = i + dx[k], j + dy[k]
                if is_possible(nx, ny) and arr[nx][ny] == 0:
                    dct += 1

            # print("arr[i][j]", arr[i][j])
            ah = arr[i][j] - dct
            # print(ah)
            if ah < 0:
                ah = 0
            tmp[i][j] = ah

    # print(tmp)
    arr = copy.deepcopy(tmp)

    # print("cnt_bingsan", cnt_bingsan(arr, N, M))
    # for ii in range(N):
    #     print(*arr[ii])
    # print(ans)

    if cnt_bingsan(arr, N, M) >= 2:
        print(ans)
        break

    tri = 0
    for i in range(N):
        if sum(arr[i]) > 0:
            tri += 1
    if tri > 0:
        continue
    print(0)
    break


import datetime
import logging

from django.core.management import BaseCommand, CommandError
from django.db.models import Q

from stats.models import Challenge, GlobalStats

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = "Calcule les statistiques globales affichées sur la page Statistiques et les stats des challenge en cours"

    def handle(self, *args, **options):
        try:
            GlobalStats.objects.get().refresh_stats()
            logger.info("STATS updated succesfully")
        except KeyboardInterrupt:
            raise CommandError("Interrompu.")

        # Compute challenges stats
        today = datetime.datetime.today()

        for challenge in Challenge.objects.filter(
            Q(
                start_date__gt=today,
            )
            | Q(start_date__lte=today, end_date__gt=today)
        ):
            try:
                challenge.refresh_stats()
                logger.info(f"STATS for challenge {challenge} updated")
            except KeyboardInterrupt:
                raise CommandError("Interrompu.")


'''
I wrote this to make tasks for the tasks.org app with an etebase sync server.

It's not feature comprehensive but it's helpful for bulk task making.

The CLI is not great, it's easier to do python -i pytasks.py and code up
whatever you want.

https://github.com/tasks/tasks
https://github.com/etesync
'''
import argparse
import datetime
import etebase
import sys
import tasks_credentials
import time

from voussoirkit import betterhelp
from voussoirkit import passwordy
from voussoirkit import pipeable
from voussoirkit import timetools
from voussoirkit import vlogging

log = vlogging.getLogger(__name__, '')

PRODID = 'voussoir/pytasks'

client = etebase.Client(tasks_credentials.CLIENT_NAME, tasks_credentials.SERVER)
account = etebase.Account.login(client, tasks_credentials.USERNAME, tasks_credentials.PASSWORD)
collection_manager = account.get_collection_manager()
collections = collection_manager.list('etebase.vtodo', etebase.FetchOptions().limit(500000))
collections = [c for c in collections.data if not c.deleted]

todo = collections[0]
item_manager = collection_manager.get_item_manager(todo)

def make_vcal(text, *, categories=[], due=None):
    now = timetools.now().strftime('%Y%m%dT%H%M%SZ')

    if due is None:
        due = ''
    elif isinstance(due, datetime.date):
        due = 'DUE;VALUE=DATE:' + due.strftime('%Y%m%d')
    elif isinstance(due, datetime.datetime):
        due = 'DUE:' + due.strftime('%Y%m%dT%H%M%S')
    else:
        raise TypeError(due)

    lines = [
        'BEGIN:VCALENDAR',
        'VERSION:2.0',
        'PRODID:' + PRODID,
        'BEGIN:VTODO',
        'DTSTAMP:' + now,
        'UID:' + passwordy.random_digits(32),
        due,
        'CREATED:' + now,
        'LAST-MODIFIED:' + now,
        'SUMMARY:' + text,
        ('CATEGORIES:' + ','.join(categories)) if len(categories) > 0 else '',
        'END:VTODO',
        'END:VCALENDAR',
    ]
    lines = [l for l in lines if l]
    vcal = '\r\n'.join(lines) + '\r\n'
    return vcal.encode('utf-8')

def make_item(*args, **kwargs):
    item = item_manager.create({}, make_vcal(*args, **kwargs))
    return item

def publish_items(items):
    if isinstance(items, etebase.Item):
        item_manager.batch([items])
    else:
        item_manager.batch(list(items))

def export_argparse(args):
    items = item_manager.list(etebase.FetchOptions().limit(50000000))
    items = list(items.data)
    for item in items:
        pipeable.stdout(item.content.decode('utf-8'))
        pipeable.stdout()
    return 0

def make_tasks_argparse(args):
    titles = pipeable.input_many(args.titles, strip=True, skip_blank=True)
    items = []
    for title in titles:
        log.info('Creating task %s.', title)
        item = make_item(title)
        items.append(item)
    publish_items(items)
    return 0

@vlogging.main_decorator
def main(argv):
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    ################################################################################################

    p_make_tasks = subparsers.add_parser('make_tasks', aliases=['make-tasks', 'maketasks', 'maketask'])
    p_make_tasks.add_argument('titles', nargs='+')
    p_make_tasks.set_defaults(func=make_tasks_argparse)

    ################################################################################################

    p_export = subparsers.add_parser('export')
    p_export.set_defaults(func=export_argparse)

    return betterhelp.go(parser, argv)

if __name__ == '__main__':
    raise SystemExit(main(sys.argv[1:]))


from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
import xml.etree.ElementTree as ET
import requests

tree = ET.parse('db.xml')
root = tree.getroot()

print("Server started")

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

# Create server
with SimpleXMLRPCServer(('localhost', 8000), requestHandler=RequestHandler) as server:
    server.register_introspection_functions()

    def check_topic_exists(topic):
        """Checks if a topic exists in the database"""

        exists = False
        for child in root:
            if (child.attrib['name'] == topic):
                exists = True

        return exists

    server.register_function(check_topic_exists, "check_topic_exists")

    def list_topics():
        """Returns a list of all the existing topics"""

        topics = []
        for child in root:
            topics.append(child.attrib)
        return topics

    server.register_function(list_topics, "list_topics")

    def get_content_of_topic(topic):
        """Returns the content of a topic"""

        topic_content = []

        for child in root:
            if (child.attrib['name'] == topic):

                # Getting the content of the topic inside the note tag
                topic_content.append(child.find("note").find("text").text)
                topic_content.append(child.find("note").find("timestamp").text)

                return topic_content

    server.register_function(get_content_of_topic, "get_content_of_topic")

    def add_data_to_existing_topic(topic, text, timestamp):
        """If topic that user wants exists, appends text to the existing topic"""

        for child in root:
            # Finding the topic to which data needs to be added
            if (child.attrib['name'] == topic):

                note = child.find("note")

                # Finding the existing text and appending the new text
                existing_text = note.find("text").text
                new_text = f"{existing_text}\n{text}"
                note.find("text").text = new_text

                # Updating the timestamp
                note.find("timestamp").text = timestamp

                tree.write('db.xml')
                # Returning True if data was added successfully
                return True

        # Returning False if data was not added
        return False

    server.register_function(add_data_to_existing_topic, "add_data_to_existing_topic")

    def add_new_topic(topic, text, timestamp):
        """If topic that user wants does not exist, creates a new topic"""

        # Adding new topic to the root
        new_topic = ET.SubElement(root, 'topic', name=topic)
        new_note = ET.SubElement(new_topic, 'note')
        new_text = ET.SubElement(new_note, 'text')
        new_timestamp = ET.SubElement(new_note, 'timestamp')

        new_text.text = text
        new_timestamp.text = timestamp

        tree.write('db.xml')
        return True

    server.register_function(add_new_topic, "add_new_topic")

    def wikipedia_data_search(topic):
        """Function to search for a topic on Wikipedia"""

        S = requests.Session()

        URL = "https://en.wikipedia.org/w/api.php"

        SEARCHPAGE = topic

        PARAMS = {
            "action": "opensearch",
            "namespace": "0",
            "search": SEARCHPAGE,
            "limit": "1",
            "format": "json"
        }

        R = S.get(url=URL, params=PARAMS)
        DATA = R.json()

        print(DATA)

        return DATA

    server.register_function(wikipedia_data_search, "wikipedia_data_search")

    # Run the server's main loop
    server.serve_forever()


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect

from .models import Question, Choice
from django.utils import timezone

# Create your views here.
def get_question(question_id):
    return Question.objects.get(id = question_id)

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')
    data = {'latest_question_list': latest_question_list}

    return render(request, 'polls_app/index.html', data)

def detail(request, question_id):
    question = get_question(question_id)

    # data = {'question': question}
    return  render(request, 'polls_app/detail.html', {'question': question})

def results(request, question_id):
    question = get_question(question_id)

    return render(request, 'polls_app/results.html', {'question': question})

def vote(request, question_id):
    question = get_question(question_id)

    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])

    except (KeyError, Choice.DoesNotExist):
        data = {'question': question,
                'error_message': "You didn't select a choice.",}
        return render(request, 'polls_app/detail.html', data)

    selected_choice.votes += 1
    selected_choice.save()

    return HttpResponseRedirect(f'/polls/{question_id}/results')

# for demo
def add_question(request, question_text):
    question = Question(question_text = question_text, pub_date= timezone.now())
    question.save()

    question.choice_set.create(choice_text='Not much')
    question.choice_set.create(choice_text='The sky', votes= 0)
    question.choice_set.create(choice_text='nothing at all')

    choices = question.choice_set.all()
    return HttpResponse(choices)


import argparse
import os
import sys

def convert(infile, outfile, num_avg, num_stdev):
    with open(infile, 'r') as in_table, open(outfile, 'w') as out_table:
        first = in_table.readline().strip("\n").split("\t")[3:]
        total = len(first)+3
        out_table.write("scaffold")
        for item in first:
            if item[-4:] == '-var':
                out_table.write("\tstdev_" + str(item.rsplit("-",1)[0]))
            else:
                out_table.write("\tavg_" + str(item))
        for line in in_table:
            line = line.strip("\n").split("\t")
            out_table.write("\n" + line[0])
            for n in range(3,total,2):
                #out_table.write("\t" + line[n])
                out_table.write("\t" + str(float(line[n])*float(num_avg)))
                sd = float(line[n+1])**0.5
                sd = sd*float(num_stdev)
                out_table.write("\t" + str(sd))

if __name__ == '__main__':

    vRhyme = argparse.ArgumentParser(description="Convert a MetaBat2 'jgi_summarize_bam_contig_depths' generated coverage table into vRhyme format for -c input.")
    vRhyme.add_argument('-i', metavar='', type=str, nargs=1, required=True, help="input coverage table in MetaBat2 format")
    vRhyme.add_argument('-o', metavar='', type=str, nargs=1, required=True, help='output coverage table in vRhyme format')
    vRhyme.add_argument('-multiplyAvg', metavar='', type=str, nargs=1, required=True, help='-multiplyAvg = num, multiply avg MetaBat for num')
    vRhyme.add_argument('-multiplyStdev', metavar='', type=str, nargs=1, required=True, help='-multiplyStdev = num, multiply stdev MetaBat for num')
    #
    args = vRhyme.parse_args()
    #
    #
    if os.path.exists(str(args.o[0])):
        sys.stderr.write("\nError: output table (-o) already exists. Exiting.\n\n")
        exit()

    convert(args.i[0], args.o[0], args.multiplyAvg[0], args.multiplyStdev[0])

#
#
#


# Steady-state temperature distribution in a thin triangular conducting plate
from math import *
from pde import *
from graphlib import *

def Func(x, y):                                  # RHS function for Poisson2D
   return 0e0

#============================================================================
def BoundCondTriangle(u, imin, imax, nx, ny, iapex):
#----------------------------------------------------------------------------
#  Determines the boundary indexes imin[j] and imax[j] (j=1,ny) for a
#  triangular domain, determined by the number of mesh points nx, ny, and the
#  apex i-index iapex, and sets values on the boundaries for the function u
#----------------------------------------------------------------------------
   amin = (iapex-1e0)/(ny-1e0)                          # slope for left side
   amax = -(nx-iapex)/(ny-1e0)                         # slope for right side

   for j in range(1,ny+1):                           # determine line-indexes
      imin[j] = int(amin*(j-1) + 1e0 + 0.5e0)           # left boundary index
      imax[j] = int(amax*(j-1) + nx + 0.5e0)           # right boundary index
                                                            # boundary values
   for i in range(imin[1],imax[1]+1): u[i][1] = 100e0                # bottom
   for j in range(2,ny): u[imin[j]][j] = u[imax[j]][j] = 0e0   # left & right
   for i in range(imin[ny],imax[ny]+1): u[i][ny] = 0e0                  # top

# main

xmin = 0e0; xmax = 10e0; ymin = 0e0; ymax = 8e0           # domain boundaries
nx = 51; ny = 41                                      # number of mesh points
iapex = 26                                         # i-index of triangle apex
eps = 1e-5                                      # relative solution tolerance

u = [[0]*(ny+1) for i in range(nx+1)]                              # solution
x = [0]*(nx+1); y = [0]*(ny+1)                       # mesh point coordinates
imin = [0]*(ny+1)                              # indexes of y-line boundaries
imax = [0]*(ny+1)

hx = (xmax-xmin)/(nx-1)
for i in range(1,nx+1): x[i] = xmin + (i-1)*hx                # x-mesh points
hy = (ymax-ymin)/(ny-1)
for j in range(1,ny+1): y[j] = ymin + (j-1)*hy                # y-mesh points

for j in range(1,ny+1):                                 # initialize solution
   for i in range(1,nx+1): u[i][j] = -1e99

BoundCondTriangle(u,imin,imax,nx,ny,iapex)                  # boundary values

for j in range(2,ny):                 # initial approximation of the solution
   for i in range(imin[j]+1,imax[j]): u[i][j] = 0e0          # interior nodes

Poisson2D(u,x,y,imin,imax,nx,ny,eps,Func)

out = open("Poisson.txt","w")                              # open output file
out.write("      x         y          u\n")
for j in range(1,ny+1):
   for i in range(1,nx+1):
      out.write(("{0:10.5f}{1:10.5f}{2:14.5e}\n").format(x[i],y[j],u[i][j]))
out.close()

umin = umax = u[imin[1]][1]             # minimum and maximum of the solution
for j in range(1,ny+1):
   for i in range(imin[j],imax[j]+1):
      if (u[i][j] < umin): umin = u[i][j]
      if (u[i][j] > umax): umax = u[i][j]

GraphInit(800,800)
Contour(u,nx,ny,xmin,xmax,ymin,ymax,umin,umax, \
        0.15,0.85,0.15,0.85,"x","y","Plate temperature")
MainLoop()


from flask import render_template, request, abort, json, Response
from settings import app
from googletrans import Translator

@app.route("/")
def index():
    return render_template('index.html',)

@app.route("/translate")
def translate():
    text = request.args.get('text', None)
    lang = request.args.get('lang', 'en')
    if text == '' or text is None:
        return abort(Response(json.dumps({
            'error': 'No text provided'
        }), status=400))
    if lang == '':
        return abort(Response(json.dumps({
            'error': 'No language provided'
        }), status=400))
    try:
        translator = Translator()
        translated = translator.translate(text, dest=lang)
        return {
            'text': translated.text,
        }
    except Exception as e:
        print(e)
        return abort(Response(json.dumps({
            'error': 'Something went wrong',
        }), status=500))


#### evaluation of topic models on information retrieval

import os
import csv
from processData import Process
import processMesh
from searchPubMed import queryPubMed

def process_data(name):
    if not os.path.isdir('./'+name):
        os.mkdir('./'+name)
    f1 = open('./'+name+'/docs.txt','w')
    f2 = open('./'+name+'/pmids_and_refer.txt','w')
    f3 = open('./'+name+'/meshes.txt','w')
    f4 = open('./'+name+'/pmids.txt','w')
    with open('./datasets/'+name+'_processed.csv') as f:
        reader = csv.reader(f)
        for row in reader:
            f1.write(row[1]+' '+row[4]+'\n')
            #print row[1],row[4]
            f2.write(row[0]+' '+row[6]+'\n')
            f3.write(row[5]+'\n')
            f4.write(row[0]+'\n')
    f1.close()
    f2.close()
    f3.close()
    f4.close()
    f.close()
    p1 = Process()
    docpath = './'+name
    p1.preprocessforlda(docpath,'docs')
    #processMesh.processmesh(docpath+'/', 'docs')
def get_meshes(name):
    f = open('./'+name+'/pmids.txt','r')
    ids = f.readlines()
    docpath = './'+name
    queryPubMed(docpath,ids)
def process_mesh(name):
    docpath = './'+name+'/'
    processMesh.processmesh(docpath, 'docs')
def build_corr_matrix(name):
    docpath = './'+name+'/'
    ldapath = './'+name+'/resultforlda'
    #for T in range(5,300,5):
    T = 55
    processMesh.compare_dists(docpath,T,ldapath)
def process_pmid(name):
    f = open('./'+name+'/pmids.txt','r')
    ids = f.readlines()
    docpath = './'+name
    queryPubMed(docpath,ids)
def main():
    name = 'UrinaryIncontinence'
    #process_pmid(name)
    #p1 = Process()
    #docpath = './'+name
    #p1.preprocessforlda(docpath,'docs')
    #process_data(name)
    #get_meshes(name)
    #process_mesh(name)
    build_corr_matrix(name)
main()


# This mnist classification implementation has a 98% accuracy rate. The other one that I made had only a 91% accuracy rate, so this one is definitely better,
# albeit, requires more prior knowledge to understand

import tensorflow as tf

from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model

### Load and prepare the MNIST dataset
mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train/255.0, x_test/255.0 # normalize all the RGB pixel values to be [0, 255] -> [0, 1] so that can be fed to sigmoid

# Add a channels dimension
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]

# use tf.data to batch and shuffle the dataset

train_ds = tf.data.Dataset.from_tensor_slices(
        (x_train, y_train)).shuffle(10000).batch(32)

test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)

### Build the tf.keras model using the Keras model subclassing API:

class MyModel(Model):
    def __init__(self):
        super(MyModel, self).__init__()
        self.conv1 = Conv2D(32, 3, activation='relu')
        self.flatten = Flatten()
        self.d1 = Dense(128, activation='relu')
        self.d2 = Dense(10)

    def call(self, x):
        x = self.conv1(x)
        x = self.flatten(x)
        x = self.d1(x)
        return self.d2(x)

# Create an instance of the model
model = MyModel()

# Choose an optimizer and loss function for training
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)

optimizer = tf.keras.optimizers.Adam()

# Select metrics to measure the loss and the accuracy of the model. These metrics accumulate the values over epochs
# and the print the overall result.

train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')

test_loss = tf.keras.metrics.Mean(name='test_loss')
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')

# Use tf.GradientTape to train the model
@tf.function
def train_step(images, labels):
    with tf.GradientTape() as tape:
        # training=True is only needed if there are layers with different
        # behavior during training versus inference (e.g. Dropout).
        predictions = model(images, training=True)
        loss = loss_object(labels, predictions)
    gradients = tape.gradient(loss, model.trainable_variables)
    optimizer.apply_gradients(zip(gradients, model.trainable_variables))

    train_loss(loss)
    train_accuracy(labels, predictions)

### Test the model
@tf.function
def test_step(images, labels):
    # training=False is only needed if there are layers with different
    # behavior during training versus inference (e.g. Dropout)
    predictions = model(images, training=False)
    t_loss = loss_object(labels, predictions)

    test_loss(t_loss)
    test_accuracy(labels, predictions)

EPOCHS = 5

for epoch in range(EPOCHS):
    # Reset the metrics at the start of the next epoch
    train_loss.reset_states()
    train_accuracy.reset_states()
    test_loss.reset_states()
    test_accuracy.reset_states()

    for images, labels in train_ds:
        train_step(images, labels)

    for test_images, test_labels in test_ds:
        test_step(test_images, test_labels)

    template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'
    print(template.format(epoch+1,
        train_loss.result(),
        train_accuracy.result()*100,
        test_loss.result(),
        test_accuracy.result()*100))


test_inputs = '''2199943210
3987894921
9856789892
8767896789
9899965678'''

def a(inputs):
    total_risk = 0
    for r in range(len(inputs)):
        for c in range(len(inputs[r])):
            up = down = left = right = 10
            if r != 0:
                up = int(inputs[r - 1][c])
            if r != len(inputs) - 1:
                down = int(inputs[r + 1][c])
            if c != 0:
                left = int(inputs[r][c - 1])
            if c != len(inputs[r]) - 1:
                right = int(inputs[r][c + 1])

            cell_value = int(inputs[r][c])
            # print(r, c, up, down, left, right)
            if up > cell_value and down > cell_value and left > cell_value and right > cell_value:
                total_risk += cell_value + 1
                print(r, c, up, down, left, right)
    return total_risk

def b(inputs):
    return

with open('inputs/09in.txt', 'r') as infile:
    inputs = infile.read()

# inputs = test_inputs
inputs = inputs.split('\n')
inputs = list(map(list, inputs))
print(a(inputs))
print(b(inputs))


# Include Libraries
import time
import RPi.GPIO as GPIO
import configparser
import Adafruit_DHT
import threading

#Global Variables
TEMP_INT = 0
HUM_INT = 0

# Define Friendly Sensor Names
DHT22_SENSOR = Adafruit_DHT.DHT22

# GPIO PINS
TRIGGER_PIN = 6 # Trigger for Ultrasonic Sensor
ECHO_PIN = 5 # Echo for Ultrasonic Sensor
FAN_PWM_PIN = 12
FAN_SPEED_PIN = 16
DHT22_PIN = 17
RELAY_WATERPUMP = 26

# GPIO SETUP MODE
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)

# GPIO SETUP
GPIO.setup(TRIGGER_PIN, GPIO.OUT)
GPIO.setup(ECHO_PIN, GPIO.IN)
GPIO.setup(FAN_PWM_PIN, GPIO.OUT)
GPIO.setup(FAN_SPEED_PIN, GPIO.IN)
GPIO.setup(DHT22_PIN, GPIO.IN, GPIO.PUD_DOWN)
#GPIO.setup(RELAY_WATERPUMP, GPIO.OUT)

# FAN CONFIG AND PID PERIMITERS
# Set PWM frequency
pwm = GPIO.PWM(FAN_PWM_PIN, 1000)
pwm.start(0)

# Get current fan speed
def get_fan_speed():
    t = time.time()
    count = 0
    while (time.time() - t) < 1:
        if GPIO.input(FAN_SPEED_PIN):
            count += 1
    return count * 60

# Set fan speed
def set_fan_speed(speed):
    duty_cycle = speed / 100.0 * 100
    pwm.ChangeDutyCycle(duty_cycle)

# PID constants
Kp = 100
Ki = 0.01
Kd = 0.01

# PID variables
integral = 0
prev_error = 0
temp_counter = 0

# DHT22 Temp and Humiditiy Sensor (Threaded)

def dht22_reader():
    global TEMP_INT, HUM_INT
    while True:
        # Read the temperature and humidity from the sensor
        HUM1, TEMP1, = Adafruit_DHT.read_retry(DHT22_SENSOR, DHT22_PIN)
        TEMP_INT = round(TEMP1, 2)
        HUM_INT = round(HUM1, 2)
        # Sleep for a short time to avoid spamming the sensor
        time.sleep(0.5)

#Ultrasonic Sensor for Water Level. (Threaded)

def get_distance():
    global distance_cm
    while True:
        # Send a 10us pulse to the trigger pin to start the measurement
        GPIO.output(TRIGGER_PIN, True)
        time.sleep(0.00001)
        GPIO.output(TRIGGER_PIN, False)

        # Wait for the pulse to be returned
        while GPIO.input(ECHO_PIN) == 0:
            pulse_start = time.time()

        while GPIO.input(ECHO_PIN) == 1:
            pulse_end = time.time()

        # Calculate the duration of the pulse
        pulse_duration = pulse_end - pulse_start

        # Calculate the distance in centimeters
        distance_cm = round(pulse_duration * 17150, 2)

        # Sleep for a short time to avoid spamming the sensor
        time.sleep(0.05)

# Main Backend Loop - Currently Pushing out Sensor Information to User.
def main_loop():
    global distance_cm, HUM_INT, TEMP_INT
    while True:
        print("Water Distance" ,distance_cm,"cm")
        print("Int. Humidity:" ,HUM_INT,"%")
        print("Int Temp:" ,TEMP_INT,"c" )
        time.sleep(0.5)

#Threads are defined here.

if __name__ == '__main__':
    # Start the ultrasonic reader thread
    ultrasonic_thread = threading.Thread(target=get_distance)
    ultrasonic_thread.daemon = True
    ultrasonic_thread.start()

    # Start the DHT22 reader thread
    dht22_thread = threading.Thread(target=dht22_reader)
    dht22_thread.daemon = True
    dht22_thread.start()

    # Start the main loop in a new thread
    main_thread = threading.Thread(target=main_loop)
    main_thread.daemon = True
    main_thread.start()

    ultrasonic_thread.join()
    dht22_thread.join()
    main_thread.join()

    # Cleanup GPIO
    GPIO.cleanup()


# Para crear una clase debemos usar la pal;abra reservada class y ademas toda clase debera tener la primer letra de cada palabra en mayusculas
# SoyUnaClase  MiClase  PersonaAdulta --> solo por nombrar unos ejemplos

class Persona:

    # En esta parte es como el constructor ya que aqui es donde definimos los parametros de una clase, por ahora esta en codigo duro
    def __init__(self):
        self.nombre = 'Jason'
        self.apellido = 'Limon'
        self.edad = 25

persona1 = Persona()

print(f'El objeto persona tiene el nombre {persona1.nombre} {persona1.apellido} y tiene {persona1.edad}')


from mpi4py import MPI

import pytest

from dolfinx.fem import extract_function_spaces, form, functionspace
from dolfinx.mesh import create_unit_square
from ufl import TestFunction, TrialFunction, dx, inner

def test_extract_forms():
    """Test extraction on unique function spaces for rows and columns of
    a block system"""
    mesh = create_unit_square(MPI.COMM_WORLD, 32, 31)
    V0 = functionspace(mesh, ("Lagrange", 1))
    V1 = functionspace(mesh, ("Lagrange", 2))
    V2 = V0.clone()
    V3 = V1.clone()

    v0, u0 = TestFunction(V0), TrialFunction(V0)
    v1, u1 = TestFunction(V1), TrialFunction(V1)
    v2, u2 = TestFunction(V2), TrialFunction(V2)
    v3, u3 = TestFunction(V3), TrialFunction(V3)

    a = form([[inner(u0, v0) * dx, inner(u1, v1) * dx],
              [inner(u2, v2) * dx, inner(u3, v3) * dx]])
    with pytest.raises(AssertionError):
        extract_function_spaces(a, 0)
    with pytest.raises(AssertionError):
        extract_function_spaces(a, 1)

    a = form([[inner(u0, v0) * dx, inner(u2, v1) * dx],
              [inner(u0, v2) * dx, inner(u2, v2) * dx]])
    with pytest.raises(AssertionError):
        extract_function_spaces(a, 0)
    Vc = extract_function_spaces(a, 1)
    assert Vc[0] is V0._cpp_object
    assert Vc[1] is V2._cpp_object

    a = form([[inner(u0, v0) * dx, inner(u1, v0) * dx],
              [inner(u2, v1) * dx, inner(u3, v1) * dx]])
    Vr = extract_function_spaces(a, 0)
    assert Vr[0] is V0._cpp_object
    assert Vr[1] is V1._cpp_object
    with pytest.raises(AssertionError):
        extract_function_spaces(a, 1)


from __future__ import absolute_import
from __future__ import division

import numpy as np
import tensorflow as tf

class adict(dict):
    ''' Attribute dictionary - a convenience data structure, similar to SimpleNamespace in python 3.3
        One can use attributes to read/write dictionary content.
    '''
    def __init__(self, *av, **kav):
        dict.__init__(self, *av, **kav)
        self.__dict__ = self

def inference_graph(vocab_size=164, num_layers=3, hidden_size=256, batch_size=1, num_steps=1, dropout_rate=0.0):
    ''' Builds an inference graph. '''

    input_data = tf.placeholder(tf.int32, [batch_size, num_steps])

    lstm_cell = lambda: tf.contrib.rnn.BasicLSTMCell(hidden_size, forget_bias=1.0, state_is_tuple=True)
    if dropout_rate > 0:
        lstm_cell = tf.nn.rnn_cell.DropoutWrapper(lstm_cell, output_keep_prob=1-dropout_rate)
    cell = tf.nn.rnn_cell.MultiRNNCell([lstm_cell() for _ in range(num_layers)], state_is_tuple=True)

    initial_state = cell.zero_state(batch_size, tf.float32)

    with tf.device("/cpu:0"):
        embedding = tf.get_variable("embedding", [vocab_size, hidden_size])
        inputs = tf.nn.embedding_lookup(embedding, input_data)

    if dropout_rate > 0:
        inputs = tf.nn.dropout(inputs, 1-dropout_rate)

    output, final_state = tf.nn.dynamic_rnn(cell, inputs, initial_state=initial_state)
    logits = tf.tensordot(output,
        tf.get_variable("softmax_w", [hidden_size, vocab_size]),
        [[2], [0]]
    )

    return adict(
        input_data=input_data,
        initial_state=initial_state,
        logits=logits,
        final_state=final_state)

def cost_graph(logits, batch_size, num_steps, vocab_size):
    ''' Builds cost graph. '''

    targets = tf.placeholder(tf.int32, [batch_size, num_steps], name='targets')

    loss = tf.contrib.seq2seq.sequence_loss(logits,
                                            targets,
                                            tf.ones([batch_size, num_steps]),
                                            average_across_timesteps=False,
                                            average_across_batch=False)
    cost = tf.div(tf.reduce_sum(loss), batch_size * num_steps, name='cost')

    return adict(
        targets=targets,
        cost=cost)

def training_graph(cost, grad_clip=5.0):
    ''' Builds training graph. '''

    # Adam's learning parameters
    lr = tf.Variable(0.001, trainable=False, name='lr')
    beta1 = tf.Variable(0.8, trainable=False, name='beta1')
    beta2 = tf.Variable(0.95, trainable=False, name='beta2')

    # collect all trainable variables
    tvars = tf.trainable_variables()

    grads = [tf.clip_by_value(t, -grad_clip, grad_clip) for t in tf.gradients(cost, tvars)]

    optimizer = tf.train.AdamOptimizer(lr, beta1, beta2)
    train_op = optimizer.apply_gradients(zip(grads, tvars))

    return adict(
        lr=lr,
        beta1=beta1,
        beta2=beta2,

        tvars=tvars,
        grads=grads,

        train_op=train_op)


from rest_framework import serializers
from django.contrib.auth.models import User
from taggit.models import Tag, TaggedItem

from .models import UserProfile
from matching.models import HelpRequest

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name', 'email')

class UserProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = UserProfile

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag

class TaggedItemSerializer(serializers.ModelSerializer):
    tag = TagSerializer()

    class Meta:
        model = TaggedItem

class HelpRequestSerializer(serializers.ModelSerializer):
    requester = UserSerializer()
    provider = UserSerializer()

    class Meta:
        model = HelpRequest

    def update(self, instance, validated_data):
        try:
            update_user = User.objects.get(email=validated_data['provider']['email'])
            instance.provider = update_user
            instance.save()
        except User.DoesNotExist:
            return instance
        return instance


from .scheduler import Scheduler
from luxio.external_clients.json_client import JSONClient
from luxio.common.enumerations import DeploymentStatus
from luxio.common.configuration_manager import ConfigurationManager
from typing import Dict
import pandas as pd

class DummyScheduler(Scheduler):
    """
    A class used to Query the scheduler and keep track of existing resources
    """

    initialized = False

    def __init__(self) -> None:
        self.resource_graph = None
        conf = ConfigurationManager.get_instance()
        self.resource_graph = JSONClient().load(conf.resource_graph_path)
        self.existing_deployments = pd.DataFrame()
        self.callbacks = None

    def set_callbacks(self, scheduler):
        self.callbacks = scheduler

    def refresh_resource_graph(self):
        return self.resource_graph

    def refresh_existing_deployments(self):
        return self.existing_deployments

    def schedule(self, job_spec:dict):
        if 'job_id' in job_spec:
            job_spec['deployment'] = self.existing_deployments[job_spec['job_id']]
        if job_spec['deployment']['status'] == DeploymentStatus.RUNNING:
            self.existing_deployments[job_spec['deployment']['job_id']].append(job_spec)
        else:
            job_id = len(self.existing_deployments.keys())
            job_spec['deployment']['job_id'] = job_id
            job_spec['deployment']['status'] = DeploymentStatus.RUNNING
            self.existing_deployments.append(job_spec['deployment'])
        if self.callbacks is not None:
            self.callbacks.refresh_resource_graph()
            self.callbacks.refresh_existing_deployments()
        return True


"""python library for accessing the openHAB REST API."""

#
# Georges Toth (c) 2016-present <georges@trypill.org>
#
# python-openhab is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# python-openhab is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with python-openhab.  If not, see <http://www.gnu.org/licenses/>.
#

# pylint: disable=bad-indentation

import datetime
import logging
import re
import typing

import dateutil.parser

import openhab.command_types
import openhab.exceptions

__author__ = 'Georges Toth <georges@trypill.org>'
__license__ = 'AGPLv3+'

class Item:
  """Base item class."""

  types: typing.Sequence[typing.Type[openhab.command_types.CommandType]] = []
  state_types: typing.Sequence[typing.Type[openhab.command_types.CommandType]] = []
  command_event_types: typing.Sequence[typing.Type[openhab.command_types.CommandType]] = []
  state_event_types: typing.Sequence[typing.Type[openhab.command_types.CommandType]] = []
  state_changed_event_types: typing.Sequence[typing.Type[openhab.command_types.CommandType]] = []

  TYPENAME = 'unknown'

  def __init__(self, openhab_conn: 'openhab.client.OpenHAB', json_data: dict) -> None:
    """Constructor.

    Args:
      openhab_conn (openhab.OpenHAB): openHAB object.
      json_data (dic): A dict converted from the JSON data returned by the openHAB
                       server.
    """
    self.openhab = openhab_conn
    self.type_: typing.Optional[str] = None
    self.quantityType: typing.Optional[str] = None
    self.editable = None
    self.label = ''
    self.category = ''
    self.tags = ''
    self.groupNames = ''
    self.group = False
    self.name = ''
    self._state = None  # type: typing.Optional[typing.Any]
    self._unitOfMeasure = ''
    self._raw_state = None  # type: typing.Optional[typing.Any]  # raw state as returned by the server
    self._members = {}  # type: typing.Dict[str, typing.Any] #  group members (key = item name), for none-group items it's empty
    self.function_name: typing.Optional[str] = None
    self.function_params: typing.Optional[typing.Sequence[str]] = None

    self.logger = logging.getLogger(__name__)

    self.init_from_json(json_data)

  def init_from_json(self, json_data: dict) -> None:
    """Initialize this object from a json configuration as fetched from openHAB.

    Args:
      json_data (dict): A dict converted from the JSON data returned by the openHAB
                        server.
    """
    self.name = json_data['name']
    if json_data['type'] == 'Group':
      self.group = True
      if 'groupType' in json_data:
        self.type_ = json_data['groupType']

      if 'function' in json_data:
        self.function_name = json_data['function']['name']

        if 'params' in json_data['function']:
          self.function_params = json_data['function']['params']

      # init members
      for i in json_data['members']:
        self.members[i['name']] = self.openhab.json_to_item(i)

    else:
      self.type_ = json_data.get('type', None)

      if self.type_ is None:
        raise openhab.exceptions.InvalidReturnException('Item did not return a type attribute.')

      parts = self.type_.split(':')
      if len(parts) == 2:
        self.quantityType = parts[1]

    if 'editable' in json_data:
      self.editable = json_data['editable']
    if 'label' in json_data:
      self.label = json_data['label']
    if 'category' in json_data:
      self.category = json_data['category']
    if 'tags' in json_data:
      self.tags = json_data['tags']
    if 'groupNames' in json_data:
      self.groupNames = json_data['groupNames']

    self._raw_state = json_data['state']

    if self.is_undefined(self._raw_state):
      self._state = None
    else:
      self._state, self._unitOfMeasure = self._parse_rest(self._raw_state)

  @property
  def state(self) -> typing.Any:
    """The state property represents the current state of the item.

    The state is automatically refreshed from openHAB on reading it.
    Updating the value via this property send an update to the event bus.
    """
    json_data = self.openhab.get_item_raw(self.name)
    self.init_from_json(json_data)

    return self._state

  @state.setter
  def state(self, value: typing.Any) -> None:
    self.update(value)

  @property
  def unit_of_measure(self) -> str:
    """Return the unit of measure. Returns an empty string if there is none defined."""
    return self._unitOfMeasure

  @property
  def members(self) -> typing.Dict[str, typing.Any]:
    """If item is a type of Group, it will return all member items for this group.

    For none group item empty dictionary will be returned.

    Returns:
      dict: Returns a dict with item names as key and `Item` class instances as value.

    """
    return self._members

  def _validate_value(self, value: typing.Union[str, typing.Type[openhab.command_types.CommandType]]) -> None:
    """Private method for verifying the new value before modifying the state of the item."""
    if self.type_ == 'String':
      if not isinstance(value, (str, bytes)):
        raise ValueError
    elif self.types:
      validation = False

      for type_ in self.types:
        try:
          type_.validate(value)
        except ValueError:
          pass
        else:
          validation = True

      if not validation:
        raise ValueError(f'Invalid value "{value}"')
    else:
      raise ValueError

  def _parse_rest(self, value: str) -> typing.Tuple[str, str]:
    """Parse a REST result into a native object."""
    return value, ''

  def _rest_format(self, value: str) -> typing.Union[str, bytes]:
    """Format a value before submitting to openHAB."""
    _value = value  # type: typing.Union[str, bytes]

    # Only ascii encoding is supported by default. If non-ascii characters were provided, convert them to bytes.
    try:
      _ = value.encode('ascii')
    except UnicodeError:
      _value = value.encode('utf-8')

    return _value

  def is_undefined(self, value: str) -> bool:
    """Check if value is undefined."""
    for aStateType in self.state_types:
      if not aStateType.is_undefined(value):
        return False

    return True

  def __str__(self) -> str:
    """String representation."""
    state = self._state
    if self._unitOfMeasure and not isinstance(self._state, tuple):
        state = f'{self._state} {self._unitOfMeasure}'
    return f'<{self.type_} - {self.name} : {state}>'

  def _update(self, value: typing.Any) -> None:
    """Updates the state of an item, input validation is expected to be already done.

    Args:
      value (object): The value to update the item with. The type of the value depends
                      on the item type and is checked accordingly.
    """
    # noinspection PyTypeChecker
    self.openhab.req_put(f'/items/{self.name}/state', data=value)

  def update(self, value: typing.Any) -> None:
    """Updates the state of an item.

    Args:
      value (object): The value to update the item with. The type of the value depends
                      on the item type and is checked accordingly.
    """
    self._validate_value(value)

    v = self._rest_format(value)

    self._state = value

    self._update(v)

  def command(self, value: typing.Any) -> None:
    """Sends the given value as command to the event bus.

    Args:
      value (object): The value to send as command to the event bus. The type of the
                      value depends on the item type and is checked accordingly.
    """
    self._validate_value(value)

    v = self._rest_format(value)

    self._state = value

    self.openhab.req_post(f'/items/{self.name}', data=v)

  def update_state_null(self) -> None:
    """Update the state of the item to *NULL*."""
    self._update('NULL')

  def update_state_undef(self) -> None:
    """Update the state of the item to *UNDEF*."""
    self._update('UNDEF')

  def is_state_null(self) -> bool:
    """If the item state is None, use this method for checking if the remote value is NULL."""
    if self.state is None:
      # we need to query the current remote state as else this method will not work correctly if called after
      # either update_state method
      if self._raw_state is None:
        # This should never happen
        raise ValueError('Invalid internal (raw) state.')

      return self._raw_state == 'NULL'

    return False

  def is_state_undef(self) -> bool:
    """If the item state is None, use this method for checking if the remote value is UNDEF."""
    if self.state is None:
      # we need to query the current remote state as else this method will not work correctly if called after
      # either update_state method
      if self._raw_state is None:
        # This should never happen
        raise ValueError('Invalid internal (raw) state.')

      return self._raw_state == 'UNDEF'

    return False

class GroupItem(Item):
  """String item type."""

  TYPENAME = 'Group'
  types: typing.List[typing.Type[openhab.command_types.CommandType]] = []
  state_types: typing.List[typing.Type[openhab.command_types.CommandType]] = []

class StringItem(Item):
  """String item type."""

  TYPENAME = 'String'
  types = [openhab.command_types.StringType]
  state_types = types

class DateTimeItem(Item):
  """DateTime item type."""

  TYPENAME = 'DateTime'
  types = [openhab.command_types.DateTimeType]
  state_types = types

  def __gt__(self, other: datetime.datetime) -> bool:
    """Greater than comparison."""
    if self._state is None or not isinstance(other, datetime.datetime):
      raise NotImplementedError('You can only compare two DateTimeItem objects.')

    return self._state > other

  def __ge__(self, other: datetime.datetime) -> bool:
    """Greater or equal comparison."""
    if self._state is None or not isinstance(other, datetime.datetime):
      raise NotImplementedError('You can only compare two DateTimeItem objects.')

    return self._state >= other

  def __lt__(self, other: object) -> bool:
    """Less than comparison."""
    if not isinstance(other, datetime.datetime):
      raise NotImplementedError('You can only compare two DateTimeItem objects.')

    return not self.__gt__(other)

  def __le__(self, other: object) -> bool:
    """Less or equal comparison."""
    if self._state is None or not isinstance(other, datetime.datetime):
      raise NotImplementedError('You can only compare two DateTimeItem objects.')

    return self._state <= other

  def __eq__(self, other: object) -> bool:
    """Equality comparison."""
    if not isinstance(other, datetime.datetime):
      raise NotImplementedError('You can only compare two DateTimeItem objects.')

    return self._state == other

  def __ne__(self, other: object) -> bool:
    """Not equal comparison."""
    if not isinstance(other, datetime.datetime):
      raise NotImplementedError('You can only compare two DateTimeItem objects.')

    return not self.__eq__(other)

  def _parse_rest(self, value: str) -> typing.Tuple[datetime.datetime, str]:  # type: ignore[override]
    """Parse a REST result into a native object.

    Args:
      value (str): A string argument to be converted into a datetime.datetime object.

    Returns:
      datetime.datetime: The datetime.datetime object as converted from the string
                         parameter.
    """
    return dateutil.parser.parse(value), ''

  def _rest_format(self, value: datetime.datetime) -> str:  # type: ignore[override]
    """Format a value before submitting to openHAB.

    Args:
      value (datetime.datetime): A datetime.datetime argument to be converted
                                 into a string.

    Returns:
      str: The string as converted from the datetime.datetime parameter.
    """
    # openHAB supports only up to milliseconds as of this writing
    return value.isoformat(timespec='milliseconds')

class PlayerItem(Item):
  """PlayerItem item type."""

  TYPENAME = 'Player'
  types = [openhab.command_types.PlayPauseType, openhab.command_types.NextPrevious, openhab.command_types.RewindFastforward]
  state_types = [openhab.command_types.PlayPauseType, openhab.command_types.RewindFastforward]

  def play(self) -> None:
    """Send the command PLAY."""
    self.command(openhab.command_types.PlayPauseType.PLAY)

  def pause(self) -> None:
    """Send the command PAUSE."""
    self.command(openhab.command_types.PlayPauseType.PAUSE)

  def next(self) -> None:
    """Send the command NEXT."""
    self.command(openhab.command_types.NextPrevious.NEXT)

  def previous(self) -> None:
    """Send the command PREVIOUS."""
    self.command(openhab.command_types.NextPrevious.PREVIOUS)

  def fastforward(self) -> None:
    """Send the command FASTFORWARD."""
    self.command(openhab.command_types.RewindFastforward.FASTFORWARD)

  def rewind(self) -> None:
    """Send the command REWIND."""
    self.command(openhab.command_types.RewindFastforward.REWIND)

class SwitchItem(Item):
  """SwitchItem item type."""

  TYPENAME = 'Switch'
  types = [openhab.command_types.OnOffType]
  state_types = types

  def on(self) -> None:
    """Set the state of the switch to ON."""
    self.command(openhab.command_types.OnOffType.ON)

  def off(self) -> None:
    """Set the state of the switch to OFF."""
    self.command(openhab.command_types.OnOffType.OFF)

  def toggle(self) -> None:
    """Toggle the state of the switch to OFF to ON and vice versa."""
    if self.state == openhab.command_types.OnOffType.ON:
      self.off()
    elif self.state == openhab.command_types.OnOffType.OFF:
      self.on()

class NumberItem(Item):
  """NumberItem item type."""

  TYPENAME = 'Number'
  types = [openhab.command_types.DecimalType]
  state_types = types

  def _parse_rest(self, value: str) -> typing.Tuple[typing.Union[float, None], str]:  # type: ignore[override]
    """Parse a REST result into a native object.

    Args:
      value (str): A string argument to be converted into a float object.

    Returns:
      float: The float object as converted from the string parameter.
      str: The unit Of Measure or empty string
    """
    if value in ('UNDEF', 'NULL'):
      return None, ''
    # m = re.match(r'''^(-?[0-9.]+)''', value)
    try:
      m = re.match(r'(-?[0-9.]+(?:[eE]-?[0-9]+)?)\s?(.*)?$', value)

      if m:
        value = m.group(1)
        unit_of_measure = m.group(2)

        return float(value), unit_of_measure

      return float(value), ''

    except (ArithmeticError, ValueError) as exc:
      self.logger.error('Error in parsing new value "%s" for "%s" - "%s"', value, self.name, exc)

    raise ValueError(f'{self.__class__}: unable to parse value "{value}"')

  def _rest_format(self, value: typing.Union[float, typing.Tuple[float, str], str]) -> typing.Union[str, bytes]:
    """Format a value before submitting to openHAB.

    Args:
      value: Either a float, a tuple of (float, str), or string; in the first two cases we have to cast it to a string.

    Returns:
      str or bytes: A string or bytes as converted from the value parameter.
    """
    if isinstance(value, tuple) and len(value) == 2:
        return super()._rest_format(f'{value[0]:G} {value[1]}')
    if not isinstance(value, str):
        return super()._rest_format(f'{value:G}')
    return super()._rest_format(value)

class ContactItem(Item):
  """Contact item type."""

  TYPENAME = 'Contact'
  types = [openhab.command_types.OpenCloseType]
  state_types = types

  def command(self, *args: typing.Any, **kwargs: typing.Any) -> None:
    """This overrides the `Item` command method.

    Note: Commands are not accepted for items of type contact.
    """
    raise ValueError(f'This item ({self.__class__}) only supports updates, not commands!')

  def open(self) -> None:
    """Set the state of the contact item to OPEN."""
    self.state = openhab.command_types.OpenCloseType.OPEN

  def closed(self) -> None:
    """Set the state of the contact item to CLOSED."""
    self.state = openhab.command_types.OpenCloseType.CLOSED

class DimmerItem(Item):
  """DimmerItem item type."""

  TYPENAME = 'Dimmer'
  types = [openhab.command_types.OnOffType, openhab.command_types.PercentType, openhab.command_types.IncreaseDecreaseType]
  state_types = [openhab.command_types.PercentType]

  def _parse_rest(self, value: str) -> typing.Tuple[float, str]:  # type: ignore[override]
    """Parse a REST result into a native object.

    Args:
      value (str): A string argument to be converted into a int object.

    Returns:
      float: The int object as converted from the string parameter.
      str: Possible UoM
    """
    return float(value), ''

  def _rest_format(self, value: typing.Union[str, int]) -> str:
    """Format a value before submitting to OpenHAB.

    Args:
      value: Either a string or an integer; in the latter case we have to cast it to a string.

    Returns:
      str: The string as possibly converted from the parameter.
    """
    if not isinstance(value, str):
      return str(value)

    return value

  def on(self) -> None:
    """Set the state of the dimmer to ON."""
    self.command(openhab.command_types.OnOffType.ON)

  def off(self) -> None:
    """Set the state of the dimmer to OFF."""
    self.command(openhab.command_types.OnOffType.OFF)

  def increase(self) -> None:
    """Increase the state of the dimmer."""
    self.command(openhab.command_types.IncreaseDecreaseType.INCREASE)

  def decrease(self) -> None:
    """Decrease the state of the dimmer."""
    self.command(openhab.command_types.IncreaseDecreaseType.DECREASE)

class ColorItem(DimmerItem):
  """ColorItem item type."""

  TYPENAME = 'Color'
  types = [openhab.command_types.OnOffType, openhab.command_types.PercentType, openhab.command_types.IncreaseDecreaseType, openhab.command_types.ColorType]
  state_types = [openhab.command_types.ColorType]

  def _parse_rest(self, value: str) -> typing.Tuple[typing.Optional[typing.Tuple[float, float, float]], str]:  # type: ignore[override]
    """Parse a REST result into a native object.

    Args:
      value (str): A string argument to be converted into a str object.

    Returns:
      HSB components
      Optional UoM
    """
    result = openhab.command_types.ColorType.parse(value)
    return result, ''

  def _rest_format(self, value: typing.Union[typing.Tuple[int, int, float], str, int]) -> str:
    """Format a value before submitting to openHAB.

    Args:
      value: Either a string, an integer or a tuple of HSB components (int, int, float); in the latter two cases we have to cast it to a string.

    Returns:
      str: The string as possibly converted from the parameter.
    """
    if isinstance(value, tuple):
      if len(value) == 3:
        return f'{value[0]},{value[1]},{value[2]}'

    if not isinstance(value, str):
      return str(value)

    return value

class RollershutterItem(Item):
  """RollershutterItem item type."""

  TYPENAME = 'Rollershutter'
  types = [openhab.command_types.UpDownType, openhab.command_types.PercentType, openhab.command_types.StopMoveType]
  state_types = [openhab.command_types.PercentType]

  def _parse_rest(self, value: str) -> typing.Tuple[int, str]:  # type: ignore[override]
    """Parse a REST result into a native object.

    Args:
      value (str): A string argument to be converted into a int object.

    Returns:
      int: The int object as converted from the string parameter.
      str: Possible UoM
    """
    return int(float(value)), ''

  def _rest_format(self, value: typing.Union[str, int]) -> str:
    """Format a value before submitting to openHAB.

    Args:
      value: Either a string or an integer; in the latter case we have to cast it to a string.

    Returns:
      str: The string as possibly converted from the parameter.
    """
    if not isinstance(value, str):
      return str(value)

    return value

  def up(self) -> None:
    """Set the state of the dimmer to ON."""
    self.command(openhab.command_types.UpDownType.UP)

  def down(self) -> None:
    """Set the state of the dimmer to OFF."""
    self.command(openhab.command_types.UpDownType.DOWN)

  def stop(self) -> None:
    """Set the state of the dimmer to OFF."""
    self.command(openhab.command_types.StopMoveType.STOP)


"""add oauth

Revision ID: 134b6ad70b5c
Revises: 44775f747bfe
Create Date: 2013-12-04 20:15:30.299940

"""

# revision identifiers, used by Alembic.
revision = '134b6ad70b5c'
down_revision = '44775f747bfe'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('oauth_clients',
    sa.Column('name', sa.Unicode(length=50), nullable=True),
    sa.Column('description', sa.Unicode(length=300), nullable=True),
    sa.Column('client_id', sa.Unicode(length=100), nullable=False),
    sa.Column('client_secret', sa.Unicode(length=100), nullable=False),
    sa.Column('user_id', sa.Integer(), nullable=False),
    sa.Column('is_confidential', sa.Boolean(), nullable=False),
    sa.Column('redirect_uri', sa.UnicodeText(), nullable=False),
    sa.Column('_default_scopes', sa.UnicodeText(), nullable=True),
    sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
    sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
    sa.PrimaryKeyConstraint('client_id')
    )
    op.create_table('tokens',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('token_type', sa.Unicode(length=10), nullable=False),
    sa.Column('client_id', sa.Unicode(length=100), nullable=True),
    sa.Column('user_id', sa.Integer(), nullable=True),
    sa.Column('access_token', sa.Unicode(length=255), nullable=True),
    sa.Column('refresh_token', sa.Unicode(length=255), nullable=True),
    sa.Column('expires', sa.DateTime(timezone=True), nullable=False),
    sa.Column('_scopes', sa.UnicodeText(), nullable=True),
    sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
    sa.ForeignKeyConstraint(['client_id'], ['oauth_clients.client_id'], ),
    sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('access_token'),
    sa.UniqueConstraint('refresh_token')
    )
    op.create_table('grants',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('user_id', sa.Integer(), nullable=True),
    sa.Column('client_id', sa.Unicode(length=100), nullable=False),
    sa.Column('code', sa.Unicode(length=255), nullable=False),
    sa.Column('redirect_uri', sa.UnicodeText(), nullable=True),
    sa.Column('_scopes', sa.UnicodeText(), nullable=True),
    sa.Column('expires', sa.DateTime(timezone=True), nullable=False),
    sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
    sa.ForeignKeyConstraint(['client_id'], ['oauth_clients.client_id'], ),
    sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('grants')
    op.drop_table('tokens')
    op.drop_table('oauth_clients')
    ### end Alembic commands ###


from typing import List

"""
Problem Name: 761. Special Binary String

Problem Section: String, Recursion

Problem Statement:
 Special binary strings are binary strings with the following two properties:

The number of 0's is equal to the number of 1's.
Every prefix of the binary string has at least as many 1's as 0's.

Given a special string S, a move consists of choosing two consecutive, non-empty, special substrings of S, and swapping them. (Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.)

At the end of any number of moves, what is the lexicographically largest resulting string possible?

Example 1:

Input: S = "11011000"
Output: "11100100"
Explanation:
The strings "10" [occuring at S[1]] and "1100" [at S[3]] are swapped.
This is the lexicographically largest string possible after some number of swaps.

Note:

    S has length at most 50.
    S is guaranteed to be a special binary string as defined above.

Resources:
https://leetcode.com/problems/special-binary-string/discuss/581356/Thorough-explanation-using-Validate-Parentheses-based-on-others'-solutions
"""

""" runtime """

# Solution techniques are

# Time complexity : O() Space complexity : O()

class Solution:
    def makeLargestSpecial(self, S: str) -> str:
        i = 0  # start of the substring
        count = 0  # to find a valid substring by counting 1's and 0's
        res = []  # store the transformed substrings
        for j, v in enumerate(S):
            # j would be the end of the substring
            # v is the current character being checked
            if v == "1":
                count += 1
            else:
                count -= 1
            # add to count when seeing 1, reduce count when seeing 0
            # when count is 0 again, means we just parsed a valid substring
            if count == 0:
                # take the inside of the substring, transform it using recursion
                # and add to the set of completed results
                res.append('1' + self.makeLargestSpecial(S[i + 1:j]) + '0')
                # move the start of the substring to the next character
                i = j + 1
        res.sort()  # make sure the substrings are ordered from lexigraphically smallest to largest
        res = res[::-1]  # now it's largest to smallest
        # join and return
        return ''.join(res)

myobj = Solution()
inpt = "11011000"
print(myobj.makeLargestSpecial(inpt))


import sys
sys.path.append("..")
from pages.homepage import HomePage
from base.basetestcase import BaseTestCase

class TemplatesPageTest(BaseTestCase):
    def test_VerifyAllTemplatesProduceResults(self):
        homepage = HomePage(self.driver)
        templatespage = homepage.templates

        for template_name in templatespage.get_templates().iterkeys():
            templatequerypage = templatespage.open_template_query(template_name)
            queryresultspage = templatequerypage.show_results

            self.assertTrue(queryresultspage.has_results, "There are no results for templete: " + template_name)

if __name__ == '__main__':
    unittest.main(verbosity=2)


import blackjack
from pylab import *

Q1 = ... # NumPy array of correct size
Q2 = ... # NumPy array of correct size

def learn(alpha, eps, numTrainingEpisodes):
    returnSum = 0.0
    for episodeNum in range(numTrainingEpisodes):
        G = 0
        ...
        # Fill in Q1 and Q2
        print("Episode: ", episodeNum, "Return: ", G)
        returnSum = returnSum + G
        if episodeNum % 10000 == 0 and episodeNum != 0:
            print("Average return so far: ", returnSum / episodeNum)

def evaluate(numEvaluationEpisodes):
    returnSum = 0.0
    for episodeNum in range(numEvaluationEpisodes):
        G = 0
        ...
        # Use deterministic policy from Q1 and Q2 to run a number of
        # episodes without updates. Return average return of episodes.
        returnSum = returnSum + G
    return returnSum / numEvaluationEpisodes


# coding=utf-8

import sys

def is_tri(_a, _b, _c):
    if _a + _b > _c and _a + _c > _b and _b + _c > _a:
        return True
    else:
        return False

for line in sys.stdin:

    a, b, c = (int(x) for x in line.split())

    result = 0

    for i in range(1, a + 1):
        for j in range(1, b + 1):
            k_max = i + j
            for k in range(1, k_max):
                if is_tri(i, j, k):
                    result += 1

    print(result)


import pygame
import random
import math

minMovement = 0.5
maxSpeed = 5

class Person:
    colors = {"healthy": "white", "sick": "red", "recovered": "blue"}

    # status - "healthy" , "sick" or "recovered"
    def __init__(self, x, y, status, socialDistancing):
        self.x = x
        self.y = y
        self.status = status
        self.socialDistancing = socialDistancing
        self.radius = 6
        self.vx = 0
        self.vy = 0
        self.turnsSick = 0
        self.recoveryTime = random.randint(100, 150)

        if not self.socialDistancing:
            while -minMovement < self.vx < minMovement and -minMovement < self.vy < minMovement:
                self.vx = random.uniform(-maxSpeed, maxSpeed)
                self.vy = random.uniform(-maxSpeed, maxSpeed)

    # screen - the main surface
    def draw(self, screen):
        pygame.draw.circle(screen, pygame.Color(self.colors[self.status]), (round(self.x), round(self.y)), self.radius)

    # execute once per frame
    def update(self, screen, people):
        self.move()
        if self.status == "sick":
            self.turnsSick += 1
            if self.turnsSick == self.recoveryTime:
                self.status = "recovered"
        self.checkCollidingWithWall(screen)
        for other in people:
            if self != other:  # ensure you don't check for collision with yourself
                if self.checkCollidingWithOther(other):
                    self.updateCollisionVelocities(other)
                    # update status
                    if self.status == "sick" and other.status == "healthy":
                        other.status = "sick"
                    elif other.status == "sick" and self.status == "healthy":
                        self.status = "sick"

    def move(self, ):
        if not self.socialDistancing:
            self.x += self.vx
            self.y += self.vy

    # check for collisions with walls and update velocities
    def checkCollidingWithWall(self, screen):
        if self.x + self.radius >= screen.get_width() and self.vx > 0:  # self.vx > 0 is to prevent it from getting
            # stuck to the wall
            self.vx *= -1
        elif self.x - self.radius <= 0 and self.vx < 0:
            self.vx *= -1
        if self.y + self.radius >= screen.get_height() and self.vy > 0:
            self.vy *= -1
        elif self.y - self.radius <= 0 and self.vy < 0:
            self.vy *= -1

    # return True if the self is colliding with the other, False otherwise
    def checkCollidingWithOther(self, other):
        distance = math.sqrt(math.pow(self.x - other.x, 2) + math.pow(self.y - other.y, 2))
        if distance <= self.radius + other.radius:
            return True
        return False

    # update velocities on collision
    def updateCollisionVelocities(self, other):
        # type 1 collision - both objects are moving; neither is social distancing

        if not self.socialDistancing and not other.socialDistancing:
            tempVX = self.vx
            tempVY = self.vy
            self.vx = other.vx
            self.vy = other.vy
            other.vx = tempVX
            other.vy = tempVY

        # type 2 collision : one object that is social distancing and one that is not

        elif other.socialDistancing:
            # works okay, not great
            # self.vx *= -1
            # self.vy *= -1
            #
            # # works okay
            # tempVX = self.vx
            # self.vx = self.vy
            # self.vy = tempVX

            magV = math.sqrt(math.pow(self.vx, 2) + math.pow(self.vy, 2))
            tempVector = (self.vx + (self.x - other.x), self.vy + (self.y - other.y))
            magTempVector = math.sqrt(math.pow(tempVector[0], 2) + math.pow(tempVector[1], 2))
            normTempVector = (tempVector[0] / magTempVector, tempVector[1] / magTempVector)
            self.vx = normTempVector[0] * magV
            self.vy = normTempVector[1] * magV


import bonobo
import pandas as pd
import datetime as dt
import random as rd
import time
import os
from os import listdir
import glob
import requests
import zipfile
import pathlib
import sys

# connection to Data Base
sys.path.append("../conf")
from db_conn import engine

# get relative data folder
PATH = pathlib.Path(__file__).parent.resolve()

YEAR=2019
DIR_PATH = os.getcwd()

def get_stock_list():

    df=pd.read_excel(str(PATH.joinpath("./securities_data.xlsx")),converters={'SBIF_ID':str})
    ruts=(df[df.TIPO == "BANCO"]["RUTSD"]).to_list()
    sbif_ids=(df[df.TIPO == "BANCO"]["SBIF_ID"]).to_list()

    banks=zip(ruts,sbif_ids)

    yield from banks

def extract(*args):
    """
    get list of excel files
    """
    bank_rut= args[0]
    bank_id= args[1]

    while True:
        try:
            print("Downloading file for..." + str(args[0]),end="\n")
            myfile = requests.get("https://www.sbif.cl/sbifweb/internet/bancos/balances/"+str(YEAR)+"/"+bank_id+".zip", allow_redirects=True)
            time.sleep(rd.randint(4,7))
            break
        except:
            print("request failed")
            pass

    open(str(PATH.joinpath("./data_banks/"+bank_id+".zip")), 'wb').write(myfile.content)
    time.sleep(rd.randint(1,2))

    yield (bank_rut,bank_id)

def process(*args):
    """
    Processing excel data
    """
    bank_rut= args[0]
    bank_id= args[1]

    print("Unzipping file for..."+str(bank_rut),end="\n")
    with zipfile.ZipFile(str(PATH.joinpath('./data_banks/'+bank_id+'.zip')), 'r') as zip_ref:
        zip_ref.extractall(str(PATH.joinpath('./data_banks/')))
    time.sleep(rd.randint(2,5))

    print("Processing File for..." + str(bank_rut),end="\n")

    df=pd.read_excel(str(PATH.joinpath('./data_banks/'+bank_id+'.xlsx')),skiprows=3,sheet_name="Resultados")
    df=df[df.columns[4:]]

    df.set_index("Descripción",inplace=True)
    df.index.name="fecha"

    df=df.T[["TOTAL INGRESOS OPERACIONALES","UTILIDAD (PERDIDA) CONSOLIDADA DEL EJERCICIO"]]*1000000
    df=df.reset_index()

    # rename columns
    df.columns=["fecha","ingreso","ganancia"]

    # add variables and transform
    df["moneda"]="PESOS"
    df["fecha_inicio"] = pd.to_datetime(df["fecha"].apply(lambda x: dt.date(x.year,1,1)))
    df["fecha_termino"] = df['fecha']
    df["rut"] = bank_rut

    yield (df, bank_rut)

def load(*args):
    """
    Save dataframe to DB

    Args:
        1: DataFrame - Data from yahoo finance
        2: String - Yahoo IDs
    """

    #args[0].to_csv(str(PATH.joinpath('./data/{}.csv'.format(args[1]))),index=False)

    try: # it will fail if duplicates
        args[0].to_sql('cmf', con=engine, if_exists='append', index=False)
    except:
        pass

def get_graph(**options):
    """
    This function builds the graph that needs to be executed.

    :return: bonobo.Graph

    """
    graph = bonobo.Graph()
    graph.add_chain(get_stock_list,extract, process, load)

    return graph

def get_services(**options):
    """
    This function builds the services dictionary, which is a simple dict of names-to-implementation used by bonobo
    for runtime injection.

    It will be used on top of the defaults provided by bonobo (fs, http, ...). You can override those defaults, or just
    let the framework define them. You can also define your own services and naming is up to you.

    :return: dict
    """
    return {}

# The __main__ block actually execute the graph.
if __name__ == '__main__':

    test = str(PATH.joinpath("./data_banks/*"))
    r = glob.glob(test)
    for i in r:
        os.remove(i)

    test = str(PATH.joinpath("./data/*"))
    r = glob.glob(test)
    for i in r:
        os.remove(i)

    parser = bonobo.get_argument_parser()
    with bonobo.parse_args(parser) as options:
        bonobo.run(
            get_graph(**options),
            services=get_services(**options)
        )


"""Pyslabs builtin-data slab manipulation module

"""

import os, io, pickle, itertools

from pyslabs.error import PE_Stabif_Typemismatch
from pyslabs.util import ScalarList, DEBUG_LEVEL, DEBUG_INFO

def length(slab, axis=0):

    return len(slab)

def slice2type(_slice, _type):

    return _type(_slice)

def shape(slab):

    s = []

    while slab:
        try:
            l = len(slab)

            if l > 0:
                s.append(l)
                slab = slab[0]

            else:
                break
        except TypeError:
            break

    return tuple(s)

def dump(path, slab):

    with io.open(path, "wb") as fp:
        pickle.dump(slab, fp)
        fp.flush()
        os.fsync(fp.fileno())

def load(tar_file):

    return pickle.load(tar_file)

def stack(stacker, lower):

    if stacker is None:
        try:
            return type(lower)([lower])

        except TypeError:
            return (lower,)

    if isinstance(stacker, list):
        stacker.append(lower)

    elif isinstance(stacker, tuple):
        stacker += (lower,)

    else:
        import pdb; pdb.set_trace()

    return stacker

def expand_dim(array):

    return type(array)([array])

def get_blank():
    return tuple()

def concatenate(concater, panel, axis):

    if DEBUG_LEVEL > DEBUG_INFO:
        print("Concatenate IN (concat, panel, axis): ", concater, panel, axis)

    from pyslabs import slabif

    if concater is None:
        return panel

    if type(concater) != type(panel) and not isinstance(concater, ScalarList):
        raise PE_Stabif_Typemismatch("%s != %s" % (type(concater).__name__,
                                    type(panel).__name__))

    if isinstance(concater, ScalarList):
        concater.concat(panel)

    elif isinstance(concater, list):
        if axis > 0:
            if len(concater) != len(panel):
                raise PE_Stabif_Lengthmismatch("%d != %d" % (len(concater),
                                        len(panel)))
            buf = []
            for idx in range(len(concater)):
                buf.append(slabif.concatenate(concater[idx], panel[idx], axis=axis-1))
            concater = buf

        else:
            concater.extend(panel)

    elif isinstance(concater, tuple):
        if axis > 0:
            if len(concater) != len(panel):
                raise PE_Stabif_Lengthmismatch("%d != %d" % (len(concater),
                                        len(panel)))
            buf = []
            for idx in range(len(concater)):
                buf.append(slabif.concatenate(concater[idx], panel[idx], axis=axis-1))
            concater = tuple(buf)

        else:
            concater += panel

    else:
        if axis > 0:
            raise PE_Stabif_Wrongaxis()

        concater = ScalarList((concater, panel))

    if DEBUG_LEVEL > DEBUG_INFO:
        print("Concatenate OUT: ", concater)
    return concater

def squeeze(array):
    if DEBUG_LEVEL > DEBUG_INFO:
        print("Squeeze IN: ", array)

    is_squeezed = False

    if isinstance(array, (list, tuple, ScalarList)):
        if len(array) == 1:
            array = array[0]
            is_squeezed = True

    else:
        import pdb; pdb.set_trace()

    if DEBUG_LEVEL > DEBUG_INFO:
        print("Squeeze OUT(array, is_squeezed): ", array, is_squeezed)

    return is_squeezed, array

def get_slice(slab, key):

    from pyslabs import slabif

    if not key:
        return slab

    if isinstance(key, (int, slice)):
        key = (key,)

    if isinstance(key[0], int):
        is_slice = False
        start, stop, step = key[0], key[0]+1, 1

    elif isinstance(key[0], slice):
        is_slice = True
        start, stop, step = key[0].start, key[0].stop, key[0].step

    buf = []

    for item in itertools.islice(slab, start, stop, step):
        if len(key) > 1:
            item_slice = slabif.get_slice(item, key[1:])
            buf.append(item_slice)
        else:
            buf.append(item)

    if not is_slice:
        return buf[0]

    else:
        return slice2type(buf, type(slab))