from django.contrib import admin
from .models import Category, Workshop

class CategoriesAdmin(admin.ModelAdmin):
    """ Workshop categories list display with order """
    list_display = (
        'name',
        'friendly_name',
    )

    ordering = ('name',)

class WorkshopsAdmin(admin.ModelAdmin):
    """ Workshops list display and order """
    list_display = (
        'name',
        'category',
        'participants',
        'start_date',
        'end_date',
        'start_time',
        'end_time',
        'price',
        'therapist',
    )

    ordering = ('name',)

admin.site.register(Workshop, WorkshopsAdmin)
admin.site.register(Category, CategoriesAdmin)


from vector_math import *
from collections import OrderedDict
from pyquaternion import Quaternion
from datetime import datetime

import numpy
import pandas as pd
import warnings
import logging
import time

warnings.filterwarnings("ignore")
GLOBAL_LOGGING_LEVEL = logging.INFO

class KeyT:
    def __init__(self):
        self.value = ''

    def on_press(self, key):
        self.value = str(key).replace('\'', '')

    def on_release(self, _):
        self.value = ''

def get_date_time():
    return datetime.now().strftime('%Y_%m_%d_%H_%M_%S')

def create_console_logger(name, level=None):
    level = GLOBAL_LOGGING_LEVEL if level is None else level

    logger = logging.getLogger(name)
    logger.setLevel(level)
    ch = logging.StreamHandler()
    ch.setLevel(level)

    formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(funcName)s @%(name)s : %(message)s')
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    logger.propagate = False

    return logger

def truncate_float(number, decimal_places):
    return ('{0:.%sf}' % decimal_places).format(number)

def get_average_rates_body(df, limit, frequency):
    shape = (limit, 3)
    linear_velocities, angular_velocities = numpy.zeros(shape), numpy.zeros(shape)

    # get average linear and angular velocities (EARTH)
    for i in range(1, limit):
        p1 = df.loc[i - 1, ['x', 'y', 'z']].values.astype(numpy.float64)
        p2 = df.loc[i, ['x', 'y', 'z']].values.astype(numpy.float64)

        q1 = Quaternion(df.loc[i - 1, ['scalar', 'i', 'j', 'k']].values)
        q2 = Quaternion(df.loc[i, ['scalar', 'i', 'j', 'k']].values)

        linear_velocities[i] = get_average_linear_velocity(p2, p1, frequency)

        axis, angle = get_average_angular_velocity(q2, q1, frequency)
        angular_velocities[i] = axis * angle

    return linear_velocities, angular_velocities

def get_xy_velocity_model(df, frequency, limit=500):
    v, w, = get_average_rates_body(df, limit, frequency=frequency)

    input_shape = (limit, 15)
    output_shape = (limit, 6)

    X, y = numpy.zeros(input_shape), numpy.zeros(output_shape)
    action_names = ['move_forward', 'yaw_ccw', 'yaw_cw', 'hover', 'move_backward', 'move_left', 'move_right']

    limit = limit - 2
    for t0, t1 in zip(range(limit), range(1, limit)):
        selected_action = [0 if a != df.loc[t1, 'aName'] else 1 for a in action_names]

        q = Quaternion(df.loc[t0, ['scalar', 'i', 'j', 'k']].values)
        roll, pitch, yaw = to_euler_angles(q)

        X[t0] = numpy.concatenate((transform_to_body_frame(v[t0], q),
                                   transform_euler_rates_to_body(w[t0], q),
                                   [roll, pitch], selected_action))

        y[t0] = numpy.concatenate((transform_to_body_frame(v[t1], q),
                                   transform_euler_rates_to_body(w[t1], q)))

    x_columns = ['dXB', 'dYB', 'dZB', 'dRoll', 'dPitch', 'dYaw', 'roll', 'pitch'] + [i for i in action_names]
    y_columns = ['dXB', 'dYB', 'dZB', 'dRoll', 'dPitch', 'dYaw']

    return pd.DataFrame(X[:-5], columns=x_columns), pd.DataFrame(y[:-5], columns=y_columns)

class StateT:
    # if update is set to True, the environment will be able to update state whenever is needed.
    def __init__(self, update, **kwargs):
        self.prevState = None

        if 'callbacks' in kwargs:
            self.callbacks = kwargs['callbacks']
        else:
            self.callbacks = OrderedDict()
            for key in kwargs:
                self.callbacks[key] = kwargs[key]
                setattr(self, key, None if update is True else kwargs[key])

    def are_equal(self, state, margins):
        for key in state.callbacks:
            diff = abs(getattr(self, key) - getattr(state, key))
            if (numpy.greater(diff, getattr(margins, key))).any():
                return False
        return True

    # States are immutable by design, each update creates a new StateT object
    def update_state(self, agent):
        temp = StateT(update=True, callbacks=self.callbacks)
        # keep track of previous state
        temp.prevState = self

        i, keys = 0, [i for i in temp.callbacks]

        while i < len(keys):
            key = keys[i]
            try:
                setattr(temp, key, self.callbacks[key](agent=agent, partialUpdate=temp))
                i += 1
            except Exception as e:  # sanity check
                raise Exception(key + " " + str(e))

        # signal garbage collector
        temp.prevState.prevState = None

        # add a time stamp to state to indicate freshness
        temp.lastUpdate = time.time()

        return temp

    def get_keys(self):
        return [i for i in self.callbacks]

    def get_key_value_pairs(self):
        return {key: getattr(self, key) for key in self.get_keys()}

    def __hash__(self):
        return hash(tuple(tuple(getattr(self, c)) for c in self.get_keys()))


import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd

# Pure dash application
app = dash.Dash()

# load data once - consider reading data in the callback if you
# have constantly changing data and need it refreshed
df = pd.read_csv('data/gapminder.csv').dropna()

# Matching Hans Rosling's 2006 TEDx talk, 1964 to 2003
df = df[(df.year > 1963) & (df.year < 2004)]

app.layout = html.Div([
    html.H1('Gapminder revisited'),
    dcc.Graph(id='gapminder-graphic'),

    dcc.Slider(
        id='year--slider',
        min=df.year.min(),
        max=df.year.max(),
        value=df.year.min(),  # start at the beginning
        step=None,
        updatemode='drag',
        marks={str(year): str(year) for year in df.year.unique()}
    )
])

def bubble_chart(df, region):
    return go.Scatter(
            x=df.fertility[df.region == region],
            y=df.life_exp[df.region == region],
            text=df.Country[df.region == region] + ':' + df['pop'][df.region == region].astype(str),
            mode='markers',
            name=region,
            marker={
                'size': df['pop'][df.region == region] / 100000,
                'sizemode': 'area',
                'sizeref': 1,
                'opacity': 0.5,
                'line': {'width': 0.5, 'color': 'white'}
            }
        )

@app.callback(
    dash.dependencies.Output('gapminder-graphic', 'figure'),
    [dash.dependencies.Input('year--slider', 'value')])
def update_graph(year_value):
    # subset dataframe by specific year
    df_year = df[df.year == year_value]

    return {
        'data': [bubble_chart(df_year, region) for region in df_year['region'].unique()],
        'layout': go.Layout(
            xaxis={
                'title': 'Children per woman (fertility rate)',
            },
            yaxis={
                'title': 'Life expectancy at birth (years)',
            },
            #margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
            hovermode='closest'
        )
    }

if __name__ == '__main__':
    app.run_server()


"""
Based on 'Neural Network from Scratch' by TheIndependentCode.
Source: https://github.com/TheIndependentCode/Neural-Network/blob/master/network.py
"""
class NN:
    """
    Represents a neural network.

    Attributes:
    network (list): The layers of the network.
    """

    def __init__(self, network):
        """
        Initializes the Network with the given layers.

        Args:
        network (list): The layers of the network.
        """
        self.network = network

    def predict(self, input):
        """
        Performs a forward pass through the network.

        Args:
        input (np.array): The input data.

        Returns:
        np.array: The output of the network.
        """
        output = input
        for layer in self.network:
            output = layer.forward(output)
        return output

    def train(self, loss, loss_prime, x_train, y_train, epochs = 1000, learning_rate = 0.01, verbose = True):
        """
        Trains the network using the given loss function and training data.

        Args:
        loss (function): The loss function.
        loss_prime (function): The derivative of the loss function.
        x_train (np.array): The training input data.
        y_train (np.array): The training output data.
        epochs (int, optional): The number of training epochs. Defaults to 1000.
        learning_rate (float, optional): The learning rate for the backward pass. Defaults to 0.01.
        verbose (bool, optional): Whether to print training progress. Defaults to True.

        Returns:
        None
        """
        for e in range(epochs):
            error = 0
            for x, y in zip(x_train, y_train):
                # forward
                output = self.predict(x)

                # error
                error += loss(y, output)

                # backward
                grad = loss_prime(y, output)
                for layer in reversed(self.network):
                    grad = layer.backward(grad, learning_rate)

            error /= len(x_train)
            if verbose:
                print(f"{e + 1}/{epochs}, error={error}")


# Tag: Recurssion + Linked List
# 24. Swap Nodes in Pairs
# -----------------------------------------------------------------------------------
# Description:
# Given a linked list, swap every two adjacent nodes and return its head.
# You may not modify the values in the list's nodes, only nodes itself may be changed.
# -----------------------------------------------------------------------------------
# Example 1:
# Given 1->2->3->4, you should return the list as 2->1->4->3.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# 思路：
# 1. 从头开始，做recursion
# 2. Base case: 如果not head or not head.next (俩俩看还剩一个数 或者没有数了--->> return head)
# 3. Recussive step: 如果每次往后看都还有数，position.next.next = swap(position.next.next)
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:

        def swap(head):
            dummy = ListNode(0)
            dummy.next = head
            if not head or not head.next:
                return head
            curr = head
            p = dummy
            new = head.next
            curr.next =  new.next
            new.next = p.next
            p.next = new
            p.next.next.next = self.swapPairs(p.next.next.next)
            return dummy.next
        if not head:
            return
        return swap(head)

#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Better solution!!!
class Solution(object):
    def swapPairs(self, head: ListNode) -> ListNode:
        """
        :type head: ListNode
        :rtype: ListNode
        """

        # If the list has no node or has only one node left.
        if not head or not head.next:
            return head

        # Nodes to be swapped
        first_node = head
        second_node = head.next

        # Swapping
        first_node.next  = self.swapPairs(second_node.next)
        second_node.next = first_node

        # Now the head is the second node
        return second_node


"""メインモジュール."""

import argparse

from base_solver import BaseSolver
from chat_gpt3_solver import ChatGPT3Solver
from environment import NormalMachine
from epsilon_greedy_solver import EpsilonGreedySolver
from random_solver import RandomSolver
from stablelm_solver import StableLMSolver

def parse_args() -> argparse.Namespace:
    """コマンドライン引数を解析する.

    Returns:
        argparse.Namespace: 解析された引数オブジェクト
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "solver_type",
        type=str,
        choices=["random", "epsilon_greedy", "chat_gpt3", "stable_lm"],
    )
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_args()
    solver_type = args.solver_type
    machine_list = [
        NormalMachine(mean=10, stddev=5),
        NormalMachine(mean=20, stddev=5),
        NormalMachine(mean=30, stddev=5),
    ]
    TRIAL_NUM = 100
    solver: BaseSolver
    if solver_type == "random":
        solver = RandomSolver(len(machine_list))
    elif solver_type == "epsilon_greedy":
        solver = EpsilonGreedySolver(len(machine_list))
    elif solver_type == "chat_gpt3":
        solver = ChatGPT3Solver(len(machine_list), TRIAL_NUM)
    elif solver_type == "stable_lm":
        solver = StableLMSolver(len(machine_list), TRIAL_NUM)
    else:
        raise ValueError(f"Unknown solver_type: {solver_type}")
    reward_sum = 0
    for _ in range(TRIAL_NUM):
        selected = solver.select()
        reward = machine_list[selected].sample()
        solver.update(selected, reward)
        print(f"selected: {selected}, reward: {reward}")
        reward_sum += reward

    reward_average = reward_sum / TRIAL_NUM
    print(f"reward_average: {reward_average:.1f}")


from django.db import models

class Global(models.Model):
    name = models.CharField(max_length=200)
    projection_period = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return self.name

VARIABLE_TYPES = [("Input","Input"), ("Table","Table"), ("Variable","Variable"),]
class Variable(models.Model):
    name = models.CharField(max_length=200)
    formula = models.TextField(null=True, blank=True)
    level = models.IntegerField(null=True, blank=True)
    round = models.IntegerField(default=0)
    type = models.CharField(max_length=200, choices=VARIABLE_TYPES)

    def __str__(self):
        return self.name

    def values_round(self):
        rounding = self.round
        values = self.values()
        values_rounded = []
        for x in values:
            values_rounded.append(round(x,rounding))
        return values_rounded

    def values(self):
        values = []
        for t in range(10):
            values.append(self.value(t))
        return values

    def value(self, t):
        formula = self.formula.strip()
        formula = self.remove_if(formula, t).strip()
        formula = self.replace_variables(formula, t)
        formula = self.replace_t(formula, t)
        try:
            result = eval(formula)
        except:
            result = formula
        return result

    def replace_t(self, formula, t):
        if formula[0:5] == "Error": return formula
        formula = formula.replace("t", str(t))
        return formula

    def replace_variables(self, formula, t):
        for x in self.referenced_variables():
            start = formula.find(x.name)
            if start != -1:
                start_t = formula.find("(", start)
                end_t = formula.find(")", start)
                if start_t == -1 or end_t == -1:
                    return("Error - brackets not found")
                variable_str = formula[start:end_t+1]
                time_str = formula[start_t+1:end_t]
                time_str = time_str.replace("t", str(t))
                try:
                    t = eval(time_str)
                except:
                    return(f"Error - 'Time String' couldn't be evaluated: 'Time String': '{time_str}'")
                formula = formula.replace(variable_str, str(x.value(t)))
        return formula

    def remove_if(self, formula, t):
        found = formula.find("if")
        if found == -1:
            return formula
        else:
            # Get Logic Statement
            start = found + 2
            end = formula.find(":")
            logic_statement = formula[start:end]
            logic_statement_str = logic_statement.strip()
            logic_statement_str = self.replace_t(logic_statement_str, t)
            logic_statement_result = eval_logic(logic_statement_str)
            # Get True Statement
            start = end + 2
            end = formula.find("else")
            true_statement = formula[start:end].strip()
            # Get False Statement
            start = end + 5
            end = None
            false_statement = formula[start:end]
            if logic_statement_result:
                return true_statement
            else:
                return false_statement

    def referenced_variables(self):
        referenced_variables = []
        variables = Variable.objects.all()
        for y in variables:
            found = self.formula.find(y.name)
            if found != -1: referenced_variables.append(y)
        return referenced_variables

def eval_logic(formula):
    if formula == 'True': return True
    equals = formula.find("=")
    lhs = float(formula[0:equals])
    rhs = float(formula[equals+1:])
    return lhs == rhs


from datetime import datetime
import numpy as np
import pickle;

from flask import Flask, request, jsonify
from flask import render_template
app = Flask(__name__)

def hello():
    return "Hello, World!"

@app.route("/")
@app.route('/home')
def home():
    return render_template(
        'index.html',
        title = '''Shu's Home Page''',
        year = datetime.now().year,
    )

@app.route('/calculation')
def calculation():
    return render_template(
        'calculation.html',
        title = '''Calculation''',
        year = datetime.now().year,
    )

@app.route('/knn')
def knn():
    return render_template(
        'knn.html',
        title = '''KNN''',
        year = datetime.now().year,
    )

@app.route('/about')
def about():
    return render_template(
        'about.html',
        title = '''About Shu''',
        year = datetime.now().year,
    )

@app.route('/add_model')
def add_model():
   value1 = request.args.get('val1', type = float);
   value2 = request.args.get('val2', type = float);
   return jsonify(data = value1 + value2);

@app.route('/multi_model')
def multi_model():
   value1 = request.args.get('val1', type = float);
   value2 = request.args.get('val2', type = float);
   return jsonify(data = value1 * value2);

@app.route('/knn_model')
def knn_model():
   value1 = request.args.get('val1', type = float);
   value2 = request.args.get('val2', type = float);

   data = np.ndarray(shape = (1, 2), dtype = float);
   data[0, 0] = value1;
   data[0, 1] = value2;

   print(data);

   knn_model = pickle.load(open('static/model/knn_model.pkl', 'rb'));
   result = knn_model.predict(data);

   if result[0] == 1:
       class_color = 'Yellow';
   elif result[0] == 0:
        class_color = 'Purple';

   del knn_model;

   return jsonify(data = class_color);


from mech.actuator import *
from lib.utils import *
from datetime import datetime

"""
Defines functions to control, calibrate, and monitor actuators.
One layer up from direct actuator functions

"""

def current_readings(sensor=None, rate_units=['s', 'sec']):

    """
    current_readings -  provides current state of system.
      scale mass (g), pump rate (steps/s), time (__), pressure (atm)

    :param sensor: specifies which sensor to read
         must be one of ['mass', 'rate', 'time', 'pressure', 'valve']
         if None, returns all readings as dict
    :return: dict of readings if sensor=None,
             else returns float
    """

    current_data = dict()

    sensors = {'mass': scale,
               'rate': lambda: pump()/60, #(60 for min->s)
               'time': datetime.now,
               'pressure': pressure,
               'valve': valve}

    for s, actuator in sensors.items():
        current_data[s] = actuator()

    if sensor:
        # provide measured value single sensor specfied
        if sensor in sensors.keys():
             current_data = sensors[sensor]()
        else:
            # invalid sensor specified; raise error/report in log
            current_data = None

    # if steps/second not desired pump rate units, convert accordingly:
    if (rate_units != ['s', 'sec'] and sensor is None) \
        or (rate_units != ['s', 'sec'] and sensor == 'rate'):

        # unpack pump rate
        if sensor:
            rate_0 = current_data
        else:
            rate_0 = current_data['rate']

        # convert pump rate from steps/sec
        rate = convert_rate(rate_0, ['s', rate_units[0]], ['sec',rate_units[1]])

        # repack pump rate
        if sensor:
            current_data = rate
        else:
            current_data['rate'] = rate

    return current_data

def attenuate_pump_rate(rate, stop_rate=None, is_lowerbound=False):

    """
    attenuate_pump_rate - checks if pump adjustment will exceed engineering limits
       or recipe stage boundaries. Attenuates rate by reducing to boundary value.
    :param rate: int - current pump rate in steps/s
    :param stop_rate: int - recipe end rate for pump in steps/s
    :param is_lowerbound" bool - indicates rate decreasing e.g. lower bound threshold
    :return: 2-list
      :rate: float cleaned up rate value
      :rate_limit_hit: bool - Indicates attenuation so stage not stuck in infinite loop trying to reach
        out of bounds stop value
    """

    # Indicates if stop_value exceeded
    rate_limit_hit = False

    # Clean up pump rate if zero (e.g.stopped) or negative (e.g. pumping in reverse)
    if rate < MIN_PUMP_RATE:

        if rate < 0:
            #if in reverse, stop pump
            rate=0
        else:

            # if non-negative but lower than minimum readjust to nominal rate
            rate = MIN_PUMP_RATE
        rate_limit_hit = True

        #raise mass recipe discrepency error and note in log
        #...

    # Reduce pump rate if exceeds mechanical pump speed threshold
    if rate > MAX_PUMP_RATE:

        rate = MAX_PUMP_RATE
        rate_limit_hit = True

        #raise mass recipe discrepency error and note in log
        #...

    if stop_rate:
        # If new rate exceeds stop rate, go with max rate
        #  (or if negative rate and min)
        if (rate > stop_rate \
             and not is_lowerbound) or \
           (rate < stop_rate \
            and is_lowerbound):

            # replace rate with stop value
            rate = stop_rate
            rate_limit_hit = True

    rate_j = [rate, rate_limit_hit]

    return rate_j

def pump_calibration():

    """
    Calibrate constant to calculate pump mass/step ratio
      using range of pump speeds to for feed solution viscocity
    """
    #...

    return step_constant

def max_pressure(bioreactor_type=DEFAULT_REACTOR_MODEL):

    """
    max_pressure - returns maximum pressure (atm) safely allowed by vessle

    :return: maximum safe pressure for given reactor.

    """

    bioreactor_specs = {'ficticfeed100':{'p_max':100}}

    specs = bioreactor_specs[bioreactor_type]
    p_max  = specs['p_max']

    return p_max

def pump_prime(prime_duration=5):
    """
     Fill dead volume of pump with glucose feedstock
      by running pump at max rate offline for set number of seconds (prime_duration)

    :param prime_duration: int time (seconds) to run pump at max speed
    :return: None
    """

    #  Priming program will depend on type of pump:
    #    peristaltic: high speed until stock starts losing weight. Continue for remainder of tubing
    #    diaphragm: high speed for several seconds.
    #    syringe: Fill to capacaity of pump.

    valve(0)
    pump(MAX_PUMP_RATE)
    sleep(prime_duration)
    pump(0)
    valve(1)

    return None

def is_feedempty(sensor_data):

    """
    Checks if glucose feed ran out.
      If scale stops decreasing while pump is going, attempts prime
      monitors if scale starts going down.
    """

    # take derivative of scale readings wrt time

    # compare to pump readings

    # if pump rate >> 0 and scale == 0 then prime

        # check scale again

        # if scale still unchanging, return True

    pass

def check_feed_contamination(sensor_data):

    """
    Checks if outgassing or foam from over-pressured vessle
    is traveling up feedstock tubing and contaminating glucose container

    """

    pass

def compare_scale_pump_pressure(sensor_data):

    """
    Checks if mass scale change, pump rate, and pressure data make physical sense
    Comparing rates of change with eachother at given times
    """

    pass

def vessle_conditions_good( maxpressure=True,
                            sensor_consistency=False,
                            feedempty=False,
                            contamination=False,
                            sensor_readings=None):

    """
    Checks multiple experimental conditions and egnineering controls at once
    Returns True if all pass, False if any fail
    """

    # Instantate list
    checks = []

    # Check if max pressure exceeded
    if maxpressure:
        goodpressure = pressure() < max_pressure()
        checks.append(goodpressure)

    # Check if atm, pump, and mass rate of changes are in agreement w/ eachother
    if sensor_consistency:
        consistent = compare_scale_pump_pressure(sensor_readings)
        checks.append(consistent)

    # Check if feedstock ran out
    if feedempty:
        feed = is_feedempty(sensor_readings)
        checks.append(feed)

    # Check if feedstock has evidence of contamination
    if contamination:
        contam = check_feed_contamination(sensor_readings)
        checks.append(contam)

    return all(checks)


def isprime(num):
    if num > 1:
        if num == 2:
            return True
        for n in range(2, num):
            if (num % n) == 0:
                return False
        return True

i = 1
while i <= 100:
    print(i)
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    if isprime(i):
        print("Prime")
    i += 1
    print()


from phenome_core.core.base.base_action import BaseAction
from phenome_core.core.base.healthscore import compute_health_score
from phenome_core.core.helpers.numeric_helpers import percent_to_float
from phenome_core.core.base.logger import root_logger as logger

from minermedic.miners.helper import get_converted_hashrate

"""

    HashCheck Healthcheck - checks miner hashrates

"""

class HashCheck(BaseAction):

    _ERROR_STATE_KEY_ = "hashrate_error"

    def __init__(self):
        super(HashCheck, self).__init__()

    def execute(self):

        # ok get the hashrate info from the miner
        hashrate_info_miner = self.results.get_result(self.object.id, 'hashrates')

        if hashrate_info_miner is None:
            # first time through here, exit
            return True

        # get some basic info from the miner hashrate stats
        current_hashrate = hashrate_info_miner.get('current')
        hashrate_units = hashrate_info_miner.get('units')

        if current_hashrate == 0:
            # the miner is just not hashing right now
            # should we add to the health score or just pass?
            # this will probably get taken care of by IDLE check
            return True

        # init some vars for the pool hashrate stats
        reported_hashrate_pool = None
        accepted_hashrate_pool = None
        current_hashrate_pool = 0
        speed_suffix_pool = None

        #  ok get the hashrate info from the pool
        hashrate_info_pool = self.results.get_result(self.object.id, 'hashrates_by_algo')

        pool_name = None

        if hashrate_info_pool is not None and len(hashrate_info_pool)==1:

            # TODO - if it is larger than 1, check the current algo
            # that the miner is processing and match the hashrate by algo

            for key, value in hashrate_info_pool.items():

                pool_name = key

                # the accepted hashrate from the pool (this is really what you are getting paid for)
                accepted_hashrate_pool = value.get('accepted')

                # some pools include "reported" hashrate, should represent how much your miner is hashing,
                # and it should be very close if not the same as the "current_hashrate" reported directly
                # from your miner.
                reported_hashrate_pool = value.get('reported')

                # get the speed of the hashing rate from the pool for conversions
                speed_suffix_pool = value.get('speed_suffix')

                break

        # first check if there could be a problem from the pool's perspective
        if accepted_hashrate_pool is not None and speed_suffix_pool is not None:
            current_hashrate_pool = get_converted_hashrate(accepted_hashrate_pool, speed_suffix_pool, hashrate_units)
            reported_hashrate_pool = get_converted_hashrate(reported_hashrate_pool, speed_suffix_pool, hashrate_units)

        # TODO - possibly use moving average in the future
        # https://stackoverflow.com/questions/13728392/moving-average-or-running-mean

        # for now, use the max hashrate achieved thus far to check expected hashrate for the miner

        max_hashrate = hashrate_info_miner['max']
        units = hashrate_info_miner['units']
        error_level = self.args['error_level']
        warning_level = self.args['warning_level']

        has_error_miner = False
        has_error_pool = False
        has_warn_pool = False
        has_warn_miner = False

        # Handle Error Levels

        if error_level is None:
            error_pct = 0
        else:
            error_pct = percent_to_float(error_level)
            has_error_pool = (current_hashrate_pool < (error_pct * max_hashrate))
            has_error_miner = (current_hashrate < (error_pct * max_hashrate))
            # do not take into account the pool hashrate to trigger an "ERROR"...
            self.has_error = (has_error_miner)

        # Handle Warning Levels

        if warning_level is None:
            warn_pct = 0
        else:
            warn_pct = percent_to_float(warning_level)
            has_warn_pool = (current_hashrate_pool < (warn_pct * max_hashrate))
            has_warn_miner = (current_hashrate < (warn_pct * max_hashrate))
            self.has_warning = (has_warn_miner or has_warn_pool)

        if self.has_error:
            self.error_message = self._build_error_message(
                "Miner '{}'".format(self.object.unique_id),current_hashrate, units, "error", error_level, max_hashrate)

        elif self.has_warning:
            if has_warn_pool:
                self.error_message = self._build_error_message(
                    "Pool '{}'".format(pool_name), current_hashrate_pool, units, "warning", error_level, max_hashrate)
            else:
                self.error_message = self._build_error_message(
                    "Miner '{}'".format(self.object.unique_id), current_hashrate, units, "warning", error_level, max_hashrate)

        # do not process health scores if both levels are not set
        if error_pct == 0 or warn_pct == 0:
            return False

        if self.has_error or self.has_warning:

            # now, determine amount of hashrate "missing" from the total potential hashrate
            if has_error_pool or has_warn_pool:
                missing_hashrate = round(max_hashrate - current_hashrate_pool)
            else:
                missing_hashrate = round(max_hashrate - current_hashrate)

            warning_missing_hashrate = round(max_hashrate - (max_hashrate * warn_pct))
            error_missing_hashrate = round(max_hashrate - (max_hashrate * error_pct))
            compute_health_score(self.object, self.results, missing_hashrate, warning_missing_hashrate, error_missing_hashrate)

            try:
                if self.has_error:
                    if self.results.object_states.get(self.object.id) is not None:
                        # set the object state flag in the case object states are used
                        self.results.object_states[self.object.id].__setattr__(self._ERROR_STATE_KEY_,1)
            except:
                logger.error(
                    "Problem setting error_state_key '{}' "
                    "for OBJECT ID={}".format(self._ERROR_STATE_KEY_, self.object.id))

        else:

            # some special cases?

            # FOR DEBUG
            if current_hashrate > 0 and current_hashrate_pool > 0 and \
                    reported_hashrate_pool is not None and reported_hashrate_pool == 0:

                # there is a problem. the reported rate should be around one of these rates.
                logger.debug("Reported Hashrate from the pool is 0 for miner '{}'. "
                             "Something could be wrong with miner or the miner "
                             "is not reporting hashrate to the pool".format(self.object.unique_id))

        return True

    def _build_error_message(self, what, current_hashrate, units, level_type, level, max_hashrate):

        return "{} hashrate {} {} is below {} threshold of {} based on max-rate of" \
               " {} {}".format(what, int(current_hashrate), units, level_type, level, max_hashrate, units)


import os
from zipfile import ZipFile
from os import path
from os.path import basename
from configure import Config
config = Config()

folders_for_zipping = []

train_path = config.train_orig
folders_for_zipping.append(train_path)

train_masks_path = config.train_orig + "_masks"
folders_for_zipping.append(train_masks_path)

validation_path = config.valid_orig
folders_for_zipping.append(validation_path)

validation_masks_path = config.valid_orig + "_masks"
folders_for_zipping.append(validation_masks_path)

def add_folder_to_zip(zipObj, folderPath):
	zipObj.write(folderPath, basename(folderPath))
	for filename in os.listdir(folderPath):
		filePath = os.path.join(folderPath, filename)
		if path.isfile(filePath):
			#print("Adding file to zip: {}".format(filename))
			zipObj.write(filePath, os.path.join(basename(folderPath),basename(filePath)))

print("Zipping files... The following folders and their contents will be zipped:")
with ZipFile ("preprocessed_images.zip", 'w') as zipObj:
	for folder_to_zip in folders_for_zipping:
		print("- {}".format(folder_to_zip))
		add_folder_to_zip(zipObj, folder_to_zip)
print("Zipping files complete.")


import tempfile
import shutil

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.test import Client, TestCase, override_settings
from django.urls import reverse
from posts.models import Group, Post, User, Comment, Follow
from posts.forms import PostForm

User = get_user_model()
TEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)

@override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT)
class PostPagesTests(TestCase):
    @classmethod
    def setUpClass(cls):
        """Создание записи в БД"""
        super().setUpClass()
        cls.user = User.objects.create_user(username='authorized')
        cls.group = Group.objects.create(
            title='Тестовая группа',
            slug='test_slug',
            description='Тестовое описание',
        )
        cls.post = Post.objects.create(
            author=cls.user,
            group=cls.group,
            text='Тестовый пост',
        )

    @classmethod
    def tearDownClass(cls):
        super().tearDownClass()
        # Метод shutil.rmtree удаляет директорию и всё её содержимое
        shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True)

    def setUp(self):
        cache.clear()
        self.authorized_client = Client()
        self.authorized_client.force_login(self.user)

    def test_pages_uses_correct_template(self):
        """URL-адрес использует соответствующий шаблон"""
        templates_pages_names = {
            reverse('posts:index'): 'posts/index.html',
            reverse('posts:group',
                    kwargs={'slug': self.group.slug}): 'posts/group_list.html',
            reverse('posts:profile',
                    kwargs={'username':
                            self.user.username}): 'posts/profile.html',
            reverse('posts:post_detail',
                    kwargs={'post_id':
                            self.post.pk}): 'posts/post_detail.html',
            reverse('posts:post_edit',
                    kwargs={'post_id':
                            self.post.id}): 'posts/create_post.html',
            reverse('posts:post_create'): 'posts/create_post.html',
        }

        for reverse_name, template in templates_pages_names.items():
            """типы полей формы в словаре context соответствуют ожиданиям"""
            with self.subTest(reverse_name=reverse_name):
                response = self.authorized_client.get(reverse_name)
                self.assertTemplateUsed(response, template)

    def test_cache_context(self):
        '''Проверка кэширования страницы index'''
        before_create_post = self.authorized_client.get(
            reverse('posts:index'))
        first_item_before = before_create_post.content
        Post.objects.create(
            author=self.user,
            text='Проверка кэша',
            group=self.group)
        after_create_post = self.authorized_client.get(reverse('posts:index'))
        first_item_after = after_create_post.content
        self.assertEqual(first_item_after, first_item_before)
        cache.clear()
        after_clear = self.authorized_client.get(reverse('posts:index'))
        self.assertNotEqual(first_item_after, after_clear)

    def test_profile_page_show_correct_context(self):
        """Шаблон profile сформирован с правильным контекстом."""
        response = self.authorized_client.get(
            reverse('posts:profile',
                    kwargs={'username': PostPagesTests.user}))
        self.assertEqual(response.context['page_obj'][0],
                         PostPagesTests.post)
        context_author = response.context.get('author')
        self.assertEqual(context_author, self.post.author)

    def test_post_detail_page_show_correct_context(self):
        """Шаблон post_detail сформирован с правильным контекстом."""
        response = self.authorized_client.get(
            reverse('posts:post_detail', kwargs={'post_id': self.post.id}))
        post_text_0 = {response.context['post'].text: 'Тестовый пост',
                       response.context['post'].group: self.group,
                       response.context['post'].author: self.user.username}
        for value, expected in post_text_0.items():
            self.assertEqual(post_text_0[value], expected)

    def test_post_create_page_show_correct_context(self):
        """Шаблон post_create сформирован с правильным контекстом."""
        response = testing_pages = (
            f'/posts/{PostPagesTests.post.pk}/edit/',
            '/create/',
        )
        for url in testing_pages:
            with self.subTest(url=url):
                response = self.authorized_client.get(url)
                self.assertIsInstance(
                    response.context['form'],
                    PostForm
                )
                if 'edit' in url:
                    self.assertEqual(
                        response.context['is_edit'],
                        True
                    )
                    self.assertEqual(
                        response.context['post'],
                        PostPagesTests.post
                    )

    def test_paginator(self):
        bulk_posts = []
        for i in range(12):
            bulk_posts.append(Post(
                text=f'Тестовый пост {i}',
                author=PostPagesTests.user,
                group=PostPagesTests.group)
            )
        Post.objects.bulk_create(bulk_posts)

        reverse_name_posts = [
            reverse('posts:index'),
            reverse('posts:profile',
                    kwargs={'username': f'{self.user.username}'}),
            reverse('posts:group',
                    kwargs={'slug': f'{self.group.slug}'}),
        ]

        for reverse_name in reverse_name_posts:
            with self.subTest(reverse_name=reverse_name):
                response = self.client.get(reverse_name)
                self.assertEqual(
                    len(response.context['page_obj']), 10,
                    'Количество постов на первой странице не равно десяти'
                )

class CommentTest(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.user = User.objects.create_user(username='auth1')
        cls.user2 = User.objects.create_user(username='auth2')

    def setUp(self):
        self.guest_client = Client()
        self.authorized_client = Client()
        self.authorized_client.force_login(self.user)
        self.group = Group.objects.create(title='Тестовая группа',
                                          slug='test_group')
        self.post = Post.objects.create(text='Тестовый текст',
                                        group=self.group,
                                        author=self.user)

    def test_post_detail_page_show_correct_context(self):
        """Шаблон post_detail сформирован с
           правильным контекстом комментария."""
        self.comment = Comment.objects.create(post_id=self.post.id,
                                              author=self.user,
                                              text='Тестовый коммент')
        response = self.authorized_client.get(
            reverse('posts:post_detail', kwargs={'post_id': self.post.id}))
        comments = {response.context['comments'][0].text: 'Тестовый коммент',
                    response.context['comments'][0].author: self.user.username
                    }
        for value, expected in comments.items():
            self.assertEqual(comments[value], expected)
            self.assertTrue(response.context['form'], 'форма получена')

class FollowViewsTest(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.user = User.objects.create_user(username='auth1')
        cls.user2 = User.objects.create_user(username='auth2')
        cls.author = User.objects.create_user(username='someauthor')

    def setUp(self):
        self.guest_client = Client()
        self.authorized_client = Client()
        self.authorized_client.force_login(FollowViewsTest.user)
        self.authorized_client2 = Client()
        self.authorized_client2.force_login(FollowViewsTest.user2)

    def test_user_follower_authors(self):
        '''Посты доступны подписчику'''
        count_follow = Follow.objects.filter(user=FollowViewsTest.user).count()
        data_follow = {'user': FollowViewsTest.user,
                       'author': FollowViewsTest.author}
        url_redirect = reverse(
            'posts:profile',
            kwargs={'username': FollowViewsTest.author.username})
        response = self.authorized_client.post(
            reverse('posts:profile_follow', kwargs={
                'username': FollowViewsTest.author.username}),
            data=data_follow, follow=True)
        new_count_follow = Follow.objects.filter(
            user=FollowViewsTest.user).count()
        self.assertTrue(Follow.objects.filter(
                        user=FollowViewsTest.user,
                        author=FollowViewsTest.author).exists())
        self.assertRedirects(response, url_redirect)
        self.assertEqual(count_follow + 1, new_count_follow)

    def test_user_unfollower_authors(self):
        '''Посты не доступны не подписчику '''
        count_follow = Follow.objects.filter(
            user=FollowViewsTest.user).count()
        data_follow = {'user': FollowViewsTest.user,
                       'author': FollowViewsTest.author}
        url_redirect = ('/auth/login/?next=/profile/'
                        f'{self.author.username}/unfollow/')
        response = self.guest_client.post(
            reverse('posts:profile_unfollow', kwargs={
                'username': FollowViewsTest.author}),
            data=data_follow, follow=True)
        new_count_follow = Follow.objects.filter(
            user=FollowViewsTest.user).count()
        self.assertFalse(Follow.objects.filter(
            user=FollowViewsTest.user,
            author=FollowViewsTest.author).exists())
        self.assertRedirects(response, url_redirect)
        self.assertEqual(count_follow, new_count_follow)

    def test_follower_see_new_post(self):
        '''У подписчика появляется новый пост избранного автора.
           А у не подписчика его нет'''
        new_post_follower = Post.objects.create(
            author=FollowViewsTest.author,
            text='Текстовый текст')
        Follow.objects.create(user=FollowViewsTest.user,
                              author=FollowViewsTest.author)
        response_follower = self.authorized_client.get(
            reverse('posts:follow_index'))
        new_posts = response_follower.context['page_obj']
        self.assertIn(new_post_follower, new_posts)

    def test_unfollower_no_see_new_post(self):
        '''У не подписчика поста нет'''
        new_post_follower = Post.objects.create(
            author=FollowViewsTest.author,
            text='Текстовый текст')
        Follow.objects.create(user=FollowViewsTest.user,
                              author=FollowViewsTest.author)
        response_unfollower = self.authorized_client2.get(
            reverse('posts:follow_index'))
        new_post_unfollower = response_unfollower.context['page_obj']
        self.assertNotIn(new_post_follower, new_post_unfollower)


"""CLI providing some useful derivation-related utilities."""

import argparse
import os
import sys

from pynix import __version__
from pynix.derivation import Derivation
from pynix.binary_cache.client import NixCacheClient

def get_args():
    """Parse command-line arguments."""
    p_root = argparse.ArgumentParser(description="Derivation Utilities")
    p_root.add_argument("--version", action="version", version=__version__)
    subparsers = p_root.add_subparsers(title="Command", dest="command")
    subparsers.required = True

    # 'show' command
    p_show = subparsers.add_parser("show", help="Show a derivation.")
    p_show.add_argument("derivation_path", help="Path to the derivation.")
    p_show.add_argument("--json", action="store_const", const="json",
                        dest="format", help="JSON format.")
    p_show.add_argument("--yaml", action="store_const", const="yaml",
                        dest="format", help="YAML format.")
    p_show.add_argument("--string", action="store_const", const="string",
                        dest="format", help="Raw derivation format.")
    p_show.add_argument("-p", "--pretty", action="store_true", default=False,
                        help="Pretty-print.")
    p_show.add_argument("-A", "--attribute", help="Attribute to show.")
    p_show.add_argument("-e", "--env-vars", nargs="+",
                        help="Environmant variable to show.")
    p_show.add_argument("-o", "--output",
                        help="Show the path of the given output.")

    # 'diff' command
    p_diff = subparsers.add_parser("diff", help="Diff two derivations.")
    p_diff.add_argument("first", help="Path to the first derivation.")
    p_diff.add_argument("second", help="Path to the second derivation.")

    # 'preview' command
    p_preview = subparsers.add_parser("preview",
        help="Show paths needed to build a derivation.")
    p_preview.add_argument("derivation_paths", nargs="*",
                          help="Paths to derivations.")
    p_preview.add_argument("-c", "--binary-cache",
                           default=os.environ.get("NIX_REPO_HTTP"),
                           help="URL of a binary cache to query for paths.")
    p_preview.add_argument("--show-existing", action="store_true",
                           default=False, help="Show paths already existing.")
    p_preview.add_argument("--show-outputs", action="store_true",
                           default=False,
                           help="Show output names that will be built, "
                                "rather than paths.")
    p_preview.add_argument("--count", action="store_true", default=False,
                           help="Only show path count, don't print paths")
    return p_root.parse_args()

def main():
    """Main entry point."""
    args = get_args()
    if args.command == "show":
        path = args.derivation_path
        if "!" in path:
            path = path.split("!")[0]
        deriv = Derivation.parse_derivation_file(path)
        print(deriv.display(
            attribute=args.attribute,
            env_vars=args.env_vars,
            output=args.output,
            format=args.format,
            pretty=args.pretty))
    elif args.command == "diff":
        first = Derivation.parse_derivation_file(args.first)
        second = Derivation.parse_derivation_file(args.second)
        print(first.diff(second))
    elif args.command == "preview":
        if len(args.derivation_paths) > 0:
            paths = args.derivation_paths
        elif not sys.stdin.isatty():
            paths = (p.strip() for p in sys.stdin)
        else:
            sys.exit("No path arguments given")
        print_preview(paths, binary_cache=args.binary_cache,
                      show_existing=args.show_existing,
                      show_outputs=args.show_outputs,
                      numbers_only=args.count)
    else:
        sys.exit("Command {} not implemented".format(repr(args.command)))

if __name__ == "__main__":
    main()


import json
from data_jps import web_scrapping, filter_status

async def Perlis_command(update, context):
    await update.message.reply_text('''Ini senarai daerah dalam /Perlis
1. /Arau
2. /Kangar
3. /Padang_Besar
''')

async def send_data(update, district):
    web_scrapping('PLS', district)
    status = ["Cetek","Normal","Waspada","Amaran","Bahaya"]
    for data in status:
        df_noti = filter_status().loc[filter_status()['Status'].isin([data])]
        result = df_noti.to_json(orient='index')
        parsed = json.loads(result)
        for p_id, p_info in parsed.items():
            print("Index ID:", p_id)
            data_to_push =f'''
ID Stesen: {parsed[p_id]['ID Stesen']}
Nama Stesen: {parsed[p_id]['Nama Stesen']}
Daerah: {parsed[p_id]['Daerah']}
Lembangan: {parsed[p_id]['Lembangan']}
Sub Lembangan: {parsed[p_id]['Sub Lembangan']}
Update sekarang: {parsed[p_id]['Update sekarang']}
Aras Air: {parsed[p_id]['Aras Air']}
Status: {parsed[p_id]['Status']}'''
            await update.message.reply_text(data_to_push)

async def Arau_command(update, context):
    await send_data(update, 'Arau')

async def Kangar_command(update, context):
    await send_data(update, 'Kangar')

async def Padang_Besar_command(update, context):
    await send_data(update, 'Padang Besar')


from typing import Tuple
from primitives import *

# Game settings
screen_size: tuple = (100, 100)
screen_title: str = "JorCademy Engine"
background_color: tuple = (0, 0, 0)
__draw_buffer: list = []
audio_channel_count: int = 0
screen = pygame.display.set_mode((100, 100))

# Initialize audio component
pygame.mixer.init()

# Create type aliases
color = Tuple[int, int, int]

# ==== Keyboard input ====

__key_status = {}

# Get whether a specific key is down
def is_key_down(key: str) -> bool:
    if key in __key_status:
        return __key_status[key]
    else:
        return False

# ==== Mouse input ====

__mouse_status = {}
__scroll_up: bool = False
__scroll_down: bool = False
mouse_position: (int, int) = (0, 0)

# Get whether a specific mouse button is down
def is_mouse_button_down(button: str) -> bool:
    if button in __mouse_status:
        return __mouse_status[button]
    else:
        return False

def is_scrolling_up() -> bool:
    return __scroll_up

# Get whether the player is scrolling down
def is_scrolling_down() -> bool:
    return __scroll_down

# Change screen size
def screen(width: int, height: int) -> None:
    global screen_size
    screen_size = (width, height)

# Change screen title
def title(t: str) -> None:
    global screen_title
    screen_title = t

# Change app icon
def icon(name: str) -> None:
    app_icon = pygame.image.load("./assets/" + name)
    pygame.display.set_icon(app_icon)

# Change screen background color
def backdrop(c: color) -> None:
    global background_color
    __draw_buffer.clear()
    background_color = c

# Draw a circle
def ellipse(c: color, x: float, y: float, w: float, h: float, rotation=0) -> None:
    e = Ellipse(c, x, y, w, h, rotation)
    __draw_buffer.append(e)

# Draw a rectangle
def rect(c: color, x: float, y: float, w: float, h: float, rotation=0) -> None:
    r = Rectangle(c, x, y, w, h, rotation)
    __draw_buffer.append(r)

# Draw a string of text
def text(content: str, size: int, c: color, x: float, y: float, font="Nunito", rotation=0) -> None:
    # Fetch font
    try:
        font = pygame.font.Font("./assets/" + font, size)
    except:
        font = pygame.font.SysFont(font, size)

    # Draw font
    text_surface = font.render(content, True, c)
    w, h = font.size(content)
    t = Text(content, text_surface, c, x, y, w, h, size, font, rotation)
    __draw_buffer.append(t)

# Load an image
def load_image(path: str) -> Image:
    full_path = "assets/" + path
    try:
        return Image(pygame.image.load(full_path).convert_alpha())
    except pygame.error as e:
        print(f"Error loading image {full_path}: {e}")

# Draw an image
def image(img: Image, x: float, y: float, scale=1.0, flipped=False, rotation=0) -> None:
    surface = img.image
    i = Image(surface, scale, x, y, flipped, rotation)
    __draw_buffer.append(i)

# Load new sound
def load_sound(path: str):
    sound = Exception
    try:
        sound = pygame.mixer.Sound(path)
    except:
        print("Error: Audio could not be loaded.")
    return sound

# Wait for new action
def sleep(msec: int):
    pygame.time.wait(msec)


from odoo import api, models,_

class ReportAccountReport(models.AbstractModel):
    _name = 'report.custom_oroval.custom_invoice_template'

    @api.model
    def render_html(self, docids, data=None):
        invoice_obj = self.env['account.invoice'].browse(docids[0])
        self.model = self.env.context.get('active_model')
        user = self.env["res.users"].browse(self._uid)
        company_data=user.company_id
#         data = {'sale_header_footer':user.company_id.sale_header_footer ,
#                 'primary_color': company_data.primary_color ,
#                 'secondary_color':  company_data.secondary_color,
#                 'sale_font_color': company_data.sale_font_color}
        docargs = {
            'doc_ids': self.ids,
            'doc_model': self.model,
            'docs': invoice_obj,
#             'data': data,
            'doc' :user,
        }

        return self.env['report'].render('custom_oroval.custom_invoice_template', values=docargs)


from callback_functions.custom_helpers import main_app,decode_token
from dash.dependencies import Output, Input, State
from pages.home_page import layout as home_page
from pages.login_page import layout as login_page
from pages.page_not_found import layout as page_not_found
import time

# app = main_app.app

c = 0

# This function updates the following
# 1 -> url2 component's pathname
# 2 -> app_output component's children
# 3 -> token component's clear_data
# It takes 2 inpiuts (1 input and 1 state)
# Input -> url1 components pathname
# State -> token components data
@main_app.app.callback(
    Output("url2","pathname"),
    Output("app_output","children"),
    Output("token","clear_data"),
    Input("url1","pathname"),
    State("token","data"))
def validate_token_and_update_screen(pathname,token):
    global c
    c+=1
    print(f'''----------------------
            Loop number = {c}
            pathname =========== {pathname}
            ---------------------------''')
    try:
        payload = decode_token(token)
        session_not_over = payload['session_end_time'] > int(time.time())
        if session_not_over:
            main_app.current_url = pathname
            if(pathname == main_app.environment_details['home_page_link'] or pathname == main_app.environment_details['login_page_link']):
                print("1.1--------------------")
                print(f"=========> {main_app.current_url}")
                return main_app.environment_details['home_page_link'],home_page,False
            elif(pathname == main_app.environment_details['logout_page_link']):
                print("1.2--------------------")
                main_app.connector = ""
                return main_app.environment_details['logout_page_link'],login_page,True
            else:
                print("1.3--------------------")
                return pathname,page_not_found,False
        else:
            print("1.4-------------------- Session over login again")
            return main_app.environment_details['login_page_link'],login_page,False
    except Exception as e:
        print("1.5 ---------------------Not a valid Token")
        # return login_page, False
        return main_app.environment_details['login_page_link'],login_page, False


import argparse
import json
import logging
import sys
from datetime import datetime
from typing import Union
from urllib.parse import urlparse

import pandas as pd
import pyangbind.lib.pybindJSON as pybindJSON

from catalog_connector.clients.ngsi_ld import NGSILDAPI
from catalog_connector.clients.yang_catalog import YangCatalogAPI
from catalog_connector.models.ngsi_ld.catalog import Module, Submodule
from catalog_connector.models.yang import yang_catalog as binding

logger = logging.getLogger(__name__)

BATCH_SIZE = 20

def chunks(lst, n):
    """
    Yield successive n-sized chunks from lst.

    Reference: https://stackoverflow.com/questions/312443/
               how-do-you-split-a-list-into-evenly-sized-chunks
    """
    for i in range(0, len(lst), n):
        yield lst[i : i + n]

def deserialize_yang(data: dict) -> binding.yang_catalog:
    return pybindJSON.loads_ietf(data, binding, "yang_catalog")

def compute_module_properties(
    data: binding.yc_module_yang_catalog__catalog_modules_module,
) -> dict:
    properties_dict = {}
    if data.ietf.ietf_wg:
        properties_dict["ietfWg"] = {"value": data.ietf.ietf_wg}
    if data.schema:
        properties_dict["schema"] = {"value": data.schema}
    if data.generated_from:
        properties_dict["generatedFrom"] = {"value": data.generated_from}
    if data.maturity_level:
        properties_dict["maturityLevel"] = {"value": data.maturity_level}
    if data.document_name:
        properties_dict["documentName"] = {"value": data.document_name}
    if data.author_email:
        properties_dict["authorEmail"] = {"value": data.author_email}
    if data.reference:
        properties_dict["reference"] = {"value": data.reference}
    if data.module_classification:
        properties_dict["moduleClassification"] = {"value": data.module_classification}
    if data.compilation_status:
        properties_dict["compilationStatus"] = {"value": data.compilation_status}
    if data.compilation_result:
        properties_dict["compilationResult"] = {"value": data.compilation_result}
    if data.prefix:
        properties_dict["prefix"] = {"value": data.prefix}
    if data.yang_version:
        properties_dict["yangVersion"] = {"value": data.yang_version}
    if data.description:
        properties_dict["description"] = {"value": data.description}
    if data.contact:
        properties_dict["contact"] = {"value": data.contact}
    if data.belongs_to:
        properties_dict["belongsTo"] = {"value": data.belongs_to}
    if data.tree_type:
        properties_dict["treeType"] = {"value": data.tree_type}
    if data.yang_tree:
        properties_dict["yangTree"] = {"value": data.yang_tree}
    if data.expires:
        properties_dict["expires"] = {"value": data.expires}
    if data.expired:
        properties_dict["expired"] = {"value": data.expired}
    if data.semantic_version:
        properties_dict["semanticVersion"] = {"value": data.semantic_version}
    if data.derived_semantic_version:
        properties_dict["derivedSemanticVersion"] = {
            "value": data.derived_semantic_version
        }
    return properties_dict

def build_dep(
    df: pd.DataFrame,
    dep_name: str,
    dep_revision: str = None,
    dep_schema: str = None,
) -> dict:
    dependency_id = None
    # (A) revision value takes preference when identifying the module
    if dep_revision:
        filtered_modules = df[
            (df["name"] == dep_name) & (df["revision"] == str(dep_revision))
        ]
        # Catch ghost dependency
        if filtered_modules.empty:
            organization = "unknown"
            module_type = "module"
        else:
            dependency_module = filtered_modules.iloc[0]
            module_type = dependency_module["module-type"]
        # Generate dependency entity ID
        dependency_id = "urn:ngsi-ld:{0}:{1}:{2}".format(
            module_type.capitalize(), dep_name, dep_revision
        )
    # (B) use schema URL to identify the module
    if not dep_revision and dep_schema:
        filtered_modules = df[
            (df["name"] == dep_name) & (df["schema"] == str(dep_schema))
        ]
        revision = None
        # Catch ghost dependency
        if filtered_modules.empty:
            # Try to figure out revision date from filename
            revision = (
                urlparse(dep_schema).path.split("/")[-1].split("@")[-1].split(".")[0]
            )
            try:
                _ = datetime.strptime(revision, "%Y-%m-%d")
                filtered_modules = df[
                    (df["name"] == dep_name) & (df["revision"] == revision)
                ]
                # Catch ghost dependency
                if filtered_modules.empty:
                    module_type = "module"
                else:
                    dependency_module = filtered_modules.iloc[0]
                    organization = dependency_module["organization"]
                    module_type = dependency_module["module-type"]
            except ValueError:
                revision = "unknown"
                module_type = "module"
        # Module found in the database
        else:
            dependency_module = filtered_modules.iloc[0]
            revision = dependency_module["revision"]
            module_type = dependency_module["module-type"]
        # Generate dependency entity ID
        dependency_id = "urn:ngsi-ld:{0}:{1}:{2}".format(
            module_type.capitalize(), dep_name, revision
        )
    # (C) fallback mechanism: set to unknown
    if not dep_revision and not dep_schema:
        revision = "unknown"
        organization = "unknown"
        module_type = "module"
        # Generate dependency entity ID
        dependency_id = "urn:ngsi-ld:{0}:{1}:{2}".format(
            module_type.capitalize(), dep_name, revision
        )

    return {
        "object": dependency_id,
        "datasetId": dependency_id,
    }

def collect_deps(
    module_id: str,
    df: pd.DataFrame,
    yang_data: binding.yc_module_yang_catalog__catalog_modules_module,
) -> dict:
    # Compute deps
    deps = {}
    # Then this entity becomes a dependency of its dependents
    if yang_data.dependents.items():
        logger.info("Collecting dependents of {0}".format(module_id))
        deps["hasDependents"] = []
        for _, dependent in yang_data.dependents.iteritems():
            dependent_object = build_dep(
                df, dependent.name, dependent.revision, dependent.schema
            )
            deps["hasDependents"].append(dependent_object)

    # Then this entity becomes a dependent of its dependents
    if yang_data.dependencies.items():
        logger.info("Collecting dependencies of {0}".format(module_id))
        deps["hasDependencies"] = []
        for _, dependency in yang_data.dependencies.iteritems():
            dependency_object = build_dep(
                df, dependency.name, dependency.revision, dependency.schema
            )
            deps["hasDependencies"].append(dependency_object)

    return deps

def build_module_entity(
    df: pd.DataFrame, yang_data: binding.yc_module_yang_catalog__catalog_modules_module
) -> Union[Module, Submodule]:

    # Compute properties
    yang_module_id = "{0}:{1}".format(
        yang_data.name, yang_data.revision)
    properties = compute_module_properties(yang_data)
    if yang_data.module_type == "module":
        id = "urn:ngsi-ld:Module:{0}".format(yang_module_id)
        deps = collect_deps(id, df, yang_data)
        if deps:
            properties.update(deps)
        module = Module(
            id=id,
            name={"value": yang_data.name},
            revision={"value": yang_data.revision},
            organization={"value": yang_data.organization},
            namespace={"value": yang_data.namespace},
            **properties
        )
        return module
    # Submodule then
    else:
        id = "urn:ngsi-ld:Submodule:{0}".format(yang_module_id)
        deps = collect_deps(id, df, yang_data)
        if deps:
            properties.update(deps)
        submodule = Submodule(
            id=id,
            name={"value": yang_data.name},
            revision={"value": yang_data.revision},
            organization={"value": yang_data.organization},
            namespace={"value": yang_data.namespace},
            **properties
        )
        return submodule

def main(ngsi_ld_api: NGSILDAPI, local_catalog: bool):
    if local_catalog:
        f = open("data.json")
        catalog_data = json.load(f)
        f.close()
    else:
        # Init YANGCatalog API Client
        yangcatalog_api = YangCatalogAPI()
        logger.info("Collecting data from YANG Catalog...")
        catalog_data = yangcatalog_api.get_whole_catalog()
        logger.info("Loaded module data from YANG Catalog!")
    # Build pandas DataFrame from module list for fast queries
    df = pd.json_normalize(catalog_data["yang-catalog:catalog"]["modules"]["module"])
    # Build Python generator from module list for NGSI-LD transformation
    module_list_generator = chunks(
        catalog_data["yang-catalog:catalog"]["modules"]["module"], BATCH_SIZE
    )
    while True:
        try:
            module_list_batch = next(module_list_generator)
        except StopIteration:
            break
        yang_batch = {
            "yang-catalog:catalog": {"modules": {"module": module_list_batch}}
        }
        yc = deserialize_yang(yang_batch)
        batch_entities = []
        for _, yang_module in yc.catalog.modules.module.iteritems():
            module_entity = build_module_entity(df, yang_module)
            batch_entities.append(module_entity.dict(exclude_none=True, by_alias=True))
        # Send batch of entities
        ngsi_ld_api.batchEntityUpsert(batch_entities, "update")

    logger.info("Synchronization with YANG Catalog completed!")

if __name__ == "__main__":
    logging.basicConfig(
        stream=sys.stdout,
        level=logging.INFO,
        format="'%(asctime)s - %(name)s - %(levelname)s - %(message)s'",
    )
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--broker-uri",
        dest="broker_uri",
        default="http://localhost:9090",
        required=False,
        help="NGSI-LD Context Broker URI.",
    )
    parser.add_argument(
        "--context-catalog-uri",
        dest="context_catalog_uri",
        default="http://context-catalog:8080/context.jsonld",
        required=False,
        help="Context Catalog URI.",
    )
    parser.add_argument(
        "--local-catalog", dest="local_catalog", default=False, required=False
    )
    argv = sys.argv[1:]
    known_args, _ = parser.parse_known_args(argv)

    # Init NGSI-LD API Client
    ngsi_ld_api = NGSILDAPI(
        url=known_args.broker_uri, context=known_args.context_catalog_uri
    )
    main(ngsi_ld_api, known_args.local_catalog)


import sys

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline

def solve():
    MOD = 10 ** 9 + 7
    N = int(rl())
    A = list(map(int, rl().split()))

    for _ in range(N - 1):
        A = [(ai + aj) % MOD for ai, aj in zip(A[:-1], A[1:])]
    print(A[0])

if __name__ == '__main__':
    solve()


from django.urls import path, re_path
from . import views
from users import views as user

urlpatterns = [
    path("index/", views.index, name="index"),

    # API Routes
    path("tracker_dashboard/<str:board>/<str:search>/", views.tracker_dashboard, name="board"),
    path("tracker_dashboard/<str:board>/<str:search>/<str:search_value>", views.tracker_dashboard, name="search_board"),
    path("tracker_dashboard/<str:client_id>", views.tracker_dashboard, name="client"),
    path("product_view/<str:product_id>", views.product_view, name="product"),
    path("client_view/<str:client_id>", views.client_view, name="client_view"),
    path("usecase_view/<str:usecase_id>", views.usecase_view, name="usecase"),
    path("create_product", views.create_product, name="create_product"),
    path("create_client", views.create_client, name="create_client"),
    path("create_usecase", views.create_usecase, name="create_usecase"),
    path("get_status/<str:board>", views.get_status, name="get_status"),
    path("delete_product", views.delete_product, name="delete_product"),
    path("delete_client", views.delete_client, name="delete_client"),
    path("delete_usecase", views.delete_usecase, name="delete_usecase"),
    path("logout", user.logout_user, name="logout")
]


#!/usr/bin/env python
# -*-coding:utf-8-*-
# Author: nomalocaris <nomalocaris.top>
""""""
from __future__ import (absolute_import, unicode_literals)
import numpy as np
from tools import plot_several_curve, convergence_judge

# set the parm
N = 500  # num of agents
sigma = 0.5
init_value_range = (-10, 10)
c = 10
beta = 0.5
# q in [1-sigma, 1]
q = np.random.uniform(1 - sigma, 1)

# cal the privacy budget
epsilon = q / (c * q + sigma - 1)
# init agant vector
theta_vec = np.random.randint(init_value_range[0], init_value_range[1], N)
tot_theta_vec = theta_vec.copy()
# init time
t = 0
t_seq = [t]

while not convergence_judge(theta_vec):
    # client send msg which added laplace noise
    eta_vec = np.random.laplace(0, c*q**t, N)
    x_vec = theta_vec + eta_vec
    print(eta_vec)
    # server cal and update itself
    y_vec = np.mean(x_vec)
    # client update itself
    theta_vec = (1 - sigma) * theta_vec + sigma * y_vec
    # record the variation of agent states
    tot_theta_vec = np.vstack((tot_theta_vec, theta_vec))

    # update t
    t += 1
    t_seq.append(t)

# set the num of curve which want to be plot
curve_num = 8
y = []
for i in range(curve_num):
    y.append(tot_theta_vec[:, i])
# plot the convergance curve
plot_several_curve(
    x=t_seq,
    y=y,
    line_num=curve_num,
    label_prefix='θ',
    title='Convergance curve(σ=%.3f, q=%.3f, ε=%.3f)' % (sigma, q, epsilon),
    xlabel='T',
    ylabel='θi(T)'
)


import random
from datetime import datetime
import numpy as np

"""
Finding Homography : Then you should calculate a Homography Matrix for each pair of
sub-images (by using RANSAC method).

It was made efficient with the following method:
https://math.stackexchange.com/questions/494238/how-to-compute-homography-matrix-h-from-corresponding-points-2d-2d-planar-homog
"""
def calculate_homography_matrix(feature_1, feature_2, distance_threshold):

    num_of_points = len(feature_1)
    optimum_H = None
    max_inliers = 0
    i = 0
    while i < 100:
        random.seed(datetime.now())
        random_numbers = random.sample(range(0, num_of_points), 4)
        p_matrix = []
        for num in random_numbers:
            x = int(feature_1[num][0])
            y = int(feature_1[num][1])
            x_d = int(feature_2[num][0])
            y_d = int(feature_2[num][1])
            p_matrix.append([0, 0, 0, -x, -y, -1, x * y_d, y_d * y, y_d])
            p_matrix.append([x, y, 1, 0, 0, 0, -x * x_d, -x_d * y, -x_d])
        p_matrix.append([0, 0, 0, 0, 0, 0, 0, 0, 1])
        p_matrix = np.asarray(p_matrix).reshape(9, 9)

        if np.linalg.det(p_matrix) == 0:
            continue
        b_mat = []
        for ind in range(8):
            b_mat.append([0])
        b_mat.append([1])
        p_inv = np.linalg.inv(p_matrix)
        H_matrix = np.dot(p_inv, b_mat)
        H_matrix = np.reshape(H_matrix, (3, 3))

        distances = calc_distances(feature_1, feature_2, H_matrix)

        num_of_inliers = 0
        for distance in distances:
            if distance < distance_threshold:
                num_of_inliers += 1

        if num_of_inliers > max_inliers:
            max_inliers = num_of_inliers
            optimum_H = H_matrix
        i += 1

    x_crop = feature_1[0][0].astype(int)
    y_pos = feature_1[0][1].astype(int)

    prime_num = base_formula(x_crop, y_pos, optimum_H)
    x_d_crop = (prime_num[0] / prime_num[2])[0].astype(int)

    return x_crop, x_d_crop

def calc_distances(feature_1, feature_2, H):
    distances = []
    for i in range(len(feature_1)):
        x = feature_1[i][0].astype(int)
        y = feature_1[i][1].astype(int)

        x_y_prime_mat = base_formula(x, y, H)
        if x_y_prime_mat[2] == 0:
            x_y_prime_mat[2] = 0.001
        x_d = (x_y_prime_mat[0] / x_y_prime_mat[2])[0].astype(int)
        y_d = (x_y_prime_mat[1] / x_y_prime_mat[2])[0].astype(int)

        x_2 = feature_2[i][0].astype(int)
        y_2 = feature_2[i][1].astype(int)

        try:
            dist = np.math.sqrt((x_2 - x_d) ** 2 + (y_2 - y_d) ** 2)
            distances.append(dist)
        except:
            pass

    return distances

def base_formula(x, y, H):
    prime = [[x], [y], [1]]
    prime_inverse = np.dot(H, prime)
    return prime_inverse


import argparse
import json

"""
Potential additions:
    Check individual HTTP methods to determine typical ratios
    Check specific client profiles if given
    If DoS detected, detect specific offending client(s)
"""

def compare_profiles(baseline_file, test_file, threshold=0.5):
    results = []
    with open(baseline_file, 'r') as f:
        baseline_profile = json.load(f)
    with open(test_file, 'r') as f:
        test_profile = json.load(f)
    baseline_avg_pps = baseline_profile['avg_pps']
    baseline_packets_sessions_ratio = baseline_profile['packets_to_sessions_ratio']
    test_avg_pps = test_profile['avg_pps']
    test_packets_sessions_ratio = test_profile['packets_to_sessions_ratio']
    baseline_avg_pps_upper_limit = baseline_avg_pps * (1 + threshold)
    baseline_avg_pps_lower_limit = baseline_avg_pps * (1 - threshold)
    baseline_packets_sessions_upper_limit = baseline_packets_sessions_ratio * (1 + threshold)
    baseline_packets_sessions_lower_limit = baseline_packets_sessions_ratio * (1 - threshold)
    if test_avg_pps > baseline_avg_pps_upper_limit or test_avg_pps < baseline_avg_pps_lower_limit:
        result = {'category': 'Anomalous Packets per Second',
                  'details': {'baseline_profile_avg_pps': baseline_avg_pps, 'test_profile_avg_pps': test_avg_pps,
                              'baseline_profile_upper_limit': baseline_avg_pps_upper_limit,
                              'baseline_profile_lower_limit': baseline_avg_pps_lower_limit,
                              'baseline_profile_threshold_percent': threshold * 100}}
        results.append(result)
    if test_packets_sessions_ratio > baseline_packets_sessions_upper_limit or test_packets_sessions_ratio < baseline_packets_sessions_lower_limit:
        result = {'category': 'Anomalous Packets to Sessions Ratio',
                  'details': {'baseline_profile_packets_sessions_ratio': baseline_packets_sessions_ratio,
                              'test_profile_packets_sessions_ratio': test_packets_sessions_ratio,
                              'baseline_profile_upper_limit': baseline_packets_sessions_upper_limit,
                              'baseline_profile_lower_limit': baseline_packets_sessions_lower_limit,
                              'baseline_profile_threshold_percent': threshold * 100}}
        results.append(result)
    return results

def main():
    parser = argparse.ArgumentParser(
        description='This application compares a baseline network traffic profile against another profile to look for malicious/anomalous activity.')
    parser.add_argument('-b', '--baseline', required=True,
                        help='File containing baseline profile (JSON format) to read from')
    parser.add_argument('-t', '--test-file', required=True,
                        help='File containing test profile (JSON format) to read from')
    parser.add_argument('-p', '--percent-threshold', default=50,
                        help='Percent difference test profile must be from baseline profile to be considered malicious/anomalous')
    parser.add_argument('-o', '--output', help='Output file to write to')
    args = parser.parse_args()

    baseline_file = args.baseline
    test_file = args.test_file
    threshold = int(args.percent_threshold) / 100
    output = args.output

    analysis = compare_profiles(baseline_file, test_file, threshold)

    if output:
        with open(output, 'w') as of:
            json.dump(analysis, of, indent=2)
    else:
        print(json.dumps(analysis, indent=2))

if __name__ == '__main__':
    main()

Section 2 code files/compare_network_profiles.py


import pandas as pd
import psrqpy
from astropy.coordinates import ICRS, AltAz, SkyCoord
from astropy.table import Table
from astropy.time import Time
from pulsar_spectra.catalogue import collect_catalogue_fluxes
from pulsar_spectra.spectral_fit import estimate_flux_density, find_best_spectral_fit

from rpnav import logger
from rpnav.observe.antenna import Antenna

logger.disabled = True

class Pulsar(SkyCoord):
    def __init__(
        self,
        name: str,
        centre_freq: float,
        flux_density: float,
        ra: float,
        dec: float,
        period: float,
        dispersion_measure: float,
        pulse_width_50: float,
        pulse_width_10: float,
        flux_density_err: float = None,
    ):
        """
        Parameters
        ----------
            NAME:   Pulsar name
            RAJD:   Right ascension (J2000) (degrees)
            DecJD:  Declination (J2000) (degrees)
            P0:     Barycentric period of the pulsar (s)
            DM:     Dispersion measure (cm-3 pc)
            W50:    Width of pulse at 50% of peak (ms)
            W10:    Width of pulse at 10% (ms)
        """
        self.name = name
        self.flux_density = flux_density
        self.period = period
        self.dispersion_measure = dispersion_measure
        self.pulse_width_50 = pulse_width_50
        self.pulse_width_10 = pulse_width_10
        super().__init__(frame=ICRS, ra=ra, dec=dec, unit="deg")

    def _to_sky_coord(self) -> SkyCoord:
        return SkyCoord(frame=ICRS, ra=self.ra, dec=self.dec, unit="deg")

    def is_observable(
        self,
        antenna: Antenna,
        t: Time,
        integ_time: float,
        horizon: float = 0,
    ) -> bool:
        is_vis: bool = self.flux_density > antenna.min_observable_flux_density(integ_time)
        observable = True
        if horizon is not None:
            altaz = self.get_alt_az(antenna, t)
            observable = altaz.alt > horizon
        return is_vis and observable

    def get_alt_az(self, antenna: Antenna, t: Time):
        return self._to_sky_coord().transform_to(AltAz(obstime=t, location=antenna.location))

    @staticmethod
    def _interpolate_flux_density(
        centre_freq: int, row: Table, cat_dict: dict
    ) -> tuple[float, float]:
        flux_dens = None
        flux_dens_err = None
        if row["NAME"] not in cat_dict:
            logger.warning("Pulsar config not found")
        else:
            model = None
            freqs, bands, fluxs, flux_errs, refs = cat_dict[row["NAME"]]
            if not freqs:
                logger.warning("Frequency values not found")
            else:
                model, m, _, _, _ = find_best_spectral_fit(
                    row["NAME"], freqs, bands, fluxs, flux_errs, refs
                )
            if model:
                flux_dens, flux_dens_err = estimate_flux_density(centre_freq, model, m)
            else:
                logger.warning(f"Failed to find best fit spectral model for {row['NAME']}")
        return flux_dens, flux_dens_err

    @staticmethod
    def load_catalogue(centre_freq: int = 1400, interpolate=False) -> list["Pulsar"]:
        """Load pulsar data from PSR Catalogue (PSRCAT)."""
        cat_dict = None
        params = [
            "NAME",
            "RAJD",
            "DECJD",
            "P0",
            "DM",
            "W50",
            "W10",
        ]
        if interpolate:
            cat_dict = collect_catalogue_fluxes()
        else:
            params.append(f"S{centre_freq}"),

        try:
            cat = psrqpy.QueryATNF(params=params).table
        except ValueError:
            raise Exception(
                "Failed to read from psrcat. Check that centre frequency" " is a valid table option"
            )

        pulsars: list[Pulsar] = []
        for row in cat:
            flux_dens = None
            flux_dens_err = None

            if interpolate:
                flux_dens, flux_dens_err = Pulsar._interpolate_flux_density(
                    centre_freq, row, cat_dict
                )
            else:
                flux_dens = row[f"S{centre_freq}"]

            if not flux_dens:
                continue

            pulsars.append(
                Pulsar(
                    name=row["NAME"],
                    ra=row["RAJD"],
                    dec=row["DECJD"],
                    period=row["P0"],
                    dispersion_measure=row["DM"],
                    pulse_width_50=row["W50"],
                    pulse_width_10=row["W10"],
                    flux_density=flux_dens,
                    flux_density_err=flux_dens_err,
                    centre_freq=centre_freq,
                )
            )
        return pulsars

    @property
    def timing_uncertainty(self):
        return self.pulse_width_10 / 10


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 15 15:48:21 2021

With this script you can make a 3D plot of 2 ROIs and its overlap

@author: lindvoo
"""

# Import libraries
import matplotlib.pyplot as plt
import numpy as np
from nilearn.image import load_img, get_data

# Import 3D projection
from mpl_toolkits.mplot3d import Axes3D

# Read in images
img1 = load_img('XXX.nii')
img2 = load_img('XXX.nii')
voxels1 = get_data(img1)
voxels2 = get_data(img2)

# Remove slices that do not contain the ROI [reduce comp load and easy plotting]
whichslices=[]
for c,val in enumerate(voxels1[:,0,0]):

    if (np.sum(voxels1[c,:,:]))>0:
        whichslices.append(c)

voxels1 = voxels1[whichslices[0]:whichslices[-1],:,:]
voxels2 = voxels2[whichslices[0]:whichslices[-1],:,:]

whichslices=[]
for c,val in enumerate(voxels1[0,0,:]):

    if (np.sum(voxels1[:,:,c]))>0:
        whichslices.append(c)

voxels1 = voxels1[:,:,whichslices[0]:whichslices[-1]]
voxels2 = voxels2[:,:,whichslices[0]:whichslices[-1]]

whichslices=[]
for c,val in enumerate(voxels1[0,:,0]):

    if (np.sum(voxels1[:,c,:]))>0:
        whichslices.append(c)

voxels1 = voxels1[:,whichslices[0]:whichslices[-1],:]
voxels2 = voxels2[:,whichslices[0]:whichslices[-1],:]

# Make boolean to create a figure with both
bool_voxels1 = np.zeros(voxels1.shape, dtype=bool)
bool_voxels2 = np.zeros(voxels2.shape, dtype=bool)
for x,xval in enumerate(voxels1[:,0,0]):
    for y,yval in enumerate(voxels1[0,:,0]):
        for z,xval in enumerate(voxels1[0,0,:]):

            bool_voxels1[x,y,z] = voxels1[x,y,z]>0
            bool_voxels2[x,y,z] = voxels2[x,y,z]>0

# Create overlap
combined = bool_voxels1 | bool_voxels2
overlap = bool_voxels1 & bool_voxels2

# Set the colors of each object
colors = np.empty(overlap.shape, dtype=object)
colors[bool_voxels1] = 'blue'
colors[bool_voxels2] = 'green'
colors[overlap] = 'red'

# With np.transpose(overlap, (2, 1, 0)) you can transpose the array

# Plot
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.voxels(combined,
          facecolors=colors,
          alpha=.5)
plt.axis('off')
plt.show()


#!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os.path
import sys

from distutils.command.build import build

from setuptools import setup
from setuptools.command.install import install

CFFI_DEPENDENCY = "cffi>=0.8"

def get_ext_modules():
    original_sys_path = sys.path[:]
    sys.path.insert(
        0,
        os.path.join(os.path.dirname(os.path.abspath(__file__)), "src"),
    )
    import http11.c
    sys.path = original_sys_path
    return [http11.c.ffi.verifier.get_extension()]

class CFFIBuild(build):
    """
    This class exists, instead of just providing ``ext_modules=[...]`` directly
    in ``setup()`` because importing cryptography requires we have several
    packages installed first.

    By doing the imports here we ensure that packages listed in
    ``setup_requires`` are already installed.
    """

    def finalize_options(self):
        self.distribution.ext_modules = get_ext_modules()
        build.finalize_options(self)

class CFFIInstall(install):
    """
    As a consequence of CFFIBuild and it's late addition of ext_modules, we
    need the equivalent for the ``install`` command to install into platlib
    install-dir rather than purelib.
    """

    def finalize_options(self):
        self.distribution.ext_modules = get_ext_modules()
        install.finalize_options(self)

metafile = os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    "src",
    "http11",
    "__about__.py",
)
meta = {}
with open(metafile) as fp:
    exec(fp.read(), meta)

readmefile = os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    "README.rst",
)
with open(readmefile) as fp:
    long_description = fp.read()

setup(
    name=meta["__title__"],
    version=meta["__version__"],

    description=meta["__summary__"],
    long_description=long_description,
    license=meta["__license__"],
    url=meta["__url__"],

    author=meta["__author__"],
    author_email=meta["__email__"],

    classifiers=[
        "License :: OSI Approved :: Apache Software License",

        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.2",
        "Programming Language :: Python :: 3.3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: Implementation :: CPython",
        "Programming Language :: Python :: Implementation :: PyPy",
    ],

    package_dir={"": "src"},
    packages=[
        "http11",
        "http11.c",
    ],

    install_requires=[
        CFFI_DEPENDENCY,
        "enum34",
    ],

    setup_requires=[
        CFFI_DEPENDENCY,
    ],

    # These are needed so that CFFI can correctly function
    zip_safe=False,
    ext_package="http11",
    cmdclass={
        "build": CFFIBuild,
        "install": CFFIInstall,
    }
)


""" Didactic example of TkFire being used

In this version, a simple GUI demonstrating input and output on a static GUI

This demonstrates:
  - How to make and reference Memory and TkFire objects
  - How to bind a command post build but before running

@author: Ben C
"""

from tkfire import *
import tkinter as tk

# Define some convenience constants
BOTH33 = {'fill': 'both', 'ipadx': 3, 'ipady': 3}
TB33 = {'side': 'top', 'fill': 'both', 'ipadx': 3, 'ipady': 3}
LB33 = {'side': 'left', 'fill': 'both', 'ipadx': 3, 'ipady': 3}

# #### Step 1 ####
# Create variables or other functions which will plug into the GUI
options = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
memory = Memory(btn_cmd=lambda *_: print("Hello!"),
                opt_A=tk.IntVar,
                opt_B=tk.IntVar,
                opt_C=tk.IntVar)

# #### Step 2 ####
# Define the structure of the GUI
# There will be left panel with two buttons stacked vertically
# There will be right panel with three option-menus stacked vertically
mother = {
    'left_panel': {
        LAYOUT: fire_pack(**LB33),
        TYPE: spec(tk.LabelFrame, text="Left Side", width=24),
        CHILDREN: {
            # The first button will print "Hello!" to the console
            'hello_button': {
                # Bind the "btn_cmd" function to the button
                TYPE: spec(tk.Button, text="Say Hello", width=12, command=memory["btn_cmd"]),
                LAYOUT: fire_grid(),
            },
            'calc_button': {
                # We can bind later as well, so omit 'command=...' for now
                TYPE: spec(tk.Button, text="A + B + C", width=12),
                LAYOUT: fire_grid(),
            }
        }
    },
    'right_panel': {
        'LAYOUT': fire_pack(**LB33),
        'TYPE': spec(tk.LabelFrame, text="Right Side", width=24),
        'CHILDREN': {
            # Create the three drop-down menus, each will provide the values present in options as allowable options
            "option_A": {
                # OptionMenu widgets must be bound to a tkinter variable, here we reference the IntVar variables
                # stored in memory, and we will give then default/initial values with the 'value=#' kwarg
                TYPE: spec(tk.OptionMenu, Memory.varspec(f'opt_A'), *options),
                LAYOUT: fire_pack(**TB33)
            },
            "option_B": {
                TYPE: spec(tk.OptionMenu, Memory.varspec(f'opt_B', value=2), *options),
                LAYOUT: fire_pack(**TB33)
            },
            "option_C": {
                TYPE: spec(tk.OptionMenu, Memory.varspec(f'opt_C', value=4), *options),
                LAYOUT: fire_pack(**TB33)
            },
        },
    },
}

# #### Step 3 ####
# create a Tk or TopLevel object for the GUI
tk_core = tk.Tk()
# Create the TkFire object
my_gui = TkFire(tk_core, memory, mother).build()

# Let us add a command to the 'calc_button' in the 'left_panel'
# Note: memory['opt_A'] -> tk.IntVar
#       to retrieve the value stored in a tkinter Variable, the get() method must be called
my_gui.bind_command(
    'left_panel!calc_button',
    lambda *_: print(memory[f'opt_A'].get() + memory[f'opt_B'].get() + memory[f'opt_C'].get())
)

# Run the gui
tk_core.mainloop()


from threading import Thread
import random
import queue
import time
import os

jogadores = []
tempo = []
dinheiro = []
resultado = list()
numeros_random = [random.randint(1,6) for _ in range(500)]
tabuleiro = [list() for s in range(100)]

class Jogador:
    def __init__(self,nickname):
        self.nickname = nickname
        self.money = 0
        self.index = 0
        self.status = "Livre"

    def Play(self):
        dado1 = random.choice(numeros_random)
        dado2 = random.choice(numeros_random)
        print(f"\nJogador: { self.nickname }\n    Dado 1: {dado1}\n    Dado 2: {dado2}\n    Status: {self.status}\n    Posição: {self.index}\n    Dinheiro: {self.money}\n")
        return dado1,dado2

    def Repeated(self,dados):
        if self.status == "Livre" and dados[0] == dados[1]:
            self.status = "Preso"
            play_again = self.Play()
            self.Repeated(play_again)
        elif self.status == "Preso" and dados[0] != dados[1]:
            play_again = self.Play()
            self.Repeated(play_again)
        elif self.status == "Preso" and dados[0] == dados[1]:
            self.status = "Livre"
        elif self.status == "Livre" and dados[0] != dados[1]:
            if self.index+(dados[0]+dados[1]) >= len(tabuleiro):
                self.index = len(tabuleiro)
            else:
                self.index = self.index +(dados[0] + dados[1])
                if self.index % 2 == 0:
                    self.money = (self.money + 79.99)
                else:
                    self.money = (self.money + 53.21)

def Board(Jogador,First):
    timer = time.time()
    while(1):
        Jogador.Repeated(Jogador.Play())
        for i in tabuleiro:
                for j in i:
                    if Jogador.nickname == j:
                        i.remove(Jogador.nickname)
        if(Jogador.index < len(tabuleiro)):
            tabuleiro[Jogador.index].append(Jogador.nickname)
        else:
            tabuleiro[len(tabuleiro)-1].append(Jogador.nickname)
        print(tabuleiro)

        if Jogador.index >= len(tabuleiro):
            print(f"\nThread finalizada --> {Jogador.nickname}!\n")
            tempo = time.time() - timer;
            First.put([Jogador.nickname,Jogador.money,tempo])
            break

if __name__ == "__main__":
    menu = int(input("Menu\n1)Jogar\n2)Sair\nOpção --> "))
    os.system("cls")
    while(menu != 2):
        submenu = int(input("Menu dos Jogadores\n1) Adicionar jogador\n2) Listar jogadores\n3) Excluir jogador\n4) Start!\n5) Sair\nOpção --> "))
        if(submenu == 1):
            os.system('cls')
            nickname = input("Digite o nickname --> ")
            jogadores.append(Jogador(nickname))
            os.system('cls')
            print("Jogador adicionado com sucesso!")
        if(submenu == 2):
            os.system('cls')
            if(len(jogadores) != 0):
                for x in jogadores:
                    print(f"Nickname: {x.nickname} | Money: {x.money}\n")
            else:
                print("Lista de jogadores vazia!")
        if(submenu == 3):
            os.system('cls')
            excluir_player = input("Digite o nickname do jogador que você deseja excluir --> ")
            for y in jogadores:
                if(excluir_player == y.nickname):
                    jogadores.pop(jogadores.index(y))
                    print("Jogador excluído com sucesso!")
                else:
                    print("Jogador não encontrado!")
        if(submenu == 4):
            for q in jogadores:
                tabuleiro[0].append(q.nickname)
            first = queue.Queue()
            thread_1 = Thread(target=Board,args=[jogadores[0],first])
            thread_2 = Thread(target=Board,args=[jogadores[1],first])
            thread_3 = Thread(target=Board,args=[jogadores[2],first])
            thread_4 = Thread(target=Board,args=[jogadores[3],first])

            thread_1.start()
            thread_2.start()
            thread_3.start()
            thread_4.start()

            thread_1.join()
            thread_2.join()
            thread_3.join()
            thread_4.join()

            for p in range(len(jogadores)):
                resultado.append(first.get())

            for u in resultado:
                dinheiro.append(u[1])
                tempo.append(u[2])
                print(f"| Jogador: {u[0]} | Tempo: {u[2]} | Montante: R${u[1]} |");

            maximo = max(dinheiro)
            minimo = min(tempo)
            index = dinheiro.index(maximo)
            index_tempo = tempo.index(minimo)
            print(f"\nJogador mais rápido --> {resultado[index_tempo][0]}")
            print(f"\nMontante mais valioso --> {maximo} pertencente à {resultado[index][0]}")
            break;
        if(submenu == 5):
            os.system('clear')
            print("Saindo...")
            time.sleep(0.5)
            break;


import pandas as pd

def dateparser(inp):
    date = pd.to_datetime(inp[:-3])
    ampm = inp.split()[-1]
    if ampm == u'午前' and date.hour == 12:
        date -= pd.Timedelta(hours=12)
    elif ampm == u'午後' and date.hour != 12:
        date += pd.Timedelta(hours=12)
    return date

def read_csv(f, raw=False):
    df = pd.read_csv(f, skiprows=1,
                         date_parser=dateparser,
                         parse_dates=[1],
                         index_col=1)
    df.index.name = 'date'
    names = df.columns.values
    for i, name in enumerate(names):
        if 'DO' in name:
            names[i] = 'DO'
        elif u'温度' in name:
            names[i] = 'temp'
        elif u'センサーの深度' in name:
            names[i] = 'depth'
        elif u'気圧' in name:
            names[i] = 'press_air'
        elif u'絶対圧力' in name:
            names[i] = 'press'
    df.columns = names
    #df = df.rename(columns={"DO 濃度, mg/L (LGR S/N: 20758290, SEN S/N: 20758290)":'DO',
    #                    "温度, °C (LGR S/N: 20758290, SEN S/N: 20758290)":'temp'})
    return df

if __name__ == '__main__':
    assert(dateparser('08/21/20 01:46:22 午後')==pd.to_datetime('2020-08-21 13:46:22'))