import pickle
import tensorflow as tf
import numpy as np
import tf_utils as U

"""Implementation of Behavioral Cloning on supervised data (state, action) collected
by performing rollouts with an expert policy.
Those rollouts are contained in pickle files available in the `trajectories/` folder.
Trajectories are pickled by running the `run_expert` script with the appropriate environment.
"""

def train(ob_dim, act_dim, hid_size, lr, niter, obs, acts, ops, ckpt):
    # Initialize the seesion and variables
    U.single_threaded_session().__enter__()
    U.initialize()

    # Unpack the operators
    train_step, compute_loss, predict = ops

    for i in range(int(niter)):
        train_step(obs, acts)
        l = compute_loss(obs, acts)
        # For reference, usual way of training and obtaining the loss
        # _, l = sess.run([train_op, loss], feed_dict={
        #     ob: obs,
        #     act: acts
        # })
        if i % 100 == 0:
            print("--- Loss: {0} ---".format(l))

    # Save the variables to disk
    U.save_state(ckpt)
    print("Model saved in file: {0}.".format(ckpt))

def roll(nepisodes, maxnsteps, ops, envname, ckpt):
    # Initialize the session and variables
    U.single_threaded_session().__enter__()
    U.initialize()
    U.load_state(ckpt)
    print("Model loaded.")

    # Unpack the operators
    _, _, predict = ops

    import gym
    env = gym.make(envname)
    print(env.action_space)
    print(env.observation_space)
    for e in range(nepisodes):
        print("--- Episode #{0} ---".format(e))
        observ = env.reset()
        done = False
        steps = 0
        while not done and steps < maxnsteps:
            if steps % 100 == 0:
                print("--- Step #{0} ---".format(steps))
            action = predict(np.reshape(observ, (1, 11)))
            observ, r, done, _ = env.step(action)
            steps += 1
            env.render()

def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--envname", type=str)
    parser.add_argument("--expert_trajectories_file", type=str)
    parser.add_argument("--model_storage_file", type=str)
    parser.add_argument("--train", action="store_true")
    args = parser.parse_args()

    # Unpickle the expert trajectories
    with open(args.expert_trajectories_file, "rb") as f:
        expert_trajectories = pickle.loads(f.read())
    obs = expert_trajectories["observations"]
    print("--- OBS shape: {0} ---".format(obs.shape))
    print("First row of observations: {0}".format(obs[0, :]))
    acts = expert_trajectories["actions"].reshape(
        (expert_trajectories["actions"].shape[0], expert_trajectories["actions"].shape[2]))
    print("--- ACTS shape: {0} ---".format(acts.shape))
    print("First row of actions: {0}".format(acts[0, :]))

    # Hyperparameters
    # Behavioral Cloning (regression)
    ob_dim = 11
    act_dim = 3
    hid_size = 64
    lr = 1e-3
    niter = 1e4
    # Rollouts
    nepisodes = 100
    maxnsteps = 5000

    # Define the regression model
    ob = U.get_placeholder(name="ob", dtype=tf.float32, shape=[None, ob_dim])
    act = U.get_placeholder(name="act", dtype=tf.float32, shape=[None, act_dim])
    last_out = ob
    last_out = U.leaky_relu(
        U.dense(last_out, hid_size, "dense0", weight_init=U.normc_initializer(1.0)),
        leak=0.2)
    pred_act = U.dense(last_out, act_dim, "dense1", weight_init=U.normc_initializer(1.0))

    loss = 0.5 * U.sum(tf.square(pred_act - act))  # could also use Huber loss
    optimizer = tf.train.AdamOptimizer(learning_rate=lr)
    train_op = optimizer.minimize(loss)

    # Create the operators
    train_step = U.function([ob, act], train_op)
    compute_loss = U.function([ob, act], loss)
    predict = U.function([ob], pred_act)
    # Pack the operators
    ops = [train_step, compute_loss, predict]

    # Train the regression model (only if the flag is up)
    if args.train:
        train(ob_dim, act_dim, hid_size, lr, niter, obs, acts, ops, args.model_storage_file)

    # Do some rollouts with the policy learned via regression (BC)
    roll(nepisodes, maxnsteps, ops, args.envname, args.model_storage_file)

if __name__ == "__main__":
    # executes only if run as a script
    main()


n = int(input())

def least_div(a, b = 2):
    for i in range(b, int(a ** 0.5) + 1):
        if a % i == 0:
            return i
    return a

def fact(a):
    d = 2
    while a > 1:
        d = least_div(a, d)
        print(d, end = ' ')
        a //= d

fact(n)


from ezaws.models.dynamodb import Table, GetItemResponse

def test_table_creation():
    table = Table(table_name="Humans", rcu=1, wcu=1)
    table.add_attribute(attribute_name="name", attribute_type="S", key_type="RANGE")
    table.add_attribute(attribute_name="id", attribute_type="N", key_type="HASH")
    assert isinstance(table, Table)

def test_GetItemResponse():
    get_item_response = GetItemResponse(
        **{
            "Item": {"id": "1828", "name": "Arnetta"},
            "ResponseMetadata": {
                "HTTPHeaders": {
                    "connection": "keep-alive",
                    "content-length": "51",
                    "content-type": "application/x-amz-json-1.0",
                    "date": "Tue, 31 May 2022 06:43:40 GMT",
                    "server": "Server",
                    "x-amz-crc32": "859391921",
                    "x-amzn-requestid": "KNCSVK20TCKSJSVFJQQTCVR647VV4KQNSO5AEMVJF66Q9ASUAAJG",
                },
                "HTTPStatusCode": 200,
                "RequestId": "KNCSVK20TCKSJSVFJQQTCVR647VV4KQNSO5AEMVJF66Q9ASUAAJG",
                "RetryAttempts": 0,
            },
        }
    )
    assert get_item_response


import queue

class BinaryTree():
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def printLevelWiseBinaryTree(root):
    # Your code goes here
    q = queue.Queue()
    if root is None:
        return
    q.put(root)
    while not q.empty():
        current_node = q.get()
        print(current_node.data, ":", sep='', end='')
        if current_node.left is None:
            print("L:-1",sep='',end=',')
        else:
            print("L:", current_node.left.data, sep='', end=",")
            q.put(current_node.left)
        if current_node.right is None:
            print("R:", -1, sep='', end="")
        else:
            print("R:", current_node.right.data, sep='', end="")
            q.put(current_node.right)
        print()

def takeLevelWiseTreeInput():
    q = queue.Queue()
    print("Enter root")
    root_data = int(input())
    if root_data == -1:
        return None
    root = BinaryTree(root_data)
    q.put(root)
    while not q.empty():
        current_node = q.get()
        print("enter left child of ", current_node.data)
        left_child_data = int(input())
        if left_child_data != -1:
            left_child = BinaryTree(left_child_data)
            current_node.left = left_child
            q.put(left_child)
        print("enter right child of ", current_node.data)
        right_child_data = int(input())
        if right_child_data != -1:
            right_child = BinaryTree(right_child_data)
            current_node.right = right_child
            q.put(right_child)
    return root

root = takeLevelWiseTreeInput()
printLevelWiseBinaryTree(root)


class Solution:
    def shipWithinDays(self, weights, D):
        if not weights or D <= 0:
            raise ValueError("Invalid input...")

        low = max(weights)
        hi = sum(weights)
        while low <= hi:
            mid = low + (hi - low) // 2
            days = self.days(weights, mid)
            if days <= D:
                # can i do it with less capacity
                hi = mid - 1
            else:
                low = mid + 1
        # this is the minimum capacity we can do it
        return low

    def days(self, weights, capacity):
        count = 0
        curr = 0
        for w in weights:
            if curr + w <= capacity:
                curr += w
            else:
                count += 1
                curr = w
        count += 1 # last ship
        return count

if __name__ == '__main__':
    s = Solution()
    ans = s.shipWithinDays([1,2,3,4,5,6,7,8,9,10], 5)
    print(ans)


# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division

# Pre-design of diaphragm walls according to Geojuanjo's recomendations
# (see document predisenio_muros_pantalla_Geojuanjo.pdf)
# http://estructurando.net/2015/11/23/prediseno-de-muros-pantalla-un-primer-paso-imprescindible/

__author__= "Ana Ortega (AO_O)"
__copyright__= "Copyright 2018, AO_O"
__license__= "GPL"
__version__= "3.0"
__email__= "ana.Ortega@ciccp.es"

def side_line(pnt1,pnt2,pnt):
    '''function to determine which side of the line from pnt1=(x1,y1) to
    pnt2=(x2,y2) a point pnt=(x,y) falls on.

    All the points that return a value <0 lie on one side of the line and
    those that return a value >0 lie in the other side (if =0 -> in the line)
    '''
    d=(pnt[0]-pnt1[0])*(pnt2[1]-pnt1[1])-(pnt[1]-pnt1[1])*(pnt2[0]-pnt1[0])
    return d

# Points (x,y) to delimit wall thickness (45-60-80-100 cm) when phreatic level
# is bellow maximum digging height
# x= maximum distance between anchors
# y= maximum effective digging height
points_60_NW=[(3,18.5),(12,3)]
points_80_NW=[(3,21),(12,6)]
points_100_NW=[(3,27.5),(12,14)]

# Points (x,y) to delimit wall thickness (45-60-80-100 cm) when phreatic level
# is above maximum digging height
# x= maximum distance between anchors
# y= maximum effective digging height
points_60_W=[(3,12.5),(12,3)]
points_80_W=[(3,17),(12,6)]
points_100_W=[(3,21),(12,11)]

class DiaphragmWallRoughModel(object):
    '''Class intended to pre-design a diaphragm wall.

    :ivar digHeight: maximum digging height [m]
    :ivar phreaticLevel: phreatic level above maximum effective digging height
          [m]. It will be =0 or negative if phreatic level below
          maximum excavation level
    :ivar distAnch: maximum distance between anchors [m] (= 0 or negative
          if no anchors)
    :ivar firstExcavHeight: height of the first phase of excavation (cantilever) [m]
    :ivar distLastAnchExc: distance from the last anchor to the bottom of excavation [m]
    :ivar unifLoad: uniform load on the ground [kN/m2]
    :ivar distLoadWall: distance from the back of the wall to the starting
          point where uniform load in applied [m]

    '''
    def __init__(self, digHeight,phreaticLevel,distAnch,firstExcavHeight,distLastAnchExc,unifLoad,distLoadWall):
        self.digHeight= digHeight
        self.phreaticLevel= phreaticLevel
        self.distAnch= distAnch
        self.firstExcavHeight= firstExcavHeight
        self.distLastAnchExc= distLastAnchExc
        self.unifLoad= unifLoad
        self.distLoadWall= distLoadWall

    def getEffectDigHeight(self):
        '''Return the maximum effective digging height'''
        if self.distLoadWall <= 0.75*self.digHeight:
            coeff=1-(1-0.5)/(0.75*self.digHeight)*self.distLoadWall
        else:
            coeff=0
        fictH=coeff*self.unifLoad/20  #fictitious digging height
        effH=self.digHeight+fictH
        return effH

    def getFffectDistAnch(self):
        ''' Return effective distance between anchors'''
        if self.phreaticLevel <=0:
            effDistAnc=max(self.distAnch,1.5*self.firstExcavHeight,self.distLastAnchExc+1)
        else:
            effDistAnc=max(self.distAnch,1.5*self.firstExcavHeight,self.distLastAnchExc+2)
        return effDistAnc

    def getWallThickness(self):
        '''Return a pre-designed diaphragm wall thickness [m]'''
        effDigH=self.getEffectDigHeight()
        effDistAnch=self.getFffectDistAnch()
        wallTh=0.45
        if self.phreaticLevel<=0:
            if side_line(points_60_NW[0],points_60_NW[1],(effDistAnch,effDigH)) < 0:
                if side_line(points_80_NW[0],points_80_NW[1],(effDistAnch,effDigH)) < 0:
                    if side_line(points_100_NW[0],points_100_NW[1],(effDistAnch,effDigH)) < 0:
                        wallTh=1.00
                    else:
                        wallTh=0.80
                else:
                    wallTh=0.60
        else:
            if side_line(points_60_W[0],points_60_W[1],(effDistAnch,effDigH)) < 0:
                if side_line(points_80_W[0],points_80_W[1],(effDistAnch,effDigH)) < 0:
                    if side_line(points_100_W[0],points_100_W[1],(effDistAnch,effDigH)) < 0:
                        wallTh=1.00
                    else:
                        wallTh=0.80
                else:
                    wallTh=0.60
        return wallTh

    def getWallEmbedmentDepth(self):
        '''Return a pre-designed embedment depth [m]
        '''
        if self.distAnch > 0:
            embdt=max(3,self.digHeight/3.,3/2.*self.phreaticLevel,2+self.unifLoad/40)
        else:
            embdt=max(3,2*self.digHeight,3/2.*self.phreaticLevel,2+self.unifLoad/40)
        return embdt

    def printResult(self):
        print('Maximum effective digging height = ', self.getEffectDigHeight(), ' m ')
        print('Maximum effective interdistance anchoring = ', self.getFffectDistAnch(), ' m ')
        print('Embedment depth of diaphragm wall = ',self.getWallEmbedmentDepth() , ' m ')
        print('Diaphragm wall thickness= ', self.getWallThickness(),  ' m ')


# Import the necessary libraries
import numpy as np
import rclpy
from rclpy.node import Node

# Import the ros messages
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan

# Create a class for Moving Forward and stop if object is detected
class MoveForward(Node):

    def __init__(self):
        #Init the node
        super().__init__('move_forward')

        # Create a publisher to send velocity commands
        self.publisher_ = self.create_publisher(Twist, '/cmd_vel', 10)
        # Define the QOS policy such that the data sent by the turtlebot is compatible with the subscriber. Change the default behavior
        qos_policy = rclpy.qos.QoSProfile(reliability=rclpy.qos.ReliabilityPolicy.BEST_EFFORT, history=rclpy.qos.HistoryPolicy.KEEP_LAST, depth=1)
        # Create a subscriber to scan topic
        self.subscription = self.create_subscription(
            LaserScan,
            '/scan',
            self.scan_callback,
            qos_profile=qos_policy)

        self.subscription  # prevent unused variable warning

        # Set the properties
        self.collision_th = 0.3
        self.vel_x = 0.1
        self.vel_theta = 0.0

    # Define the scan callback function
    def scan_callback(self, msg):
        # Compute the range from the object in front by taking mean of ranges in -5 to 5 degrees
        front_range = (np.mean(msg.ranges[0:5]) + np.mean(msg.ranges[355:]))/2

        # Check if the range is below threshold
        obj_detected = front_range < self.collision_th

        # Print the range for debugging
        print("Range is ", obj_detected, front_range)

        # If object not detected, move the robot with predefined velocity
        if(not obj_detected):
            self.move(self.vel_x, self.vel_theta)
        else:
            # Stop the robot if object detected
            self.move(0.0, 0.0)

    # Move the vehicle with input velocities
    def move(self, vel_x, vel_theta):
        # Create a Twist message
        msg = Twist()
        msg.linear.x = vel_x
        msg.angular.z = vel_theta
        # Publish the data
        self.publisher_.publish(msg)
        print("Send the velocities: ", vel_x, " and ", vel_theta)

# Define main function for ROS to begin with
def main(args=None):
    # Init the ros node
    rclpy.init(args=args)

    # Create a Move Forward object
    move_forward = MoveForward()

    # Spin the node to register all callbacks
    rclpy.spin(move_forward)

    # Destroy the node explicitly
    # (optional - otherwise it will be done automatically
    # when the garbage collector destroys the node object)
    move_forward.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()


class UnionFind(object):
    def __init__(self, grid):
        row = len(grid)
        col = len(grid[0])
        self.root = [-1] * (row * col)
        self.cnt = row * col
        for i in range(0, row*col):
            self.root[i] = i

    def find(self, x):
        if x == self.root[x]:
            return self.root[x]
        else:
            self.root[x] = self.find(self.root[x])
            return self.root[x]

    def union(self, x, y):
        if self.find(x) != self.find(y):
            self.root[self.root[x]] = self.root[y]
            self.cnt -= 1

    def getCnt(self):
        return self.cnt

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        if grid is None or len(grid) == 0:
            return 0
        row = len(grid)
        col = len(grid[0])
        waters = 0
        uf = UnionFind(grid)
        for i in range(0, row):
            for j in range(0, col):
                if grid[i][j] == '0':
                    waters += 1
                else:
                    directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]
                    for x, y in directions:
                        x = x + i
                        y = y + j
                        if x >= 0 and y >= 0 and x < row and y < col and grid[x][y] == '1':
                            uf.union(x * col + y, i * col + j)
        return uf.getCnt() - waters

grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
s = Solution()
print(s.numIslands(grid))


import numpy as np
import tensorflow as tf
from typing import Tuple
from typing import Any
from typing import AnyStr

def triangular_causal_mask(B, L) -> tf.Tensor:
    mask_shape = [B, 1, L, L]
    mask = tf.equal(x=tf.linalg.band_part(input=tf.ones(shape=mask_shape, dtype=tf.bool),
                                          num_lower=-1, num_upper=0), y=tf.constant(False))

    return mask

def prob_mask(B, H, L, index, scores) -> tf.Tensor:
    mask = tf.equal(x=tf.linalg.band_part(index=tf.ones(L, scores.shape[-1], dtype=tf.bool),
                                          num_lower=-1, num_upper=0), y=tf.constant(False))
    mask_ex = mask[None, None, :].expand(B, H, L, scores.shape[-1])
    indicator = mask_ex[np.arange(B)[:, None, None], np.arange(H)[None, :, None], index, :]
    return indicator.reshape(scores.shape)

def positional_embedding(position: Any, d_model: Any, d_type: tf.dtypes.DType = tf.float32) -> tf.Tensor:
    """ PE(pos,2i) = sin(pos/10000^(2i/d_model)) | PE(pos,2i+1) = cos(pos/10000^(2i/d_model))

    :param position: 字符总数
    :param d_model: 词嵌入大小
    :param d_type: 运算精度
    :return:
    """
    angle_rates = 1 / np.power(10000, (2 * (np.arange(d_model)[np.newaxis, :] // 2)) / np.float32(d_model))
    angle_rads = np.arange(position)[:, np.newaxis] * angle_rates

    angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])
    angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])
    pos_encoding = angle_rads[np.newaxis, ...]

    return tf.cast(pos_encoding, dtype=d_type)

def data_embedding(embedding_dim: Any, d_type: tf.dtypes.DType = tf.float32,
                   position: Any = 5000, name: AnyStr = "data_embedding") -> tf.keras.Model:
    """ Data Embedding

    :param embedding_dim: 特征维度
    :param d_type: 运行精度
    :param position: 位置总数
    :param name: 名称
    :return: Data Embedding
    """
    inputs = tf.keras.Input(shape=(None, embedding_dim), dtype=d_type, name="{}_inputs".format(name))
    month_inputs = tf.keras.Input(shape=(None,), dtype=d_type, name="{}_month_inputs".format(name))

    # token_embedding = tf.keras.layers.Conv1D(filters=embedding_dim, kernel_size=3, padding="same")(inputs)

    pos_inputs = inputs * tf.math.sqrt(x=tf.cast(x=embedding_dim, dtype=d_type), name="{}_sqrt".format(name))
    pos_encoding = positional_embedding(position=position, d_model=embedding_dim, d_type=d_type)
    pos_embeddings = pos_inputs + pos_encoding[:, :tf.shape(pos_inputs)[1], :]

    month_embedding = tf.keras.layers.Embedding(input_dim=13, output_dim=embedding_dim)(month_inputs)

    embeddings = pos_embeddings + month_embedding  # token_embedding +

    return tf.keras.Model(inputs=[inputs, month_inputs], outputs=embeddings, name=name)

def scaled_dot_product_attention(queries: Any, keys: Any, values: Any,
                                 mask: Any = None, d_type: tf.dtypes.DType = tf.float32):
    """ 点积注意力

    :param queries: 请求的形状 == (..., seq_len_q, depth)
    :param keys: 主键的形状 == (..., seq_len_k, depth)
    :param values: 数值的形状 == (..., seq_len_v, depth_v)
    :param mask: 填充遮罩
    :param d_type: 运算精度
    :return: 上下文向量和attention权重
    """

    matmul_qk = tf.matmul(queries, keys, transpose_b=True)
    dk = tf.cast(x=tf.shape(keys)[-1], dtype=d_type)
    scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)

    if mask is not None:
        scaled_attention_logits += (mask * -1e9)

    attention_weights = tf.nn.softmax(logits=scaled_attention_logits, axis=-1)
    output = tf.matmul(attention_weights, values)

    return output

def prob_query_key(query: tf.Tensor, key: tf.Tensor, sample_key: Any, n_top: Any) -> Tuple:
    """

    :param query: 查询
    :param key: 键
    :param sample_key: 采样个数
    :param n_top: top数量
    :return:
    """
    B, H, L, E = key.shape
    _, _, S, _ = query.shape
    key_expand = tf.broadcast_to(input=tf.expand_dims(input=key, axis=-3), shape=(B, H, S, L, E))
    index_sample = np.random.randint(low=0, high=L, size=(S, sample_key))
    key_sample = key_expand[:, :, tf.expand_dims(input=np.arange(S), axis=1), index_sample, :]
    query_key_sample = tf.matmul(tf.expand_dims(inputs=query, axis=-2),
                                 tf.squeeze(input=tf.transpose(key_sample, perm=[-2, -1])))

    M = np.max(a=query_key_sample, axis=-1)[0] - tf.divide(x=tf.reduce_sum(input_tensor=query_key_sample, axis=-1), y=L)
    M_top = tf.math.top_k(input=M, k=n_top, sorted=False)[1]

    query_reduce = query[np.arange(B)[:, None, None], np.arange(H)[None, :, None], M_top, :]
    query_key = tf.matmul(query_reduce, tf.transpose(key, perm=[-2, -1]))

    return query_key, M_top

def get_initial_context(value: Any, L_query: Any) -> tf.Tensor:
    value_sum = tf.reduce_sum(input_tensor=value, axis=-2)
    context = tf.broadcast_to(input=tf.expand_dims(input=value_sum, axis=-2),
                              shape=(value.shape[0], value.shape[1], L_query, value_sum.shape[-1]))

    return context

def update_context(context_in, value, scores, index) -> tf.Tensor:
    attention = tf.nn.softmax(logits=scores, axis=-1)
    context_in[np.arange(value.shape[0])[:, None, None], np.arange(value.shape[1])[None, :, None], index,
    :] = tf.matmul(attention, value)

    return context_in

def prob_attention(batch_size: Any, num_heads: Any, depth: Any, factor: Any = 5, mask: Any = None,
                   d_type: tf.dtypes.DType = tf.float32, scale: tf.Tensor = None,
                   name: AnyStr = "scaled_dot_produce_attention") -> tf.keras.Model:
    queries = tf.keras.Input(shape=(None, num_heads, depth), dtype=d_type, name="{}_queries".format(name))
    keys = tf.keras.Input(shape=(None, num_heads, depth), dtype=d_type, name="{}_keys".format(name))
    values = tf.keras.Input(shape=(None, num_heads, depth), dtype=d_type, name="{}_values".format(name))

    query = tf.reshape(queries, shape=(batch_size, num_heads, queries.shape[1], -1))
    key = tf.reshape(keys, shape=(batch_size, num_heads, keys.shape[1], -1))
    value = tf.reshape(values, shape=(batch_size, num_heads, values.shape[1], -1))

    U = factor * np.ceil(np.log(keys.shape[1])).astype("int").item()
    u = factor * np.ceil(np.log(queries.shape[1])).astype("int").item()

    scores_top, index = prob_query_key(query, key, u, U)
    scale_vote = scale or 1. / tf.math.sqrt(queries.shape[3])
    if scale_vote is not None:
        scores_top = scores_top * scale_vote

    context = get_initial_context(value, queries.shape[1])
    context = update_context(context, value, scores_top, index)

    return tf.keras.Model(inputs=[queries, keys, values], outputs=context, name=name)

def attention_layer(batch_size: Any, d_model: Any, num_heads: Any, attention: tf.keras.Model = None,
                    d_type: tf.dtypes.DType = tf.float32, name: AnyStr = "attention_layer") -> tf.keras.Model:
    """ Attention Layer

    :param batch_size: batch大小
    :param d_model: 特征维大小
    :param num_heads: 头注意力数量
    :param attention: 使用的self-attention类型
    :param d_type: 运算精度
    :param name: 名称
    :return: Attention Layer
    """
    queries = tf.keras.Input(shape=(None, d_model), dtype=d_type, name="{}_queries".format(name))
    keys = tf.keras.Input(shape=(None, d_model), dtype=d_type, name="{}_keys".format(name))
    values = tf.keras.Input(shape=(None, d_model), dtype=d_type, name="{}_values".format(name))

    assert d_model % num_heads == 0
    depth = d_model // num_heads

    query = tf.keras.layers.Dense(units=d_model)(queries)
    key = tf.keras.layers.Dense(units=d_model)(keys)
    value = tf.keras.layers.Dense(units=d_model)(values)

    query = tf.transpose(tf.reshape(query, (batch_size, -1, num_heads, depth)), perm=[0, 2, 1, 3])
    key = tf.transpose(tf.reshape(key, (batch_size, -1, num_heads, depth)), perm=[0, 2, 1, 3])
    value = tf.transpose(tf.reshape(value, (batch_size, -1, num_heads, depth)), perm=[0, 2, 1, 3])

    if attention is None:
        context = scaled_dot_product_attention(queries=query, keys=key, values=value, d_type=d_type)
    else:
        context = attention(inputs=[query, key, value])
    context = tf.transpose(context, perm=[0, 2, 1, 3])
    concat_context = tf.reshape(context, (batch_size, -1, d_model))

    outputs = tf.keras.layers.Dense(d_model)(concat_context)

    return tf.keras.Model(inputs=[queries, keys, values], outputs=outputs, name=name)


# pylint: disable=import-outside-toplevel
"""Test importers with info from Scopus downloaded in 2023-10-05."""

import os

import pandas as pd

DATABASE_FILES = [
    "tmp/databases/_cited_by.csv.zip",
    "tmp/databases/_main.csv.zip",
    "tmp/databases/_references.csv.zip",
]

def test_isbn_importer():
    """Test."""

    # Test data:
    if not os.path.exists("tmp/databases"):
        os.makedirs("tmp/databases")

    for file in DATABASE_FILES:
        pd.DataFrame(
            {
                "isbn": [
                    "008045108x; 978-008045108-4",
                    "0780357728",
                    "979-888697185-9; 979-888697052-4",
                    pd.NA,
                ],
            }
        ).to_csv(file, index=False, compression="zip")

    # Run:
    from techminer2.ingest.field_importers.issb_isbn_eissn_importer import (
        run_issb_isbn_eissn_importer,
    )

    run_issb_isbn_eissn_importer(root_dir="tmp/")

    # Check:
    for file in DATABASE_FILES:
        test_df = pd.read_csv(file, compression="zip", dtype={"issn": str})

        assert "isbn" in test_df.columns

        assert test_df.loc[0, "isbn"] == "008045108x; 978-008045108-4"
        assert test_df.loc[1, "isbn"] == "0780357728"
        assert test_df.loc[2, "isbn"] == "979-888697185-9; 979-888697052-4"
        assert pd.isna(test_df.loc[3, "isbn"])

def test_issn_importer():
    """Test."""

    # Test data:
    if not os.path.exists("tmp/databases"):
        os.makedirs("tmp/databases")

    for file in DATABASE_FILES:
        pd.DataFrame(
            {
                "issn": [
                    "00010782",
                    pd.NA,
                ],
            }
        ).to_csv(file, index=False, compression="zip")

    # Run:
    from techminer2.ingest.field_importers.issb_isbn_eissn_importer import (
        run_issb_isbn_eissn_importer,
    )

    run_issb_isbn_eissn_importer(root_dir="tmp/")

    # Check:
    for file in DATABASE_FILES:
        test_df = pd.read_csv(file, compression="zip", dtype={"issn": str})

        assert "issn" in test_df.columns

        assert test_df.loc[0, "issn"] == "00010782"
        assert pd.isna(test_df.loc[1, "issn"])


from model import Team as T
from data import Const as C
import math

"""
Defines a set of two teams, with all 10 players
"""

class TeamSet:
    def __init__(self, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10):

        self.t1 = T.Team(p1, p2, p3, p4, p5)
        self.t2 = T.Team(p6, p7, p8, p9, p10)

        self.score = 0
        self.rating = 0
        self.level_diff = 0
        self.role_pref = 0
        self.value_diff = 0
        self.synergy = 0
        self.other_value_diff = 0

        self.calc_score()

    def __hash__(self):
        return hash(self.t1) + hash(self.t2)

    def __eq__(self, other):
        return (self.t1 == other.t1 and self.t2 == other.t2) or (self.t1 == other.t2 and self.t2 == other.t1)

    def __ne__(self, other):
        return not self.__eq__(other)

    def calc_score(self):
        rating = (self.t1.rank_sum + self.t2.rank_sum) / 10 / C.AVG_RANK

        level_diff = 1 - abs(self.t1.rank_sum - self.t2.rank_sum) / 5

        pref_role_sum = (self.t1.role_pref + self.t2.role_pref) / C.MAX_ROLE_PREF

        synergy = (self.t1.synergy_sum + self.t2.synergy_sum) / 10 + 1

        other_value_diff = 0
        for i in range(C.VAL_COEFF_COUNT):
            other_value_diff += abs(self.t1.other_values[i] - self.t2.other_values[i]) * \
                                C.PLAYER_OTHER_STATS_DIFF_WEIGHTS[i]

        other_value_diff = math.exp(-other_value_diff)

        value_diff = math.exp(- abs(self.t1.value - self.t2.value))

        self.rating = round(rating, 2)
        self.level_diff = round(level_diff, 2)
        self.role_pref = round(pref_role_sum, 2)
        self.synergy = round(synergy, 2)
        self.value_diff = round(value_diff, 2)
        self.other_value_diff = round(other_value_diff, 2)

        score = rating * C.weight_factors[0] + \
                pref_role_sum * C.weight_factors[1] + \
                level_diff * C.weight_factors[2] + \
                synergy * C.weight_factors[3] + \
                value_diff * C.weight_factors[4] +\
                other_value_diff * C.weight_factors[5]

        score = round(score, 5)  # 5 Decimal places
        self.score = score

    def detailed_score(self):
        return "Score Parameters (Each field is out of 1)\n" +\
        "Role Pref = " + str(self.role_pref) + "\n" + \
        "Level Diff = " + str(self.level_diff) + "\t" + \
            str(self.t1.rank_sum) + " vs " + str(self.t2.rank_sum) + "\n" + \
        "Synergy Score = " + str(self.synergy) + "\n" + \
        "Rating = " + str(self.rating) + "\n" + \
        "Value Diff = " + str(self.value_diff) + "\t" + str(self.t1.value) + " vs " + str(self.t2.value) + "\n" + \
        "Other Value Diff = " + str(self.other_value_diff) + "\n" +\
            "\tComms " + str(self.t1.comms_value) + " vs " + str(self.t2.comms_value) + "\n" + \
            "\tFlex " + str(self.t1.flex_value) + " vs " + str(self.t2.flex_value) + "\n" + \
            "\tUntilt " + str(self.t1.untilt_value) + " vs " + str(self.t2.untilt_value) + "\n" + \
            "\tConsistency " + str(self.t1.consist_value) + " vs " + str(self.t2.consist_value)

    def to_string(self):
        return self.t1.players[0].name + "\t\t" + self.t2.players[0].name + "\n" + \
            self.t1.players[1].name + "\t\t" + self.t2.players[1].name + "\n" + \
            self.t1.players[2].name + "\t\t" + self.t2.players[2].name + "\n" + \
            self.t1.players[3].name + "\t\t" + self.t2.players[3].name + "\n" + \
            self.t1.players[4].name + "\t\t" + self.t2.players[4].name


""""
Confeccionar una función que le enviemos como parámetro un string y nos retorne la
cantidad de caracteres que tiene. En el bloque principal solicitar la carga de dos
nombres por teclado y llamar a la función dos veces. Imprimir en el bloque principal
cuál de las dos palabras tiene más caracteres.
"""
#funcion

import os
os.system("cls")

def contador_caracteres(caracter):
    largo= len(caracter)
    return largo

def datos():
    palabra1= input("Ingrese una palabra: ")
    largo_palabra_1 = contador_caracteres(palabra1)

    palabra2 = input("Ingrese otra palabra: ")
    largo_palabra_2 =contador_caracteres(palabra2)

    if largo_palabra_1 ==  largo_palabra_2:
        print (f"La cantidad de caracteres entre {palabra1} y {palabra2} es la misma '{largo_palabra_1}'")
    elif largo_palabra_1 > largo_palabra_2:
        print(f"La diferencia de caracteres entre {palabra1} y {palabra2} es: '{largo_palabra_1-largo_palabra_2}', por ende el mayor es palabra 1: {palabra1}")
    else:
        print(f"La diferencia de caracteres entre {palabra1} y {palabra2} es: '{largo_palabra_2-largo_palabra_1}', por ende el mayor es palabra 2: {palabra2}")

#main
datos()

profe_David/Concepto de funciones - Programación estructurada/largo_cadena.py


import wx
import common
import wcodegen
from edit_windows import ManagedBase, EditStylesMixin
from tree import Node
import new_properties as np

class EditStaticLine(ManagedBase, EditStylesMixin):
    "Class to handle wxStaticLine objects"
    _PROPERTIES = ["Widget", "attribute"]
    PROPERTIES = ManagedBase.PROPERTIES + _PROPERTIES + ManagedBase.EXTRA_PROPERTIES
    PROPERTIES.remove("font")
    _PROPERTY_LABELS = {"attribute":'Store as attribute'}
    _PROPERTY_HELP={"attribute":'Store instance as attribute of window class; e.g. self.line_1 = wx.wxStaticLine(...)\n'
                                'Without this, you can not access the line from your program.'}
    def __init__(self, name, parent, id, style, sizer, pos):
        ManagedBase.__init__(self, name, 'wxStaticLine', parent, id, sizer, pos)
        EditStylesMixin.__init__(self)

        # initialise instance properties
        self.attribute = np.CheckBoxProperty(False, default_value=False)
        if style: self.properties["style"].set(style)

    def create_widget(self):
        self.widget = wx.StaticLine(self.parent.widget, self.id, style=self.style)
        wx.EVT_LEFT_DOWN(self.widget, self.on_set_focus)

    def finish_widget_creation(self):
        ManagedBase.finish_widget_creation(self)
        self.sel_marker.Reparent(self.parent.widget)
        #del self.properties['font']

    def __getitem__(self, key):
        if key != 'font':
            return ManagedBase.__getitem__(self, key)
        return lambda: "", lambda v: None

editor_class = EditStaticLine
editor_icon = 'static_line.xpm'
editor_name = 'EditStaticLine'
editor_style = ''

dlg_title = _('wxStaticLine')
box_title = _('Orientation')
choices = 'wxLI_HORIZONTAL|wxLI_VERTICAL'
tmpl_label = 'static_line'

def builder(parent, sizer, pos, number=[1]):
    "factory function for editor objects from GUI"
    dialog = wcodegen.WidgetStyleSelectionDialog(dlg_title, box_title, choices)
    res = dialog.ShowModal()
    style = dialog.get_selection()
    dialog.Destroy()
    if res != wx.ID_OK:
        return

    label = '%s_%d' % (tmpl_label, number[0])
    while common.app_tree.has_name(label):
        number[0] += 1
        label = '%s_%d' % (tmpl_label, number[0])
    widget = editor_class(label, parent, wx.ID_ANY, style, sizer, pos)
    node = Node(widget)
    widget.node = node
    if parent.widget: widget.create()
    common.app_tree.insert(node, sizer.node, pos-1)

def xml_builder(attrs, parent, sizer, sizeritem, pos=None):
    "Factory to build editor objects from a XML file"
    from xml_parse import XmlParsingError
    try:
        name = attrs['name']
    except KeyError:
        raise XmlParsingError(_("'name' attribute missing"))
    if sizer is None or sizeritem is None:
        raise XmlParsingError(_("sizer or sizeritem object cannot be None"))
    widget = editor_class(name, parent, wx.ID_ANY, editor_style, sizer, pos)
    sizer.set_item(widget.pos, proportion=sizeritem.proportion, flag=sizeritem.flag, border=sizeritem.border)
    node = Node(widget)
    widget.node = node
    if pos is None:
        common.app_tree.add(node, sizer.node)
    else:
        common.app_tree.insert(node, sizer.node, pos-1)
    return widget

def initialize():
    "initialization function for the module: returns a wxBitmapButton to be added to the main palette"
    common.widgets[editor_name] = builder
    common.widgets_from_xml[editor_name] = xml_builder
    return common.make_object_button(editor_name, editor_icon)


def htn(n,s,v,to1):
    k=0
    if n==1:
        return 1
    else:
        return htn(n-1,s,v,to1)+1+htn(n-1,v,to1,s)#사실 htn(n-1,s,v,to1)=htn(n-1,v,to1,s)임을 알 수 있음
def htop(n,start,to,via):
    if n==1:
        print(start,to)
        return
    else:
        htop(n-1,start,via,to)
        print(start,to)
        htop(n-1,via,to,start)
    return
k=int(input())
print(htn(k,1,3,2))
htop(k,1,3,2)


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Author: Stéphan Pissot
A minimalistic launcher to start the tools
"""
import sys
from PyQt5.Qt import qApp
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel
from octavvs import preprocessing, clustering, mcr_als

def start_preprocessing():
    preprocessing.MyMainWindow.run_octavvs_application(isChild=True)
def start_clustering():
    clustering.MyMainWindow.run_octavvs_application(isChild=True)
def start_mcrals():
    mcr_als.MyMainWindow.run_octavvs_application(isChild=True)

def main():
   app = QApplication(sys.argv)
   widget = QWidget()

   label=QLabel(widget)
   label.setText('OCTAVVS')
   label.move(10,10)

   button1 = QPushButton(widget)
   button1.setText("Preprocessing")
   button1.move(10,42)
   button1.clicked.connect(start_preprocessing)

   button2 = QPushButton(widget)
   button2.setText("Clustering")
   button2.move(10,72)
   button2.clicked.connect(start_clustering)

   button3 = QPushButton(widget)
   button3.setText("MCR-ALS")
   button3.move(10,102)
   button3.clicked.connect(start_mcrals)

   widget.setWindowTitle("OCTAVVS Launcher")
   widget.show()
   qApp.lastWindowClosed.connect(qApp.quit);
   sys.exit(app.exec_())

#if __name__ == '__main__':
#    main()


import torch
import torch.nn as nn

from models.modules import *

class LRCM(nn.Module):

    def __init__(
        self,
        bb_name,
        backbone_pretrained_path,
        in_channels_list,
        embedding_dim,
        rlow_pool_size,
        rmid_pool_size,
        rhig_pool_size,
        vlow_pool_size,
        vmid_pool_size,
        vhig_pool_size,
        low_patch_num,
        mid_patch_num,
        hig_patch_num,
        n_head,
        reduced_dim,
        atte_hidden_unit,
        dropout,
        num_class = 200,
        pretrained_model_path = None
    ):
        super(LRCM,self).__init__()

        latent_features = embedding_dim // 4

        self.r_module = RepresentationModule(
            bb_name = bb_name,
            bb_weight_path = backbone_pretrained_path,
            channels_list = in_channels_list,
            rlow_pool_size = rlow_pool_size,
            rmid_pool_size = rmid_pool_size,
            rhig_pool_size = rhig_pool_size,
            embedding_dim = embedding_dim,
            atte_hidden_unit = atte_hidden_unit,
            latent_features = latent_features,
            num_class = num_class
        )

        self.v_module = VectorsEmbeddingModule(
            low_pool_size = vlow_pool_size,
            mid_pool_size = vmid_pool_size,
            hig_pool_size = vhig_pool_size,
            low_patch_num = low_patch_num,
            mid_patch_num = mid_patch_num,
            hig_patch_num = hig_patch_num,
            embedding_dim = embedding_dim,
            dropout = dropout
        )

        self.c_module = ComprehensionModule(
            embedding_dim = embedding_dim,
            reduced_dim = reduced_dim,
            n_head = n_head,
            atte_hidden_unit = atte_hidden_unit,
            dropout = dropout,
            num_class = num_class
        )

        if pretrained_model_path is not None:
            self.load_state_dict(torch.load(pretrained_model_path))

    def forward(self,img,low_patch_indices = None,mid_patch_indices = None,hig_patch_indices = None,step = "final"):

        if step == "coarse":
            return self.r_module(img,low_patch_indices,mid_patch_indices,hig_patch_indices,step)
        elif step == "fine":
            return self.c_module(*self.v_module(*self.r_module(img,low_patch_indices,mid_patch_indices,hig_patch_indices,step)))
        else:
            low_fea,mid_fea,hig_fea,\
            low_coarse_vectors,mid_coarse_vectors,hig_coarse_vectors,\
            low_logits,mid_logits,hig_logits = self.r_module(img,low_patch_indices,mid_patch_indices,hig_patch_indices,step)
            coarse_logits,com_logits = self.c_module(*self.v_module(low_fea,mid_fea,hig_fea,low_coarse_vectors,mid_coarse_vectors,hig_coarse_vectors))
            return low_logits,mid_logits,hig_logits,coarse_logits,com_logits


#!python
import re, sys, subprocess
lineparser = re.compile("#\d+ (0x[abcdef\d]+)")
gdbparser = re.compile('(\d+) .* "(.+)" (0x[a-f,0-9]+) (.+)')

def decode(line):
    addrs = lineparser.findall(line)
    binary = sys.argv[1] if len(sys.argv) > 1 else "/opt/opengauss/bin/gaussdb"
    gdbl = "gdb " + binary + ' ' + ' '.join(['-ex "info line *' + hx + '"' for hx in addrs])
    gdbl += ' -ex "quit"'
    gd = subprocess.run(gdbl, shell=True, stdout=subprocess.PIPE, universal_newlines=True).stdout

    idx,pos = (0,0)

    while pos >=0:
        idx+=1
        pos = gd.find('Line', pos+1)
        if pos == -1: continue
        st = gd.find('starts', pos)
        e = gd.find('\n', st)
        ln = gd[pos:e].replace('\n', "").replace("   ", " ").replace("starts at address ", "")
        fields = gdbparser.search(ln).groups()
        print (f"#{idx} {fields[2]} in {fields[3]} at {fields[1]}:{fields[0]}")

if __name__ == "__main__":
    for line in sys.stdin:
        decode(line)


import json
import logging
import os
import numpy as np
import equation as eqn
from utility import get_config, DictionaryUtility
from solver import FeedForwardModel

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
# import tensorflow as tf

FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('config_path', './configs/sdg_d2_ma.json',
                           """The path to load json file.""")
tf.app.flags.DEFINE_string('exp_name', None,
                           """The name of numerical experiments.""")
tf.app.flags.DEFINE_integer('num_run', 1,
                            """The number of experiments to repeatedly run for the same problem.""")
tf.app.flags.DEFINE_string('log_dir1', './logs',
                           """Directory where to write event logs and output array.""")

def main():
    config = get_config(FLAGS.config_path)
    bsde = getattr(eqn, config.eqn_config.eqn_name)(config.eqn_config)
    if FLAGS.exp_name is None: # use config name as exp_name
        FLAGS.exp_name = os.path.splitext(os.path.basename(FLAGS.config_path))[0]
    if not os.path.exists(FLAGS.log_dir1):
        os.mkdir(FLAGS.log_dir1)
    path_prefix = os.path.join(FLAGS.log_dir1, FLAGS.exp_name)
    with open('{}_config.json'.format(path_prefix), 'w') as outfile:
        json.dump(DictionaryUtility.to_dict(config), outfile, indent=2)
    logging.basicConfig(level=logging.INFO,
                        format='%(levelname)-6s %(message)s')

    dim = config.eqn_config.dim

    for idx_run in range(1, FLAGS.num_run+1):
        tf.reset_default_graph()
        with tf.Session() as sess:
            logging.info('Begin to solve %s with run %d' % (FLAGS.exp_name, idx_run))
            model = FeedForwardModel(config, bsde, sess)
            if config.eqn_config.eigenpair == 'first':
                model.build()
            else:
                model.build_second()
            result = model.train()
            training_history = result[0]
            # save training history
            np.savetxt('{}_log{}.csv'.format(path_prefix, idx_run),
                       training_history,
                       fmt=['%d', '%.5e', '%.5e', '%.5e', '%.5e', '%.5e', '%.5e', '%.5e', '%.5e', '%d'],
                       delimiter=",",
                       header="step,train_loss, eg_err, egfcn_l2_err, egfcn_infty_err, grad_l2_err, grad_infty_err, consistency_loss, norm_factor, elapsed_time",
                       comments='')
            figure_data = result[1]
            if dim == 1:
                np.savetxt('{}_hist.csv'.format(path_prefix), figure_data, delimiter=",",
                           header="x,y_true,y_NN", comments='')
            else:
                np.savetxt('{}_hist.csv'.format(path_prefix), figure_data, delimiter=",",
                           header="y_true,y_NN", comments='')

if __name__ == '__main__':
    main()


from typing import Any, Dict, Tuple

import numpy as np
from do_mpc.model import Model
from do_mpc.simulator import Simulator

from dompcacadoscoupler.acados_simulator_for_dompc import set_acados_simulator

def setup_simple_model() -> Model:
    model_type = 'continuous'
    model = Model(model_type)
    x = model.set_variable('_x', 'x')
    z = model.set_variable('_z', 'z')
    z_2 = model.set_variable('_z', 'z_2')
    u = model.set_variable('_u', 'u')
    p = model.set_variable('_p', 'p')

    model.set_rhs('x', z + u + p)
    model.set_alg('z_alg_0', z - 1)
    model.set_alg('z_alg_1', z_2 - 1)
    model.setup()
    return model

def create_simple_simulator(model: Model) -> Simulator:
    simulator = Simulator(model)
    simulator.set_param(t_step=1, integration_tool='idas')
    p_template = simulator.get_p_template()

    def p_fun(t_now):
        p_template['p'] = 1
        return p_template

    simulator.set_p_fun(p_fun)
    simulator.x0 = 1
    return simulator

def setup_simple_simulator() -> Simulator:
    model = setup_simple_model()
    simulator = create_simple_simulator(model)
    simulator.setup()
    return simulator

def test_simulator() -> None:
    simulator = setup_simple_simulator()
    simulator.acados_options = {'integrator_type': 'IRK'}  # type: ignore
    set_acados_simulator(simulator)
    x_result = []
    u0 = np.array([[0]])
    for _ in range(10):
        next_x = simulator.make_step(u0)
        x_result.append(next_x)
    expected_x = np.array([3., 5., 7., 9., 11., 13., 15., 17., 19., 21.])
    np.testing.assert_allclose(np.asarray(x_result).squeeze(), expected_x)

if __name__ == '__main__':
    test_simulator()


import matplotlib.pyplot as plt
import numpy as np
import cv2

from PyQt5 import QtGui,QtCore,QtWidgets
from PyQt5.QtCore import QDateTime, Qt, QTimer,QCoreApplication
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import (QApplication, QGridLayout, QGroupBox, QComboBox,
                             QHBoxLayout, QLabel, QLineEdit, QPushButton,
                             QSizePolicy, QDialog, QTableWidget, QTextEdit,
                             QVBoxLayout, QWidget, QFileDialog, QTableWidgetItem)

print("No Problem ImportingLibraries --> Starting the tool -->")

class mainWindow(QDialog):
    def __init__(self,parent=None):
        super(mainWindow,self).__init__(parent)
        scale = 1.4
        self.setFixedSize(1400 * scale,1000 * scale)
        self.setWindowTitle('tableDraw Tool')
        self.guiCols = 4

        self.globalFont = QtGui.QFont('consolas',10)
        self.wStatement = QLabel('I\'ll tell you the number of cuts horizontal, vertical and their width\n \n \n \n ')
        self.wStatement.setFont(self.globalFont)

        self.createGroupPanel()
        self.createGroupPieces()
        self.createGroupCalc()
        self.createGroupSaw()

        # Create image window
        self.wImg = QLabel()

        self.eval()

        mainLayout = QGridLayout()
        mainLayout.addWidget(self.wImg,0,0,5,self.guiCols,QtCore.Qt.AlignCenter)
        mainLayout.addWidget(self.wStatement,5,0,1,self.guiCols,QtCore.Qt.AlignCenter)
        mainLayout.addWidget(self.gPanel,6,0,2,2)
        mainLayout.addWidget(self.gPieces,6,2,2,2)
        mainLayout.addWidget(self.gSaw,8,0,1,self.guiCols)
        mainLayout.addWidget(self.gCalc,9,0,1,self.guiCols)

        self.setLayout(mainLayout)

    def createGroupPanel(self):
        self.gPanel = QGroupBox("Panel Dimensions")
        self.gPanel.setFont(self.globalFont)

        xText = QLabel('Panel X (mm) :')
        xText.setFont(self.globalFont)
        yText = QLabel('Panel Y (mm) :')
        yText.setFont(self.globalFont)
        zText = QLabel('Panel Z (mm) :')
        zText.setFont(self.globalFont)

        self.xEdit = QLineEdit(str(2400))
        self.xEdit.setFont(self.globalFont)
        self.yEdit = QLineEdit(str(1200))
        self.yEdit.setFont(self.globalFont)
        self.zEdit = QLineEdit(str(18))
        self.zEdit.setFont(self.globalFont)

        panelLayout = QGridLayout()
        panelLayout.addWidget(xText,0,0)
        panelLayout.addWidget(self.xEdit,0,1)
        panelLayout.addWidget(yText,1,0)
        panelLayout.addWidget(self.yEdit,1,1)
        panelLayout.addWidget(zText,2,0)
        panelLayout.addWidget(self.zEdit,2,1)

        self.gPanel.setLayout(panelLayout)

    def createGroupPieces(self):
        self.gPieces = QGroupBox("Piece Dimensions")
        self.gPieces.setFont(self.globalFont)

        lText = QLabel('Piece Length (mm) :')
        lText.setFont(self.globalFont)
        dText = QLabel('Piece Depth  (mm) :')
        dText.setFont(self.globalFont)
        wText = QLabel('Piece Width  (mm) :')
        wText.setFont(self.globalFont)

        self.lEdit = QLineEdit(str(60))
        self.lEdit.setFont(self.globalFont)
        self.dEdit = QLineEdit(str(30))
        self.dEdit.setFont(self.globalFont)
        self.wEdit = QLineEdit(self.zEdit.text())
        self.wEdit.setFont(self.globalFont)
        self.wEdit.setReadOnly(True)

        panelLayout = QGridLayout()
        panelLayout.addWidget(lText,0,0)
        panelLayout.addWidget(self.lEdit,0,1)
        panelLayout.addWidget(dText,1,0)
        panelLayout.addWidget(self.dEdit,1,1)
        panelLayout.addWidget(wText,2,0)
        panelLayout.addWidget(self.wEdit,2,1)

        self.gPieces.setLayout(panelLayout)

    def createGroupSaw(self):
        self.gSaw = QGroupBox('Saw Parameters')
        self.gSaw.setFont(self.globalFont)

        saw = QLabel('Saw Width (mm) :')
        saw.setFont(self.globalFont)
        dep = QLabel('Twiddle   (mm) :')
        dep.setFont(self.globalFont)

        self.sawEdit = QLineEdit(str(3))
        self.sawEdit.setFont(self.globalFont)
        self.depEdit = QLineEdit(str(1))
        self.depEdit.setFont(self.globalFont)

        panelLayout = QGridLayout()

        panelLayout.addWidget(saw,0,0)
        panelLayout.addWidget(self.sawEdit,0,1)
        panelLayout.addWidget(dep,0,2)
        panelLayout.addWidget(self.depEdit,0,3)

        self.gSaw.setLayout(panelLayout)

    def createGroupCalc(self):
        self.gCalc = QGroupBox('Calculation Result')
        self.gCalc.setFont(self.globalFont)

        self.wNumCols = QLabel('Cuts X : 0')
        self.wNumCols.setFont(self.globalFont)
        self.wNumRows = QLabel('Cuts Y : 0')
        self.wNumRows.setFont(self.globalFont)
        self.wRotated = QLabel('Rotation : 0')
        self.wRotated.setFont(self.globalFont)
        self.wNumPieces = QLabel('Pieces : 0')
        self.wNumPieces.setFont(self.globalFont)
        self.wCalcButton = QPushButton('Calculate Number of Pieces')
        self.wCalcButton.setFont(self.globalFont)
        self.wCalcButton.clicked.connect(lambda: self.eval())

        panelLayout = QGridLayout()

        panelLayout.addWidget(self.wNumCols,0,0)
        panelLayout.addWidget(self.wNumRows,0,1)
        panelLayout.addWidget(self.wRotated,0,2)
        panelLayout.addWidget(self.wNumPieces,0,3)
        panelLayout.addWidget(self.wCalcButton,1,0,1,self.guiCols)

        self.gCalc.setLayout(panelLayout)

    def eval(self):
        self.checkData()

        if (self.dataOK):
            self.calc()
            self.vizualise()
        else:
            self.wStatement.setText('There was something wrong with your dimensions\n'
                                    + 'It can\'t possibly exist!\n \n \n ')

    def checkData(self):
        self.dataOK = True

        # Check the Panel data
        self.dataOK &= self.testInt(self.xEdit)
        self.dataOK &= self.testInt(self.yEdit)
        self.dataOK &= self.testInt(self.zEdit)

        # Force the z data and Width data to be aligned
        self.wEdit.setText(self.zEdit.text())

        # Check the Piece data
        self.dataOK &= self.testInt(self.lEdit)
        self.dataOK &= self.testInt(self.dEdit)
        self.dataOK &= self.testInt(self.wEdit)

        # Check the Saw data
        self.dataOK &= self.testInt(self.sawEdit)
        self.dataOK &= self.testInt(self.depEdit,True)

    def testInt(self, lineEditWidget,okZero=False):
        # Check that the input can be cast to an int
        # If is can, make it positive, otherwise make it 0
        try:
            deadVar = int(lineEditWidget.text())
            if (deadVar < 0):
                lineEditWidget.setText(str(-deadVar))
            return (deadVar != 0) or (okZero)
        except:
            lineEditWidget.setText(str(0))
            return False

    def calc(self):
        # Preallocate some values so its easier to read
        sawWidth = int(self.sawEdit.text())
        twiddle  = int(self.depEdit.text())
        inputX   = int(self.xEdit.text())
        inputY   = int(self.yEdit.text())

        maxArea  = inputX * inputY # in mm^2
        self.orientation = -1

        tempLength = float(int(self.lEdit.text()) + sawWidth)
        tempDepth  = float(int(self.dEdit.text()) + sawWidth + twiddle)

        rows   = []
        cols   = []
        pieces = []

        # Get the number of non-rotated cuts
        if (inputX >= int(self.lEdit.text())) and (inputY >= int(self.dEdit.text())):
            outX0 = inputX - int(self.lEdit.text())
            outY0 = inputY - int(self.dEdit.text())
            rows.append(1)
            cols.append(1)

            cols[0] += int(outX0 / tempLength)
            rows[0] += int(outY0 / tempDepth)
        else:
            cols.append(0)
            rows.append(0)

        # Get the number of rotated cuts
        if (inputX >= int(self.dEdit.text())) and (inputY >= int(self.lEdit.text())):
            outX1 = inputX - int(self.dEdit.text())
            outY1 = inputY - int(self.lEdit.text())
            rows.append(1)
            cols.append(1)

            cols[1] += int(outX1 / tempDepth)
            rows[1] += int(outY1 / tempLength)
        else:
            cols.append(0)
            rows.append(0)

        # Calculate the number of pieces made
        pieces.append(rows[0] * cols[0])
        pieces.append(rows[1] * cols[1])

        if (pieces[0] >= pieces[1]):
            self.orientation = 0
        elif(pieces[1] > 0):
            self.orientation = 1

        warnArea = False
        if (self.orientation == -1):
            self.wStatement.setText('There was something wrong with the dimensions\n'
                                    + 'It can\'t possibly exist\n \n \n ')

        else:
            usedArea = (pieces[self.orientation]
                       * int(self.lEdit.text())
                       * int(self.dEdit.text())) # mm^2

            sawnArea = ((cols[self.orientation]) * inputX * sawWidth
                       +(rows[self.orientation]) * inputY * sawWidth
                       - pieces[self.orientation] * sawWidth * sawWidth)

            wasteArea = maxArea - usedArea # mm^2

            tableArea  = (pieces[self.orientation]
                         * int(self.wEdit.text())
                         * int(self.lEdit.text())
                         * 1e-6)

            if (wasteArea < 0):
                wasteArea = 0

            if (sawnArea < 0):
                sawnArea = 0
            else:
                if (cols[self.orientation] == 1) and (rows[self.orientation] == 1):
                    sawnArea = 0
                elif (cols[self.orientation] == 1):
                    sawnArea = rows[self.orientation] * inputY
                elif (rows[self.orientation] == 1):
                    sawnArea = cols[self.orientation] * inputX

            # assert(usedArea <= maxArea)
            # assert(wasteArea < maxArea)
            # assert(wasteArea >= sawnArea)

            self.wNumPieces.setText('Pieces : ' + str(pieces[self.orientation]))
            self.wRotated.setText('Rotation : ' + str(self.orientation))
            self.wNumCols.setText('Cuts X : ' + str(rows[self.orientation]))
            self.wNumRows.setText('Cuts Y : ' + str(cols[self.orientation]))
            self.wStatement.setText('Wow, you actually gave good dimensions \^.^/'
                                    + '\nThe wastage is   : ' + str((wasteArea * 100 / maxArea)) + ' %'
                                    + '\nBut sawn area is : ' + str((sawnArea * 100 / maxArea)) + ' %'
                                    + '\nSo real waste is : ' + str((wasteArea - sawnArea) * 100 / maxArea) + ' %'
                                    + '\nThe coverable area is : ' + str(tableArea) + ' m^2')

    def vizualise(self):
        pCols = int(self.xEdit.text())
        pRows = int(self.yEdit.text())
        sawWidth = int(self.sawEdit.text())
        twiddle  = int(self.depEdit.text())

        canvas = np.ones((pRows,pCols,3))

        if (self.orientation == 0):
            cutX = int(self.lEdit.text()) + sawWidth
            cutY = int(self.dEdit.text()) + sawWidth + twiddle
            widX = sawWidth
            widY = sawWidth + twiddle
        elif (self.orientation == 1):
            cutX = int(self.dEdit.text()) + sawWidth + twiddle
            cutY = int(self.lEdit.text()) + sawWidth
            widX = sawWidth + twiddle
            widY = sawWidth
        else:
            return -1

        imgDim = 3

        # Make marks on the columns
        cCols = cutX
        fullCol = np.zeros((pRows,1,imgDim))
        while (cCols < pCols):

            for i in range(widX):
                canvas[:,cCols - i,:] = fullCol[:,0,:]

            cCols += cutX

        # Make marks on the columns
        cRows = cutY
        fullRow = np.zeros((1,pCols,imgDim))
        while (cRows < pRows):
            for i in range(widY):
                canvas[cRows - i,:,:] = fullRow[0,:,:]

            cRows += cutY

        # Mark off the grey area of true wastage
        cCols -= cutX
        cRows -= cutY
        gCols  = np.ones((pRows,1,imgDim)) * 0.5
        gRows  = np.ones((1,pCols,imgDim)) * 0.5

        if cCols > 0:
            for cols in range(cCols,pCols):
                canvas[:,cols,:] = gCols[:,0,:]

        if cRows > 0:
            for rows in range(cRows,pRows):
                canvas[rows,:,:] = gRows[0,:,:]

        dummyName = 'tempResultant.png'
        cv2.imwrite(dummyName,canvas * 255)
        canvas = cv2.imread(dummyName)

        canvas = self.imageUnskew(canvas)

        # Perform image scaling
        maxRows    = 700
        scale      = maxRows / pRows
        scaledRows = maxRows
        scaledCols = int(scale * pCols)

        canvas = cv2.resize(canvas,(scaledCols,scaledRows))

        qImg = QtGui.QImage(canvas,canvas.shape[1],canvas.shape[0],QtGui.QImage.Format_RGB888).rgbSwapped()
        pMap = QtGui.QPixmap.fromImage(qImg)
        self.wImg.setPixmap(pMap)

    def imageUnskew(self,npArray):
        return npArray

if __name__ == "__main__":
    app = QApplication([])
    gui = mainWindow()
    gui.show()
    app.exec_()


import torch
import torch.nn as nn
from torch.autograd import Variable
import math
import torch.nn.functional as F

def check_unitFraction(x):
    a = 1/x
    return a==int(a)

class S2Conv(nn.Module):
    # q is parameter that control output channel size.
    def __init__(self, c_in, shift_size, q=1, dilation=1):
        super(S2Conv, self).__init__()
        self.c_in = c_in
        self.shift_size = shift_size
        self.d = dilation
        self.q = q
        if q<1:
            self.conv = nn.Conv1d(int(self.shift_size*c_in*q), int(c_in*q), kernel_size=1, padding=0, stride=1, bias=False, groups=int(c_in*q))
        elif q>=1:
            self.conv = nn.Conv1d(self.shift_size*c_in, int(c_in*q), kernel_size=1, padding=0, stride=1, bias=False, groups=c_in)
        self.bn = nn.BatchNorm1d(int(c_in*q))

    def shift(self, x):
        out = torch.zeros_like(x)
        for k in range(self.c_in):
            sh_n = (k % self.shift_size) - (self.shift_size//2) # if shift_size=7, sh_n -> -3~3
            sh_n = sh_n * self.d
            if sh_n < 0:
                out[:, k, :sh_n] = x[:, k, -sh_n:]  # shift left
            elif sh_n >0:
                out[:, k, sh_n:] = x[:, k, :-sh_n]  # shift right
            else:
                out[:,k,:] = x[:,k,:] # not shift

        return out

    def forward(self, x):
        x = self.shift(x)
        n, c, t = x.size()
        pad = self.shift_size//2
        t_p = Variable(torch.zeros(n, pad, t))
        if self.shift_size % 2 ==0:
            pad = pad -1
        b_p = Variable(torch.zeros(n, pad, t))

        if next(self.parameters()).is_cuda:
            t_p = t_p.cuda()
            b_p = b_p.cuda()

        x = torch.cat((t_p, x, b_p), dim=1)
        if self.q <= 1:
            stride=int(1/self.q)
        else:
            stride = 1
        h = torch.cat([x[:,i*stride:i*stride+self.shift_size,:] for i in range((x.size(1)-self.shift_size+1)//stride)], dim=1)
        out = self.conv(h)
        out = self.bn(out)
        return F.relu_(out)

class BasicConv1d(nn.Module):
    def __init__(self, i_nc, o_nc, **kwargs):
        super(BasicConv1d, self).__init__()
        self.conv = nn.Sequential(
            nn.Conv1d(i_nc, o_nc, **kwargs),
            nn.BatchNorm1d(o_nc)
        )
    def forward(self, x):
        x = self.conv(x)
        return F.relu_(x)

class MTS_module(nn.Module):
    def __init__(self, i_nc, o_nc, n_b):
        super(MTS_module, self).__init__()
        self.o_ncs = self.split_branch(o_nc, n_b+1)
        self.l1 = BasicConv1d(i_nc, self.o_ncs[0], kernel_size=1, stride=1, padding=0, bias=False)
        self.ls = nn.ModuleList()
        for i in range(n_b):
            shift_size = i*2+3
            self.ls.append(S2Conv(self.o_ncs[i+1], shift_size))
    def forward(self, x):
        x1 = self.l1(x)
        tx = x1[:,:self.o_ncs[1],:]
        out = torch.cat([conv(tx) for conv in self.ls], dim=1)
        outputs = torch.cat([x1, out], dim=1)
        return outputs
    def split_branch(self, total_channels, num_groups):
        import numpy as np
        split = [int(np.floor(total_channels / num_groups)) for _ in range(num_groups)]
        split[0] += total_channels - sum(split)
        return split

class MTS_ConvNet(nn.Module):
    def __init__(self, in_nc, class_num, segment_size):
        super(MTS_ConvNet, self).__init__()
        n_fs = 64
        self.T = segment_size
        n_b = 3

        self.stem = BasicConv1d(in_nc, n_fs, kernel_size=1, stride=1, padding=1,bias=False)

        if in_nc == 113: # in case of OPPORTUNITY
            self.conv1 = MTS_module(n_fs, n_fs*2, n_b)
            self.conv2 = MTS_module(n_fs*2, n_fs, n_b)
        else:
            self.conv1 = MTS_module(n_fs, n_fs, n_b)
            self.conv2 = MTS_module(n_fs, n_fs, n_b)
        self.conv3 = MTS_module(n_fs, n_fs, n_b)
        self.conv4 = MTS_module(n_fs, n_fs*2, n_b)
        self.conv5 = MTS_module(n_fs*2, n_fs*4, n_b)

        self.fc = nn.Linear(n_fs*4, class_num)

    def forward(self, x):
        x = self.stem(x)

        x = self.conv1(x)
        x = self.conv2(x)
        x = self.conv3(x)
        x = F.adaptive_max_pool1d(x,self.T//2)
        x = self.conv4(x)
        x = F.adaptive_max_pool1d(x,self.T//4)
        x = self.conv5(x)
        x = F.adaptive_avg_pool1d(x,1)
        x = x.view(x.size(0), -1)

        x = self.fc(x)
        return x


#!/usr/bin/python
import Adafruit_BBIO.GPIO as GPIO
import logging
from control import send
import time
import socket

# create log file handler and set to debug
log = logging.getLogger('')
log_format = logging.Formatter('%(asctime)s - %(levelname)-8s - %(message)s')
fh = logging.FileHandler('button.log')
fh.setFormatter(log_format)
log.addHandler(fh)

# button connected to this pin and +3.3v, with pulldown
# so if high, button is pressed
pin = "P9_12"
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# wait for bipod process to start
log.warning("waiting for bipod process to start")
while True:
    try:
        send('programs')
        break
    except socket.error:
        pass
    time.sleep(1)

def wait_for_button():
    log.warning("waiting for button press")
    while True:
        GPIO.wait_for_edge(pin, GPIO.RISING)
        # try to avoid noise issues that cause false triggers
        time.sleep(0.25)
        # if button still pressed
        if GPIO.input(pin):
            break

# first button we will send start
wait_for_button()
log.warning("button pressed, starting")
send('start')

# second button press will halt
wait_for_button()
log.warning("button pressed, halting")
send('halt')

GPIO.cleanup()


import pytest

from stellar_sdk import TimeBounds

class TestTimeBounds:
    @pytest.mark.parametrize(
        "min_time, max_time, xdr",
        [
            (1560844454, 1560846000, "AAAAAF0ImKYAAAAAXQiesA=="),
            (1560844454, 0, "AAAAAF0ImKYAAAAAAAAAAA=="),
            (1583633108, 1583633108, "AAAAAF5kUtQAAAAAXmRS1A=="),
        ],
    )
    def test_to_xdr(self, min_time, max_time, xdr):
        op_xdr_object = TimeBounds(min_time, max_time).to_xdr_object()
        assert op_xdr_object.to_xdr() == xdr
        from_instance = TimeBounds.from_xdr_object(op_xdr_object)
        assert isinstance(from_instance, TimeBounds)
        assert from_instance.max_time == max_time
        assert from_instance.min_time == min_time

    @pytest.mark.parametrize(
        "min_time, max_time, message",
        [
            (-1, 1560844454, "min_time cannot be negative."),
            (1560844454, -1, "max_time cannot be negative."),
            (1560844455, 156084454, "min_time cannot be greater than max_time."),
        ],
    )
    def test_to_xdr_with_invalid_time_raise(self, min_time, max_time, message):
        with pytest.raises(ValueError, match=message):
            TimeBounds(min_time, max_time)

    def test_equals(self):
        assert TimeBounds(1, 2) == TimeBounds(1, 2)
        assert TimeBounds(1, 2) != TimeBounds(1, 0)
        assert TimeBounds(1, 2) != TimeBounds(0, 2)


from sklearn.metrics import silhouette_samples, silhouette_score
import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from util import getAdultData, getWineData
from sklearn import metrics
from scipy.spatial.distance import cdist

data = getWineData()

dataX = data.iloc[:,:-1]
dataY = data.iloc[:,-1]

clusters =  [2,3,4,5,6,7,8,9,10]

distortions = []
# time1 = []
# ARSk = []
# AMISk = []
# HSk = []
# CSk = []
# VMSk = []
Sil = []
SSE = []
for k in clusters:
    start_time = time.time()

    kmeanModel = KMeans(n_clusters=k, max_iter = 500, random_state=0,init="k-means++").fit(dataX)
    kmeanModel.fit(dataX)
    prediction = kmeanModel.fit_predict(dataX)
    end_time = time.time()

    sil_avg = silhouette_score(dataX, prediction)
    # ARS = metrics.adjusted_rand_score(dataY, prediction)
    # AMIS = metrics.adjusted_mutual_info_score(dataY, prediction)
    # HS = metrics.homogeneity_score(dataY, prediction)
    # CS = metrics.completeness_score(dataY, prediction)
    # VMS = metrics.v_measure_score(dataY, prediction)
    sse = (kmeanModel.score(dataX) * -1) / 100000000000000.0

    # ARSk.append(ARS)
    # AMISk.append(AMIS)
    # HSk.append(HS)
    # CSk.append(CS)
    # VMSk.append(VMS)
    Sil.append(sil_avg)
    SSE.append(sse)

    cls_time = end_time - start_time
    # time1.append(cls_time)
    distortions.append(sum(np.min(cdist(dataX, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) / dataX.shape[0])

# print("time:", time1)
# print("Adjusted Random Score:", ARSk)
# print("AMIS:", AMISk)
# print("HS:", HSk)
# print("CS:", CSk)
# print("VMS:", VMSk)
print("Sil:", Sil)
print("SSE:", SSE)
# Plot the elbow
# plt.plot(clusters, AMISk, label = "Mutual info")
# plt.plot(clusters, ARSk, label = "Adjusted Random")
# plt.plot(clusters, HSk, label = "homogeneity")
# plt.plot(clusters, CSk, label = "completeness")
# plt.plot(clusters, VMSk, label = "v_measure")
# plt.plot(clusters, distortions, "bx-")

plt.plot(clusters,SSE, label = "Sum of squared error")
plt.plot(clusters,Sil, label = "Silhouette Average")

plt.xlabel('k')
# plt.ylabel('Distortion')
# plt.title('The Elbow Method showing the optimal k')
plt.ylabel('Score')
plt.title('Different score showing the optimal k')
plt.legend()
plt.grid()
plt.show()

plt.plot(clusters,distortions, label = "distortions Average")
plt.xlabel('k')
plt.ylabel('Distortion')
plt.title('The Elbow Method showing the optimal k')
plt.legend()
plt.grid()
plt.show()


"""
technical.py

A Flask Blueprint module for the technical site.
"""
from flask import Blueprint, render_template, current_app, g, abort
from .. import common as c
from meerkat_frontend import auth
from slugify import slugify
import meerkat_frontend
import json

technical = Blueprint('technical', __name__, url_prefix='/<language>')

@technical.before_request
def requires_auth():
    """
    Checks that the user has authenticated before returning any page from
    this Blueprint.
    """
    # We load the arguments for check_auth function from the config files.
    auth.check_auth(
        *current_app.config['AUTH'].get('technical', [['BROKEN'], ['']])
    )

@technical.route('/')
@technical.route('/<tab>')
@technical.route('/<tab>/loc_<int:locID>')
def index(tab=None, locID=None):
    """
    Serves a tab for the technical dashboard, filtered by the specified
    location.
    """
    # Initialise locID to allowed location
    # Can't be done during function declaration because outside app context
    locID = g.allowed_location if not locID else locID

    # If no tab is provided, load the first tab in the tab list the user
    # has access to.
    tabs = current_app.config['TECHNICAL_CONFIG']['tabs']
    if tab is None:
        for t in tabs:
            country = current_app.config['TECHNICAL_CONFIG']['auth_country']
            tab_access = t.get('access', False)
            in_arr = meerkat_frontend.in_array(
                tab_access,
                g.payload['acc'][country]
            )
            if in_arr or not tab_access:
                tab = t
                break
    else:
        try:
            tab = next(filter(lambda t: slugify(t['name']) == tab, tabs))
        except StopIteration:
            abort(404, '{} page does not exist'.format(tab))

    # Create a page state object defining the page to be shown
    page_state = {
        'type': 'tab',
        'dataID': slugify(tab['name']),
        'locID': str(locID),
        **tab
    }
    page_state.pop("access", None)
    page_state.pop("name", None)
    page_state = json.dumps(page_state)

    return render_template(
        'technical/index.html',
        content=g.config['TECHNICAL_CONFIG'],
        page=page_state,
        langauge=g.get("language", current_app.config["DEFAULT_LANGUAGE"]),
        week=c.api('/epi_week'),
        user=g.payload
    )

@technical.route('/alerts/<alertID>')
def alert(alertID=1):
    """
    Serves an individual alert investigation report for the given alert ID.
    """
    pageState = "{ type: 'alert', dataID: '" + alertID + "' }"
    return render_template(
        'technical/index.html',
        content=g.config['TECHNICAL_CONFIG'],
        page=pageState,
        langauge=g.get("language", current_app.config["DEFAULT_LANGUAGE"]),
        week=c.api('/epi_week')
    )

@technical.route('/diseases/<diseaseID>/')
@technical.route('/diseases/<diseaseID>/loc_<int:locID>')
def disease(diseaseID='tot_1', locID=None):
    """
    Serves a disease report page for the given aggregation variable and
    lcoation ID.
    """
    # Initialise locID to allowed location
    # Can't be done during function declaration because outside app context
    locID = g.allowed_location if not locID else locID

    pageState = ("{ type: 'disease', dataID: '" + str(diseaseID) +
                 "', locID: " + str(locID) + " }")
    return render_template(
        'technical/index.html',
        content=g.config['TECHNICAL_CONFIG'],
        page=pageState,
        langauge=g.get("language", current_app.config["DEFAULT_LANGUAGE"]),
        week=c.api('/epi_week')
    )


import discord
import discord.utils
import asyncio
from discord.ext.commands import Bot
from discord.ext import commands
import platform
import sys
import sqlite3
import MySQLdb
import datetime
import os
import json
from pprint import pprint

client = Bot(description="Butler utility for AGC Server",
             command_prefix="*", pm_help=False)

@client.event
async def on_ready():
    await client.wait_until_ready()
    print('Current Discord.py Version: {} | Current Python Version: {}'.format(
        discord.__version__, platform.python_version()))
    print('--------')
    print('Use this link to invite {}:'.format(client.user.name))
    print('https://discordapp.com/oauth2/authorize?client_id={}&scope=bot&permissions=8'.format(client.user.id))
    print('--------')
    print('You are running AGC Butler[BETA]')
    print('Created by bot-steev0#0420')
    game = discord.Game("At your service, master")
    return await client.change_presence(status=discord.Status.idle, activity=game)

#! GLOBAL VARIABLES FOR SERVER

conn = MySQLdb.connect("localhost", "butler", "Zer045kin!", "agc_butler")
c = conn.cursor()

key_file = open('./api_key.txt', 'r')
if not key_file:
    print('File key.txt can\'t be found')
    sys.exit(0)

api_key = key_file.read().splitlines()[0]
if not api_key:
    print('No API key in discord_key.txt')
    sys.exit(0)

key_file.close()

msg_buffer = []
nadeko_lb = []

async def spin_db(message):
    await client.wait_until_ready()
    today = datetime.datetime.today().date().__format__("%Y-%m-%d")
    server_member_total = 0
    server = client.get_guild(458888334291369987)
    server_members = server.members
    spawn_date = datetime.datetime.today().date().__format__("%Y-%m-%d")
    dev_spam = client.get_channel(458904356016619521)
    print(server)
    c.execute('DELETE from user_information')
    for member in server_members:
        if member.bot == False:
            c.execute('INSERT INTO user_information(user_discord_id, user_nickname, user_total_xp, user_current_level, user_last_msg) VALUES(%s,%s,%s,%s,%s)', (member.id, member.name, 0, 0, today))
            server_member_total += 1
            print(member.id, today)
    conn.commit()
    c.execute('SELECT count("user_id") FROM user_information')
    db_count = c.fetchall()
    (user_id,) = db_count[0]
    await dev_spam.send('Database has been filled with members from Server: '+str(server)+'\nServer Member Count: '+str(server_member_total)+'\nDatabase Member Count: '+str(user_id))

# async def backup_db(message):

# async def spawn_webclient(message):
# https://discord.gg/tC4EedV

# async def clear_messages(message, user, num_msgs)

async def db_update(message, msg_buffer):

    await client.wait_until_ready()

    while not client.is_closed:

        await client.send_message(message.channel, msg_buffer)

        print('CURRENT BUFFER\n')
        de_duped_buffer = list(set(msg_buffer))
        print(de_duped_buffer)
        print('\n')
        msg_buffer.clear()
        if len(msg_buffer) == 0:
            print('Main Buffer Cleared')
        else:
            print('Failed to clear Main Buffer')

        for user_data in de_duped_buffer:

          # Message Buffer Info
            user_data = user_data.split('_')
            buffer_user_id = user_data[0]
            new_date = '2018-05-10'  # user_data[1]

            # SQL Info
            c.execute('SELECT * FROM user_info WHERE user_id == (?)',
                      (buffer_user_id,))
            user_entry = c.fetchall()

            if len(user_entry) == 0:
                c.execute('INSERT INTO user_info VALUES(?,?)',
                          (buffer_user_id, new_date))
                await client.send_message(message.channel, 'UserID: '+buffer_user_id+' has been inserted into the DB with the latest date of: ' + new_date)
                conn.commit()
            else:
                c.execute(
                    'UPDATE user_info SET date_time = (?) WHERE user_id == (?)', (new_date, buffer_user_id))
                await client.send_message(message.channel, 'UserID: '+buffer_user_id+' has been updated in the DB with the latest date of: '+new_date)
                conn.commit()

        de_duped_buffer.clear()

        if len(de_duped_buffer) == 0:
            print('Auxiliary Buffer Cleared')
        else:
            print('Failed to clear Auxiliary Buffer')

        await asyncio.sleep(120)

@client.event
async def on_message(message):
    await client.wait_until_ready()

    # if message.content.startswith('*'):
    #   pass
    # else
    #   msg_buffer.append(message.author.id+'_'+today)
    # if bool(server) == False:
    #    await client.send_message(dev_spam,'Apologies sir, but it would seem that you have not yet #configured the server parameters, please do so by executing the `*init` command.')
    #else:

    if message.content.startswith('*bot'):
        await client.send_message(message.channel, 'Beep Boop Beep')

    elif message.content.startswith('*update'):
        client.loop.create_task(db_update(message, msg_buffer))
        await client.send_message(message.channel, 'Database Update Task Initialised')

    elif message.author.id == 116275390695079945 and len(message.embeds)>0:
        #~ Piece of shit emojis to handle Nadeko's leaderboard interaction
        #~ U+2B05 	\xE2\xAC\x85 ⬅
        #~ U+27A1 	\xE2\x9E\xA1 ➡
        me = discord.utils.get(server_members, name='- bot steev -')
        await asyncio.sleep(4)
        nadeko_lb.append(message.embeds)
        print('page: 1')
        print(nadeko_lb)
        for x in range(10):
            await client.wait_for_reaction(emoji='\u27A1')
            await asyncio.sleep(2)
            nadeko_lb.append(message.embeds)
            print('page:'+str(x+x))
            print(message.embeds)
            await client.remove_reaction(message,'\u27A1',me)
            await asyncio.sleep(2)
            nadeko_lb.append(message.embeds)
            print('page:'+str((x+x)-1))
            print(message.embeds)

    elif message.content.startswith('*write'):
        print('\n\n\n')
        with open('AGC_Leaderboard_JSON.txt', 'a') as f:
            for nadeko_lb_page in nadeko_lb:
                for page_info in nadeko_lb_page:
                    f.write(json.dumps(page_info))
        f.close

    elif message.content.startswith('*parse'):
        with open('AGC_Leaderboard.JSON', 'r') as f:
            json_data = json.load(f)
            cntr = 0
            for x in json_data:
                raw_fields = json_data[cntr]['fields']
                cntr2 = 0
                for y in raw_fields:
                    raw_entry_value = raw_fields[cntr2]['value']
                    raw_entry_name = raw_fields[cntr2]['name']

                    split_entry_value = raw_entry_value.split('-')

                    final_entry_value = split_entry_value[1].lstrip()
                    final_entry_name = raw_entry_name[3:].lstrip()

                    print(final_entry_name + ' ' + final_entry_value)
                    cntr2 += 1
                cntr += 1
        f.close()

    elif message.content.startswith('*clfilelb'):
        with open('AGC_Leaderboard_JSON.txt', 'w') as f:
            f.write('')
        f.close()
        nadeko_lb.clear()

    elif message.content.startswith('*spindb'):
        await spin_db(message)

    #elif message.content.startswith('*test'):
    #    for member in server_members:
    #        if member.bot == False:
    #            mem_roles = server.get_member(member.id).roles
    #            for role in mem_roles:
    #                if role.id == '446281091603628033':
    #                    print(member, role, today)
    #                elif role.id == '446281026894037003':
    #                    print(member, role)
    #                elif role.id == '446280876658262017':
    #                    print(member, role)
    #                elif role.id == '446280757183512586':
    #                    print(member, role)
    #        else:
    #            pass
    #    conn.commit()
    #    await client.send_message(message.channel, 'Info to terminal')

client.run(str(api_key))


# Q1. program to find average of three numbers entered by the user
n1 = int(input('enter first number :'))
n2 = int(input('enter second number :'))
n3 = int(input('enter third number :'))
avg = (n1 + n2 + n3)/3
print("average of the three numbers is :",avg)

# Q2. program to compute a person's income tax
income = float(input("enter your gross income (to the nearest penny): "))
no_of_dependents = int(input("enter the number of dependents: "))
taxable_income = income - 10000 - (3000*no_of_dependents)
tax = (taxable_income * 20)/100
print("your tax is :", tax)

# Q3. program to store different data type values into a list.
SID=int(input('Enter your SID : '))
Name= str(input('Enter your Name: '))
Gender=str(input('Enter your Gender(M/F/U): '))
Course_name=str(input('Enter your Course: '))
CGPA=float(input('Enter your CGPA: '))
Student=[SID,Name,Gender,Course_name,CGPA]
print(Student)

# Q4. To enter marks of 5 students into a list and display them in sorted manner.
m1 = int(input('enter the marks of first student: '))
m2 = int(input('enter the marks of second student: '))
m3 = int(input('enter the marks of third student: '))
m4 = int(input('enter the marks of fouth student: '))
m5 = int(input('enter the marks of fifth student: '))
list = [m1,m2,m3,m4,m5]
print(sorted(list))

# Q5.(a) and (b)
color = ['Red','Green','White','Black','Pink','Yellow']
color.pop(3)
print(color)
color[3] = 'Purple'
print(color)


import sys
from heapq import *
input = sys.stdin.readline
INF = sys.maxsize

def shot(x, y, nx, ny): # 대포 타고 이동하는 경우
    d = ((x-nx) ** 2 + (y-ny) ** 2) ** 0.5
    t = abs(50 - d) / 5
    return 2 + t

def walk(x, y, nx, ny): # 걸어서 이동하는 경우
    d = (((x-nx) ** 2 + (y-ny) ** 2) ** 0.5)
    t = d / 5
    return t

pX, pY = map(float, input().split())
dX, dY = map(float, input().split())

n = int(input())
G = [[dX, dY]]
for _ in range(n):
    G.append(list(map(float, input().split())))

D = [INF] * (n+1)
Q = []
for i in range(n+1): # 일단 시작점에서는 대포 or 목적지까지 걸어가야하므로 walk로 D 테이블 초기화
    nx, ny = G[i]
    D[i] = walk(pX, pY, nx, ny)
    heappush(Q, (D[i], nx, ny, i))

while Q:
    t, x, y, n1 = heappop(Q)

    if D[n1] < t:
        continue

    for n2, axis in enumerate(G):
        nx, ny = axis
        ct = shot(x, y, nx, ny)
        if t + ct < D[n2]:
            D[n2] = t + ct
            heappush(Q, (D[n2], nx, ny, n2))

        ct = walk(x, y, nx, ny)
        if t + ct < D[n2]:
            D[n2] = t + ct
            heappush(Q, (D[n2], nx, ny, n2))

print(D[0])


import math

start = 999*999
solution = 1
for i in range(start, start-100000, -1):
    pow = len(str(i))-1
    if(int(i/math.pow(10,pow)) == int(i%10)):
        value = str(i)
        k = 1
        while(value[k:k+1] == value[-k-1:-k] and k <= len(value)-1):
            k+=1
            if(k == len(value)-1):
                for j in range(999,100,-1):
                    if(i%j == 0 and len(str(int(i/j))) == 3):
                        solution = i
print("Solution: ",solution)


###############################################################################
#Author: arvon
#Email: arvon2014@gmail.com
#Date: 2018/05/05
#Description: register etcd v3 and used by ansible lookup
#Notes:
###############################################################################

from ansible.plugins.lookup import LookupBase
import etcd3
import os

'''
Require and Document
pip install etcd3
V3-api: http://python-etcd3.readthedocs.io/en/latest/usage.html
'''

class Etcd_v3:
    def __init__(self, prefix, shardsinfo, ANSIBLE_ETCD_URL, type_module):
        self.prefix = prefix
        #self.version = version
        self.shardsinfo = shardsinfo
        self.etcd_url = ANSIBLE_ETCD_URL
        self.port = 2379
        self.type_module = type_module

    def gets(self):
        client = etcd3.client(host=self.etcd_url, port=self.port)
        client.get_prefix()
        return_dict = {}
        for shardid in self.shardsinfo:
            assign_dict = {}
            v3_prefix = os.path.join(self.prefix, str(self.shardsinfo[shardid]['gid']),self.type_module, str(shardid))
            #print v3_prefix
            gid = str(self.shardsinfo[shardid]['gid'])
            for v3_kv in client.get_prefix(v3_prefix, sort_order=None, sort_target='key'):
                #print v3_kv[1].key, v3_kv[0]
                assign_dict[v3_kv[1].key.split('/')[-1]] = v3_kv[0]
            default_prefix = os.path.join(self.prefix, gid, 'default')
            for default_kv in client.get_prefix(default_prefix, sort_order=None, sort_target='key'):
                #print default_kv[1].key,  default_kv[0]
                assign_dict[default_kv[1].key.split('/')[-1]] = default_kv[0]
            return_dict[shardid] =  assign_dict
        return return_dict
        # if self.type_module == 'gamex':
        #     for shardid in self.shardsinfo:
        #         assign_dict = {}
        #         v3_prefix = os.path.join(self.prefix, str(self.shardsinfo[shardid]['gid']),str('shards'), str(shardid))
        #         #print v3_prefix
        #         gid = str(self.shardsinfo[shardid]['gid'])
        #         for v3_kv in client.get_prefix(v3_prefix, sort_order=None, sort_target='key'):
        #             #print v3_kv[1].key, v3_kv[0]
        #             assign_dict[v3_kv[1].key.split('/')[-1]] = v3_kv[0]
        #         default_prefix = os.path.join(self.prefix, gid, 'default')
        #         for default_kv in client.get_prefix(default_prefix, sort_order=None, sort_target='key'):
        #             #print default_kv[1].key,  default_kv[0]
        #             assign_dict[default_kv[1].key.split('/')[-1]] = default_kv[0]
        #         return_dict[shardid] =  assign_dict
        #     return return_dict
        # elif self.type_module == 'auth':
        #     for shardid in self.shardsinfo:
        #         assign_dict = {}
        #         v3_prefix = os.path.join(self.prefix, str(self.shardsinfo[shardid]['gid']),str('auth'), str(shardid))
        #         gid = str(self.shardsinfo[shardid]['gid'])
        #         for v3_kv in client.get_prefix(v3_prefix, sort_order=None, sort_target='key'):
        #             assign_dict[v3_kv[1].key.split('/')[-1]] = v3_kv[0]
        #         default_prefix = os.path.join(self.prefix, gid, 'default')
        #         for default_kv in client.get_prefix(default_prefix, sort_order=None, sort_target='key'):
        #             assign_dict[default_kv[1].key.split('/')[-1]] = default_kv[0]
        #         return_dict[shardid] =  assign_dict
        # else:
        #     pass

class LookupModule(LookupBase):

    def run(self, terms, variables, **kwargs):
        # validate_certs = kwargs.get('validate_certs', True)
        if len(terms) != 4:
            raise AnsibleError("parameter should be 4. prefix, dict of shardsinfo")
        etcd = Etcd_v3(terms[0], terms[1], terms[2], terms[3])
        return [etcd.gets()]

# Test command
if __name__ == '__main__':
    etcd = Etcd_v3('root_v3/wpys', {'15501':{'gid':155}},'10.17.1.32','gamex')
    #etcd = Etcd_v3('root_v3/wpys', {'15501': {'gid': 155},'15502':{'gid':155}}, '10.17.1.32', 'gamex')
    #a=etcd.gets('root_v3/wpys', {'15501':{'gid':155}},'http://10.17.1.32:2379','gamex')
    a=etcd.gets()
    print (a)


#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import pints.io

iid_noise_sigma = 25  # pA
file_chain_A = 'out/mcmc-model_A/model_A-sinewave-chain_0.csv'
file_chain_B = 'out/mcmc-model_B/model_B-sinewave-chain_0.csv'

chain_A = pints.io.load_samples(file_chain_A, n=None)
chain_B = pints.io.load_samples(file_chain_B, n=None)

sigma_A = chain_A[-50000:, -1]
sigma_B = chain_B[-50000:, -1]

n_bins = np.arange(20, 55, 0.05)

plt.figure(figsize=(6, 3))
plt.hist(sigma_A, bins=n_bins, alpha=0.75, density=True,
        label='Model A (mean=%.2f pA)' % np.mean(sigma_A))
plt.hist(sigma_B, bins=n_bins, alpha=0.75, density=True,
        label='Model B (mean=%.2f pA)' % np.mean(sigma_B))
plt.axvline(iid_noise_sigma, ls='--', c='#7f7f7f',
        label=r'True $\sigma$ in data')
plt.xlim((24, 51))
plt.xlabel(r'$\sigma$ (pA)')
plt.ylabel('Posterior')
plt.legend()
plt.tight_layout()
plt.savefig('fig/iid-sigma.pdf', format='pdf', bbox_inches='tight')
plt.close()


import sys

# the standard input according to the problem statement.
n = int(input())
for i in range(n):
    x = input()
    num = x
    num_list = []
    while num not in num_list:
        print(num, file=sys.stderr, flush=True)
        num_list.append(num)
        num = sum(int(digit) ** 2 for digit in str(num))
    if num == 1:
        print(x, ":)")
    else:
        print(x, ":(")


from view import *
from operations import *

def button_click():
    choice_main_menu = 0
    field_notes()
    while choice_main_menu != 5:
        choice_main_menu = show_main_menu()

        # Добавление новой заметки
        if choice_main_menu == 1:
            note = add_notes()
            record_data(note)

        # Чтение заметок
        if choice_main_menu == 2:
            choice_read_menu = 0
            while choice_read_menu != 3:
                choice_read_menu = show_read_menu()
                # Чтение всех имеющихся заметок
                if choice_read_menu == 1:
                    reading_all_notes()
                # Поиск заметок по дате создания
                if choice_read_menu == 2:
                    search_for_notes_by_date(input('Введите дату в формате ГГГГ-ММ-ДД: '))

        # Редактирование заметки
        if choice_main_menu == 3:
            choice_editing_menu = 0
            reading_all_notes()
            id = int(input("Введите ID заметки для редактирования: "))
            while choice_editing_menu != 3:
                choice_editing_menu = show_editing_menu()
                # Редактирование заголовка заметки
                if choice_editing_menu == 1:
                    editing_title_notes(id)
                # Редактирование тела заметки
                if choice_editing_menu == 2:
                    editing_body_notes(id)

        # Удаление заметки
        if choice_main_menu == 4:
            reading_all_notes()
            delete_notes(int(input("Введите ID заметки для удаления: ")))

        # Завершение работы программы
        if choice_main_menu == 5:
            print("До свидания!")


# doing necessary imports
from flask import Flask, render_template, request, jsonify, make_response
from flask_cors import CORS, cross_origin
import requests
import pymongo
import json
import os
from Conversations import *
#from DataRequests import MakeApiRequests
#from sendEmail import EMailClient
from pymongo import MongoClient

app = Flask(__name__)  # initialising the flask app with the name 'app'

# geting and sending response to dialogflow
@app.route('/webhook', methods=['POST'])
@cross_origin()
def webhook():
    req = request.get_json(silent=True, force=True)
    res = processRequest(req)
    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

# processing the request from dialogflow
def processRequest(req):
    # dbConn = pymongo.MongoClient("mongodb://localhost:27017/")  # opening a connection to Mongo
    log = Log.saveConversations()
    sessionID = req.get('responseId')
    result = req.get("queryResult")
    intent = result.get("intent").get('displayName')
    query_text = result.get("queryText")
    parameters = result.get("parameters")
    cust_name = parameters.get("cust_name")
    cust_contact = parameters.get("cust_contact")
    cust_email = parameters.get("cust_email")
    db = configureDataBase()

    if intent == "confirmation":
        fulfillmentText = result.get("fulfillmentText")
        log.saveConversations(sessionID, query_text, fulfillmentText, intent, db)
    elif intent == "Continue":
        fulfillmentText = result.get("fulfillmentText")
        log.saveConversations(sessionID, query_text, fulfillmentText, intent, db)

    elif intent == "Welcome" or intent== "fallback":
        fulfillmentText = result.get("fulfillmentText")
        log.saveConversations(sessionID, query_text, fulfillmentText, intent, db)

    else:
        return {
            "fulfillmentText": "something went wrong,Lets start from the begning, Say Hi",
        }

def configureDataBase():
    client = MongoClient("mongodb+srv://chatwithnerd:password@cluster0.rbm6q.mongodb.net/shravan?retryWrites=true&w=majority")
    return client.get_database('shravan')

'''def makeAPIRequest(query):
    api = MakeApiRequests.Api()

    if query == "world":
        return api.makeApiWorldwide()
    if query == "state":
        return api.makeApiRequestForIndianStates()

    else:
        return api.makeApiRequestForCounrty(query)'''

if __name__ == '__main__':
    port = int(os.getenv('PORT'))
    print("Starting app on port %d" % port)
    app.run(debug=False, port=port, host='0.0.0.0')
'''if __name__ == "__main__":
    app.run(port=5000, debug=True)''' # running the app on the local machine on port 8000


[m, n] = input().split(" ")
m = int(m)
n = int(n)
while ((m > 0) and (n > 0)):
    linha = ''
    soma = 0
    if m > n:
        maior = m + 1
        menor = n
    else:
        maior = n + 1
        menor = m

    for x in range (menor, maior):
        linha += str(x) + ' '
        soma += x

    linha += 'Sum=' + str(soma)

    print(linha)
    [m, n] = input().split(" ")
    m = int(m)
    n = int(n)


import pyttsx3
import speech_recognition as sr
import datetime
import time
import os
import pyautogui
import wikipedia
import webbrowser
import playsound
import pywhatkit
import pyjokes
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
print(voices[0].id)
engine.setProperty('voices', voices[0].id)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

    os.startfile("C:\\Program Files\Rainmeter\\Rainmeter.exe")

    # engine.runAndWait()

    # playsound.playsound("power down.mp3")

# def startup():
    # speak("Initializing Jarvis")
    # speak("Starting all systems applications")
    # speak("Installing and checking all drivers")
    # speak("Caliberating and examining all the core processors")
    # speak("Checking the internet connection")
    # speak("Wait a moment sir")
    # speak("All drivers are up and running")
    # speak("All systems have been activated")
    # speak("Now I am online")
    # hour = int(datetime.datetime.now().hour)
    #speak("I am Jarvis. Online and ready sir. Please tell me how may I help you")

def wish():
    hour = int(datetime.datetime.now().hour)
    tt = time.strftime("%I:%M %p")

    if hour >= 0 and hour < 12:
      playsound.playsound("power up.mp3")

      print(f"Good Morning Ruchi, its {tt}")
      speak(f"Good Morning Ruchi, its {tt}")

    elif hour >= 12 and hour < 18:
        playsound.playsound("power up.mp3")

        print(f"Good Afternoon Ruchi, its {tt}")
        speak(f"Good Afternoon Ruchi, its {tt}")

    else:
     playsound.playsound("power up.mp3")
    speak("Hello and good evening Ruchi")
    playsound.playsound("Jarvis.mp3")

    speak("I am Jarvis. Online and ready mam. Please tell me how may I help you")

def takecommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("listening...")
        r.pause_threshold = 1
        audio = r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='eng-in')
        print(f"Ruchi Said: {query}\n")

    except Exception as e:
        speak("Mam please say that again")
        print("Say That Again")
        return "None"
    return query

#if __name__ == '__main__':
def TaskExecution():
    #startup()
    wish()
    takecommand()

    while True:

        query = takecommand().lower()

        # to find something on wikipedia

        if "wikipedia" in query:
            playsound.playsound("power up.mp3")

            speak("I am finding on wikipedia")
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            speak("According to wikipedia")
            print(results)
            speak(results)

        elif 'Can you tell me about any legend of india' in query:
            playsound.playsound("power up.mp3")

            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            speak("According to wikipedia")
            print(results)
            speak(results)

        elif "open youtube" in query:
            playsound.playsound("power up.mp3")

            webbrowser.open("youtube.com")

        elif "Battery percent of my lappy" in query:
            speak("Its only 12 percent")
            playsound.playsound("Battery power.mpeg")

        elif "search on google" in query:
            playsound.playsound("power up.mp3")

            speak("Mam what you want to search on google")
            search = takecommand().lower()
            webbrowser.open(f"{search}")

        elif "play music" in query:
            playsound.playsound("power up.mp3")
            playsound.playsound("Sharukh's Song.mpeg")

        elif "Jarvis are you single" in query:
          playsound.playsound("power up.mp3")
          speak("No ruchi i m in a relationship with Wifi")

        elif "Okay Shutdown my system" in query:
            playsound.playsound("Shuting down.mpeg")

    if "which song tony stark like most" in condition:
                music_dir = 'E:\\Jarvis\\Tony Stark Fav Song'
                songs = os.listdir(music_dir)
                os.startfile(os.path.join(music_dir, songs[1]))

    elif "take a screenshot" in query:

            speak("Mam, please tell me name for this screenshot file")
            name = takeCommand().lower()
            speak("please hold the screen for few seconds i am taking screenshot")
            time.sleep(2)
            img = pyautogui.screenshot()
            img.save(f"{name}.jpg")
            speak("i am done Mam, the screenshot is saved to our main folder now i am ready to take next command")

if __name__ == '__main__':
    TaskExecution()