# -*- coding: utf-8 -*-
from odoo import api, fields, models, _
from odoo.exceptions import UserError

import logging
import re

_logger = logging.getLogger(__name__)

class QuantProductRepackWizard(models.TransientModel):
    _name = 'quant.product.repack.wizard'
    _description = 'Repack Process by Product'

    product_id = fields.Many2one('product.product', string="Initial Product")
    location_id = fields.Many2one('stock.location', string="Location")
    lot_id = fields.Many2one('stock.production.lot', string="Lot")
    initial_qty = fields.Float(string="Initial Qty")
    main_qty = fields.Float(string="Main Lot Qty")
    product_dest_id = fields.Many2one('product.product', string="Destination Product")
    lot_dest_calculated = fields.Char(string='Destination Lot')
    lot_dest_id = fields.Many2one('stock.production.lot', string="Destination Lot")
    final_qty = fields.Float(string="Final Lot Qty")

    scrap_qty = fields.Float(string="Scrap Qty")

    @api.onchange('product_id', 'location_id')
    def _onchange_product_id(self):
        domain = [('lot_id', '!=', False), ('quantity', '>', 0)]
        if self.product_id:
            domain += [('product_id', '=', self.product_id.id)]
        if self.location_id:
            domain += [('location_id', '=', self.location_id.id)]
        lot_ids = [qt.lot_id.id for qt in self.env['stock.quant'].search(domain)]
        variant_ids = [pp.id for pp in self.product_id.product_variant_ids if pp != self.product_id]
        self.lot_id = False
        return {'domain': {'lot_id': [('id', 'in', lot_ids)],
                           'product_dest_id': [('id', 'in', variant_ids)]}}

    def _update_quantities(self, initial=0.0, main=0.0, final=0.0, scrap=0.0):
        self.initial_qty = initial
        self.main_qty = main
        #self.final_qty = final
        self.scrap_qty = scrap

    def _update_lot_name(self):
        """
        Return Custom Name for Lot
        """
        if self.lot_dest_id:
            self.lot_dest_calculated = self.lot_dest_id.name
        else:
            initial_name = ''
            final_name = ''
            for value in self.product_id.product_template_attribute_value_ids:
                initial_name = value.product_attribute_value_id.name
                break
            for value in self.product_dest_id.product_template_attribute_value_ids:
                final_name = value.product_attribute_value_id.name
                break
            if not initial_name or not final_name:
                raise UserError(
                    _('it is not possible to calculate the batch name because the product has no variant name'))
            self.lot_dest_calculated = self.lot_id.name.replace(initial_name, final_name) + 'R'

    @api.onchange('lot_id')
    def _onchange_lot_id(self):
        if self.lot_id and self.lot_dest_id:
            self._update_quantities(initial=self.lot_id.product_qty,
                                    main=self.lot_id.product_qty,
                                    final=self.lot_dest_id.product_qty)
            self._update_lot_name()
            return
        # Search First Lots and Lots Product Repack
        elif self.lot_id.type_lot == 'product_repack':
            self._update_quantities()
            # Update Correct Parent and child
            if self.lot_id.parent_lod_id:
                # Change lots
                ref = self.lot_id.parent_lod_id
                ref_dest = self.lot_id
                self.lot_id = ref
                self.lot_dest_id = ref_dest
                # Change Product Dest
                self.product_dest_id = self.lot_dest_id.product_id
                return self._onchange_lot_id()
            if self.lot_id.child_lot_ids:
                lot_pp_child = [lot for lot in self.lot_id.child_lot_ids if lot.type_lot == 'product_repack']
                if lot_pp_child:
                    self.lot_dest_id = lot_pp_child[0]
                    # Change Product Dest
                    self.product_dest_id = self.lot_dest_id.product_id
                    return self._onchange_lot_id()
        # Calculate Lot Child
        self._update_quantities(initial=self.lot_id.product_qty, main=self.lot_id.product_qty)

    @api.onchange('product_dest_id')
    def _onchange_product_dest_id(self):
        if self.product_id and self.product_dest_id and self.lot_id:
            self._update_lot_name()

    @api.onchange('final_qty', 'scrap_qty')
    def _onchange_final_qty(self):
        self.main_qty = self.initial_qty - self.final_qty - self.scrap_qty
        self._check_valid_quantity()

    def _get_sum_qty(self):
        return self.main_qty + self.final_qty + self.scrap_qty

    def _check_valid_quantity(self):
        if self.main_qty < 0:
            raise UserError('Invalid Quantity, Please Fix it !')

    def _get_dest_lot_from_child_ids(self):
        if self.lot_id.child_lot_ids:
            for lot in self.lot_id.child_lot_ids:
                if '#1' or '#2' not in lot.name:
                    return lot
        return False

    def get_or_creat_lot(self, vals):
        sql = """select id, name
                    from stock_production_lot
                    where name=%(name)s AND product_id = %(product_id)s"""
        self.env.cr.execute(sql, vals)
        result = self.env.cr.dictfetchone()
        if result:
            return self.env['stock.production.lot'].sudo().browse(result.get('id'))
        return self.env['stock.production.lot'].sudo().create(vals)

    def get_name_lot_from_variant(self, product_id):
        name = ''
        for attr in product_id.product_template_attribute_value_ids:
            name += attr.product_attribute_value_id.name
        return name

    def process_repack(self):
        _logger.info("Product Repack!!!")
        # _logger.info(self._get_sum_qty_lines())
        if self._get_sum_qty() > self.initial_qty:
            raise UserError('Invalid quantities, Please Fix it !')
        if self.final_qty < 0.0:
            raise UserError('Final quantity in repack lots cannot be 0, Please Fix it !')
        # Create Inventory Adjust
        val = {
            'name': 'Product_repacker_Assistance v %s' % (str(self.id)),
            'product_ids': [(4, self.product_id.id)],
            'location_ids': [(4, self.location_id.id)],
        }
        si = self.env['stock.inventory'].sudo().create(val)
        si.sudo().action_start()
        # Create Lots
        if self.lot_dest_id:
            self.lot_dest_id.write({'analytic_tag_ids': self.lot_id.analytic_tag_ids})
        lot_ids = [self.lot_id, self.lot_dest_id or self.get_or_creat_lot({'name': self.lot_dest_calculated,
                                                                           'product_id': self.product_dest_id.id,
                                                                           'company_id': self.location_id.company_id.id,
                                                                           'parent_lod_id': self.lot_id and self.lot_id.parent_lod_id and self.lot_id.parent_lod_id.id or self.lot_id.id,
                                                                           'analytic_tag_ids': self.lot_id.analytic_tag_ids,
                                                                           })]
        list_line_ids = [((0, 0, {
            'company_id': self.location_id.company_id.id,
            'prod_lot_id': lot_ids[0].id,
            'product_id': self.product_id.id,
            'location_id': self.location_id.id,
            'product_qty': self.main_qty + self.scrap_qty
        })), ((0, 0, {
            'company_id': self.location_id.company_id.id,
            'prod_lot_id': lot_ids[1].id,
            'product_id': self.product_dest_id.id,
            'location_id': self.location_id.id,
            'product_qty': lot_ids[1].product_qty + self.final_qty #aumentar lo que originalmente tiene
        }))]
        si.line_ids = False
        si.line_ids = list_line_ids
        # Write Type Lot
        lot_ids[0].type_lot = 'product_repack'
        lot_ids[1].type_lot = 'product_repack'
        si.sudo().action_validate()
        self._update_scrap_qty()

    def _update_scrap_qty(self):
        StockScrap = self.env['stock.scrap']
        if self.scrap_qty > 0:
            # Create Scrap
            ss = StockScrap.sudo().create({
                'product_id': self.product_id.id,
                'scrap_qty': self.scrap_qty,
                'lot_id': self.lot_id.id,
                'location_id': self.location_id.id,
                'product_uom_id': self.product_id.uom_id.id,
                'origin': 'WZRPACK{}'.format(self.lot_id.id)
            })

            ss.sudo().action_validate()


# Import the 'pika' library for RabbitMQ communication.
import pika
import time

from PIL import Image
from io import BytesIO
import base64

def callback(ch, method, properties, body):
    try:
        # Decode the image from base64 to binary format
        image_data = base64.b64decode(body)

        # Convert the binary image data to an image object
        image = Image.open(BytesIO(image_data))

        # Resize the image (e.g., to 50x50 pixels)
        resized_image = image.resize((50, 50))

        # Save the resized image locally
        resized_image.save('resized_image.jpg')

        print("Image successfully resized and saved as 'resized_image.jpg'")
    except Exception as e:
        print(f"Error processing the image: {e}")

def consume_image_from_queue():
    # Establish a connection to RabbitMQ
    url_params = pika.URLParameters('amqp://rabbit_mq?connection_attempts=10&retry_delay=10')

    connection = pika.BlockingConnection(url_params)
    channel = connection.channel()

    # Declare the queue for receiving images
    channel.queue_declare(queue='image_queue')

    # Set the callback function for image processing
    channel.basic_consume(queue='image_queue', on_message_callback=callback, auto_ack=True)

    print("Waiting for an image from the queue...")
    channel.start_consuming()

consume_image_from_queue()


import datetime
from models import db

class NoteModel(db.Model):
    #Table name for note
    __tablename__ = 'notes'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.String(1000), nullable=False)

    created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now())
    updated_at = db.Column(db.DateTime, nullable=True)

    def __init__(self, title, content, created_at):
        self.title = title
        self.content = content
        self.created_at = created_at

    def __repr__(self):
        return "<Note {}{}{}{}{}>".format(
            self.id, self.content, self.created_at, self.updated_at, self.updated_at
        )


from django.urls import path
from .views import CreateAccountView, UserListView, UserProfileView

app_name = 'users'

urlpatterns = [
    path('create-account/', CreateAccountView.as_view(), name='createAccount'),
    path('create/', CreateAccountView.as_view(), name='createAccount'),
    path('profile/', UserListView.as_view(), name = 'list'),
    path('profile/<int:pk>/', UserProfileView.as_view(), name = 'profile'),
    path('profile/<str:slug>/',UserProfileView.as_view(), name = 'profile'),
]


#import requests.
import requests

def requestSummonerData(region, summonerName, APIKey):

    #URL

    URL = "https://" + region + ".api.pvp.net/api/lol/" + region + "/v1.4/summoner/by-name/" + summonerName + "?api_key=" + APIKey
    print (URL)
    #requests.get . It basically goes to the URL we made and gives us back a JSON. Basicamente va a la URL creada y nos devuelve un JSON.
    response = requests.get(URL)
    #Retorna el JSON.
    return response.json()

def requestRankedData(region, ID, APIKey):
    URL = "https://" + region + ".api.pvp.net/api/lol/" + region + "/v2.5/league/by-summoner/" + ID + "/entry?api_key=" + APIKey
    print (URL)
    response = requests.get(URL)
    return response.json()

def main():
    print ("\Digita tu region para comenzar")
    print ("Digita una de las siguientes regiones, de lo contrario el programa no funcionara:\n")
    print ("NA EUW EUNE LAN BR KR LAS OCE TR RU PBE\n")

    #Se le pregunta al usuario tres cosas, la region, el nombre de invocador, y el API key.
    #Solo se necesitan esas tres cosas en ese orden para crear la URL y poder obtener el ID.

    region = (str(input('Digita una de las regiones: ')))
    summonerName = (str(input('Escribe tu nombre de invocador y NO INCLUYAS ESPACIOS NI MAYUSCULAS: ')))
    APIKey = (str(input('Copia y pega tu API key aqui: ')))

    #Devuelve un JSON.
    responseJSON  = requestSummonerData(region, summonerName, APIKey)

    ID = responseJSON[summonerName]['id']
    ID = str(ID)
    print (ID)
    responseJSON2 = requestRankedData(region, ID, APIKey)
    print (responseJSON2[ID][0]['tier'])
    print (responseJSON2[ID][0]['entries'][0]['division'])
    print (responseJSON2[ID][0]['entries'][0]['leaguePoints'])

#Comienza el programa!
if __name__ == "__main__":
    main()


# LeetCode 1293
import collections

class Solution:
    def shortestPath(self, grid, k: int) -> int:
        m, n = len(grid), len(grid[0])
        if m == 1 and n == 1:
            return 0

        k = min(k, m + n - 3)
        visited = set([(0, 0, k)])
        q = collections.deque([(0, 0, k)])

        step = 0
        while len(q) > 0:
            step += 1
            cnt = len(q)
            for _ in range(cnt):
                x, y, rest = q.popleft()
                for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                    nx, ny = x + dx, y + dy
                    if 0 <= nx < m and 0 <= ny < n:
                        if grid[nx][ny] == 0 and (nx, ny, rest) not in visited:
                            if nx == m - 1 and ny == n - 1:
                                return step
                            q.append((nx, ny, rest))
                            visited.add((nx, ny, rest))
                        elif grid[nx][ny] == 1 and rest > 0 and (nx, ny, rest - 1) not in visited:
                            q.append((nx, ny, rest - 1))
                            visited.add((nx, ny, rest - 1))
        return -1

mat = []
k = 0
while True:
    test = input()
    if len(test) <= 5:
        k = eval(test)
        break
    else:
        test = test[1:len(test) - 1]
        mat.append(eval(test))
s = Solution()
print(s.shortestPath(mat, k))


import flask
from Controllers.VideoGameController import VideoGameController
from Controllers.BookController import BookController
from Controllers.MovieController import MovieController
from Controllers.BoardGameController import BoardGameController
from Controllers.RPGController import RPGController
from Controllers.AnimeController import AnimeController
from Controllers.MusicController import MusicController
import concurrent.futures
import json

app = flask.Flask(__name__)
app.config['DEBUG'] = True

def init():
    controller_dict = {}
    controller_dict['books'] = BookController()
    controller_dict['movies'] = MovieController()
    controller_dict['video_game'] = VideoGameController()
    controller_dict['board_game'] = BoardGameController()
    controller_dict['rpg'] = RPGController()
    controller_dict['anime'] = AnimeController()
    controller_dict['music'] = MusicController()
    return controller_dict

controllers = init()

@app.route('/lookup/<media>/<title>', methods=['GET'])
def lookup_data(media, title):
    if media not in controllers:
        response = flask.jsonify('Invalid media type')
        response.status_code = 400
    else:
        lookup_response = controllers[media].lookup_entry(title)
        if('Exception' in lookup_response[0]):
            response = flask.jsonify(lookup_response[0]['Exception'])
            response.status_code = 500
        else:
            response = flask.jsonify(lookup_response)
    return response

@app.route('/lookup/bulk/<media>', methods=['GET'])
def bulk_lookup_data(media):
    if media not in controllers:
        response = flask.jsonify('Invalid media type')
        response.status_code = 400
    else:
        request_dict = flask.request.get_json()
        if "titles" not in request_dict:
            response = flask.jsonify("No titles found. Please insert titles as list under key \'titles\'")
            response.status_code = 400
        else:
            total_results = []
            picky = "picky" in request_dict and request_dict["picky"]
            with concurrent.futures.ThreadPoolExecutor() as executor:
                lookups = [executor.submit(controllers[media].lookup_entry, title, picky) for title in request_dict['titles']]
            for lookup in concurrent.futures.as_completed(lookups):
                total_results.append(lookup.result())
            response = flask.jsonify(total_results)
    return response

@app.route('/<media>/<key>', methods=['PUT'])
def put_entry(media, key):
    if media not in controllers:
        response = flask.jsonify('Invalid media type')
        response.status_code = 400
    else:
        if(controllers[media].put_key(key)):
            response = flask.jsonify('Key {} successfully inserted'.format(key))
        else:
            response = flask.jsonify('Insert failed')
            response.status_code = 500
    return response

@app.route('/<media>/bulk', methods=['PUT'])
def put_entries_bulk(media):
    if media not in controllers:
        response = flask.jsonify('Invalid media type')
        response.status_code = 400
    else:
        request_dict = flask.request.get_json()
        total_inserts = len(request_dict['keys'])
        successful_inserts = 0
        with concurrent.futures.ThreadPoolExecutor() as executor:
            inserts = [executor.submit(controllers[media].put_key, key) for key in request_dict['keys']]
        for insert in concurrent.futures.as_completed(inserts):
            if insert:
                successful_inserts += 1
        response = flask.jsonify("{} out of {} keys successfully submitted".format(successful_inserts, total_inserts))
    return response

@app.route('/<media>/<key>', methods=['GET'])
def get_entry(media, key):
    if media not in controllers:
        response = flask.jsonify('Invalid media type')
        response.status_code = 400
    else:
        lookup_result = controllers[media].get_key(key)
        if(lookup_result['status'] != 'FAIL'):
            response = flask.jsonify(lookup_result['item'])
        else:
            response = flask.jsonify(lookup_result['error_message'] if 'error_message' in lookup_result else "Lookup failed")
            response.status_code = 500
    return response

@app.route('/<media>/<key>', methods=['DELETE'])
def delete_entry(media, key):
    if media not in controllers:
        response = flask.jsonify('Invalid media type')
        response.status_code = 400
    else:
        lookup_result = controllers[media].delete_key(key)
        if(lookup_result['status'] != 'FAIL'):
            response = flask.jsonify(lookup_result['item'])
        else:
            response = flask.jsonify(lookup_result['error_message'] if 'error_message' in lookup_result else "Lookup failed")
            response.status_code = 500
    return response

@app.route('/<media>', methods=['GET'])
def get_table(media):
    if media not in controllers:
        response = flask.jsonify('Invalid media type')
        response.status_code = 400
    else:
        lookup_result = controllers[media].get_table()
        if('Items' in lookup_result and 'error_message' not in lookup_result):
            response = flask.jsonify(lookup_result['Items'])
        else:
            response = flask.jsonify(lookup_result['error_message'] if 'error_message' in lookup_result else "Lookup failed")
            response.status_code = 500
    return response

def call_backup(controller):
    return controllers[controller].back_up_table()

@app.route('/backup', methods=['PUT'])
def backup_tables():
    response = {'failed_backups': 0, 'successful_backups': 0, 'error_messages': []}
    try:
        with concurrent.futures.ThreadPoolExecutor() as executor:
            backup_results = [executor.submit(call_backup, controller) for controller in controllers]
        for controller_response in concurrent.futures.as_completed(backup_results):
            result_body = controller_response.result()
            print("Received response for controller {}".format(result_body))
            if(result_body['status'] == 'FAIL'):
                response['failed_backups'] += 1
                response['error_messages'].append({'Controller': result_body['controller'], 'error_message': result_body['error_message']})
            else:
                response['successful_backups'] += 1
        json_response = flask.jsonify(response)
    except Exception as e:
        print("Exception while backing up tables: {}".format(e))
        response['error_message'] = str(e)
        json_response = flask.jsonify(response)
        json_response.status_code = 500
    return json_response

def call_restore(controller):
    return controllers[controller].back_up_table()

@app.route('/restore', methods=['PUT'])
def restore_tables():
    response = {'failed_restores': 0, 'successful_restores': 0, 'error_messages': []}
    try:
        with concurrent.futures.ThreadPoolExecutor() as executor:
            restore_results = [executor.submit(call_restore, controller) for controller in controllers]
        for controller_response in concurrent.futures.as_completed(restore_results):
            result_body = controller_response.result()
            print("Received response for controller {}".format(result_body))
            if(result_body['status'] == 'FAIL'):
                response['failed_restores'] += 1
                response['error_messages'].append({'Controller': result_body['controller'], 'error_message': result_body['error_message']})
            else:
                response['successful_restores'] += 1
        json_response = flask.jsonify(response)
    except Exception as e:
        print("Exception while backing up tables: {}".format(e))
        response['error_message'] = str(e)
        json_response = flask.jsonify(response)
        json_response.status_code = 500

@app.route('/lib-compare/<media>', methods=['GET'])
@app.route('/lib-compare/<media>/<key>', methods=['GET'])
def lookup_in_library(media, key=None):
    if media != 'books':
        response = flask.jsonify('Invalid media type')
        response.status_code(400)
    elif not key:
        table_get_result = controllers[media].get_table()
        if('Items' in table_get_result and 'error_message' not in table_get_result):
            items = table_get_result['Items']

            with concurrent.futures.ThreadPoolExecutor() as executor:
                lookup_results = [executor.submit(controllers[media].library_compare, key) for key in [item['original_guid'] for item in items]]

            results = {"lookup_results": []}
            for controller_response in concurrent.futures.as_completed(lookup_results):
                results['lookup_results'].append(controller_response.result())
            response = flask.jsonify(results)
        else:
            response = flask.jsonify(lookup_result['error_message'] if 'error_message' in lookup_result else "Lookup failed")
            response.status_code = 500
    else:
        lookup_result = controllers[media].library_compare(key)
        if(lookup_result['status'] != 'FAIL'):
            response = flask.jsonify(lookup_result)
        else:
            response = flask.jsonify(lookup_result['error_message'] if 'error_message' in lookup_result else 'Lookup failed')
            response.status_code = 500
    return response
"""
@app.route('/<media>')
def clear_table(media) """


#!/usr/bin/env python

import re
import os
import argparse
import logging

mrc_header = """[COURSE HEADER]
VERSION = 2
UNITS = ENGLISH
DESCRIPTION = Sample
FILE NAME = sample.mrc
MINUTES PERCENT
[END COURSE HEADER]
[COURSE DATA]
"""

mrc_trailer = """[END COURSE DATA]"""

zone_to_percent = {
    'lz1': 45, 'z1': 50, 'hz1': 55,
    'lz2': 58, 'z2': 65, 'hz2': 73,
    'lz3': 78, 'z3': 82, 'hz3': 88,
    'lz4': 93, 'z4': 98, 'hz4': 103,
    'lz5': 107, 'z5': 108, 'hz5': 118,
    'z5+': 130, 'max': 150
}

range_to_zones = {
    'z1>z2': ('z1', 'z2'),
    'z1>z3': ('z1', 'z3'),
    'z1>z4': ('z1', 'z4'),
    'z2>z1': ('z2', 'z1'),
    'z3>z1': ('z3', 'z1')
}

class WorkoutParser:

    def __init__(self, workout):
        self.workout = workout
        self.sm = {
            'SINGLE_STEP': self.parse_single_step,
            'REPEAT_BLOCK': self.parse_repeat_block
        }
        self.cur_state = 'SINGLE_STEP'
        self.steps = []
        self.repeat_count = 0
        self.torepeat = []

    def parse(self):
        lines = [line.lower() for line in self.workout.split('\n') if line]
        for line in lines:
            if re.search('^#', line):
                continue
            self.parseline(line)
        return self.steps

    def parseline(self, line):
        self.sm[self.cur_state](line)

    def parse_single_step(self, line):
        mobj = re.search('repeat\s+([\d]+):', line)
        if mobj:
            self.repeat_count = int(mobj.group(1))
            self.cur_state = 'REPEAT_BLOCK'
            return

        mobj = re.search('^([\d.]+)\s+([\w><]+)', line)
        if mobj:
            self.steps.append((mobj.group(1), mobj.group(2)))

    def parse_repeat_block(self, line):
        mobj = re.search('\s+([\d.]+)\s+([\w><]+)', line)
        if mobj:
            self.torepeat.append((mobj.group(1), mobj.group(2)))
            return

        mobj = re.search('^([\d.]+)\s+([\w><]+)', line)
        if mobj:
            self.insert_repeat_steps()
            self.cur_state = 'SINGLE_STEP'
            self.parse_single_step(line)

    def insert_repeat_steps(self):
        self.steps += self.torepeat * self.repeat_count
        self.torepeat = []
        self.repeat_count = 0

class MrcGenerator:

    def __init__(self, workout):
        self.body = ''
        self.workout = workout

    def generate(self, workout):
        self.generate_header()
        self.generate_body()
        self.generate_trailer()
        return self.body

    def generate_header(self):
        self.body += mrc_header

    def generate_trailer(self):
        self.body += mrc_trailer

    def generate_body(self):
        start = 0
        for step in self.workout:
            duration = float(step[0])
            if step[1] in range_to_zones:
                zones = range_to_zones[step[1]]
                self.body_block(start, duration, zones[0], zones[1])
                start += duration
            else:
                self.body_block(start, duration, step[1], step[1])
                start += duration

    def body_line(self, start, percent):
        return "%0.2f\t%d\n" % (start, percent)

    def body_block(self, start, duration, start_zone, end_zone):
        self.body += self.body_line(start, zone_to_percent[start_zone])
        self.body += self.body_line(start + duration,
                                    zone_to_percent[end_zone])

def generate_mrc(name, workout):
    p = WorkoutParser(workout)
    g = MrcGenerator(p.parse())
    return g.generate(workout)

def mrc_filename(in_filename):
    return os.path.splitext(in_filename)[0] + '.mrc'

def write_mrc_file(filename, mrc):
    with open(filename, 'w') as outf:
        outf.write(mrc)

def main():
    parser = argparse.ArgumentParser(description="MRC File Generator")
    parser.add_argument('-v', '--verbose', action='store_true',
                        help="Verbose output")
    parser.add_argument('--ftp', type=int,
                        help='Users functional threshold power')
    parser.add_argument('--type', choices=['mrc', 'erg'], default='mrc')
    parser.add_argument('workout', type=argparse.FileType('r'))

    args = parser.parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.INFO)

    mrc = generate_mrc('Sample', args.workout.read())
    write_mrc_file(mrc_filename(args.workout.name), mrc)

if __name__ == "__main__":
    main()


from typing import Iterable, List, Optional, Set, Tuple, Union

DeltaPosition = Optional[int]
NumericDeltaPosition = Union[int, float]  # float is added here to support math.inf
DeltaRange = Tuple[DeltaPosition, DeltaPosition]

def merge_intervals(intervals: Set[DeltaRange]) -> Set[DeltaRange]:
    """Merges a set of N input intervals into a minimal number of output intervals.

    All input intervals will be merged into a minimal number of output intervals in O(N log N) time.

    Example:
        >>> merge_intervals((3, 9), (8, 12), (15, 19))
        ((3, 12), (15, 19))

    Example:
        >>> merge_intervals((3, 9), (None, 15), (13, 30))
        ((None, 30))

    Args:
        intervals: A list of intervals with an int type representing finite, closed bounded values and
            a None type representing infinity.

    Returns:
        A minimal number of output intervals
    """
    merged: Set[DeltaRange] = set()
    intervals_list: List[DeltaRange] = list(intervals)

    if len(intervals_list) == 0:
        return merged

    _to_numeric_values(intervals_list)
    intervals_list.sort()  # sort by starting range numbers

    merge_start, merge_end = None, None
    for interval in intervals_list:
        start, end = interval
        if start > end:
            raise ValueError(
                f"Invalid stream position range interval: ({start}, {end})"
            )

        if merge_start is None and merge_end is None:
            merge_start, merge_end = start, end
            continue

        if merge_end < start:
            # add current merge interval if no overlap, begin new interval
            _add_merged_interval(merged, merge_start, merge_end)
            merge_start, merge_end = start, end
        elif merge_end < end:
            merge_end = end  # expand current merge interval if there is an overlap

    # add final merge interval
    _add_merged_interval(merged, merge_start, merge_end)

    return merged

def _add_merged_interval(
    result_set: set, start: NumericDeltaPosition, end: NumericDeltaPosition
):
    start_pos: DeltaPosition = start if isinstance(start, int) else None
    end_pos: DeltaPosition = end if isinstance(end, int) else None
    result_set.add((start_pos, end_pos))

def _to_numeric_values(intervals_list: List[DeltaRange]):
    for i, interval in enumerate(intervals_list):
        start, end = _get_validated_interval(interval)
        if start is None:
            start = float("-inf")
        if end is None:
            end = float("inf")

        intervals_list[i] = (start, end)

def _get_validated_interval(interval: DeltaRange) -> DeltaRange:
    if not isinstance(interval, Iterable) or len(interval) != 2:
        raise ValueError(f"Interval {interval} must be a tuple of size 2")

    start, end = interval
    if not (isinstance(start, int) or start is None) or not (
        isinstance(end, int) or end is None
    ):
        raise ValueError(
            f"Invalid stream position value types: "
            f"({start}, {end}) - ({type(start), type(end)})"
        )

    return start, end


from tqdm import tqdm
import os, sys, pdb

"""Alter the names of everything in a directory based on current strings"""

if os.path.abspath('.../my_utils') not in sys.path: sys.path.insert(1, os.path.abspath('.../my_utils'))

from my_os import recursive_file_retrieval

_, all_fps = recursive_file_retrieval('/homes/bdoc3/my_data/world_vocoder_data/vctk')
all_fps = [p for p in all_fps if p.endswith('npy')]

pdb.set_trace()
for i, p in tqdm(enumerate(all_fps)):
    print(i)
    if p.endswith('npy.npy'):
        pdb.set_trace()
        new_p = p[:-7] +'.npy'
        os.rename(p, new_p)


import contextlib
import os
import threading

import redis

class HotClient(redis.Redis):
    """
    A Redis client wrapper that loads Lua functions and creates
    client methods for calling them.
    """

    def __init__(self, *args, **kwargs):
        kwargs.setdefault("decode_responses", True)
        super(HotClient, self).__init__(*args, **kwargs)
        requires_luabit = ("number_and", "number_or", "number_xor",
                           "number_lshift", "number_rshift")
        with open(self._get_lua_path("bit.lua")) as f:
            luabit = f.read()
        for name, snippet in self._get_lua_funcs():
            if name in requires_luabit:
                snippet = luabit + snippet
            self._create_lua_method(name, snippet)

    def _get_lua_path(self, name):
        """
        Joins the given name with the relative path of the module.
        """
        parts = (os.path.dirname(os.path.abspath(__file__)), "lua", name)
        return os.path.join(*parts)

    def _get_lua_funcs(self):
        """
        Returns the name / code snippet pair for each Lua function
        in the atoms.lua file.
        """
        with open(self._get_lua_path("atoms.lua")) as f:
            for func in f.read().strip().split("function "):
                if func:
                    bits = func.split("\n", 1)
                    name = bits[0].split("(")[0].strip()
                    snippet = bits[1].rsplit("end", 1)[0].strip()
                    yield name, snippet

    def _create_lua_method(self, name, code):
        """
        Registers the code snippet as a Lua script, and binds the
        script to the client as a method that can be called with
        the same signature as regular client methods, eg with a
        single key arg.
        """
        script = self.register_script(code)
        setattr(script, "name", name)  # Helps debugging redis lib.
        method = lambda key, *a, **k: script(keys=[key], args=a, **k)
        setattr(self, name, method)

_thread = threading.local()
_config = {}

def default_client():
    try:
        _thread.client
    except AttributeError:
        setattr(_thread, "client", HotClient(**_config))
    return _thread.client

def configure(**config):
    global _config
    _config = config

@contextlib.contextmanager
def transaction():
    """
    Swaps out the current client with a pipeline instance,
    so that each Redis method call inside the context will be
    pipelined. Once the context is exited, we execute the pipeline.
    """
    client = default_client()
    _thread.client = client.pipeline()
    try:
        yield
        _thread.client.execute()
    finally:
        _thread.client = client


import platform
import cpuinfo
import socket
import os

# System class
class System:
    #Constructor method
    def init(self):
        self.system = platform.system()
        self.architecture = platform.architecture()
        self.processor = cpuinfo.get_cpu_info()["brand_raw"]
        self.hostname = socket.gethostname()
        self.ip = socket.gethostbyname(self.hostname)
        self.username = os.getlogin()

    # to_array method to return a python dictionary with all the variables of the constructor
    def to_dict(self):
        return {
            "system": self.system,
            "architecture": self.architecture,
            "cpu": self.processor,
            "hostname": self.hostname,
            "ip_address": self.ip,
            "user": self.username
        }


from __future__ import print_function
import argparse
import os
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import torch.multiprocessing as mp
from torchvision import datasets, transforms
from tensorboardX import GlobalSummaryWriter

# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
                    help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
                    help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=2, metavar='N',
                    help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
                    help='learning rate (default: 0.01)')
parser.add_argument('--momentum', type=float, default=0.5, metavar='M',
                    help='SGD momentum (default: 0.5)')
parser.add_argument('--seed', type=int, default=1, metavar='S',
                    help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
                    help='how many batches to wait before logging training status')
parser.add_argument('--num-processes', type=int, default=2, metavar='N',
                    help='how many training processes to use (default: 2)')
parser.add_argument('--cuda', action='store_true', default=False,
                    help='enables CUDA training')

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
        self.conv2_drop = nn.Dropout2d()
        self.fc1 = nn.Linear(320, 50)
        self.fc2 = nn.Linear(50, 10)

    def forward(self, x):
        x = F.relu(F.max_pool2d(self.conv1(x), 2))
        x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
        x = x.view(-1, 320)
        x = F.relu(self.fc1(x))
        x = F.dropout(x, training=self.training)
        x = self.fc2(x)
        return F.log_softmax(x, dim=1)

def train(rank, args, model, device, dataloader_kwargs):
    torch.manual_seed(args.seed + rank)

    train_loader = torch.utils.data.DataLoader(
        datasets.MNIST('../data', train=True, download=True,
                    transform=transforms.Compose([
                        transforms.ToTensor(),
                        transforms.Normalize((0.1307,), (0.3081,))
                    ])),
        batch_size=args.batch_size, shuffle=True, num_workers=1,
        **dataloader_kwargs)

    optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)
    for epoch in range(1, args.epochs + 1):
        train_epoch(epoch, args, model, device, train_loader, optimizer)

def train_epoch(epoch, args, model, device, data_loader, optimizer):
    model.train()
    pid = os.getpid()
    for batch_idx, (data, target) in enumerate(data_loader):
        optimizer.zero_grad()
        output = model(data.to(device))
        loss = F.nll_loss(output, target.to(device))
        loss.backward()
        optimizer.step()
        if batch_idx % args.log_interval == 0:
            writer.add_scalar("Loss", loss)
            print('{}\tTrain Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                pid, epoch, batch_idx * len(data), len(data_loader.dataset),
                100. * batch_idx / len(data_loader), loss.item()))

writer = GlobalSummaryWriter()

if __name__ == '__main__':
    args = parser.parse_args()

    use_cuda = args.cuda and torch.cuda.is_available()
    device = torch.device("cuda" if use_cuda else "cpu")
    dataloader_kwargs = {'pin_memory': True} if use_cuda else {}

    torch.manual_seed(args.seed)
    # mp.set_start_method('spawn')

    model = Net().to(device)
    model.share_memory() # gradients are allocated lazily, so they are not shared here
    processes = []
    for rank in range(args.num_processes):
        p = mp.Process(target=train, args=(rank, args, model, device, dataloader_kwargs))
        # We first train the model across `num_processes` processes
        p.start()
        processes.append(p)
    for p in processes:
        p.join()


import numpy as np
import matplotlib.pyplot as plt

# %matplotlib inline
X = [0,0.12,0.25,0.27,0.38,0.42,0.44,0.55,0.92,1.0]
Y = [0,0.15,0.54,0.51, 0.34,0.1,0.19,0.53,1.0,0.58]

#uncomment to see a plot of X versus Y values
#plt.plot(X,Y)
#plt.show()

costs = []
#Step 1: Parameter initialization
W = 0.45
b = 0.75

epochs = 100
lr = 0.001

for j in range(1, epochs):
  for i in range(1, 100):
    #Step 2: Calculate Cost
    Y_pred = np.multiply(W, X) + b
    Loss_error = 0.5 * (Y_pred - Y)**2
    cost = np.sum(Loss_error)/10

    #Step 3: Calculate dW and db
    db = np.sum((Y_pred - Y))
    dw = np.dot((Y_pred - Y), X)
    costs.append(cost)

    #Step 4: Update parameters:
    W = W - lr*dw
    b = b - lr*db

    if i%50 == 0:
      print("Cost at epoch", j,"= ", cost)

#Plot cost versus # of iterations
print("W = ", W,"& b = ",  b)
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.show()

books/Machine Learning/Python for TensorFlor Pocket Primer supp/code/chapter2/plain-linreg2.py


import argparse
import base64
import time
from io import BytesIO
from PIL import Image

from config import auto_timeout, image_depth, trial_laps
from pilot import Autopilot
from client import Client
from sim_recorder import SimRecorder

class AutoClient(Client):

    def __init__(self, address, conf, poll_socket_sleep_time=0.01):
        self.pilot = Autopilot(conf)
        self.mode = conf['mode']
        self.current_image = None
        self.current_telem = None
        self.fresh_data = False
        self.later_lap_sum = 0

        # give time for the autopilot to start up
        # time.sleep(1)

        super().__init__(address, conf=conf, poll_socket_sleep_time=poll_socket_sleep_time)
        if self.mode == 'train':
            self.recorder = SimRecorder(conf)
            self.braking = 0.0
        if self.mode == 'trial':
            self.trial_times = []

        # time.sleep(1)

        # only holds at the starting line if there's a race
        self.driving = self.mode in ['train', 'trial']

        # keep from rolling forward while setting up
        self.send_controls(0.0, 0.0, 1.0)

    def on_telemetry(self, data):
        # print(f"{data['time'] = }")
        self.check_progress(data) # no longer needed since Race Edition v22.05.30
        self.update_telemetry(data)
        if self.mode == 'train':
            data['brake'] = self.braking
            data['lap'] = self.current_lap
            self.recorder.record(data)

    def update_telemetry(self, data):
        # decode image
        if image_depth  == 1:
            self.current_image = Image.open(
                BytesIO(base64.b64decode(data['image']))).getchannel(image_depth)
        else:
            self.current_image = Image.open(
                BytesIO(base64.b64decode(data['image'])))
            # add specified telemetry from json
        if 'first_lap' in self.pilot.telemetry_columns:
            data['first_lap'] = self.current_lap == 1
        self.current_telem = [data[x] for x in self.pilot.telemetry_columns]
        self.fresh_data = True
        if self.mode == 'train':
            self.check_reset(data['time'], data['hit'])

    def check_reset(self, time_stamp, hit):
        if self.lap_start:
            lap_elapsed = time.time() - self.lap_start
            timed_out = lap_elapsed > auto_timeout
            # print(lap_elapsed)
            crashed = hit != 'none'
            if timed_out: # or crashed:
                print(f"{'Auto timeout' * timed_out}{'Crashed!' * crashed}")
                self.reset_car = True
                # self.stop()

    def update(self):
        steering, throttle, brake = 0.0, 0.0, 0.0
        if not self.current_image:
            print("Waiting for first image")
            self.driving = False
            # return
        if self.fresh_data:
            inputs = self.current_image, self.current_telem
            steering, throttle, brake = self.pilot.infer(inputs)
            if brake < 0.01:
                brake = 0
            self.fresh_data = False
        if not self.driving:
            steering, throttle, brake = 0.0, 0.0, 1.0
        if self.mode == 'train':
            self.braking = brake
        self.send_controls(steering, throttle, brake)

    def on_full_lap(self, lap_time):
        dirty_lap = self.hit_count > 0
        print(f"Lap {self.current_lap}: {lap_time:.2f}", end="")
        if self.hit_count > 0:
            print('*', end="")
        if self.current_lap > 1:
            self.later_lap_sum += lap_time
            later_lap_avg = self.later_lap_sum / (self.current_lap - 1)
            print(f" | avg: {later_lap_avg:.3f}", end="")
        self.print_fastest_lap(lap_time)
        if self.mode == 'trial' and self.current_lap <= trial_laps:
            self.trial_times.append(lap_time)
            if self.current_lap > 1:
                self.print_trial_times(dirty_lap)

    def print_trial_times(self, dirty_lap):
        print('trial times: ', end='')
        for n, t in enumerate(self.trial_times):
            print(f'{t:.2f}' + ('*' * dirty_lap) + (',' * (n < (len(self.trial_times) - 1))), end=' ')
        trial_avg = sum(self.trial_times[1:])/(len(self.trial_times)-1)
        print(f'| {trial_avg:.3f}')

# Create client and connect it with the simulator
def run_client(conf):
    host = conf["host"]
    port = conf["port"]
    client = AutoClient(address=(host, port), conf=conf,)

    # msg = '{ "msg_type" : "exit_scene" }'
    # client.send(msg)
    time.sleep(0.5)

    # time.sleep(2)

    # Load Track
    msg = f'{{"msg_type" : "load_scene", "scene_name" : "{conf["track"]}"}}'
    client.send(msg)
    time.sleep(1.0)
    # doesn't work when this isn't here
    # Configure Car
    client.send_config()
    time.sleep(1.0)

    # Drive car
    run_sim = True
    refresh_sim = False
    while run_sim:
        try:
            client.update()
            if client.aborted:
                # print("Client aborted, stopping driving.")
                run_sim = False
            if client.reset_car:
                # print("Refreshing sim")
                refresh_sim = True
                run_sim = False
            if not client.driving:
                _ = input('press Enter to start driving')
                client.driving = True
        except KeyboardInterrupt:
            run_sim = False
        time.sleep(0.1)

    # msg = '{ "msg_type" : "exit_scene" }'
    # client.send(msg)
    # time.sleep(0.5)

    # Close down client
    # print("waiting for msg loop to stop")
    client.stop()
    return refresh_sim

if __name__ == "__main__":

    track_list = [
        'generated_road',
        'warehouse',
        'sparkfun_avc',
        'generated_track',
        'roboracingleague_1',
        'waveshare',
        'mini_monaco',
        'warren',
        'circuit_launch',
        'mountain_track'
        ]

    parser = argparse.ArgumentParser(description="donkeysim_client")
    parser.add_argument("--host",
                        type=str,
                        # default="127.0.0.1",
                        default="donkey-sim.roboticist.dev",
                        help="host to use for tcp",)
    parser.add_argument("--port",
                        type=int,
                        default=9091,
                        help="port to use for tcp",)
    parser.add_argument("--track",
                        type=str,
                        default="sparkfun_avc",
                        help="name of donkey sim environment",
                        choices=track_list,)
    parser.add_argument("--model_number",
                        type=int,
                        default=None,
                        help='model number for pilot')
    parser.add_argument("--mode",
                        type=str,
                        default="trial",
                        help="autonomous driving mode",
                        choices=['race', 'train', 'trial']
                        )

    args = parser.parse_args()
    conf = {
        "host": args.host,
        "port": args.port,
        "mode": args.mode,
        "track": args.track,
        "model_number": args.model_number,
        "record_format": 'CSV', # None, 'CSV', 'tub' (Donkey Car), 'ASL' (openvslam)
        "image_format": 'PNG', # 'JPG', 'PNG', 'TGA'
        "image_depth": 1, # 1:'grayscale', 3:'rgb'
        "telem_type": 'donkey_extended_brake' # 'donkey_basic', 'donkey_extended_brake', 'gym'
    }
    while True:
        refresh = run_client(conf)
        if not refresh:
            break
        # time.sleep(3)
    print("client stopped")


import collections
import itertools
import traceback
import sys
from gnocchiclient import auth
from config import Config
from gnocchiclient.v1 import client
from gnocchiclient import exceptions
from keystoneauth1 import session
import operator
import ConfigParser
import time
import json
class Gnocchi(object):
    def config(self):
        self.conf  = ConfigParser.ConfigParser()
        self.conf.read("amqp-gnocchi.conf")

    def init(self):
        auth_plugin = auth.GnocchiBasicPlugin(user="admin",endpoint="http://localhost:8041")
        self.g= client.Client(session_options={'auth': auth_plugin})
        self._resource_type = "qpid_amqp"
        try:
            self.g.resource_type.get(self._resource_type)
        except exceptions.ResourceTypeNotFound:
            self.g.resource_type.create({
                "name": self._resource_type,
                "attributes": {
                    "host": {
                        "required": True,
                        "type": "string",
                    },
                },
            })

    @staticmethod
    def _serialize_identifier(index, v):
        """Based of FORMAT_VL from collectd/src/daemon/common.h.
        The biggest difference is that we don't prepend the host and append the
        index of the value, and don't use slash.
        """
        return (v["plugin"] + ("-" + v["plugin_instance"]
                            if v["plugin_instance"] else "")
                + "@"
                + v["type"] + ("-" + v["type_instance"]
                            if v["type_instance"] else "")
                + "-" + str(index))

    def _ensure_resource_exists(self, host_id, host):
        attrs = {"id": host_id, "host": host}
        try:
            try:
                self.g.resource.create(self._resource_type, attrs)
            except exceptions.ResourceTypeNotFound:
                self._ensure_resource_type_exists()
                self.g.resource.create(self._resource_type, attrs)
        except exceptions.ResourceAlreadyExists:
            pass

    def _ensure_resource_type_exists(self):
        try:
            self.g.resource_type.create({
                "name": self._resource_type,
                "attributes": {
                    "host": {
                        "required": True,
                        "type": "string",
                    },
                },
            })
        except exceptions.ResourceTypeAlreadyExists:
            pass

    def write(self, metric_values):
        parsed_json=json.loads(metric_values)
        host_id = "qpid_amqp:" + parsed_json[0]["host"].replace("/", "_")
        host=parsed_json[0]["host"]
        measures = {host_id: collections.defaultdict(list)}
        i=0
        for value in parsed_json[0]["values"]:
            measures[host_id][self._serialize_identifier(i,parsed_json[0])].append({"timestamp":parsed_json[0]["time"],"value":value,})
            i+=1
        try:
            print(measures)
            self.g.metric.batch_resources_metrics_measures(
            measures, create_metrics=True)
        except exceptions.BadRequest:
            # Create the resource and try again
            self._ensure_resource_exists(host_id, host)
            self.g.metric.batch_resources_metrics_measures(
            measures, create_metrics=True)


from collections import deque
import sys

n , m = map(int, sys.stdin.readline().strip().split())
maze = []
for i in range(n):
    maze.append(list(map(int,sys.stdin.readline().strip())))

def bfs(i,j):
    global n
    global m
    queue = deque()
    queue.append([i,j,1])
    while queue:
        now = queue.popleft()
        if now[0] == n-1 and now[1] == m-1: #목적지에 도착했을 때 함수 종료
            return now[2]

        if not now[1] == m-1 :
            if maze[now[0]][now[1]+1] == 1:
                queue.append([now[0],now[1]+1,now[2]+1])
                maze[now[0]][now[1]+1] = 0

        if not now[0] == n-1 :
            if maze[now[0]+1][now[1]] == 1:
                queue.append([now[0]+1,now[1],now[2]+1])
                maze[now[0]+1][now[1]] = 0

        if not now[1] == 0 :
            if  maze[now[0]][now[1]-1] == 1:
                queue.append([now[0],now[1]-1,now[2]+1])

        if not now[0] == 0 :
            if  maze[now[0]-1][now[1]] == 1:
                queue.append([now[0]-1,now[1],now[2]+1])
                maze[now[0]-1][now[1]] = 0

print(bfs(0,0))


from __future__ import absolute_import, division, print_function
__metaclass__ = type

DOCUMENTATION = '''
---
module: cs_zone
short_description: Manages zones on Apache CloudStack based clouds.
description:
    - Create, update and remove zones.
author: René Moser (@resmo)
version_added: 0.1.0
options:
  name:
    description:
      - Name of the zone.
    type: str
    required: true
  id:
    description:
      - uuid of the existing zone.
    type: str
  state:
    description:
      - State of the zone.
    type: str
    default: present
    choices: [ present, enabled, disabled, absent ]
  domain:
    description:
      - Domain the zone is related to.
      - Zone is a public zone if not set.
    type: str
  network_domain:
    description:
      - Network domain for the zone.
    type: str
  network_type:
    description:
      - Network type of the zone.
    type: str
    default: Basic
    choices: [ Basic, Advanced ]
  dns1:
    description:
      - First DNS for the zone.
      - Required if I(state=present)
    type: str
  dns2:
    description:
      - Second DNS for the zone.
    type: str
  internal_dns1:
    description:
      - First internal DNS for the zone.
      - If not set I(dns1) will be used on I(state=present).
    type: str
  internal_dns2:
    description:
      - Second internal DNS for the zone.
    type: str
  dns1_ipv6:
    description:
      - First DNS for IPv6 for the zone.
    type: str
  dns2_ipv6:
    description:
      - Second DNS for IPv6 for the zone.
    type: str
  guest_cidr_address:
    description:
      - Guest CIDR address for the zone.
    type: str
  dhcp_provider:
    description:
      - DHCP provider for the Zone.
    type: str
  local_storage_enabled:
    description:
      - Whether to enable local storage for the zone or not..
    type: bool
  securitygroups_enabled:
    description:
      - Whether the zone is security group enabled or not.
    type: bool
extends_documentation_fragment:
- ngine_io.cloudstack.cloudstack
'''

EXAMPLES = '''
- name: Ensure a zone is present
  ngine_io.cloudstack.cs_zone:
    name: ch-zrh-ix-01
    dns1: 8.8.8.8
    dns2: 8.8.4.4
    network_type: basic

- name: Ensure a zone is disabled
  ngine_io.cloudstack.cs_zone:
    name: ch-zrh-ix-01
    state: disabled

- name: Ensure a zone is enabled
  ngine_io.cloudstack.cs_zone:
    name: ch-zrh-ix-01
    state: enabled

- name: Ensure a zone is absent
  ngine_io.cloudstack.cs_zone:
    name: ch-zrh-ix-01
    state: absent
'''

RETURN = '''
---
id:
  description: UUID of the zone.
  returned: success
  type: str
  sample: 04589590-ac63-4ffc-93f5-b698b8ac38b6
name:
  description: Name of the zone.
  returned: success
  type: str
  sample: zone01
dns1:
  description: First DNS for the zone.
  returned: success
  type: str
  sample: 8.8.8.8
dns2:
  description: Second DNS for the zone.
  returned: success
  type: str
  sample: 8.8.4.4
internal_dns1:
  description: First internal DNS for the zone.
  returned: success
  type: str
  sample: 8.8.8.8
internal_dns2:
  description: Second internal DNS for the zone.
  returned: success
  type: str
  sample: 8.8.4.4
dns1_ipv6:
  description: First IPv6 DNS for the zone.
  returned: success
  type: str
  sample: "2001:4860:4860::8888"
dns2_ipv6:
  description: Second IPv6 DNS for the zone.
  returned: success
  type: str
  sample: "2001:4860:4860::8844"
allocation_state:
  description: State of the zone.
  returned: success
  type: str
  sample: Enabled
domain:
  description: Domain the zone is related to.
  returned: success
  type: str
  sample: ROOT
network_domain:
  description: Network domain for the zone.
  returned: success
  type: str
  sample: example.com
network_type:
  description: Network type for the zone.
  returned: success
  type: str
  sample: basic
local_storage_enabled:
  description: Local storage offering enabled.
  returned: success
  type: bool
  sample: false
securitygroups_enabled:
  description: Security groups support is enabled.
  returned: success
  type: bool
  sample: false
guest_cidr_address:
  description: Guest CIDR address for the zone
  returned: success
  type: str
  sample: 10.1.1.0/24
dhcp_provider:
  description: DHCP provider for the zone
  returned: success
  type: str
  sample: VirtualRouter
zone_token:
  description: Zone token
  returned: success
  type: str
  sample: ccb0a60c-79c8-3230-ab8b-8bdbe8c45bb7
tags:
  description: List of resource tags associated with the zone.
  returned: success
  type: list
  sample: [ { "key": "foo", "value": "bar" } ]
'''

from ansible.module_utils.basic import AnsibleModule
from ..module_utils.cloudstack import (
    AnsibleCloudStack,
    cs_argument_spec,
    cs_required_together,
)

class AnsibleCloudStackZone(AnsibleCloudStack):

    def __init__(self, module):
        super(AnsibleCloudStackZone, self).__init__(module)
        self.returns = {
            'dns1': 'dns1',
            'dns2': 'dns2',
            'internaldns1': 'internal_dns1',
            'internaldns2': 'internal_dns2',
            'ipv6dns1': 'dns1_ipv6',
            'ipv6dns2': 'dns2_ipv6',
            'domain': 'network_domain',
            'networktype': 'network_type',
            'securitygroupsenabled': 'securitygroups_enabled',
            'localstorageenabled': 'local_storage_enabled',
            'guestcidraddress': 'guest_cidr_address',
            'dhcpprovider': 'dhcp_provider',
            'allocationstate': 'allocation_state',
            'zonetoken': 'zone_token',
        }
        self.zone = None

    def _get_common_zone_args(self):
        args = {
            'name': self.module.params.get('name'),
            'dns1': self.module.params.get('dns1'),
            'dns2': self.module.params.get('dns2'),
            'internaldns1': self.get_or_fallback('internal_dns1', 'dns1'),
            'internaldns2': self.get_or_fallback('internal_dns2', 'dns2'),
            'ipv6dns1': self.module.params.get('dns1_ipv6'),
            'ipv6dns2': self.module.params.get('dns2_ipv6'),
            'networktype': self.module.params.get('network_type'),
            'domain': self.module.params.get('network_domain'),
            'localstorageenabled': self.module.params.get('local_storage_enabled'),
            'guestcidraddress': self.module.params.get('guest_cidr_address'),
            'dhcpprovider': self.module.params.get('dhcp_provider'),
        }
        state = self.module.params.get('state')
        if state in ['enabled', 'disabled']:
            args['allocationstate'] = state.capitalize()
        return args

    def get_zone(self):
        if not self.zone:
            args = {}

            uuid = self.module.params.get('id')
            if uuid:
                args['id'] = uuid
                zones = self.query_api('listZones', **args)
                if zones:
                    self.zone = zones['zone'][0]
                    return self.zone

            args['name'] = self.module.params.get('name')
            zones = self.query_api('listZones', **args)
            if zones:
                self.zone = zones['zone'][0]
        return self.zone

    def present_zone(self):
        zone = self.get_zone()
        if zone:
            zone = self._update_zone()
        else:
            zone = self._create_zone()
        return zone

    def _create_zone(self):
        required_params = [
            'dns1',
        ]
        self.module.fail_on_missing_params(required_params=required_params)

        self.result['changed'] = True

        args = self._get_common_zone_args()
        args['domainid'] = self.get_domain(key='id')
        args['securitygroupenabled'] = self.module.params.get('securitygroups_enabled')

        zone = None
        if not self.module.check_mode:
            res = self.query_api('createZone', **args)
            zone = res['zone']
        return zone

    def _update_zone(self):
        zone = self.get_zone()

        args = self._get_common_zone_args()
        args['id'] = zone['id']

        if self.has_changed(args, zone):
            self.result['changed'] = True

            if not self.module.check_mode:
                res = self.query_api('updateZone', **args)
                zone = res['zone']
        return zone

    def absent_zone(self):
        zone = self.get_zone()
        if zone:
            self.result['changed'] = True

            args = {
                'id': zone['id']
            }
            if not self.module.check_mode:
                self.query_api('deleteZone', **args)

        return zone

def main():
    argument_spec = cs_argument_spec()
    argument_spec.update(dict(
        id=dict(),
        name=dict(required=True),
        dns1=dict(),
        dns2=dict(),
        internal_dns1=dict(),
        internal_dns2=dict(),
        dns1_ipv6=dict(),
        dns2_ipv6=dict(),
        network_type=dict(default='Basic', choices=['Basic', 'Advanced']),
        network_domain=dict(),
        guest_cidr_address=dict(),
        dhcp_provider=dict(),
        local_storage_enabled=dict(type='bool'),
        securitygroups_enabled=dict(type='bool'),
        state=dict(choices=['present', 'enabled', 'disabled', 'absent'], default='present'),
        domain=dict(),
    ))

    module = AnsibleModule(
        argument_spec=argument_spec,
        required_together=cs_required_together(),
        supports_check_mode=True
    )

    acs_zone = AnsibleCloudStackZone(module)

    state = module.params.get('state')
    if state in ['absent']:
        zone = acs_zone.absent_zone()
    else:
        zone = acs_zone.present_zone()

    result = acs_zone.get_result(zone)

    module.exit_json(**result)

if __name__ == '__main__':
    main()


"""
Toy example to visualize RGB-D boxes on pointcloud.
"""
import os
import numpy as np
from time import time
from datetime import datetime
from tqdm import tqdm

from utils.scannet_io_utils import read_mesh_vertices_rgb, read_alignment, write_bbox, write_ply_rgb, GT_MODE, class2type, align_mesh

# Visualization Configurations
SCANNET_3DBOXS = "/share/suzhengyuan/data/RegionCLIP_boxes/3D_GSS_LSeg_multi" # output path
SCANNET_DIR = "/share/suzhengyuan/data/ScanNetv2/scan"
SCENE_ID = "scene0000_00"
VIS_ROOT = "/home/zhengyuan/packages/RegionCLIP/output/visualizations"

# constructions
BOX_TAG = os.path.split(SCANNET_3DBOXS)[1]
SCANNET_3DBOX_PATH = os.path.join(SCANNET_3DBOXS, "{}_bbox.npy") # scene_id, mode
SCANNET_PC_PATH = os.path.join(SCANNET_DIR, '{}', '{}_vh_clean_2.ply')
SCANNET_META_PATH = os.path.join(SCANNET_DIR, '{}', '{}.txt')
VIS_PATH = os.path.join(VIS_ROOT, f'{datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}-{BOX_TAG}-{SCENE_ID}', '{}.ply')
scan_name = SCENE_ID

os.makedirs(os.path.join(VIS_ROOT, f'{datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}-{BOX_TAG}-{SCENE_ID}'), exist_ok=True)

if __name__ == '__main__':
    start = time()
    point_cloud, pc_color = read_mesh_vertices_rgb(SCANNET_PC_PATH.format(scan_name, scan_name))
    axis_align_matrix = read_alignment(SCANNET_META_PATH.format(scan_name, scan_name))
    assert axis_align_matrix is not None
    axis_align_matrix = np.array(axis_align_matrix).reshape((4,4))
    mesh = align_mesh(SCANNET_PC_PATH.format(scan_name, scan_name), axis_align_matrix)
    mesh.write(VIS_PATH.format('mesh'))
    pts = np.ones((point_cloud.shape[0], 4))
    pts[:,0:3] = point_cloud[:,0:3]
    pts = np.dot(pts, axis_align_matrix.transpose()) # Nx4
    aligned_vertices = np.copy(point_cloud)
    point_cloud[:,0:3] = pts[:,0:3]
    boxes = np.load(SCANNET_3DBOX_PATH.format(scan_name))

    # write_ply_rgb(point_cloud, pc_color, VIS_PATH.format('pointcloud'))
    # print(boxes)
    for i, box in enumerate(tqdm(boxes)):
        # box: 6 + 1
        box_label = box[6]
        box[6] = 0
        write_bbox(box, GT_MODE, VIS_PATH.format(f'{i}-{class2type[box_label]}-score{box[7]}-size{box[8]}-area{box[9]}'))
    # biggest_box = np.zeros(7)
    # biggest_box[:3] = (point_cloud.max(0) + point_cloud.min(0)) / 2
    # biggest_box[3:6] = point_cloud.max(0) - point_cloud.min(0)
    # write_bbox(biggest_box, GT_MODE, VIS_PATH.format('axis'))

    print("Done! Elapsed {}s.".format(time() - start))


from __future__ import annotations
from asyncio import gather
from typing import TYPE_CHECKING, Dict

if TYPE_CHECKING:
    from sceneify.core.source import Source
    from sceneify.core.scene import Scene

class SceneItem:
    def __init__(self, source: Source, scene: Scene, id: int, ref: str):
        self.source = source
        self.scene = scene
        self.id = id
        self.ref = ref
        self.transform = {
            "positionX": 0,
            "positionY": 0,
            "rotation": 0,
            "scaleX": 1,
            "scaleY": 1,
            "cropTop": 0,
            "cropBottom": 0,
            "cropLeft": 0,
            "cropRight": 0,
            "alignment": 0,
            "boundsAlignment": 0,
            "sourceWidth": 0,
            "sourceHeight": 0,
            "width": 0,
            "height": 0,
            "boundsWidth": 0,
            "boundsHeight": 0,
            "boundsType": "OBS_MONITORING_TYPE_NONE",
        }

    async def fetch_properties(self):
        args = {
            "sceneName": self.scene.name,
            "sceneItemId": self.id,
        }

        [transformResp, enabledResp, lockedResp] = await gather(
            *[
                self.source.obs.call("GetSceneItemTransform", args),
                self.source.obs.call("GetSceneItemEnabled", args),
                self.source.obs.call("GetSceneItemLocked", args),
            ]
        )

        self.transform = transformResp["sceneItemTransform"]
        self.enabled = enabledResp["sceneItemEnabled"]
        self.locked = lockedResp["sceneItemLocked"]

    async def set_transform(self, transform: Dict):
        await self.source.obs.call(
            "SetSceneItemTransform",
            {
                "sceneName": self.scene.name,
                "sceneItemId": self.id,
                "sceneItemTransform": transform,
            },
        )

        self.transform.update(transform)

        self.update_size_from_source()

    async def set_enabled(self, enabled: bool):
        await self.source.obs.call(
            "SetSceneItemEnabled",
            {
                "sceneName": self.scene.name,
                "sceneItemId": self.id,
                "sceneItemEnabled": enabled,
            },
        )

        self.enabled = enabled

    async def set_locked(self, locked: bool):
        await self.source.obs.call(
            "SetSceneItemLocked",
            {
                "sceneName": self.scene.name,
                "sceneItemId": self.id,
                "sceneItemLocked": locked,
            },
        )

        self.locked = locked

    def update_size_from_source(
        self, source_width: float = None, source_height: float = None
    ):
        self.transform["sourceWidth"] = source_width or self.transform["sourceWidth"]
        self.transform["sourceHeight"] = source_height or self.transform["sourceHeight"]

        self.transform["width"] = (
            self.transform["scaleX"] * self.transform["sourceWidth"]
        )
        self.transform["height"] = (
            self.transform["scaleY"] * self.transform["sourceHeight"]
        )

    async def remove(self):
        await self.source.obs.call(
            "RemoveSceneItem",
            {
                "sceneName": self.scene.name,
                "sceneItemId": self.id,
            },
        )

        self.source.item_instances.remove(self)
        self.scene.items.remove(self)


import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
# import smote_variants as sv
from random import shuffle
import random

def extract(data_file, anno_file):
    # read files:
    path1 = './data/sleep_edf_npy/'
    x_data = np.load(path1 + data_file + '.npy')
    y_data = np.load(path1 + anno_file + '.npy')

    sleepStart = np.min(np.argwhere(y_data != 0))
    sleepEnd = len(y_data) - np.min(np.argwhere(y_data[::-1] != 0))
    W_reserve = 120
    print(sleepStart)
    print(len(y_data) - sleepEnd)
    if sleepStart > W_reserve and len(y_data) > sleepEnd + W_reserve:
        x_data = x_data[sleepStart-W_reserve:sleepEnd+W_reserve, :, :]
        y_data = y_data[sleepStart-W_reserve:sleepEnd+W_reserve]

    pad = 1000
    d1 = len(y_data)
    x_prev = x_data[:d1-2]
    x_behind = x_data[2:]
    x_new = np.concatenate((x_prev[:, :, 3000-pad:], x_data[1:d1-1], x_behind[:, :, :pad]), axis=2)

    y_new = y_data[1: d1-1]
    print("x_new: ", x_new.shape)
    print("y_new: ", y_new.shape)
    return x_new, y_new

def data_preparation(BATCH_SIZE, num_id):

    data_file = pd.read_table('data_file.txt', header=None)
    anno_file = pd.read_table('anno_file.txt', header=None)

    r=random.random
    random.seed(5)
    a = list(range(len(data_file)))
    shuffle(a, random=r)

    for j in range(6):
        for i in range(j*30, j*30+30):
            x_tmp, y_tmp = extract(data_file.iloc[a[i], 0], anno_file.iloc[a[i], 0])
            if i == j*30:
                x_30 = x_tmp
                y_30 = y_tmp
            else:
                x_30 = np.concatenate((x_30, x_tmp), axis=0)
                y_30 = np.concatenate((y_30, y_tmp), axis=0)
        if j == 0:
            x_60 = x_30
            y_60 = y_30
        else:
            x_60 = np.concatenate((x_60, x_30), axis=0)
            y_60 = np.concatenate((y_60, y_30), axis=0)

    for i in range(180, num_id):
        x_tmp, y_tmp = extract(data_file.iloc[a[i], 0], anno_file.iloc[a[i], 0])
        if i == 180:
            x_17 = x_tmp
            y_17 = y_tmp
        else:
            x_17 = np.concatenate((x_17, x_tmp), axis=0)
            y_17 = np.concatenate((y_17, y_tmp), axis=0)

    class EEGdataset(Dataset):
        def __init__(self, x, y):
            self.batch_size = BATCH_SIZE

            num_batch = int(x.shape[0] / self.batch_size)
            self.x_data = torch.from_numpy(x[:num_batch * self.batch_size, :, :])
            self.x_data = self.x_data.type(torch.FloatTensor)

            self.y_data = torch.LongTensor(y[:num_batch * self.batch_size])
            self.len = self.y_data.shape[0]

        def __getitem__(self, index):
            return self.x_data[index], self.y_data[index]

        def __len__(self):
            return self.len

    train_data = EEGdataset(x_60, y_60)
    train_loader = DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)
    test_data = EEGdataset(x_17, y_17)
    test_loader = DataLoader(dataset=test_data, batch_size=BATCH_SIZE, shuffle=True)

    return train_loader, test_loader


#!/usr/bin/python
# -*- coding: utf-8 -*-
from .aba_graph import ABA_Graph
from .aba_dispute_tree import ABA_Dispute_Tree
from .aba_constants import *
from .aba_perf_logger import ABA_Perf_Logger
import networkx as nx
import logging
import functools

class ABA():
    """
    ABA: Assumption-based Argumentation, consists of
    - L: sentences = R + A
    - R: inference rules <ABA_Rules>
    - A: assumptions <ABA_Rules, where rhs = None>
        in flat-ABA, A is all symbols that cannot be derived using R
    - c: contrary set: mapping from A to L; which assumptions "attacks" another sentences
    """
    def __init__(self):
        self.symbols = []
        self.rules = []
        self.assumptions = []
        self.contraries = dict()
        self.nonassumptions = []

        self.arguments = []
        self.potential_arguments = []
        self.dispute_trees = []

    def is_all_assumption_have_contrary(self):
        """
        Each assumption must have a contrary.
        """
        all_assumption_have_contrary = True
        for assumption in self.assumptions:
            if assumption not in self.contraries.keys():
                all_assumption_have_contrary = False
                break
        return all_assumption_have_contrary

    def infer_assumptions(self):
        self.nonassumptions = list(self.symbols)

        for key in self.contraries:
            if key not in self.assumptions:
                self.assumptions.append(key)

        for assumption in self.assumptions:
            if assumption in self.nonassumptions:
                self.nonassumptions.remove(assumption)

    def construct_arguments(self):
        if not self.is_all_assumption_have_contrary():
            raise Exception("All assumptions must have contrary")

        for symbol in self.symbols:
            potential_argument = ABA_Graph(self, symbol)
            for i in range(len(potential_argument.graphs)):
                self.potential_arguments.append((potential_argument, i))
                if potential_argument.is_actual_argument(i):
                    self.arguments.append((potential_argument, i))

    def construct_dispute_trees(self):
        if not self.is_all_assumption_have_contrary():
            raise Exception("All assumptions must have contrary")

        args_grounded = {}

        for argument, i in self.arguments:
            if argument:
                if argument.root not in args_grounded:
                    args_grounded[argument.root] = False
                if args_grounded[argument.root]: # if grounded, then also must be admissible
                    logging.debug("Skipping DT <%s, %d>", argument.root, i)
                    # Skipping DT generation if previously a grounded DT has been found
                    continue

                perf_logger = ABA_Perf_Logger("ABA_Dispute_Tree <%s>" % argument)
                perf_logger.start()
                dt = ABA_Dispute_Tree(self, argument, i)
                perf_logger.end()

                self.dispute_trees.append(dt)

                args_grounded[argument.root] = functools.reduce(lambda x,y: x or y, dt.is_grounded)

        perf_logger = ABA_Perf_Logger("__determine_dispute_tree_is_ideal")
        perf_logger.start()
        self.__determine_dispute_tree_is_ideal()
        perf_logger.end()

        perf_logger = ABA_Perf_Logger("__determine_dispute_tree_is_complete")
        perf_logger.start()
        self.__determine_dispute_tree_is_complete()
        perf_logger.end()

    def __determine_dispute_tree_is_ideal(self):
        for tree in self.dispute_trees:
            for tree_idx, graph in enumerate(tree.graphs):
                ideal = False
                if tree.is_admissible[tree_idx]:
                    ideal = True
                    for node in graph.nodes(data = True):
                        if node[1]['label'] == DT_OPPONENT:
                            opponent_dispute_tree = self.get_dispute_tree(node[0], tree.arg_index)
                            if opponent_dispute_tree and opponent_dispute_tree.is_admissible:
                                ideal = False
                                break
                tree.is_ideal[tree_idx] = ideal
                logging.debug("Dispute Tree <%s, %s> is ideal: %s", tree.root_arg.root, tree_idx, tree.is_ideal[tree_idx])

    def __get_arguments_attackable(self, arg):
        """
        Given an argument, which other arguments it can attack?
        """
        attackables = []
        for argument, i in self.arguments:
            attackable = arg.root in argument.assumptions[i].values()

            if attackable:
                attackables.append((argument, i))
        return attackables

    def __determine_dispute_tree_is_complete(self):
        for tree in self.dispute_trees:
            for tree_idx, graph in enumerate(tree.graphs):
                complete = False
                if tree.is_admissible[tree_idx]:
                    complete = True
                    if not tree.is_grounded[tree_idx]: # if tree is grounded, it is guaranteed to be complete

                        # 1. Get all arguments root_arg can attack --> assign as x
                        # 2. Get all arguments that can be attacked by x --> assign as y
                        # 3. If ALL y inside root_arg, then complete
                        attackables_by_root = self.__get_arguments_attackable(tree.root_arg)
                        # Note: since root_arg is admissible, then it is conflict-free, i.e. root_arg is guaranteed not to be inside attackables_by_root

                        defendable_arguments = []
                        for attackable, i in attackables_by_root:
                            defendable_arguments.extend(self.__get_arguments_attackable(attackable))

                        all_in_argument = True
                        for argument, i in defendable_arguments:
                            if argument.root not in tree.root_arg.graphs[i].nodes():
                                all_in_argument = False
                                break
                        complete = all_in_argument
                        # logging.debug("DT<%s> Defendable arguments: %s", tree.root_arg.root, defendable_arguments)

                tree.is_complete[tree_idx] = complete
                logging.debug("Dispute Tree <%s, %s> is complete: %s", tree.root_arg.root, tree_idx, tree.is_complete[tree_idx])

    def get_argument(self, symbol, index = 0, allow_potential = False):
        source = self.arguments
        if allow_potential:
            source = self.potential_arguments
        argument = [x for x in source if x[0].root == symbol and x[1] == index]

        if len(argument) > 0:
            return argument[0]
        return None, None

    def get_dispute_tree(self, symbol, index = 0):
        dispute_tree = [x for x in self.dispute_trees if x.root_arg.root == symbol and x.arg_index == index]
        if len(dispute_tree) > 0:
            return dispute_tree[0]
        return None

    def get_combined_argument_graph(self):
        combined = nx.DiGraph()
        for potential_argument, index in self.potential_arguments:
            symbol = potential_argument.root
            argument, i = self.get_argument(symbol, index = index, allow_potential = True)

            if argument is None:
                arg_root = "τ"
                combined.add_node(symbol + "_" + arg_root, group = arg_root)
                continue

            arg_root = argument.root
            for node in argument.graphs[i].nodes():
                if node is None:
                    node = "τ"
                combined.add_node(node + "_" + arg_root, group = arg_root)

            for edge in argument.graphs[i].edges_iter():
                edge0, edge1 = edge
                if edge0 is None:
                    edge0 = "τ"
                if edge1 is None:
                    edge1 = "τ"
                combined.add_edge(edge0 + "_" + arg_root, edge1 + "_" + arg_root)

        return combined


r""" a sample implementation of LAS for HKUST """
import sys
import json
import tensorflow as tf
from absl import logging
from athena import DecoderSolver
from athena.main import (
    parse_config,
    build_model_from_jsonfile
)

def decode(jsonfile):
    """ entry point for model decoding, do some preparation work """
    p, model, _, checkpointer, dataset_builder = build_model_from_jsonfile(jsonfile, 0)
    checkpointer.restore_from_best()
    solver = DecoderSolver(model, config=p.decode_config)
    dataset_builder = dataset_builder.load_csv(p.test_csv).compute_cmvn_if_necessary(True)
    solver.decode(dataset_builder.as_dataset(batch_size=1))

if __name__ == "__main__":
    logging.set_verbosity(logging.INFO)
    tf.random.set_seed(1)

    JSON_FILE = sys.argv[1]
    CONFIG = None
    with open(JSON_FILE) as f:
        CONFIG = json.load(f)
    PARAMS = parse_config(CONFIG)
    DecoderSolver.initialize_devices(PARAMS.solver_gpu)
    decode(JSON_FILE)


import numpy as np
import scipy.spatial as sps
from mayavi import mlab
import argparse
import scipy.stats as stats

# Example using Mayavi

def helix(t):
    return np.array([np.sin(5*t), np.cos(5*t), t])

def testHelix():
    t = np.linspace(0, 10, 1000)
    return helix(t).T

def chPic3d(arr):
    assert(len(arr.shape) == 2)
    assert(arr.shape[1] == 3)

    cHull = sps.ConvexHull(arr)
    mlab.triangular_mesh(arr[:,0], arr[:, 1], arr[:, 2],
                         cHull.simplices)

def plot3d(arr):
    assert(len(arr.shape) == 2)
    assert(arr.shape[1] == 3)

    mlab.plot3d(arr[:,0], arr[:,1], arr[:,2], line_width=0.8)

def expit(x):
    return 1/(1+np.exp(-x))

def makeArr():
    beta = np.linspace(0, 5, 1000)
    f = lambda x : np.array((x, x*x, 20 * expit((x-1)/0.1) * expit(4.5-x)/0.05))
    return f(beta).T

def makeArrPois():
    beta = np.linspace(0.01, 8, 1000)
    f = lambda y,beta : stats.poisson.pmf(y,beta)
    arr = np.zeros((1000, 3))
    arr[:,2] = beta
    arr[:,0] = f(2, beta)
    arr[:,1] = f(6, beta)

    return arr

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('-t', '--test', action='store_true', default=False)
    parser.add_argument('-p', '--plot', action='store_true', default=False)
    args = parser.parse_args()

    if args.test:
        arr = testHelix()
    else:
        arr = makeArrPois()

    if args.plot:
        plot3d(arr)
    else:
        chPic3d(arr)
    mlab.show()

if __name__ == "__main__":
    main()


from django.shortcuts import render,get_object_or_404,render_to_response
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.decorators import login_required
from django.conf import  settings
from . import models,forms
from django.contrib.auth.models import User
from .models import Asset

import uuid

import json,time,random
from django.utils.html import escape
# Create your views here.
@login_required
def list(request):
    query_data=Asset.objects.all().values()
    return render_to_response("./asset/list.html", locals())

@login_required
@csrf_protect
def add(request):
    user = request.user
    error = ''
    if request.method == 'POST':
        form = forms.Asset_create_form(request.POST)
        if form.is_valid():
            asset_id = settings.VULN_PRE + str(uuid.uuid4())
            asset_name = form.cleaned_data['asset_name']
            asset_type = form.cleaned_data['asset_type']
            asset_key = form.cleaned_data['asset_key']
            asset_link = form.cleaned_data['asset_link']
            user_email = form.cleaned_data['user_email']
            asset_create = models.Asset.objects.get_or_create(
                asset_id=asset_id,
                asset_name=asset_name,
                asset_type=asset_type,
                asset_key=asset_key,
                asset_link=asset_link,
                )
            if asset_create[1]:
                asset = asset_create[0]
                if user.is_superuser:
                    asset.user_email = user_email
                    user_get = User.objects.filter(email = user_email).first()
                    if user_get:
                        asset.asset_inuse=True
                        asset.asset_user.add(user)
                    else:
                        asset.asset_inuse=False
                else:
                    asset.asset_inuse=True
                    if user_email:
                        asset.user_email = user_email
                    else:
                        asset.user_email = user.email
                    asset.asset_user.add(user)
                asset.save()
            error = '添加成功'
        else:
            error ='非法输入或资产已存在，请进行资产申请'
        return render(request,'./asset/add.html',{'form':form,'post_url':'add','error':error})
    else:
        form = forms.Asset_create_form()
    return render(request,'./asset/add.html',{'form':form,'post_url':'assetcreate'})


import typing
import unittest

def read_numbers(filename: str) -> typing.List[int]:
    with open(filename, 'r') as source:
        source.readline()
        return list(map(int, source.readline().split()))

def calc_ones(numbers: typing.List[int]) -> typing.List[int]:
    dest = []
    for number in numbers:
        count = 0
        while number > 0:
            count += (number & 1)
            number >>= 1
        dest.append(count)
    return dest

class TestTaskImplementation(unittest.TestCase):

    def test_example(self):
        self.assertEqual([2, 3, 0], calc_ones([5, 13, 0]))

    def test_task(self):
        self.assertEqual([8, 15, 16, 17, 15, 16, 17, 15], calc_ones(read_numbers("./ones.in")))

if __name__ == "__main__":
    unittest.main()