import time
import tensorflow as tf

time_start = time.clock()

# 读取下一批数据
def train_batch_x(f, num):
    sum = []
    for i in range(num):
        temp = f.readline()
        temp1 = temp.split('\t')
        temp1 = list(map(float, temp1))
        sum.append(temp1)
    return sum

def train_batch_label(f, num):
    sum = []
    for i in range(num):
        temp = f.readline()
        temp1 = temp.split('\t')
        temp1 = list(map(float, temp1))
        sum.append(temp1)
    return sum

def batch_x_test(num):
    sum = []
    with open('data/test_TCGA_x.txt', 'r') as f:
        for i in range(num):
            temp = f.readline()
            temp1 = temp.split('\t')
            temp1 = list(map(float, temp1))
            sum.append(temp1)
    return sum

def batch_label_test(num):
    sum = []
    with open('data/test_TCGA_label.txt', 'r') as f:
        for i in range(num):
            temp = f.readline()
            temp1 = temp.split('\t')
            temp1 = list(map(float, temp1))
            sum.append(temp1)
    return sum

# 设置输入参数
x = tf.placeholder(tf.float32, [None, 998])
labels = tf.placeholder(tf.float32, [None, 3])

# 权重和偏置
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.zeros(shape=shape)
    return tf.Variable(initial)

# 各层神经元数
layer1 = 100
layer2 = 37
out_layer = 3

# 3层隐藏层
w1 = weight_variable([998, layer1])         # normal配合relu使用，zeros只测试过一层softmax
b1 = bias_variable([layer1])
w2 = weight_variable([layer1, layer2])
b2 = bias_variable(layer2)
w3 = weight_variable([layer2, out_layer])
b3 = bias_variable([out_layer])

y1 = tf.nn.relu(tf.matmul(x, w1) + b1)             # relu为正则化L1，softplus为正则化L2
y2 = tf.nn.relu(tf.matmul(y1, w2) + b2)
y3 = tf.nn.softmax(tf.matmul(y2, w3) + b3)         # 最后一步使用softmax分配不同类的概率

# 成本评估
loss = -tf.reduce_sum(labels*tf.log(y3))
#loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=y3, labels=labels))        # sum和mean的区别
# 梯度下降最小化成本
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
# 评估模型
correct_prediction = tf.equal(tf.argmax(y3, 1), tf.argmax(labels, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 初始化向量并启动session
init = tf.initialize_all_variables()
sess = tf.InteractiveSession()
sess.run(init)

# 循环训练并评估
with open('data/train_TCGA_x.txt', 'r') as train_data:
    with open('data/train_TCGA_label.txt', 'r') as train_labels:
        for i in range(59):
            batch_size = 3
            xs = train_batch_x(train_data, batch_size)
            ys = train_batch_label(train_labels, batch_size)
            train_step.run(feed_dict={x: xs, labels: ys})
            if i % 9 == 0:
                train_accuracy = accuracy.eval(feed_dict={x: xs, labels: ys})
                print('训练集准确率：%.2f' % (train_accuracy * 100), '%')
        time_end = time.clock()
        print('训练时间：%g s' % (time_end - time_start))

# 测试集准确率
test_size = 60
test_accuracy = accuracy.eval(feed_dict={x: batch_x_test(test_size), labels: batch_label_test(test_size)})
print('测试集准确率：%.2f' % (test_accuracy * 100), '%')

'''
# 保存训练好的模型
model_path = 'model/RNN_MNIST'
saver = tf.train.Saver()
save_path = saver.save(sess, model_path, global_step=1000)
'''


d = dict(name='Bob', age=20, score=88)
#{'name': 'Bob', 'age': 20, 'score': 88}
print(d)
print(d.items())
for k,v in d.items() :
	print(k,v)
class Dict(dict):
	def __init__(self,**kw):
		super(Dict,self).__init__(**kw)

	def __getattr__(self,key):
		return self[key]

	def __setattr__(self,key,value):
		self[key] = value

def dict(**kw):
	obj = {}

	for k,v in kw.items():
		obj[k] = v

	return obj

print(dict(name='Bob', age=20, score=88))

print('--------------------------------------')

d = dict(name='Bob', age=20, score=88)

v = Dict(name='Bob', age=20, score=88)['name']

print(v)

import pickle

print('-------------------------------------')
d = dict(name='Bob', age=20, score=88)
v = pickle.dumps(d)
print(v)

c = pickle.loads(v)
print(c)
print('----------------------------------')
with open('dump.txt','wb') as f:
	pickle.dump(d,f)

with open('dump.txt','rb') as f:
	v = pickle.load(f)
	print(v)

print('---------------------------------')
import json
d = dict(name='Bob', age=20, score=88)
v = json.dumps(d)
print(v)

print('--------------------------------')
json_str = '{"name": "Bob", "age": 20, "score": 88}'
v = json.loads(json_str)

print(v)

print('----------------------------------------')
# d = {"name": "Bob", "age": 20, "score": 88}
# with open('json.txt','wb') as f:
# 	json.dump(d,f)

# with open('json.txt','rb') as f:
# 	v = json.load(f)
# 	print(v)
# json.dump()
# JSON进阶
# 可以通过创建类来初始化JSON
class Student(object):
	def __init__(self,name,age,sex):
		self.name = name
		self.age = age
		self.sex = sex

s = Student('Ken',20,'Man')

def student2dict(std):
	return {
		"name" : std.name,
		"age" : std.age,
		"sex" : std.sex
	}
print(json.dumps(s, default=student2dict))


#!/usr/bin/env python

import argparse
import sys

from copy import copy

import rospy
import actionlib
import baxter_interface
import baxter_tools

from control_msgs.msg import (
    FollowJointTrajectoryAction,
    FollowJointTrajectoryGoal,
    GripperCommandActionGoal
)
from std_msgs.msg import String
from trajectory_msgs.msg import (
    JointTrajectoryPoint,
)

from baxter_hrc.msg import PlannedTrajectory

from baxter_interface import CHECK_VERSION

# Global variables
limb = ""
wait_time = 0

class Trajectory(object):

    def __init__(self, limb):
        ns = 'robot/limb/' + limb + '/'
        self._client = actionlib.SimpleActionClient(
            ns + "follow_joint_trajectory",
            FollowJointTrajectoryAction,
        )
        self._goal = FollowJointTrajectoryGoal()
        self._goal_time_tolerance = rospy.Time(0.05)
        self._goal.goal_time_tolerance = self._goal_time_tolerance
        server_up = self._client.wait_for_server(timeout=rospy.Duration(10.0))
        if not server_up:
            rospy.logerr("Timed out waiting for Joint Trajectory"
                         " Action Server to connect. Start the action server"
                         " before running example.")
            rospy.signal_shutdown("Timed out waiting for Action Server")
            sys.exit(1)
        self.clear(limb)
        gripper_topic = "/robot/end_effector/" + limb + "_gripper/gripper_action/goal"
        self.gripper_publisher = rospy.Publisher(gripper_topic, GripperCommandActionGoal, queue_size=10)

    def add_point(self, positions, velocities, accelerations, time):
        point = JointTrajectoryPoint()
        point.positions = copy(positions)
        point.velocities = copy(velocities)
        point.accelerations = copy(accelerations)
        point.time_from_start = rospy.Duration(time)
        self._goal.trajectory.points.append(point)

    def start(self):
        self._goal.trajectory.header.stamp = rospy.Time.now()
        self._client.send_goal(self._goal)

    def stop(self):
        self._client.cancel_goal()

    def wait(self, timeout=15.0):
        self._client.wait_for_result(timeout=rospy.Duration(timeout))

    def result(self):
        return self._client.get_result()

    def clear(self, limb):
        self._goal = FollowJointTrajectoryGoal()
        self._goal.goal_time_tolerance = self._goal_time_tolerance
        self._goal.trajectory.joint_names = [limb + '_' + joint for joint in \
            ['s0', 's1', 'e0', 'e1', 'w0', 'w1', 'w2']]

    def open_gripper(self):
    	gripperCommandMsg = GripperCommandActionGoal()
    	gripperCommandMsg.goal.command.position = 100.0
    	self.gripper_publisher.publish(gripperCommandMsg)

    def close_gripper(self):
    	gripperCommandMsg = GripperCommandActionGoal()
    	gripperCommandMsg.goal.command.position = 0.0
    	self.gripper_publisher.publish(gripperCommandMsg)

def trajectory_callback(msg):

    if(limb == msg.arm):
        global wait_time
        rospy.sleep(wait_time)

        arm = msg.arm
        operation = msg.operation

        n = len(msg.trajectory)
        close_gripper_idx = 1
        open_gripper_idx = n - 2
        wait_before_returning = n - 3
        wait_before_opening =  1 if operation == "pickandplace" else 2

        for i in range(len(msg.trajectory)):

            traj = Trajectory(arm)
            # Start with open gripper
            if i == 0:
                    traj.open_gripper()

            rospy.on_shutdown(traj.stop)
            # Command Current Joint Positions first
            limb_interface = baxter_interface.limb.Limb(arm)

            t = 1
            step = 0.1 if i != 1 else 0.2
            for point in msg.trajectory[i].joint_trajectory.points:
                traj.add_point(point.positions, point.velocities, point.accelerations, t)
                t += step

            traj.start()
            traj.wait(t + 1)
            # Close gripper on grasping
            if i == close_gripper_idx:
                    rospy.sleep(1)
                    traj.close_gripper()
            # Reopen gripper on release
            elif i == open_gripper_idx:
                    rospy.sleep(wait_before_opening)
                    traj.open_gripper()
                    rospy.sleep(1)

            # If operation is component handover, wait several seconds before returning object
            if(operation == "component_handover" and i == wait_before_returning):
                    rospy.sleep(15)

            print("Joint Trajectory Action Complete")

def main():

    arg_fmt = argparse.RawDescriptionHelpFormatter
    parser = argparse.ArgumentParser(formatter_class=arg_fmt,
                                     description=main.__doc__)
    required = parser.add_argument_group('required arguments')
    required.add_argument(
        '-l',
        '--limb',
        required=True,
        choices=['left', 'right'],
        help='Send joint trajectory to which limb'
    )
    required.add_argument(
        '-w',
        '--wait_time',
        required=True,
        type=int,
        help='Wait time before moving real robot'
    )

    args = parser.parse_args(rospy.myargv()[1:])
    global limb
    global wait_time
    limb = args.limb
    wait_time = args.wait_time

    print("Initializing node... ")
    rospy.init_node("rsdk_joint_trajectory_client_%s" % (limb,))
    print("Getting robot state... ")
    rs = baxter_interface.RobotEnable(CHECK_VERSION)
    print("Enabling robot... ")
    rs.enable()
    print("Running. Ctrl-c to quit")
    rospy.Subscriber(limb + "_group/baxter_moveit_trajectory", PlannedTrajectory, trajectory_callback)

    rospy.spin()

if __name__ == "__main__":
    main()


from typing import List

class Solution:
    def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:
        m = [[0 for i in range(n)] for j in range(m)]
        for i in ops:
            for j in range(i[0]):
                for k in range(i[1]):
                    m[j][k] += 1
            print(m)
        mx = m[0][0]
        mcount = 0
        for i in m:
            for j in i:
                if j == mx:
                    mcount += 1
        return mcount

s = Solution()
print(s.maxCount(3, 3, [[2, 2], [3, 3]]))


# Author: Karl Zylinski, Uppsala University

# Parses metadata outputted along db

import os

def get(db_folder):
    metadata_filename = "%s/metadata" % db_folder
    assert os.path.isfile(metadata_filename), "metadata mising: %s" % metadata_filename
    metadata_fh = open(metadata_filename, "r")
    metadata = metadata_fh.readlines()
    metadata_fh.close()
    metadata_dict = {}

    for mdi in metadata:
        key_value_pair = mdi.split(":")

        if len(key_value_pair) != 2:
            error("metadata in %s is of incorrect format" % db_folder)

        metadata_dict[key_value_pair[0]] = eval(key_value_pair[1])

    return metadata_dict


# lista_nomes =("Ana", "Bia", "Celi", "Diana", "Eva", "Fabia")
#
# def combinacaoPossible(nomes):
#     for a in nomes:
#         for b in nomes:
#             if a != b:
#                 if nomes.index(b) > nomes.index(a):
#                     print(a, "e", b)
#
# print(combinacaoPossible(lista_nomes))

def combinacoes(nomes):
    for a in range(len(nomes)):
        for b in range(len(nomes)):
            if (nomes[a] != nomes[b]) and (b > a):
                print(nomes[a], "e", nomes[b])

nomes = ("Ana", "Bia", "Celi", "Diana", "Eva", "Fabia")
combinacoes(nomes)


from mpi4py import MPI

import numpy as np
import pytest

from basix.ufl import element
from dolfinx import la
from dolfinx.fem import Function, functionspace
from dolfinx.mesh import create_unit_square

@pytest.mark.parametrize("e", [
    element("Lagrange", "triangle", 1),
    element("Lagrange", "triangle", 1, shape=(2,))])
def test_scatter_forward(e):

    mesh = create_unit_square(MPI.COMM_WORLD, 5, 5)
    V = functionspace(mesh, e)
    u = Function(V)
    bs = V.dofmap.bs

    u.interpolate(lambda x: [x[i] for i in range(bs)])

    # Forward scatter should have no effect
    w0 = u.x.array.copy()
    u.x.scatter_forward()
    assert np.allclose(w0, u.x.array)

    # Fill local array with the mpi rank
    u.x.array.fill(MPI.COMM_WORLD.rank)
    w0 = u.x.array.copy()
    u.x.scatter_forward()

    # Now the ghosts should have the value of the rank of the owning
    # process
    ghost_owners = u.function_space.dofmap.index_map.owners
    ghost_owners = np.repeat(ghost_owners, bs)
    local_size = u.function_space.dofmap.index_map.size_local * bs
    assert np.allclose(u.x.array[local_size:], ghost_owners)

@pytest.mark.parametrize("e", [
    element("Lagrange", "triangle", 1),
    element("Lagrange", "triangle", 1, shape=(2, ))])
def test_scatter_reverse(e):

    comm = MPI.COMM_WORLD
    mesh = create_unit_square(MPI.COMM_WORLD, 5, 5)
    V = functionspace(mesh, e)
    u = Function(V)
    bs = V.dofmap.bs

    u.interpolate(lambda x: [x[i] for i in range(bs)])

    # Reverse scatter (insert) should have no effect
    w0 = u.x.array.copy()
    u.x.scatter_reverse(la.InsertMode.insert)
    assert np.allclose(w0, u.x.array)

    # Fill with MPI rank, and sum all entries in the vector (including
    # ghosts)
    u.x.array.fill(comm.rank)
    all_count0 = MPI.COMM_WORLD.allreduce(u.x.array.sum(), op=MPI.SUM)

    # Reverse scatter (add)
    u.x.scatter_reverse(la.InsertMode.add)
    num_ghosts = V.dofmap.index_map.num_ghosts
    ghost_count = MPI.COMM_WORLD.allreduce(num_ghosts * comm.rank, op=MPI.SUM)

    # New count should have gone up by the number of ghosts times their
    # rank on all processes
    all_count1 = MPI.COMM_WORLD.allreduce(u.x.array.sum(), op=MPI.SUM)
    assert all_count1 == (all_count0 + bs * ghost_count)


import os
import re
import pandas as pd
import pdb
import numpy as np
#######################################
# Jan 2021 - Jared - preprocess jobs
#         `
#######################################

sbatch = ""
ct = 0
# start = [0,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000]
# end = [1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000,12416]
start = np.arange(0,186000,1000,dtype=np.int32)
end = start[:] + 1000
end[-1] = 185550
for i in range(len(start)):
    ct += 1
    #for each unique lake
    print(i)
    l = start[i]
    l2 = end[i]

    # if not os.path.exists("../../../models/single_lake_models/"+name+"/PGRNN_basic_normAll_pball"):
    header = "#!/bin/bash -l\n#SBATCH --time=08:59:00\n#SBATCH --ntasks=8\n#SBATCH --mem=20g\n#SBATCH --mail-type=ALL\n#SBATCH --mail-user=willa099@umn.edu\n#SBATCH --gres=gpu:k40:2\n#SBATCH --output=final_output_%s.out\n#SBATCH --error=final_output_%s.err\n\n#SBATCH -p k40"%(i,i)
    script = "source /home/kumarv/willa099/takeme_evaluate.sh\n" #cd to directory with training script
    # script2 = "python write_NLDAS_xy_pairs.py %s %s"%(l,l2)
    script2 = "python predict_lakes_EALSTM_final.py %s %s"%(l,l2)
    # script2 = "python predict_lakes_EALSTM_COLD_DEBUG.py %s %s"%(l,l2)

    # script3 = "python singleModel_customSparse.py %s"%(l)
    all= "\n".join([header,script,script2])
    sbatch = "\n".join(["sbatch job_finalout_%s.sh"%(i),sbatch])
    with open('../../hpc/job_finalout_{}.sh'.format(i), 'w') as output:
        output.write(all)

compile_job_path= '../../hpc/finalout_jobs.sh'
with open(compile_job_path, 'w') as output2:
    output2.write(sbatch)

print(ct, " jobs created, run this to submit: ", compile_job_path)


"""Recurrent network for DQN.

Based on QRnnNetwork and LSTMEncodingNetwork in tf.agents library.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

from tf_agents.networks import dynamic_unroll_layer
from tf_agents.networks import encoding_network
from tf_agents.networks import network
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import time_step
from tf_agents.utils import nest_utils

FUSED_IMPLEMENTATION = 2

def get_cell(cell_type, hidden_size, dtype):
  """Returns an RNNCell in tf.keras.layers."""

  def get_single_cell(cell_type, num_units):
    if cell_type == 'simple_rnn':
      cell = tf.keras.layers.SimpleRNNCell(
          num_units, dtype=dtype, implementation=FUSED_IMPLEMENTATION)
    elif cell_type == 'gru':
      cell = tf.keras.layers.GRUCell(
          num_units, dtype=dtype, implementation=FUSED_IMPLEMENTATION)
    elif cell_type == 'lstm':
      cell = tf.keras.layers.LSTMCell(
          num_units, dtype=dtype, implementation=FUSED_IMPLEMENTATION)
    else:
      raise ValueError('Unsupported cell type %s' % cell_type)
    return cell

  if len(hidden_size) == 1:
    cell = get_single_cell(cell_type, hidden_size[0])
  else:
    cell = tf.keras.layers.StackedRNNCells(
        [get_single_cell(cell_type, size) for size in hidden_size])
  return cell

class RnnNetwork(network.Network):
  """Recurrent network."""

  def __init__(
      self,
      input_tensor_spec,
      action_spec,
      preprocessing_layers=None,
      preprocessing_combiner=None,
      conv_layer_params=None,
      input_fc_layer_params=(75, 40),
      cell_type='lstm',
      hidden_size=(40,),
      output_fc_layer_params=(75, 40),
      activation_fn=tf.keras.activations.relu,
      dtype=tf.float32,
      name='RnnNetwork',
  ):
    """Creates an instance of `RnnNetwork`.

    Input preprocessing is possible via `preprocessing_layers` and
    `preprocessing_combiner` Layers.  If the `preprocessing_layers` nest is
    shallower than `input_tensor_spec`, then the layers will get the subnests.
    For example, if:

    ```python
    input_tensor_spec = ([TensorSpec(3)] * 2, [TensorSpec(3)] * 5)
    preprocessing_layers = (Layer1(), Layer2())
    ```

    then preprocessing will call:

    ```python
    preprocessed = [preprocessing_layers[0](observations[0]),
                    preprocessing_layers[1](obsrevations[1])]
    ```

    However if

    ```python
    preprocessing_layers = ([Layer1() for _ in range(2)],
                            [Layer2() for _ in range(5)])
    ```

    then preprocessing will call:
    ```python
    preprocessed = [
      layer(obs) for layer, obs in zip(flatten(preprocessing_layers),
                                       flatten(observations))
    ]
    ```

    Args:
      input_tensor_spec: A nest of `tensor_spec.TensorSpec` representing the
        observations.
      action_spec: A nest of `tensor_spec.BoundedTensorSpec` representing the
        actions.
      preprocessing_layers: (Optional.) A nest of `tf.keras.layers.Layer`
        representing preprocessing for the different observations. All of these
        layers must not be already built.
      preprocessing_combiner: (Optional.) A keras layer that takes a flat list
        of tensors and combines them.  Good options include
        `tf.keras.layers.Add` and `tf.keras.layers.Concatenate(axis=-1)`. This
        layer must not be already built.
      conv_layer_params: Optional list of convolution layers parameters, where
        each item is a length-three tuple indicating (filters, kernel_size,
        stride).
      input_fc_layer_params: Optional list of fully connected parameters, where
        each item is the number of units in the layer. These feed into the
        recurrent layer.
      cell_type: Type of RNNCell implementation to use.
      hidden_size: An iterable of ints specifying the LSTM cell sizes to use.
      output_fc_layer_params: Optional list of fully connected parameters, where
        each item is the number of units in the layer. These are applied on top
        of the recurrent layer.
      activation_fn: Activation function, e.g. tf.keras.activations.relu,.
      dtype: The dtype to use by the convolution, LSTM, and fully connected
        layers.
      name: A string representing name of the network.

    Raises:
      ValueError: If any of `preprocessing_layers` is already built.
      ValueError: If `preprocessing_combiner` is already built.
    """
    kernel_initializer = tf.variance_scaling_initializer(
        scale=2.0, mode='fan_in', distribution='truncated_normal')

    input_encoder = encoding_network.EncodingNetwork(
        input_tensor_spec,
        preprocessing_layers=preprocessing_layers,
        preprocessing_combiner=preprocessing_combiner,
        conv_layer_params=conv_layer_params,
        fc_layer_params=input_fc_layer_params,
        activation_fn=activation_fn,
        kernel_initializer=kernel_initializer,
        dtype=dtype)

    # Create RNN cell
    cell = get_cell(cell_type, hidden_size, dtype)

    output_encoder = []
    if output_fc_layer_params:
      output_encoder = [
          tf.keras.layers.Dense(
              num_units,
              activation=activation_fn,
              kernel_initializer=kernel_initializer,
              dtype=dtype,
              name='/'.join([name, 'dense']))
          for num_units in output_fc_layer_params
      ]

    action_spec = tf.nest.flatten(action_spec)[0]
    num_actions = action_spec.maximum - action_spec.minimum + 1
    q_projection = tf.keras.layers.Dense(
        num_actions,
        activation=None,
        kernel_initializer=tf.compat.v1.initializers.random_uniform(
            minval=-0.03, maxval=0.03),
        bias_initializer=tf.compat.v1.initializers.constant(-0.2),
        dtype=dtype,
        name='num_action_project/dense')
    output_encoder.append(q_projection)

    counter = [-1]

    def create_spec(size):
      counter[0] += 1
      return tensor_spec.TensorSpec(
          size, dtype=dtype, name='network_state_%d' % counter[0])

    state_spec = tf.nest.map_structure(create_spec, cell.state_size)

    super(RnnNetwork, self).__init__(
        input_tensor_spec=input_tensor_spec, state_spec=state_spec, name=name)

    self._conv_layer_params = conv_layer_params
    self._input_encoder = input_encoder
    self._dynamic_unroll = dynamic_unroll_layer.DynamicUnroll(cell)
    self._output_encoder = output_encoder

  def call(self, observation, step_type, network_state=(), training=False):
    """Applies the network.

    Args:
      observation: A tuple of tensors matching `input_tensor_spec`.
      step_type: A tensor of `StepType.
      network_state: (optional.) The network state.

    Returns:
      `(outputs, network_state)` - the network output and next network state.

    Raises:
      ValueError: If observation tensors lack outer `(batch,)` or
        `(batch, time)` axes.
    """
    num_outer_dims = nest_utils.get_outer_rank(observation,
                                               self.input_tensor_spec)
    if num_outer_dims not in (1, 2):
      raise ValueError(
          'Input observation must have a batch or batch x time outer shape.')

    has_time_dim = num_outer_dims == 2
    if not has_time_dim:
      # Add a time dimension to the inputs.
      observation = tf.nest.map_structure(lambda t: tf.expand_dims(t, 1),
                                          observation)
      step_type = tf.nest.map_structure(lambda t: tf.expand_dims(t, 1),
                                        step_type)

    state, _ = self._input_encoder(observation, step_type,
                                   network_state=(), training=training)

    with tf.name_scope('reset_mask'):
      reset_mask = tf.equal(step_type, time_step.StepType.FIRST)

    # Unroll over the time sequence.
    state, network_state = self._dynamic_unroll(
        state, reset_mask, initial_state=network_state)

    for layer in self._output_encoder:
      state = layer(state)

    if not has_time_dim:
      # Remove time dimension from the state.
      state = tf.squeeze(state, [1])

    return state, network_state


from nltk.translate.bleu_score import corpus_bleu, sentence_bleu
from tqdm import tqdm

TICKS_PER_BEAT = 24
TICKS_PER_MEASURE = 4 * TICKS_PER_BEAT
TICKS_PER_SENTENCE = 8 * TICKS_PER_MEASURE

class BleuScore:

    def __init__(self, sequence_len):
        self.seq_len = sequence_len

    def evaluate_bleu_score(self, predictions, targets, ticks=False, corpus=True):
        """
        Given an array of predicted sequences and ground truths, compute the BLEU score across the sequences.
        :param predictions: an num_sequences x seq_length numpy matrix
        :param targets: an num_sequences x seq_length numpy matrix
        :return: the BLEU score across the corpus of predicted ticks
        """
        if ticks:
            ref_sentences = self._ticks_to_sentences(targets)
            cand_sentences = self._ticks_to_sentences(predictions)
        else:
            ref_sentences = [[str(x) for x in seq] for seq in predictions]
            cand_sentences = [[str(x) for x in seq] for seq in targets]

        if corpus:
            bleu_score = corpus_bleu([[l] for l in ref_sentences], cand_sentences)
        else:
            bleu_score = 0.0
            num_sentences = 0

            for i in tqdm(range(len(ref_sentences))):
                sentence_bleu_score = sentence_bleu(ref_sentences[i], cand_sentences[i])
                print(sentence_bleu_score)
                bleu_score += sentence_bleu_score
                num_sentences += 1

            bleu_score /= num_sentences

        return bleu_score

    def _ticks_to_sentences(self, ticks):
        """
        Given an array of ticks, converts vector values to strings, returning a list of 8 measure "sentence" concatenations.
        :param ticks: an np array of ticks to convert to sentences
        :return: a list of sentences
        """
        sentences = []

        for seq in ticks:
            sentence = []
            for i in range(seq.shape[0]):
                word = ''.join([str(x) for x in seq[i, :]])
                sentence.append(word)
            sentences.append(sentence)

        return sentences


# asyncio runtime logger
# cant log anything before load_modules()

import sys
import os
import asyncio

from aiologger import Logger
from aiologger.handlers.streams import AsyncStreamHandler
from aiologger.handlers.files import AsyncFileHandler
from aiologger.formatters.base import Formatter

from utils.misc import aobject
from utils.files import *
class LoggerParent(aobject):
    async def __init__(self, main, log_path=None, logger_payloads=[]) -> None:

        self.main = main

        if(not log_path):
            log_path = self.main.pwd

        self.all_loggers = dict()
        self.log_path = log_path
        self.primary = None

        main.all_loggers = self.all_loggers

        for payload in logger_payloads:
            await self.CreateLogger(*payload)

        # only inject pre defined loggers
        for name, logger in self.all_loggers.items():

            self.main.inject_globals(name, logger[0])

    async def CreateLogger(self, name: str, logginglevel: str, filename: str, primary:bool = False, Streamhandler: bool = False, Filehandler:bool = True, format: str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'):
        args = locals()
        # print(name, logginglevel, filename)

        filename = os.path.join(self.main.pwd, filename)
        if([key for key,val in self.all_loggers.items() if key == name]):
            raise Exception("cannot have 2 loggers with same name")
        if([val for key,val in self.all_loggers.items() if val[1] == filename]):
            raise Exception("cannot have 2 loggers with same file")
        formatter = Formatter(format)
        logger = Logger(name=name,level=logginglevel)

        if(Streamhandler):
            streamhandler = AsyncStreamHandler(stream=sys.stdout)
            streamhandler.level = logginglevel
            streamhandler.formatter = formatter
            logger.add_handler(streamhandler)

        if(Filehandler):
            if(not os.path.exists(os.path.dirname(filename))):
                create_dir_path(filename)
            else:
                open(filename, 'w').close() #flawless
            filehandler = AsyncFileHandler(os.path.join(self.log_path, filename))
            filehandler.level = logginglevel
            filehandler.formatter = formatter
            logger.add_handler(filehandler)

        if(primary and self.primary == None):
            self.primary = logger
            self.main.primary = logger
        if(not self.primary):
            raise Exception("Logger was created before primary was created")
        else:
            await self.primary.debug("Logger created with with args {}".format(args))

        self.all_loggers[name] = [logger, filename]

MOD = LoggerParent
NAME = "logger"


import discord
from discord.ext import commands, tasks
from twitchAPI.twitch import Twitch
from dotenv import load_dotenv
import requests
from lib.working_with_json import *
from pprint import pprint as pp

load_dotenv()

# check for stream_state.json
create_json_if_not_exists('JSON/stream_state.json')

def create_embed(title, userid, viewer_count, get_user_profile_pic):
    embed = discord.Embed(title=title, url=f"https://twitch.tv/{userid}")
    embed.add_field(name="Viewers", value=viewer_count)
    embed.set_author(name=userid, icon_url=get_user_profile_pic)
    embed.set_image(url=f"https://static-cdn.jtvnw.net/previews-ttv/live_user_{userid}-320x180.jpg")
    embed.set_thumbnail(url=get_user_profile_pic)
    return embed

# Authentication with Twitch API.
client_id = os.environ.get("TWITCH_CLIENT_ID")
client_secret = os.environ.get("TWITCH_CLIENT_SECRET")
twitch = Twitch(client_id, client_secret)
twitch.authenticate_app([])
TWITCH_STREAM_ENDPOINT = "https://api.twitch.tv/helix/streams?user_login="
TWITCH_USER_ENDPOINT = "https://api.twitch.tv/helix/users?login="
body = {
    'client_id': client_id,
    'client_secret': client_secret,
    'grant_type': 'client_credentials'
}

r = requests.post('https://id.twitch.tv/oauth2/token', body)
keys = r.json()
print(keys)

API_HEADERS = {
    'Client-ID': client_id,
    'Authorization': 'Bearer ' + keys['access_token'],
    'Accept': 'application/vnd.twitchtv.v5+json'
}

# Returns true if online, false if not.
def checkuser(userid):
    # Get Twitch user infomation
    get_user_url = TWITCH_USER_ENDPOINT + userid
    get_user_req = requests.Session().get(get_user_url, headers=API_HEADERS)
    get_user_json = get_user_req.json()
    get_user_profile_pic = get_user_json['data'][0]['profile_image_url']
    get_user_display_name = get_user_json['data'][0]['display_name']
    # Get Twitch stream data
    get_stream_url = TWITCH_STREAM_ENDPOINT + userid
    get_stream_req = requests.Session().get(get_stream_url, headers=API_HEADERS)
    get_stream_json = get_stream_req.json()
    if get_stream_json['data']:
        # load stream_state.json
        stream_state = load_json('JSON/stream_state.json')
        title = get_stream_json['data'][0]['title']
        game_name = get_stream_json['data'][0]['game_name']
        viewer_count = get_stream_json['data'][0]['viewer_count']
        if userid not in stream_state:
            stream_state[userid] = []
            stream_state[userid].append({
                'is_live': True,
                'title': title,
                'game_name': game_name

            })
            save_json(stream_state, 'JSON/stream_state.json')
            return create_embed(title, get_user_display_name, viewer_count, get_user_profile_pic), get_user_display_name
        elif userid in load_json('JSON/stream_state.json'):
            stream_state = load_json('JSON/stream_state.json')
            if stream_state[userid][0]['is_live']:
                return True
            elif not load_json('JSON/stream_state.json')[userid][0]['is_live']:
                stream_state = load_json('JSON/stream_state.json')
                stream_state[userid][0]['is_live'] = True
                title = get_stream_json['data'][0]['title']
                stream_state[userid][0]['title'] = title
                stream_state[userid][0]['game_name'] = game_name
                viewer_count = get_stream_json['data'][0]['viewer_count']
                save_json(stream_state, 'JSON/stream_state.json')
                return create_embed(title, get_user_display_name, viewer_count,
                                    get_user_profile_pic), get_user_display_name
    else:
        if userid not in load_json('JSON/stream_state.json'):
            # load stream_state.json
            stream_state = load_json('JSON/stream_state.json')
            stream_state[userid] = []
            stream_state[userid].append({
                'is_live': False,
                'title': None,
                'game_name': None

            })
            save_json(stream_state, 'JSON/stream_state.json')
        elif userid in load_json('JSON/stream_state.json'):
            # load stream_state.json
            stream_state = load_json('JSON/stream_state.json')
            if stream_state[userid][0]['is_live']:
                stream_state[userid][0]['is_live'] = False
                save_json(stream_state, 'JSON/stream_state.json')
            return False

class Twitch(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @tasks.loop(seconds=5)
    async def live_notifs_loop(self):
        name = 'tayxo'
        check = checkuser(name)

        try:
            await self.bot.get_channel(911372583235092485).send(
                f"{check[1]} is now live on https://twitch.tv/{name}! Go check it out!", embed=check[0])
        except AttributeError:
            pass

    @commands.Cog.listener()
    async def on_ready(self):
        self.live_notifs_loop.start()

async def setup(bot):
    await bot.add_cog(Twitch(bot))


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
    from urlparse import urlparse
except ImportError:
    from urllib.parse import urlparse

from django.core import mail
from django.core.urlresolvers import reverse
from django.core.management import call_command, CommandError
from django.contrib.auth import get_user_model
import pytest

def _assert_redirect_to(_client, url):
    send_invite_url = reverse("send-invite")
    response = _client.get(send_invite_url, follow=True)
    assert response.redirect_chain
    redirected_to, status_code = response.redirect_chain[-1]
    assert status_code == 302
    parsed = urlparse(redirected_to)
    assert parsed.path == url
    assert parsed.query == "next=%s" % send_invite_url

@pytest.mark.django_db
def test_anonymous_users_are_redirected_to_site_login(client):
    login_url = reverse("login")
    _assert_redirect_to(client, login_url)

@pytest.mark.django_db
def test_unprivileged_users_are_redirected_to_admin_login(auth_client):
    admin_login_url = reverse("admin:login")
    _assert_redirect_to(auth_client, admin_login_url)

@pytest.mark.django_db
def test_staff_are_allowed(admin_client):
    response = admin_client.get(reverse("send-invite"))
    assert response.status_code == 200

@pytest.mark.django_db
def test_send_invite_view(admin_client):
    email = 'tester@test.com'
    N = len(mail.outbox)
    response = admin_client.post(
        reverse("send-invite"), {'registered_to': 'tester@test.com'},
        follow=True,
    )
    assert response.status_code == 200
    assert len(mail.outbox) == N+1

@pytest.mark.django_db
def test_non_interactive_send_invite_command():
    # email is required
    with pytest.raises(CommandError) as e:
        call_command("invite", interactive=False)
    assert e.value.args[0] == "Missing parameter 'email'"

    # if domain is given, a matching Site must exist
    email = 'tester@test.com'
    with pytest.raises(CommandError) as e:
        call_command("invite", interactive=False, email=email, domain="nope")
    assert e.value.args[0] == "A site with domain 'nope' does not exist"

    # if no domain is given, the default is used, but no mail is sent unless
    # specifically requested
    N = len(mail.outbox)
    call_command("invite", interactive=False, email=email)
    assert len(mail.outbox) == N
    call_command("invite", interactive=False, email=email, send=True)
    assert len(mail.outbox) == N+1


# coding: utf-8
import numpy as np
import random
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import svm
from sklearn.model_selection import train_test_split
import cmath
from svm_pso_predictor_K import PSO_K
from svm_pso_predictor_TVIW import PSO_W
from svm_pso_predictor_TVAC import PSO_TVAC
from svm_pso_predictor_mTVAC import PSO_MTVAC
from svm_pso_predictor_mhTVAC import PSO_MHTVAC
from svm_pso_predictor_mTVAC_RIW import PSO_MTVACRW
from svm_pso_predictor_hTVAC import PSO_HTVAC
from svm_pso_predictor_original import PSO
from svm_pso_predictor_RANDIW import PSO_RW
import time

drug = '17-AAG'
fn = 40
n_splits = 3    # 将数据随机切分成三份，每份数据训练集60%，测试集40%，模型准确率为三份数据对应的平均
data = pd.read_csv('data/drug_cell/drug/%s/%s_train_data-rfe-sa-%d.csv' % (drug, drug, fn))
# data = pd.read_csv('data/drug_cell/drug/%s/%s_train_data-rfe-mrmr-sa-%d.csv' % (drug, drug, fn))
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
# random_state=1不变的话，每次得到的数据都是一样的，random_state=None，每次的数据不一样
train_size = 0.6
# x_train, x_test, y_train, y_test = train_test_split(X, y, random_state=1, train_size=train_size)

MAX_ITER = 800
feature_number = X.shape[1]

for run in range(3):
    # ----------------------程序执行-----------------------
    start = time.time()

    # pso_K = PSO_K(max_iter=MAX_ITER, x_train=x_train, y_train=y_train, x_test=x_test,
    #               y_test=y_test)  # 维度代表变量的个数
    # pso_K.init_Population()
    # fitness_K = pso_K.iterator()

    # pso_W = PSO_W(max_iter=MAX_ITER, x_train=x_train, y_train=y_train, x_test=x_test,
    #               y_test=y_test)  # 维度代表变量的个数
    # pso_W.init_Population()
    # fitness_W = pso_W.iterator()

    pso_TVAC = PSO_TVAC(max_iter=MAX_ITER, data_X=X, data_y=y, n_splits=n_splits)  # 维度代表变量的个数
    pso_TVAC.init_Population()
    fitness_TVAC = pso_TVAC.iterator()

    pso_mTVAC = PSO_MTVAC(max_iter=MAX_ITER, data_X=X, data_y=y, n_splits=n_splits)  # 维度代表变量的个数
    pso_mTVAC.init_Population()
    fitness_mTVAC = pso_mTVAC.iterator()

    # 去掉了线性递减的惯性权重，改为0.5+rand(0,1)/2
    # pso_mTVACRW = PSO_MTVACRW(max_iter=MAX_ITER, x_train=x_train, y_train=y_train, x_test=x_test,
    #                       y_test=y_test)  # 维度代表变量的个数
    # pso_mTVACRW.init_Population()
    # fitness_mTVACRW = pso_mTVACRW.iterator()

    # pso_hTVAC = PSO_HTVAC(max_iter=MAX_ITER, data_X=X, data_y=y, n_splits=n_splits)  # 维度代表变量的个数
    # pso_hTVAC.init_Population()
    # fitness_hTVAC = pso_hTVAC.iterator()

    pso_mhTVAC = PSO_MHTVAC(max_iter=MAX_ITER, data_X=X, data_y=y, n_splits=n_splits)  # 维度代表变量的个数
    pso_mhTVAC.init_Population()
    fitness_mhTVAC = pso_mhTVAC.iterator()

    pso_original = PSO(max_iter=MAX_ITER, data_X=X, data_y=y, n_splits=n_splits)  # 维度代表变量的个数
    pso_original.init_Population()
    fitness_original = pso_original.iterator()

    # pso_RW = PSO_RW(max_iter=MAX_ITER, x_train=x_train, y_train=y_train, x_test=x_test,
    #                    y_test=y_test)  # 维度代表变量的个数
    # pso_RW.init_Population()
    # fitness_RW = pso_RW.iterator()

    end = time.time()

    best = pso_TVAC  # 找到准确率最高的---越小越高
    if pso_mTVAC.fit < best.fit:
        best = pso_mTVAC
    # if pso_hTVAC.fit < best.fit:
    #     best = pso_hTVAC6
    if pso_mhTVAC.fit < best.fit:
        best = pso_mhTVAC
    if pso_original.fit < best.fit:
        best = pso_original
    # -------------------画图--------------------
    plt.figure(figsize=(10, 8))
    plt.title('drug:%s\n feature number=%d,train_size:%.1f,cost: %d seconds\n best:%.4f  C=%.4f,gamma=%.5f' % (
        drug, feature_number, train_size, end - start, -best.fit, best.gbest[0], best.gbest[1]), size=16)
    plt.xlabel("number of generations", size=16)
    plt.ylabel("SVM model accuracy rate", size=16)
    t = np.array([t for t in range(0, MAX_ITER)])
    # fitness_K = np.array(fitness_K)
    # fitness_K2 = [-v for v in fitness_K]  # 取反，得到正数，模型准确率

    # fitness_W2 = [-v for v in fitness_W]  # 取反，得到正数，模型准确率

    fitness_TVAC2 = [-v for v in fitness_TVAC]  # 取反，得到正数，模型准确率

    fitness_mTVAC2 = [-v for v in fitness_mTVAC]  # 取反，得到正数，模型准确率

    # fitness_mTVACRW2 = [-v for v in fitness_mTVACRW]  # 取反，得到正数，模型准确率

    # fitness_hTVAC2 = [-v for v in fitness_hTVAC]  # 取反，得到正数，模型准确率

    fitness_mhTVAC2 = [-v for v in fitness_mhTVAC]  # 取反，得到正数，模型准确率

    pso_original2 = [-v for v in fitness_original]  # 取反，得到正数，模型准确率

    # fitness_RW2 = [-v for v in fitness_RW]  # 取反，得到正数，模型准确率

    # plt.plot(t, fitness_K2, color='b', linewidth=3, label='PSO-K')
    plt.plot(t, pso_original2, color='b', linewidth=3.2, label='PSO', ls='-.')
    # plt.plot(t, fitness_W2, color='r', linewidth=3, label='PSO-TVIW', ls=':')
    plt.plot(t, fitness_TVAC2, color='g', linewidth=3.1, label='PSO-TVAC', ls='--')
    # plt.plot(t, fitness_RW2, color='lightblue', linewidth=3, label='PSO-RANDIW', ls='-')
    plt.plot(t, fitness_mTVAC2, color='orange', linewidth=3, label='PSO-mTVAC', ls=':')
    plt.plot(t, fitness_mhTVAC2, color='red', linewidth=2.9, label='PSO-mhTVAC', ls='-')
    # plt.plot(t, fitness_mTVACRW2, color='black', linewidth=3, label='PSO-mTVACRW')
    # plt.plot(t, fitness_hTVAC2, color='yellow', linewidth=2.8, label='PSO-hTVAC')
    plt.legend(loc="lower right", fontsize=16)
    plt.yticks(fontsize='14')
    plt.xticks(fontsize='14')
    # plt.rcParams['savefig.dpi'] = 300  # 图片像素
    # plt.rcParams['figure.dpi'] = 300  # 分辨率
    # plt.savefig(
    #     'image/pso_TVAC/c-%s/fn%d/sa-%d-pso-cv-compare-%s-%d.png' % (
    #         drug, feature_number, feature_number, drug, 1 + run))
    # plt.show()
    plt.savefig(
        'image/pso_TVAC/c-%s/fn%d/sa-mrmr-%d-pso-cv-compare-%s-%d.png' % (
            drug, feature_number, feature_number, drug, 10 + run))
    # plt.show()
    plt.cla()


money = int(input("투입한 돈: "))
price = int(input("물건값: "))

a = money - price
print("거스름돈",a)
c500 = a // 500
a %= 500

c100 = a // 100
a %= 500

print("500원 동전의 개수:",c500)
print("100원 동전의 개수:",c100)

투입한 돈과 물건값 입력 후 거스름돈 반환.py

투입한 돈과 물건값 입력 후 거스름돈 반환.py


from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import *
from .models import *

@api_view(['GET'])
def get_todos(request):
    try:
        queryset = Todo.objects.all().order_by('id')
        todos = TodoSerializer(queryset, many=True)
        return Response(todos.data)
    except:
        return Response({'message': 'Getting todos -> FAILED'})

@api_view(['GET'])
def get_todo_by_id(request, id):
    try:
        queryset = Todo.objects.get(id=id)
        todo = TodoSerializer(queryset, many=False)
        return Response(todo.data)
    except:
        return Response({'message': 'Getting todo by ID -> FAILED'})

@api_view(['POST'])
def add_todo(request):
    try:
        new_todo = TodoSerializer(data=request.data)
        if new_todo.is_valid():
            new_todo.save()
        return Response(new_todo.data)
    except:
        return Response({'message': 'Adding -> FAILED'})

@api_view(['PUT'])
def update_todo(request, id):
    try:
        todo = Todo.objects.get(id=id)
        updated_todo = TodoSerializer(instance=todo, data=request.data)
        if updated_todo.is_valid():
            updated_todo.save()
        return Response(updated_todo.data)
    except:
        return Response({'message': 'Updating -> FAILED'})

@api_view(['DELETE'])
def delete_todo(request, id):
    try:
        todo = Todo.objects.get(id=id)
        todo.delete()
        return Response({'message': 'Deleting todo was successfull'})
    except:
        return Response({'message': 'Deleting -> FAILED'})


from datetime import datetime
import requests
from bs4 import BeautifulSoup
import itertools
import pymorphy2
import re

morph = pymorphy2.MorphAnalyzer()
state = []
nully = []
news = [[]]
d = {}

def get_html(url):
    response = requests.get(url)
    return response.text

def get_all_links(html): #, state, news):
    soup = BeautifulSoup(html, 'lxml')

    title = soup.find('h1')
    aftertitle = soup.find('div', class_ = 'preview-text')#.find_all('div', class_ = 'news-item')
    text = soup.find('div', class_ ='detail-text')

    apaftertitle = str(aftertitle)[35:-16]
    aptitle = str(title)[4:-6]

    before_aptext = str(str(title) + ' ' + str(aptitle) + ' ' + str(text))

    s = set()
    new = []

    str1 = before_aptext.split()
    for i in str1: #data[0]:
        p = morph.parse(i)[0]
        l = p.tag.POS
        p = p.normal_form
        result = re.sub(r',' , '', p)
        result = re.sub(r'»', '', result)
        result = re.sub(r'«', '', result)
        result = re.sub(r'
', '', result)
        result = re.sub(r'-', '', result)
        result = re.sub(r'–', '', result)
        result = re.sub(r'', '', result)
        result = re.sub(r'', '', result)
        result = re.sub(r'<div', '', result)
        result = re.sub(r'
', '', result)
        #result = re.sub(r'.', '', result)
        if (result.find('.') != -1):
            result = result[:-1]
        if (result.find(':') != -1):
            result = result[:-1]
        if (result.find('?') != -1):
            result = result[:-1]
        #print(result.find('.'))

        if ((l == 'NOUN') or (l == None)):
        #if ((l == 'VERB') or (l == None) or (l == 'INFN') or (l == 'PRTS') or (l == 'PRTF') or (l == 'GRND')):
        #if (l == 'ADJF' or l == 'ADJS' or l == 'ADVB' or l == None):
            if (result != '' and result != ' ' and result not in s):
                new.append(result)
                s.add(result)

    pairs = list(itertools.combinations(new, 2))
    for i in range(len(pairs)):
        if d.get(pairs[i]) == None:
            d[pairs[i]] = 1
        else:
            d[pairs[i]] += 1

def main():
    page = 'https://gazeta-n1.ru/news/' # 60143/ - 73269/

    for i in range(60143, 73269):#, 230):
        print(i - 60142, end='\n')
        url = page + str(i) + '/'
        all_links = get_all_links(get_html(url)) # state, news)
        print(i)

    my_file = open("gazeta_n1_pairs.txt", "a")
    for w in sorted(d, key=d.get, reverse=True):
        #print(w[0], ' ', d[w])
        if d[w] > 100:
            print("yahoo!")
            my_file.write(str(max(w[0], w[1])))
            my_file.write(' ')
            my_file.write(str(min(w[1], w[0])))
            my_file.write(' ')
            my_file.write(str(d[w]))
            my_file.write('\n')

    my_file.close()

if __name__ == '__main__':
    main()


import numpy as np

def lightsOut(matriz):
    n = len(matriz)
    luces = [] # Sistema de equaciones
    for i in range(n):
        for j in range(n):
            luz = [0] * (n ** 2 + 1) # Inicializa la luz (ecuación) que contendrá los valores de la misma
            luz[i * n + j] = 1  # Coeficiente de la luz actual
            luz[-1] = matriz[i][j]  # Resultado esperado (encendido o apagado)

            lucesCercanas = [
                (i - 1, j),  # Luz superior
                (i + 1, j),  # Luz inferior
                (i, j - 1),  # Luz izquierda
                (i, j + 1),  # Luz derecha
            ]

            for x, y in lucesCercanas:
                if 0 <= x < n and 0 <= y < n:
                    luz[x * n + y] = 1  # Coeficientes de las luces cercanas

            luces.append(luz)

    # Eliminación gaussiana
    for i in range(n ** 2):
        fila = i
        while fila < n ** 2 and luces[fila][i] == 0:
            fila += 1

        if fila == n ** 2:
            continue

        luces[i], luces[fila] = luces[fila], luces[i]

        for j in range(i + 1, n ** 2):
            if luces[j][i] == 1:
                for k in range(i, n ** 2 + 1):
                    luces[j][k] ^= luces[i][k]

    # Sustitución hacia atrás
    solucion = [luces[i][-1] for i in range(n ** 2)]
    for i in range(n ** 2 - 1, -1, -1):
        for j in range(i + 1, n ** 2):
            solucion[i] ^= luces[i][j] & solucion[j]

    solucionTemp = [solucion[i * n: (i + 1) * n] for i in range(n)]
    solucionVector = [element for row in solucionTemp for element in row]
    return solucionVector

# Pide al usuario el orden de la matriz, verificando que sea un numero y sea mayor o igual a 2
def pedirN():
    while True:
        try:
            n = int(input("\nIngrese el orden de la matriz cuadrada: "))
            if n >= 2:
                break
            else:
                print("El número debe ser mayor o igual a 2. Intente nuevamente.")
        except ValueError:
            print("Eso no es un número entero válido. Intente nuevamente.")
    return n

# Crea la matriz ingresada por el usuario
def crearMatriz(n):
    # Crear una matriz de ceros de tamaño n x n
    matriz = np.zeros((n, n), dtype=int)

    # Pedir al usuario que ingrese las filas de la matriz separadas por comas
    print("\nIngrese las filas de la matriz separadas por comas (0s Verde y 1s Rojo):")
    for i in range(n):
        fila_input = input(f"Fila {i + 1}: ").strip().split(',')

        while len(fila_input) != n:
            print(f"Debe ingresar exactamente {n} valores por fila.")
            fila_input = input(f"Fila {i + 1}: ").strip().split(',')

        try:
            fila = [int(valor) for valor in fila_input]
            if all(valor == 0 or valor == 1 for valor in fila):
                matriz[i] = fila
            else:
                print("Los valores deben ser 0 o 1. Intente nuevamente.")
                i -= 1  # Volver a pedir la fila si los valores no son 0 o 1
        except ValueError:
            print("Ingrese solo valores numéricos (0 o 1). Intente nuevamente.")

    # Retorna la matriz
    return matriz

# Imprime el vector en "formato matriz" para que sea mas amigable al usuario.
def convertirVector(vector,n):
    texto = "\nSolución"
    fila_actual = 1
    for i in range(0, len(vector), n):
        fila = vector[i:i + n]
        texto += f"\nFila {fila_actual}: {fila}"
        fila_actual += 1
    texto += "\n"
    print(texto)
    return

# Funcion principal que llama a todas las funciones necesarias para resolver el problema.
def jugar():
    n = pedirN()
    matriz = crearMatriz(n)
    solucion = lightsOut(matriz)
    convertirVector(solucion,n)
    print("Vector solución:", solucion, "\n")
    return

# Permite jugar varias veces.
while True:
    jugar()
    jugar_de_nuevo = input("¿Quieres jugar de nuevo? (s/n): ")
    if jugar_de_nuevo.lower() != 's':
        break
    print("\n======================================================")

print("\nGracias por jugar.\n")


"""
Utils for training LSTM on parallel on different gpus
"""
import os
import json
import numpy as np

from coldstart.seq2seq.train import fit, load_and_arrange_data
from coldstart.seq2seq.model import create_model
from coldstart.lstm.train_manager import TrainManager

def train_single_model(conf):
    """
    Trains a single model using the given data and configuration.
    Saves the model, history and configuration to file
    """
    train_x, train_y, val_x, val_y = load_and_arrange_data(conf, conf['verbose'])
    if not os.path.exists(conf['models_dir']):
        os.makedirs(conf['models_dir'], exist_ok=True)

    model = create_model(train_x, train_y, conf['model_conf'])
    if conf['verbose']:
        model.summary()
    model_path = os.path.join(conf['models_dir'], '%s_%i_working%i.h5' % (
        conf['window'], conf['input_days'], int(conf['only_working_day'])))
    conf['train_conf']['model_path'] = model_path
    conf_path = model_path.replace('.h5', '.json')
    with open(conf_path, 'w') as f:
        json.dump(conf, f)

    model, ret = fit(model, train_x, train_y, [val_x, val_y], conf['train_conf'])
    _print_train_summary(conf, ret.history)

def _print_train_summary(conf, history):
    print('%s input_days %i_%i\tcv: %i\tloss: %.4f\tval_loss: %.4f'% (
        conf['window'], conf['input_days'], conf['only_working_day'],
        conf['fold_idx'],
        np.min(history['loss']), np.min(history['val_loss'])))


from django.urls import path

from . import views

app_name = 'tokens'

urlpatterns = [
    path('create/', views.Create.as_view(), name='create'),
    path('list/', views.TokenList.as_view(), name='list'),
    path('total_supply/', views.TotalSupply.as_view(), name='total_supply'),
]


# The solution found from z3 is that Alex has to be a knave, and no conclusions can be drawn about the mother
from z3 import *
s = Solver()
a = Bool('a')
m = Bool('m')

# Build the model with the proper initial constraints
s.add(Implies(a, m == And(a != m)))

result = s.check()

# Check satisfiablity and if satisfiable, find all possible solutions to the model
if result == unsat:
    print("unsatisfiable constraints")
elif result == sat:
    while s.check() == sat:
        j = s.model()
        print(', '.join([str(x) + ' = ' + str(j[x]) for x in [a, m]]))
        s.add(Or(a != s.model()[a], m != s.model()[m]))
else:
    print('unable to solve')


import random

def game():
    damage = 0
    strength = 0
    char_class = ""
    loyalty = 0
    wisdom = 0
    stamina = 0
    health = 0
    weapon_dmg = 0
    opponent = ""
    opponent_weapon = ""
    opponent_health = 0

    message = input("Choose your class: [Knight, Wizard, Archer, Troll]: ")
    if message == "knight" or message == "Knight":
        strength = 30
        health = 45
        char_class = "Knight"
        loyalty = 15
        wisdom = 5
        stamina = 25
        weapon_dmg = 45
        weapons = ['Sword',]
    elif message == "wizard" or message == "Wizard":
        strength = 5
        char_class = "Wizard"
        health = 30
        loyalty = 50
        wisdom = 65
        stamina = 15
        weapon_dmg = 20
        weapons = ['Magic',]
    elif message == "archer" or message == "Archer":
        strength = 10
        health = 35
        char_class = "Archer"
        loyalty = 5
        wisdom = 0
        stamina = 35
        weapon_dmg = 55
        weapons = ['Bow',]
    elif message == "troll" or message == "Troll":
        strength = 70
        health = 50
        char_class = "Troll"
        loyalty = 10
        wisdom = 0
        stamina = 10
        weapon_dmg = 60
        weapons = ['Hands',]
    # print(f"Strength: {strength} | Character Class {char_class} | Loyalty {loyalty} | Wisdom {wisdom} | Weapon Damage {weapon_dmg}")

    message = input("Welcome to the game. You will play now. Also, for story purposes, the troll and archer are on one team, and the knight and wizard are on the other. Also this first bit is the tutorial, so if you wanna skip, which is recommended, type EXIT: ")
    print()
    if char_class is "Troll" or char_class is "Archer":
        print("You are walking in the forest when you see something up ahead of you. It is very faint, but there is a glow. You don't know what it is. \n You have 2 options. Do you run straight towards the light, or sneak up on it? \n")
        message = input("Run or Sneak? ")
        if message == "Run" or message == "run":
            print("You decide the best option is to confront the light. You start running towards it. It gets brighter the more you come towards it. \n It becomes apparent someone is holding a stick, with a lantern atop of it. \n There is no going back, you have to face the light. What weapon are you going to have prepared in case an altercation takes place?")
            message = input("Hands: ")
            if message == "Hands" or message == "hands":
                print(f"You get your fists ready. You are approaching the light. But alas, you now have a stamina bar. And guess what, you only have {stamina}% left. And because you're a {char_class}, you don't have much to being with")
                print(f"Do you want to continue running? Or do you want to walk the rest of the way? ")
                message = input("Run or Walk? ")
                if message == "Run" or message == "run":
                    stamina -= 6
                    print(f"Stats: \n Stamina: {stamina} \n Health: {health} \n You are within 10 metres of the building. Of course, it cost you stamina. You now have {stamina}% left. \n But luckily for you, you are able to see the figure. It is a wizard. He is holding a staff in his hand, and on top of the staff is a glowing light. Now fight him!")
                else:
                    stamina -= 2
                    print(f"Stats: \n Stamina: {stamina} \n Health: {health} \n There is a wizard in front of you. Yep, believe it or not, there is. Which sucks I guess. He's just standing there. Waving his wand around like an autistic kid who thinks he has a wand. He is saying some things which are quite gibberish, almost in a foreign language. You have your {weapons} out.")
                    message = input("Attack or Stay")
                    if message == "Attack" or message == "attack":
                        health -= 15
                        print(f"Stats: \n Stamina: {stamina} \n Health: {health} \n You lay into him with your {weapons}. The wizard starts screeching and fires his wand back at you, giving you a taste of medicine. Your health is now down to {health}%. You have to do something. ")

    if message == "EXIT" or message == "exit":
        pass

game()


# https://www.acmicpc.net/problem/9417

# readline을 사용하기 위해 import합니다.
from sys import stdin

# 두 수의 최대공약수를 반환하는 함수를 구현합니다.
def gcd(num1, num2):
    # 유클리드 호제법을 사용해서 최대공약수를 구합니다.
    while num2 > 0:
        num1, num2 = num2, num1 % num2

    return num1

# 첫째 줄에 테스트 케이스의 개수 N을 입력합니다.
# 1 < N < 100
N = int(stdin.readline())

# 테스트 케이스의 개수 N만큼 반복합니다.
for test_case_idx in range(N):
    # 양의 정수 M개를 공백으로 구분해 입력합니다.
    # 각각 정수형으로 변환하고 리스트 변수에 넣어줍니다.
    # 모든 수는 -2^31보다 크거나 같고, 2^31 - 1보다 작거나 같습니다.
    numbers = list(map(int, stdin.readline().split(' ')))
    # 입력한 수의 개수를 저장하는 변수를 저장하는 변수를 선언합니다.
    numbers_len = len(numbers)
    # 모든 두 수의 쌍의 최대공약수 중 가장 큰 값을 저장할 변수를 선언합니다.
    max_gcd = 1

    # 양의 정수 리스트에서 두 개씩 묶어 최대공약수를 구해봅니다.
    for idx1 in range(numbers_len - 1):
        for idx2 in range(idx1 + 1, numbers_len):
            this_time_gcd = gcd(numbers[idx1], numbers[idx2])

            # 이번 두 수의 최대공약수가 이전까지의 최대공약수 중 가장 크다면
            if this_time_gcd > max_gcd:
                # max_gcd의 값을 이번 최대공약수로 변경합니다.
                max_gcd = this_time_gcd

    # max_gcd의 값을 출력합니다.
    print(max_gcd)


from config import file

class TimeRange:
    day = ''
    start_time = ''
    end_time= ''
    hours = []

    def __init__(self, time_range):
        self.hours = []
        self.day = time_range[:2]
        self.start_time = time_range[2:7]
        self.end_time = time_range[8:]

        if len(time_range) > 1:
            for hour in range (int(self.start_time[:2]), int(self.end_time[:2])):
                self.hours.append(str(hour))

class Schedule:
    time_ranges = []

    def __init__(self, schedule):
        self.time_ranges = []
        time_ranges = schedule.split(',')

        for time_range in time_ranges:
            new_time_range = TimeRange(time_range)
            self.time_ranges.append(new_time_range)

class Employee:
    def __init__(self, name, schedule) -> None:
        self.name = name
        self.schedule = schedule

class FileParser:
    rows = []

    def __init__(self, file) -> None:
        self.data_file = file

    def _load_rows(self):
        with open(self.data_file) as f:
            self.rows = f.readlines()

    def get_employees(self):
        data = []
        self._load_rows()
        for row in self.rows:
            name = row.split('=')[0]
            schedule = row.split('=')[1]
            employee_schedule = Schedule(schedule)
            employee = Employee(name, employee_schedule)
            data.append(employee)
        return data

class SalaryCalculator:
    sat_sun = {'SA', 'SU'}
    first_turn_hours = {'0','1','2','3','4','5','6','7','8'}
    second_turn_hours = {'9','10','11','12','13','14','15','16','17'}
    salary_matrix = {'special': {'first_turn':30, 'second_turn':20, 'third_turn':25},
                     'normal' : {'first_turn':25, 'second_turn':15, 'third_turn':20}}

    def calculate_salary(self, schedule):
        salary = 0
        turn = ''

        for time_range in schedule.time_ranges:
            if time_range.day in self.sat_sun:
                day_type = 'special'
            else:
                day_type = 'normal'
            for hour in time_range.hours:
                if hour in self.first_turn_hours:
                    turn = 'first_turn'
                elif hour in self.second_turn_hours:
                    turn = 'second_turn'
                else:
                    turn = 'third_turn'

                if turn:
                    salary += self.salary_matrix[day_type][turn]

        return salary

if __name__=='__main__':

    fp = FileParser(file)
    salary_calculator = SalaryCalculator()

    employees = fp.get_employees()
    for employee in employees:
        salary = salary_calculator.calculate_salary(employee.schedule)
        print(f'The amount to pay {employee.name.upper()} is: {salary} USD'), employee.name, salary


###########################################################
    #  CSE 231 Project #9
    #
    #  Dictionaries and Functions
    #    open and read CSV files
    #       read for certain values in a CSV file
    #    output appropriate value in the function
    #       call appropriate functions
    #    display closing message
    #
    ###########################################################

import csv
import matplotlib.pyplot as plt
plt.style.use("ggplot")
from operator import itemgetter

def open_file():
    ''' This function prompts for a file and opens it in read '''
    x = True
    #create a loop until correct file is input
    while x is True:
        try:
            filename = input("Data file: ")
            if filename == '':
                fp = open('ncov.csv', 'r')
            else:
                fp = open(filename, 'r')
            x = False
        #output error message
        except FileNotFoundError:
            print("Error. Try again.")
    #return openned file
    return fp

def build_dictionary(fp):
    ''' This function accepts the file pointer as input and returns the required dictionary '''
    #read csv file and create a master list
    reader = csv.reader(fp)
    next(reader,None)
    master_list = []
    #append master_list with each line list
    for i in reader:
        master_list.append(i)
    #create an empty dictionary for all the countries
    master_dict = {}
    for line in master_list:
        #iterate through each value in the master list
        areadict = {}
        country = line[2].strip()
        area = line[1].strip()
        if area == '':
            area = 'N/A'
        last_update = line[3].strip()
        cases = int(line[4].strip())
        deaths = int(line[5].strip())
        recovered = int(line[6].strip())
        #create a tuple to add into a smaller dictionary
        area_tup = (last_update, cases, deaths, recovered)
        areadict[area] = area_tup
        if country in master_dict:
            #if country is already in dictionary then append the smaller dictionary to the list
            master_dict[country].append(areadict)
        else:
            #if country is not already in dictionary then create a list with the smaller dictionary
            master_dict[country] = [areadict]
    #return the dictionary
    return master_dict

def top_affected_by_spread(master_dict):
    ''' This function accepts the dictionary and returns a list of the top 10 most affected countries '''
    #create an empty list
    area_list = []
    #iterate through each list in the dictionary
    for key,value in master_dict.items():
        #append the country and the length of its list to area list created above
        x = len(value)
        area_tup = (key, x)
        area_list.append(area_tup)
    #sort the list alphabetically and numerically
    area_list.sort()
    area_list.sort(key = itemgetter(1), reverse = True)
    #return the top ten results
    return area_list[:10]

def top_affected_by_numbers(master_dict):
    ''' This function accepts the dictionary and returns a list of the countries with the top 10 cases '''
    #create an empty list
    area_list = []
    #iterate through each list in the dictionary
    for key,value in master_dict.items():
        x = 0
        #iterate through each dictionary in the list
        for case in value:
            #iterate through each value in the dictionary
            for i in case.values():
        #find the sum of the values and append the tuple to area list
                x += i[1]
        area_tup = (key, x)
        area_list.append(area_tup)
    #sort the list alphabetically and numerically
    area_list.sort()
    area_list.sort(key = itemgetter(1), reverse = True)
    #return the top ten results
    return area_list[:10]

def is_affected(master_dict, country):
    ''' This function accepts in the dictionary and a country and returns a Boolean on whether a country is affected '''
    #set country to lowercase and provide a false boolean variable
    country = country.lower()
    x = False
    #iterate through the keys in the dictionary
    for keys in master_dict.keys():
        #change the boolean variable if the country matches the key
        if country == keys.lower():
            x = True
        #if country is not in the dictionary then continue
        else:
            continue
    #return the boolean
    return x

def plot_by_numbers(list_of_countries, list_of_numbers):
    '''
        This function plots the number of areas/people inffected by country.

        parameters:
            list_of_countries: list of countries
            list_of_numbers: list of the number of areas/people inffected

        Returns: None
    '''
    fig, ax = plt.subplots()

    x_pos = [i for i, _ in enumerate(list_of_countries)]

    ax.barh(x_pos, list_of_numbers, align='center', color='red')
    ax.set_yticks(x_pos)
    ax.set_yticklabels(list_of_countries)
    ax.invert_yaxis()
    ax.set_xlabel('Count')
    ax.set_title('Novel Coronavirus statistics')

    plt.show()

def affected_states_in_country(master_dict, country):
    ''' This function accepts in the dictionary and a country and returns a set of affected areas '''
    #set country to lowercase and create an empty set
    country = country.lower()
    areas = set()
    #iterate through each item in the dictionary
    for keys,values in master_dict.items():
        #find a country that matches a key
        if country == keys.lower():
            #iterate through each key in each dictionary in the list
            for i in values:
                for area in i.keys():
                    #add the area to the empty set
                    areas.add(area)
        #if country is not in the dictionary then continue
        else:
            continue
    #return the set
    return areas

def main():
    BANNER = '''
.__   __.   ______   ______   ____    ____
|  \ |  |  /      | /  __  \  \   \  /   /
|   \|  | |  ,----'|  |  |  |  \   \/   /
|  . `  | |  |     |  |  |  |   \      /
|  |\   | |  `----.|  `--'  |    \    /
|__| \__|  \______| \______/      \__/
    '''
    print(BANNER)
    MENU = '''
[1] Countries with most areas infected
[2] Countries with most people affected
[3] Affected areas in a country
[4] Check if a country is affected
[5] Exit

Choice: '''
    #open file and call dictionary function
    fp = open_file()
    master_dict = build_dictionary(fp)
    x = True
    y = True
    #create a loop to prompt for the choices
    while y ==True:
        #create a nested loop to produce the error line in case of an error
        while x == True:
            #prompt for choice between 1 and 5
            try:
                choice = int(input(MENU))
                if 1 <= choice <= 5:
                    break
                #raise error if choice does not satisfy rules
                else:
                    raise ValueError
            #print error statement and loop
            except:
                print("Error. Try again.")

        if choice == 1:
            #create a table for areas affected
            print("{:<20s} {:15s}".format("Country", "Areas affected"))
            print("-"*40)
            #call function
            areas = top_affected_by_spread(master_dict)
            #create empty plot lists for x and y values
            plot_x = []
            plot_y = []
            #iterate through the tuples and print the values appropriately
            for tups in areas:
                area = tups[0]
                number = tups[1]
                #add the values to the plot lists
                plot_x.append(area)
                plot_y.append(number)
                print("{:<20s} {:5d}".format(area,number))
            #plot first five points if plot prompt is yes
            plot = input('Plot? (y/n) ')
            if plot == 'y':
                plot_by_numbers(plot_x[:5],plot_y[:5])

        if choice == 2:
            #create a table for people affected
            print("{:<20s} {:15s}".format("Country", "People affected"))
            print("-"*40)
            #call function
            areas = top_affected_by_numbers(master_dict)
            #create empty plot lists for x and y values
            plot_x = []
            plot_y = []
            #iterate through the tuples and print the values appropriately
            for tups in areas:
                area = tups[0]
                number = tups[1]
                #add the values to the plot lists
                plot_x.append(area)
                plot_y.append(number)
                print("{:<20s} {:5d}".format(area,number))
            #plot first five points if plot prompt is yes
            plot = input('Plot? (y/n) ')
            if plot == 'y':
                plot_by_numbers(plot_x[:5],plot_y[:5])

        if choice == 3:
            #prompt for a country and create table
            country = input("Country name: ")
            print("-"*30)
            #call function
            states = affected_states_in_country(master_dict,country)
            #if country is not in dictionary (or set is empty) then print error line
            if len(states) == 0:
                print("Error. Country not found.")
            else:
                #create table for the affected areas
                print("{:<30s}".format("Affected area"))
                print("-"*30)
                val = 1
                for state in sorted(states):
                    print("[{:02d}] {:<30s}".format(val,state))
                    val += 1

        if choice == 4:
            #prompt for a country and create table
            country = input("Country name: ")
            print("-"*30)
            #call function
            covid = is_affected(master_dict, country)
            #print appropriate lines
            if covid == True:
                print("{} is affected.".format(country))
            else:
                print("{} is not affected.".format(country))

        if choice == 5:
            #print exit line and break loop
            print("Stay at home. Protect your community against COVID-19")
            break

if __name__ == "__main__":
    #call main function
    main()


from mindstorms import MSHub
from projects.uartremote import *
from hub import port

# Create your objects here.
ms_hub = MSHub()
ur = UartRemote('E')

# Write your program here.
ms_hub.speaker.beep()

# Test remote connection
print(ur.call('echo','repr','Uart command loop tested with echo'))

while True:
    # print(ur.call('echo','repr','Uart command loop tested with echo'))
    ack, payload = ur.call('blob')
    if ack == 'bloback':
        if len(payload) == 2:
            direction = int((payload[0]-60)/2) # x coordinate of blob
            distance = int(payload[1]/3)+20
            port.A.motor.pwm(distance+direction)
            port.B.motor.pwm(-distance+direction)
        else:
            port.A.motor.pwm(0)
            port.B.motor.pwm(0)
    else:
        print(ack, payload)
        port.A.motor.pwm(0)
        port.B.motor.pwm(0)


import math

m=int(input())
n=int(input())
answer=[]
for i in range(m,n+1):
    if int(math.sqrt(i))**2==i:
        answer.append(i)
if answer:
    print(sum(answer))
    print(answer[0])
else:
    print(-1)


from django.urls import path, include

from .apis import (
    UserSessionLoginApi,
    UserSessionLogoutApi,

    UserJwtLoginApi,
    UserJwtLogoutApi,

    UserMeApi,
)

urlpatterns = [
    path(
        'session/',
        include(([
            path(
                'login/',
                UserSessionLoginApi.as_view(),
                name='login'
            ),
            path(
                'logout/',
                UserSessionLogoutApi.as_view(),
                name='logout'
            )

        ], "session"))
    ),
    path(
        'jwt/',
        include(([
            path(
                "login/",
                UserJwtLoginApi.as_view(),
                name="login"
            ),
            path(
                "logout/",
                UserJwtLogoutApi.as_view(),
                name="logout"
            )
        ], "jwt"))
    ),
    path(
        'me/',
        UserMeApi.as_view(),
        name='me'
    )
]


import collections

class Solution:
    # my solution is correct, but it takes a lot of time!
    # O(k * (n - k))
    def maxSlidingWindow(self, nums, k):
        res = []
        window = []

        for i in range(k):
            window.append(nums[i])

        windowMax = max(window)
        res.append(windowMax)

        l = 0

        for r in range(k, len(nums)):
            window.remove(nums[l])
            window.append(nums[r])

            windowMax = max(window)

            res.append(windowMax)

            l += 1

        return res

    # O(1) * O(n)
    # Monotonically Decreasing Que
    def neetcode_maxSlidingWindow(self, nums, k):
        output = []
        q = collections.deque()  # index

        l = r = 0

        while r < len(nums):
            # pop smaller values from q
            while q and nums[q[-1]] < nums[r]:
                q.pop()

            q.append(r)

            # remove left value from window
            if l > q[0]:
                q.popleft()

            if (r + 1) >= k:
                output.append(nums[q[0]])
                l += 1

            r += 1

        return output

leetcode#150/Sliding Window/239. Sliding Window Maximum.py


from src.controllers.login import post_login
from flask import Blueprint, request, jsonify, make_response, g

login_blueprint = Blueprint(
    'login', __name__, template_folder='routes', static_folder='routes')

@login_blueprint.route('/', methods=['POST'], strict_slashes=False)
def post():
    try:
        user_id = g.user_id
        token = post_login(user_id)
        return make_response(jsonify({'success': True, 'data': token, 'message': 'OK'}), 200)
    except Exception as e:
        raise e


import cv2

cap = cv2.VideoCapture("ds1.mp4")

while True:
    _, frame = cap.read()
    images = cv2.resize(frame,(1280,720))
    cv2.imshow("frame",images)
    key = cv2.waitKey(1)
    if key == 27:
        break

cap.release()
cv2.destroyAllWindows()


#!usr/bin/python3

#import stuff
##import os
##import glob
import RPi.GPIO as GPIO
import time
from datetime import datetime
import json
##import tempTest
##
##
### init list pin numbers

GPIO.setmode(GPIO.BCM)

pinList = [18, 23, 24, 25, 12, 16, 20, 21]

# loop pins and the sleep time

for i in pinList:
        GPIO.setup(i, GPIO.OUT)
        GPIO.output(i, GPIO.HIGH)
GPIO.setup(17, GPIO.IN)

sleepTime = 1
ato_counter = 0
ato_max = 120

#datetime.strptime(input("End Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")

def reset_times():
        ssTimes = {
            "startTimes": {
                    "start1": '00:00:00',
                    "start2": '00:00:00',
                    "start3": '00:00:00',
                    "start4": '00:00:00',
                    "start5": '00:00:00',
                    "start6": '00:00:00',
                    "start7": '00:00:00',
                    "start8": '00:00:00'
                    },
            "endTimes": {
                    "end1": '23:59:59',
                    "end2": '23:59:59',
                    "end3": '23:59:59',
                    "end4": '23:59:59',
                    "end5": '23:59:59',
                    "end6": '23:59:59',
                    "end7": '23:59:59',
                    "end8": '23:59:59'
                    }
            }
        with open("times.txt","w") as f:
            s=json.dumps(ssTimes, f, ensure_ascii=False)
            f.write(s)
        with open("times.txt","r") as f:
            s=f.read()
            ssTimes=json.loads(s)

f=open("times.txt","r")
s=f.read()
ssTimes=json.loads(s)

start1 = datetime.strptime(ssTimes["startTimes"]["start1"],"%H:%M:%S").strftime("%H:%M:%S")
end1 = datetime.strptime(ssTimes["endTimes"]["end1"],"%H:%M:%S").strftime("%H:%M:%S")
start2 = datetime.strptime(ssTimes["startTimes"]["start2"],"%H:%M:%S").strftime("%H:%M:%S")
end2 = datetime.strptime(ssTimes["endTimes"]["end2"],"%H:%M:%S").strftime("%H:%M:%S")
start3 = datetime.strptime(ssTimes["startTimes"]["start3"],"%H:%M:%S").strftime("%H:%M:%S")
end3 = datetime.strptime(ssTimes["endTimes"]["end3"],"%H:%M:%S").strftime("%H:%M:%S")
start4 = datetime.strptime(ssTimes["startTimes"]["start4"],"%H:%M:%S").strftime("%H:%M:%S")
end4 = datetime.strptime(ssTimes["endTimes"]["end4"],"%H:%M:%S").strftime("%H:%M:%S")
start5 = datetime.strptime(ssTimes["startTimes"]["start5"],"%H:%M:%S").strftime("%H:%M:%S")
end5 = datetime.strptime(ssTimes["endTimes"]["end5"],"%H:%M:%S").strftime("%H:%M:%S")
start6 = datetime.strptime(ssTimes["startTimes"]["start6"],"%H:%M:%S").strftime("%H:%M:%S")
end6 = datetime.strptime(ssTimes["endTimes"]["end6"],"%H:%M:%S").strftime("%H:%M:%S")
start7 = datetime.strptime(ssTimes["startTimes"]["start7"],"%H:%M:%S").strftime("%H:%M:%S")
end7 = datetime.strptime(ssTimes["endTimes"]["end7"],"%H:%M:%S").strftime("%H:%M:%S")
start8 = datetime.strptime(ssTimes["startTimes"]["start8"],"%H:%M:%S").strftime("%H:%M:%S")
end8 = datetime.strptime(ssTimes["endTimes"]["end8"],"%H:%M:%S").strftime("%H:%M:%S")
f.close()

# Set up a another outlet

def another_outlet():
    set_another = input("would you like to set up another start stop timer? y/n: ").lower()
    if set_another == "y":
        outlet_number()
    if set_another == "n":
        main_loop()
    else:
        print ("Sorry, that is not a valid outlet, please try again")
        another_outlet()

# Input outlet number
def outlet_number():
    outlet = input("Which outlet(number) would you like to use, please choose from the list:\n\
one-eight, reset to reset times or run to skip to run\n\
").lower()
    if outlet == "one":
        outlet1_start()
        outlet1_stop()
    elif outlet == "two":
        outlet2_start()
        outlet2_stop()
    elif outlet == "three":
        outlet3_start()
        outlet3_stop()
    elif outlet == "four":
        outlet4_start()
        outlet4_stop()
    elif outlet == "five":
        outlet5_start()
        outlet5_stop()
    elif outlet == "six":
        outlet6_start()
        outlet6_stop()
    elif outlet == "seven":
        outlet7_start()
        outlet7_stop()
    elif outlet == "eight":
        outlet8_start()
        outlet8_stop()
    elif outlet == "reset":
        reset_times()
        outlet_number()
    elif outlet == "run":
        main_loop()
    else:
        print ("Idiot!! Pick a valid outlet!")
        outlet_number()

def outlet1_start():
    global start1
    global ssTimes
    try:
        ssTimes["startTimes"]["start1"] = datetime.strptime(input("Start Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                start1 = datetime.strptime(ssTimes["startTimes"]["start1"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet1_start()
def outlet1_stop():
    global end1
    global ssTimes
    try:
        ssTimes["endTimes"]["end1"] = datetime.strptime(input("End Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                end1 = datetime.strptime(ssTimes["endTimes"]["end1"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet1_stop()
    if start1 > end1:
        print ("I'm sorry, your end time is before your start time, please input a new start time")
        outlet1_start()
    else:
        another_outlet()
def outlet2_start():
    global start2
    global ssTimes
    try:
        ssTimes["startTimes"]["start2"] = datetime.strptime(input("Start Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                start2 = datetime.strptime(ssTimes["startTimes"]["start2"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet2_start()
def outlet2_stop():
    global end2
    global ssTimes
    try:
        ssTimes["endTimes"]["end2"] = datetime.strptime(input("End Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                end2 = datetime.strptime(ssTimes["endTimes"]["end2"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet2_stop()
    if start2 > end2:
        print ("I'm sorry, your end time is before your start time, please input a new start time")
        outlet1_start()
    else:
        another_outlet()
def outlet3_start():
    global start3
    global ssTimes
    try:
        ssTimes["startTimes"]["start3"] = datetime.strptime(input("Start Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                start3 = datetime.strptime(ssTimes["startTimes"]["start3"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet3_start()
def outlet3_stop():
    global end3
    global ssTimes
    try:
        ssTimes["endTimes"]["end3"] = datetime.strptime(input("End Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                end3 = datetime.strptime(ssTimes["endTimes"]["end3"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet3_stop()
    if start3 > end3:
        print ("I'm sorry, your end time is before your start time, please input a new start time")
        outlet1_start()
    else:
        another_outlet()
def outlet4_start():
    global start4
    global ssTimes
    try:
        ssTimes["startTimes"]["start4"] = datetime.strptime(input("Start Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                start4 = datetime.strptime(ssTimes["startTimes"]["start4"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet4_start()
def outlet4_stop():
    global end4
    global ssTimes
    try:
        ssTimes["endTimes"]["end4"] = datetime.strptime(input("End Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                end4 = datetime.strptime(ssTimes["endTimes"]["end4"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet4_stop()
    if start4 > end4:
        print ("I'm sorry, your end time is before your start time, please input a new start time")
        outlet1_start()
    else:
        another_outlet()
def outlet5_start():
    global start5
    global ssTimes
    try:
        ssTimes["startTimes"]["start5"] = datetime.strptime(input("Start Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                start5 = datetime.strptime(ssTimes["startTimes"]["start5"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet5_start()
def outlet5_stop():
    global end5
    global ssTimes
    try:
        ssTimes["endTimes"]["end5"] = datetime.strptime(input("End Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                end5 = datetime.strptime(ssTimes["endTimes"]["end5"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet6_stop()
    if start5 > end5:
        print ("I'm sorry, your end time is before your start time, please input a new start time")
        outlet1_start()
    else:
        another_outlet()
def outlet6_start():
    global start6
    global ssTimes
    try:
        ssTimes["startTimes"]["start6"] = datetime.strptime(input("Start Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                start6 = datetime.strptime(ssTimes["startTimes"]["start6"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet6_start()
def outlet6_stop():
    global end6
    global ssTimes
    try:
        ssTimes["endTimes"]["end6"] = datetime.strptime(input("End Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                end6 = datetime.strptime(ssTimes["endTimes"]["end6"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet6_stop()
    if start6 > end6:
        print ("I'm sorry, your end time is before your start time, please input a new start time")
        outlet1_start()
    else:
        another_outlet()
def outlet7_start():
    global start7
    global ssTimes
    try:
        ssTimes["startTimes"]["start7"] = datetime.strptime(input("Start Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                start7 = datetime.strptime(ssTimes["startTimes"]["start7"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet7_start()
def outlet7_stop():
    global end7
    global ssTimes
    try:
        ssTimes["endTimes"]["end7"] = datetime.strptime(input("End Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                end7 = datetime.strptime(ssTimes["endTimes"]["end7"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet7_stop()
    if start7 > end7:
        print ("I'm sorry, your end time is before your start time, please input a new start time")
        outlet1_start()
    else:
        another_outlet()
def outlet8_start():
    global start8
    global ssTimes
    try:
        ssTimes["startTimes"]["start8"] = datetime.strptime(input("Start Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                start8 = datetime.strptime(ssTimes["startTimes"]["start8"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet8_start()
def outlet8_stop():
    global end8
    global ssTimes
    try:
        ssTimes["endTimes"]["end8"] = datetime.strptime(input("End Time HH:MM:SS format: "),"%H:%M:%S").strftime("%H:%M:%S")
        with open("times.txt","w") as f:
                s=json.dumps(ssTimes, f, ensure_ascii=False)
                f.write(s)
        with open("times.txt","r") as f:
                s=f.read()
                ssTimes=json.loads(s)
                end8 = datetime.strptime(ssTimes["endTimes"]["end8"],"%H:%M:%S").strftime("%H:%M:%S")
    except ValueError:
        print ("Not in valid date format, please try again ")
        outlet8_stop()
    if start8 > end8:
        print ("I'm sorry, your end time is before your start time, please input a new start time")
        outlet1_start()
    else:
        another_outlet()

# Main Loop
try:

    def main_loop():
        global ato_counter
        global ato_max
        #hour is equal to the current time in %H:%M:%S format
        hour = time.strftime("%T")
        def time_in_range(start,end,x):
            if start <= end:
                return start <= x <= end
            else:
                return start <= x or x <= end

        input_state = GPIO.input(17)

        while hour <= "23:59:59":
            print (time.strftime("%T"))
            if time_in_range(start1,end1,time.strftime("%T")):
                print ("Pin One is ON")
                #print (start1)
                #print (end1)
                GPIO.output(18, GPIO.LOW)
            else:
                print ("Pin one is OFF")
                #print (start1)
                #print (end1)
                GPIO.output(18, GPIO.HIGH)
            if time_in_range(start2,end2,time.strftime("%T")):
                print ("Pin two is ON")
                #print (start2)
                #print (end2)
                GPIO.output(23, GPIO.LOW)
            else:
                print ("Pin two is OFF")
                #print (start2)
                #print (end2)
                GPIO.output(23, GPIO.HIGH)
            if time_in_range(start3,end3,time.strftime("%T")):
                print ("Pin three is ON")
                #print (start3)
                #print (end3)
                GPIO.output(24, GPIO.LOW)
            else:
                print ("Pin three is OFF")
                #print (start3)
                #print (end3)
                GPIO.output(24, GPIO.HIGH)
            if time_in_range(start4,end4,time.strftime("%T")):
                print ("Pin four is ON")
                #print (start4)
                #print (end4)
                GPIO.output(25, GPIO.LOW)
            else:
                print ("Pin four is OFF")
                #print (start4)
                #print (end4)
                GPIO.output(25, GPIO.HIGH)
            if time_in_range(start5,end5,time.strftime("%T")):
                print ("Pin five is ON")
                #print (start5)
                #print (end5)
                GPIO.output(12, GPIO.LOW)
            else:
                print ("Pin five is OFF")
                #print (start5)
                #print (end5)
                GPIO.output(12, GPIO.HIGH)
            if time_in_range(start6,end6,time.strftime("%T")):
                print ("Pin six is ON")
                #print (start6)
                #print (end6)
                GPIO.output(16, GPIO.LOW)
            else:
                print ("Pin six is OFF")
                #print (start6)
                #print (end6)
                GPIO.output(16, GPIO.HIGH)
            if time_in_range(start7,end7,time.strftime("%T")):
                print ("Pin seven is ON")
                #print (start7)
                #print (end7)
                GPIO.output(20, GPIO.LOW)
            else:
                print ("Pin seven is OFF")
                #print (start7)
                #print (end7)
                GPIO.output(20, GPIO.HIGH)
            if time_in_range(start8,end8,time.strftime("%T")) & input_state == False & ato_counter < ato_max & ato_counter >= 0:
                print ("Pin eight is ON")
                #print (start8)
                #print (end8)
                print (ato_counter)
                print (ato_max)
                ato_counter += 1
                GPIO.output(21, GPIO.LOW)
            elif ato_counter > ato_max & input_state == False:
                ato_counter = -120
                print (ato_counter)
                GPIO.output(21, GPIO.HIGH)
            elif ato_counter < 0 & input_state == False or input_state == True:
                ato_counter += 1
                print (ato_counter)
                print ("counting")
                GPIO.output(21, GPIO.HIGH)
            else:
                print ("Pin eight is OFF")
                #print (start8)
                #print (end8)
                print (ato_counter)
                #print (input_state)
                ato_counter = 0
                GPIO.output(21, GPIO.HIGH)
            break

# End program cleanly

except KeyboardInterrupt:
    print ("Quit")
# Reset GPIO Pins
    GPIO.cleanup()

outlet_number()
try:
        while True:
            main_loop()
            time.sleep(1)
except KeyboardInterrupt:
        GPIO.cleanup()


#!/usr/bin/env python3

import subprocess
import sys
import pickle

salida_comando = []
file_name = "salida.p"

try:
    salida = pickle.load( open( file_name, "rb" ) )
except:
    salida = {}

try:
    p = subprocess.run(['pinky'], capture_output=True)
    salida_comando = p.stdout.decode().split("\n")

    if p.returncode !=0:
        print(p.stderr.decode())
        sys.exit(1)
except:
    sys.exit(1)
print(salida_comando)
# salida_comando=salida_comando[6:]

for line in salida_comando[1:-1]:
    print(line)
    line_split = line.split()
    login = line_split[0]
    fecha = line_split[-3]
    hora = line_split[-2]
    ip = line_split[-1]
    fecha_hora = " ".join([fecha,hora])
    if ip in salida:
        salida[ip].add(fecha_hora)
    else:
        salida[ip]=set([fecha_hora])

pickle.dump( salida, open( file_name, "wb" ) )
sys.exit(0)