import argparse
import logging
import os
import shutil
import sys
import tempfile

from cros.factory.utils.process_utils import Spawn

# A pattern in TEMPLATE to be replaced with real module list.
MODULES_PATTERN = '__MODULES_HERE__'

# The template is a stub to be inserted in the beginning of output PAR file.
TEMPLATE = """#!/bin/sh
EXEC_FILE="$(basename "$0")"
REAL_PATH="$(readlink -f "$0")"
REAL_DIR="$(dirname "${REAL_PATH}")"
COMMANDS=""
MODULES="__MODULES_HERE__"
MODULE=""

find_command() {
  local command="$1" module="" name=""
  COMMANDS=""
  for module in ${MODULES}; do
    name="${module##*.}"
    if [ "${name}" = "${command}" ]; then
      MODULE="${module}"
      return 0
    fi
    COMMANDS="${COMMANDS} ${name}"
  done
  return 1
}

if ! find_command "${EXEC_FILE}"; then
  if find_command "$1"; then
    shift
  else
    echo "ERROR: No ${EXEC_FILE} in ${REAL_PATH}. Available:${COMMANDS}" >&2
    exit 1
  fi
fi

export PYTHONPATH="${PYTHONPATH}:${REAL_PATH}"
export PAR_PATH="${REAL_PATH}"
export PATH="${PATH}:${REAL_DIR}"
exec python3 -m "${MODULE}" "$@"
exit 1
# Should never reach here. Anything below are reserved for ZIP.
"""

def CollectFiles(pkg_dir, modules, output, init_modules):
  """Collects files needed from modules into given output folder.

  Args:
    pkg_dir: a path to the root of modules.
    modules: a list of string for Python module (a.b.c).
    output: a path to the root of output.
    init_modules: a list of string for __init__ style modules.
  """
  for module in modules:
    src_path = module.replace('.', '/') + '.py'
    par_dir = os.path.dirname(src_path)
    dest_path = output

    # Build directory and init files.
    for entry in par_dir.split('/'):
      dest_path = os.path.join(dest_path, entry)
      if os.path.exists(dest_path):
        continue

      logging.debug('%s => %s (mkdir + init)', src_path, dest_path)
      os.mkdir(dest_path)
      for init in init_modules:
        with open(os.path.join(dest_path, init + '.py'), 'a'):
          pass

    # Copy the real module file.
    logging.debug('%s => %s', src_path, dest_path)
    shutil.copy(os.path.join(pkg_dir, src_path), dest_path)

def BuildPythonZip(py_dir, zip_name='_stage.zip'):
  """Builds a Python zip file from given directory.

  Args:
    py_dir: a path to folder with all Python files available.
    zip_name: the file name to be created.

  Returns:
    A path to the created Zip file (in py_dir).
  """
  zip_path = os.path.join(py_dir, zip_name)
  Spawn(['zip', '-qr', zip_path, '.'], check_call=True, log=True, cwd=py_dir)
  return zip_path

def main(argv=None):
  parser = argparse.ArgumentParser(
      description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  parser.add_argument(
      '--output', '-o', default='tinypar.par',
      help='output file. default: %(default)s')
  parser.add_argument(
      '--pkg', '-k', default='.',
      help='path to the Python package folder to find modules.')
  parser.add_argument(
      '-m', '--module', dest='modules', action='append', default=[],
      help='include given module with main (which can be a command).')
  parser.add_argument(
      '--extra_init',
      help=('extra init-like file to create in each module directory. '
            'default: %(default)s'))
  parser.add_argument(
      '--verbose', '-v', action='count', help='increase output verbosity.')
  # TODO(hungte) Add an option to add extra PATH in invocation.
  # TODO(hungte) Add an option to "add dependency but not as executable".
  # TODO(hungte) Add an option to "add a full directory".
  args = parser.parse_args(argv)
  logging.basicConfig(level=logging.WARNING - 10 * (args.verbose or 0))

  if not args.modules:
    sys.exit('ERROR: Need at least one module (-m).')

  init_modules = ['__init__']
  if args.extra_init:
    init_modules += [args.extra_init]

  tmp_dir = os.path.realpath(tempfile.mkdtemp(prefix='tiny_par.'))
  try:
    CollectFiles(args.pkg, args.modules, tmp_dir, init_modules)
    zip_path = BuildPythonZip(tmp_dir)
    with open(args.output, 'wb') as f:
      template = TEMPLATE.replace(MODULES_PATTERN, ' '.join(args.modules))
      f.write(template.encode('utf-8'))
      with open(zip_path, 'rb') as z:
        f.write(z.read())
    os.chmod(args.output, 0o755)
    print('Successfully created PAR executable: %s' % args.output)
  finally:
    shutil.rmtree(tmp_dir)

if __name__ == '__main__':
  main()


import random
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, Aer

"""
IMPROVEMENTS
  - figure out an easier for way for people to see the results rather than
    having to access public variable result
"""
class QuantumCoinFlip: # Maybe change this name later to something more generic as we refactor code
  def __init__(self):
    self.result = self.generate_random_flip()

  def generate_random_flip(self):
    registers = self._build_registers()
    circuit = self._build_circuit(registers)
    counts = self._run_circuit(circuit)
    converted_output = self._convert_counts(counts)

    return converted_output # Sloppy, leaving for now

  def print_counts(self, converted_output):
    print(converted_output)

  def _build_registers(self, register_size=1):
    # not ready for register_size != 1 yet
    return (QuantumRegister(register_size), ClassicalRegister(register_size))

  def _build_circuit(self, registers):
    quantum_register = registers[0]
    classical_register = registers[1]

    circuit = QuantumCircuit(quantum_register, classical_register)
    circuit.h(quantum_register[0]) #Hadamard on 0th bit of register
    circuit.measure(quantum_register, classical_register)

    return circuit

  def _run_circuit(self, circuit):
    backend = Aer.get_backend('qasm_simulator')

    job_simulation = execute(circuit, backend, shots=1)
    result = job_simulation.result()
    counts = result.get_counts(circuit) #get_counts() returns either a dict or list of dicts

    return counts

  def _convert_counts(self, counts):
    counts = dict(counts) # Hard coding as a dict for now since qiskit is sloppy
    if type(counts) is list:
      raise Exception('Unimplemented')
    elif type(counts) is dict:
      key_list = list(counts)
      for key in key_list:
        return int(key) # Broken implementation, only doing this for one case
    else:
      raise Exception('Invalid input in convert_counts')

flip = QuantumCoinFlip()
print(flip.result)


import os
import sys

SEPARATOR = "\t"

#
# main entry point of the application
#
if len(sys.argv) < 4:
    print('usage: python3 ' + sys.argv[0] + ' <input-file1> <input-file2> <output-file>\n')
    sys.exit()

first_file = {}
with open(sys.argv[1], "r") as input1:
    for line in input1.readlines():
        parts = line.split()
        first_file[parts[0] + " " + parts[1]] = parts[2:]

with open(sys.argv[3],"w") as output:
    with open(sys.argv[2],"r") as input2:
        for line in input2.readlines():
            parts = line.split()
            time_point = parts[0] + " " + parts[1]

            if time_point in first_file:
                output.write(line.rstrip() + SEPARATOR + SEPARATOR.join(first_file[time_point]) + "\n")
            else:
                output.write(line)


#PLC communication file through automation HAT

import time

import automationhat

# sensor 0:temperature 1: pressure 2: acceleration
# 3 digit input
def plc_input():
	if automationhat.is_automation_hat():
		automationhat.light.power.write(1)
	sensor = ''
	if automationhat.input[0].read():
		sensor = 'Temperature'
	elif automationhat.input[1].read():
		sensor = 'Pressure'
	elif automationhat.input[2].read():
		sensor = 'Acceleration'
	if sensor != '':
		return sensor

# sensor: temperature, pressure, acceleration
# result: pass:1 fail:0
# currently the output is 2-digit for each sensor (probably need to change it)
# output: relay 0: no result; relay 1: has result; output 0: fail; ouput 1: pass
def plc_output(sensor,result):
	if automationhat.is_automation_hat():
		automationhat.light.power.write(1)
	channel = 3
	if sensor == 'Temperature':
		channel = 0
	elif sensor == 'Pressure':
		channel = 1
	elif sensor == 'Acceleration':
		channel = 2
	if channel != 3:
		automationhat.relay[channel].write(1)
		if result == 1:
			automationhat.output[channel].write(1)
		elif result == 0:
			automationhat.output[channel].write(0)
		plc_result = int(str(automationhat.output[channel].read())+str(automationhat.relay[channel].read()))
		print(sensor,plc_result)
		return plc_result

while True:
	automationhat.output.write(0)
	automationhat.relay.write(0)
	if plc_input()!= None:
		print(plc_output(plc_input(),0))
		time.sleep(1)
		automationhat.output.write(1)
		automationhat.relay.write(1)
	else:
		continue


"""
views for application geokret
"""

import re
from datetime import datetime
from lxml import etree

from django.http import HttpResponse
from django.shortcuts import render
from django.template.loader import render_to_string
from django.db.models import Max
from django.utils.translation import ugettext_lazy as _

from gpsfun.main.db_utils import get_object_or_none
from gpsfun.main.ajax import accept_ajax
from gpsfun.main.db_utils import sql2table
from gpsfun.main.GeoKrety.models import GeoKret
from gpsfun.main.GeoName.models import GeoCountry
from gpsfun.main.models import LogUpdate, log_api
from gpsfun.main.utils import points_rectangle
from gpsfun.main.utils import MAX_POINTS

GEOKRETY_ONMAP_STATES = [0, 3]
SEARCH_TOOLTIP = _("Geokret or waypoint")

class KretyWaypoint:
    """ Kret waypoint """
    waypoint = None
    latitude = None
    longitude = None
    count = 0
    distance = 0

def geokrety_map(request):
    """ get map with geokrety """
    krety = []

    default_mapbounds = {
        'bottom': 49.5,
        'top': 50.5,
        'left': 36.2,
        'right': 36.6,
    }

    def rectagle_center(rectangle):
        """ get center of the rectangle """
        return {
            'lat': (rectangle['bottom'] + rectangle['top']) / 2.0,
            'lng': (rectangle['left'] + rectangle['right']) / 2.0
        }

    map_zoom = request.session.get('geokrety_zoom') or 14

    user_waypoint = request.session.get('geokrety_map_waypoint', '')
    geokret_waypoint = request.session.get('geokret_waypoint')
    mapbounds = request.session.get('geokrety_mapbounds') or default_mapbounds
    map_center = request.session.get(
        'geokrety_center') or rectagle_center(default_mapbounds)
    krety = waypoints_rectangle(mapbounds)

    update_date = LogUpdate.objects.filter(update_type='kret')\
        .aggregate(last_date=Max('update_date'))

    return render(
        request,
        'Map/geokrety_map.html',
        {
            'geokrety': krety,
            'geokrety_count': len(krety),
            'map_rect': points_rectangle(krety),
            'update_date': update_date.get("last_date"),
            'tooltip_text': SEARCH_TOOLTIP,
            'user_waypoint': user_waypoint,
            'max_points': MAX_POINTS,
            'map_center': map_center,
            'map_zoom': map_zoom,
            'geokret_waypoint': geokret_waypoint,
        })

@accept_ajax
def map_geokret_info(request):
    """ get map information """
    result = {'status': 'ERR'}
    waypoint = request.GET.get('waypoint')
    krety = GeoKret.objects.filter(
        waypoint=waypoint,
        state__in=GEOKRETY_ONMAP_STATES)
    krety = krety.order_by('name')
    waypoint_url = url_by_waypoint(waypoint)
    result['content'] = render(
        request,
        'Map/geokret_info.html',
        {
            'geokrety': krety,
            'waypoint': {
                'code': waypoint,
                'url_to': waypoint_url}
        })
    result['status'] = 'OK'

    return result

@accept_ajax
def geokrety_map_get_geokrety(request):
    """ get list of geokrety """
    result = {'status': 'ERR'}

    mapbounds = {
        'top': float(request.GET.get('top') or 0),
        'left': float(request.GET.get('left') or 0),
        'bottom': float(request.GET.get('bottom') or 0),
        'right': float(request.GET.get('right') or 0),
    }

    request.session['geokrety_mapbounds'] = mapbounds
    request.session['geokrety_zoom'] = request.GET.get('zoom') or 14
    request.session['geokrety_center'] = {
        'lat': request.GET.get('center_lat'),
        'lng': request.GET.get('center_lng'), }
    # user_waypoint = request.session.get('geokrety_map_waypoint', '')
    krety = waypoints_rectangle(mapbounds)

    result['krety'] = get_kret_list(krety)
    result['rect'] = points_rectangle(krety)
    result['count'] = len(krety)
    result['status'] = 'OK'

    return result

@accept_ajax
def geokrety_map_change_country(request):
    """ change country """
    result = {'status': 'ERR'}
    country_code = request.GET.get('country')
    request.session['geokrety_map_country'] = country_code

    if not country_code:
        return result

    if country_code != 'SEARCH':
        request.session['geokrety_map_waypoint'] = None

    country = get_object_or_none(GeoCountry, iso=country_code)

    address = 'Ukraine, Kharkov'
    if country:
        address = f'{country.name},{country.capital}'

    krety = waypoints_with_geokrety(country_code)

    result['krety'] = get_kret_list(krety)
    result['rect'] = points_rectangle(krety)
    result['address'] = address
    result['status'] = 'OK'

    return result

@accept_ajax
def geokrety_map_search_waypoint(request):
    """ search waypoint """
    result = {'status': 'ERR'}

    waypoint = request.GET.get('waypoint')
    request.session['geokrety_map_waypoint'] = waypoint

    if waypoint is None:
        return result

    found_kret = None
    krety = []

    if waypoint:
        krety = waypoints_by_mask(waypoint)[:1]
        if krety:
            found_kret = {
                'lat': krety[0].latitude,
                'lng': krety[0].longitude}
            request.session['geokret_waypoint'] = found_kret

            # krety_list = get_kret_list(krety)
            rect = points_rectangle(krety)

            mapbounds = {
                'top': rect['lat_max'],
                'left': rect['lng_min'],
                'bottom': rect['lat_min'],
                'right': rect['lng_max'],
            }
            krety = waypoints_rectangle(mapbounds)
    if not krety:
        mapbounds = request.session.get('geokrety_mapbounds')
        krety = waypoints_with_geokrety_rectangle(mapbounds)

    result['krety'] = get_kret_list(krety)
    result['rect'] = points_rectangle(krety)
    result['kret_waypoint'] = found_kret
    result['status'] = 'OK'

    return result

def waypoints_with_geokrety(user_country):
    """ get list of waypoints """
    sql = None
    if user_country == 'SEARCH':
        return []
    if user_country and len(user_country) == 2:
        sql = get_country_sql(user_country)
    if user_country and user_country == 'ALL':
        sql = get_all_countries_sql()
    if user_country and user_country == 'NONE':
        sql = get_no_country_sql()

    return get_krety_list(sql)

def waypoints_with_geokrety_rectangle(mapbounds):
    """ get list of waypoints for the rectangle """
    sql = get_rectangle_sql(mapbounds)
    return get_krety_list(sql)

def url_by_waypoint(waypoint):
    """ get url for waypoint """
    wpoint = ''
    su_t = re.compile(r'TR|MS\d+')
    if waypoint and len(waypoint) > 3:
        wpoint = waypoint.upper()
        treg = re.compile(r'\w{1,2}[\dA-F]+')
        if not treg.match(wpoint):
            wpoint = ''
    if wpoint and wpoint.startswith('OB'):
        return f'http://www.opencaching.nl/viewcache.php?wp={wpoint}'

    if su_t.match(wpoint):
        wpoint = f'{wpoint[:2]}/{wpoint[2:]}'

    return f'http://geokrety.org/go2geo/{wpoint}'

def geokrety_api_who_in_cache(request, cache_code):
    """ get geokrety in cache """
    root_tree = etree.Element('waypoint')
    root_tree.attrib['code'] = cache_code
    desc_tree = etree.SubElement(root_tree, 'description')
    desc_tree.text = 'Krety in Cache Listing Generated from gps-fun.info'
    url_tree = etree.SubElement(root_tree, 'url')
    url_tree.text = f'http://geokrety.org/szukaj.php?wpt={cache_code}'
    time_tree = etree.SubElement(root_tree, 'time')
    time_tree.text = datetime.now().isoformat()
    geokrety_tree = etree.SubElement(root_tree, 'geokrety')
    geokrety = GeoKret.objects.filter(
        state__in=GEOKRETY_ONMAP_STATES,
        waypoint=cache_code)
    for geokret in geokrety:
        geokret_tree = etree.SubElement(geokrety_tree, 'geokret')
        id_tree = etree.SubElement(geokret_tree, 'id')
        id_tree.text = str(geokret.gkid)
        refnum_tree = etree.SubElement(geokret_tree, 'refnum')
        refnum_tree.text = geokret.reference_number
        name_tree = etree.SubElement(geokret_tree, 'name')
        name_tree.text = geokret.name
        distance_tree = etree.SubElement(geokret_tree, 'distance')
        distance_tree.text = str(geokret.distance)
        kret_url_tree = etree.SubElement(geokret_tree, 'kret_url')
        kret_url_tree.text = geokret.url

    response_text = f'<?xml version="1.0" encoding="utf-8"?>{etree.tostring(root_tree).decode("utf-8")}'
    response = HttpResponse(response_text)
    response['Content-Type'] = 'text/xml'
    response['Content-Length'] = str(len(response_text))

    try:
        log_api('whoincache', request.META.get('REMOTE_ADDR', ''))
    except:
        pass

    return response

def waypoints_rectangle(mapbounds):
    """ get list of waypoints for map bounds """
    sql = all_krety_sql()
    if len(mapbounds.keys()):
        sql += f"""
        HAVING l.ns_degree > {mapbounds['bottom']}
            and l.ns_degree < {mapbounds['top']}
            and l.ew_degree > {mapbounds['left']}
            and l.ew_degree < {mapbounds['right']}
        """

    sql += f" LIMIT {MAX_POINTS + 1}"

    krety = get_krety_list(sql)

    return krety

def waypoint_mask_sql(waypoint):
    """ get sql query to get waypoints by the mask """
    if not waypoint:
        return all_krety_sql()

    sql = None
    wpoint = waypoint.strip().upper()
    pwp = re.compile(
        r'(OP|TR|MS|GC|OC|OX|GR|GL|OK|GA|OZ|TR|RH|OU|TC|OS|ON|OL|OJ|N|GE|WM|SH|TP|TB|OB)[\d,A-F]*')  # OB GL
    pgk = re.compile(r'GK([\d,A-F]+)')
    if pwp.match(wpoint) and len(wpoint) < 9:
        return waypont_sql(wpoint)

    if pgk.match(wpoint):
        hexcode = pgk.findall(wpoint)
        if hexcode and len(hexcode):
            hexcode = hexcode[0]
            try:
                kret_id = int(hexcode, 16)
            except:
                kret_id = 0
            return geokret_sql(kret_id)

    if not waypoint:
        return all_krety_sql()
    sql = kret_name_sql(waypoint)
    return sql

def waypoints_by_mask(waypoint):
    """ get list of waypoints by the mask """
    sql = waypoint_mask_sql(waypoint)
    return get_krety_list(sql)

def get_kret(kret_point):
    """ get geokret """
    krety = GeoKret.objects.filter(
        waypoint=kret_point.waypoint, state__in=(0, 3)).exclude(
            location__isnull=True)
    waypoint_url = krety[0].waypoint_url if krety.count() else ''

    return {
        'waypoint': kret_point.waypoint,
        'name': kret_point.waypoint,
        'distance': kret_point.distance or 0,
        'content': render_to_string(
            'Map/geokret_info.html',
            {
                'kret_point': kret_point,
                'krety': krety,
                'waypoint_url': waypoint_url}),
        'latitude': kret_point.latitude,
        'longitude': kret_point.longitude}

def get_kret_list(krety):
    """ get list of geokrety """
    return [get_kret(kret) for kret in krety]

def get_rectangle_sql(mapbounds):
    """ get sql query to get geokrety for map bounds """
    return f"""
        select
           kret.waypoint,
           l.ns_degree as latitude,
           l.ew_degree as longitude,
           COUNT(kret.id) as cnt,
           MAX(kret.distance) as distance
        from geokret kret
        left join location l on kret.location_id=l.id
        where kret.state in (0,3) and kret.waypoint is not null
            and length(kret.waypoint) > 0 and l.id is not null
            and l.ns_degree > {mapbounds['bottom']}
            and l.ns_degree < {mapbounds['top']}
            and l.ew_degree > {mapbounds['left']}
            and l.ew_degree < {mapbounds['right']}
        group by kret.waypoint, l.ns_degree, l.ew_degree
        """

def all_krety_sql():
    """ sql query to get all geokrety """
    return """
        select
           kret.waypoint,
           l.ns_degree,
           l.ew_degree,
           COUNT(kret.id) as cnt,
           MAX(kret.distance) as distance
        from geokret kret
        left join location l on kret.location_id=l.id
        where kret.state in (0,3) and kret.waypoint is not null
            and length(kret.waypoint) > 0 and l.id is not null
        group by kret.waypoint, l.ns_degree, l.ew_degree
        """

def get_country_sql(user_country):
    """ sql query to get geokrety for the country """
    return f"""
        select
           kret.waypoint,
           l.ns_degree,
           l.ew_degree,
           COUNT(kret.id) as cnt,
           MAX(kret.distance) as distance
        from geokret kret
        left join location l on kret.location_id=l.id
        where kret.country_code='{user_country}' and
            kret.state in (0,3) and kret.waypoint is not null
            and length(kret.waypoint) > 0 and l.id is not null
        group by kret.waypoint, l.ns_degree, l.ew_degree
        """

def get_all_countries_sql():
    """ get sql query to get geokrety for all countries """
    return """
        select
            kret.waypoint,
            l.ns_degree,
            l.ew_degree,
            COUNT(kret.id) as cnt,
            MAX(kret.distance) as distance
        from geokret kret
        left join location l on kret.location_id=l.id
        where
            kret.state in (0,3) and kret.waypoint is not null
            and length(kret.waypoint) > 0 and l.id is not null
        group by kret.waypoint, l.ns_degree, l.ew_degree
        """

def get_no_country_sql():
    """ get geokrety that is not linked to any country """
    return """
        select
            kret.waypoint,
            l.ns_degree,
            l.ew_degree,
            COUNT(kret.id) as cnt,
            MAX(kret.distance) as distance
        from geokret kret
        left join location l on kret.location_id=l.id
        where kret.country_code IS NULL and
            kret.state in (0,3) and kret.waypoint is not null
            and length(kret.waypoint) > 0 and l.id is not null
        group by kret.waypoint, l.ns_degree, l.ew_degree
        """

def waypont_sql(waypoint):
    """ get geokrety for the waypoint by mask """
    return f"""
        select
            kret.waypoint,
            l.ns_degree,
            l.ew_degree,
            COUNT(kret.id) as cnt,
            MAX(kret.distance) as distance
        from geokret kret
        left join location l on kret.location_id=l.id
        where kret.waypoint is not null and length(kret.waypoint) > 0
            and kret.waypoint RLIKE '^{waypoint}.*' and
            kret.state in (0,3)
            and l.id is not null
        group by kret.waypoint, l.ns_degree, l.ew_degree
        """

def geokret_sql(kret_id):
    """ query to get geokret by id """
    return f"""
            select
                kret.waypoint,
                l.ns_degree,
                l.ew_degree,
                COUNT(kret.id) as cnt,
                MAX(kret.distance) as distance
            from geokret kret
            left join location l on kret.location_id=l.id
            where kret.waypoint is not null and length(kret.waypoint) > 0
                and kret.gkid = {kret_id} and
                kret.state in (0,3)
                and l.id is not null
            group by kret.waypoint, l.ns_degree, l.ew_degree
            """

def kret_name_sql(name):
    """ query to get geokret by name """
    name = name.replace(' ', '%')
    return f"""
            select
                kret.waypoint,
                l.ns_degree,
                l.ew_degree,
                COUNT(kret.id) as cnt,
                MAX(kret.distance) as distance
            from geokret kret
            left join location l on kret.location_id=l.id
            where kret.waypoint is not null and length(kret.waypoint) > 0
                and kret.name LIKE '%{name}%' and
                kret.state in (0,3)
                and l.id is not null
            group by kret.waypoint, l.ns_degree, l.ew_degree
            """

def get_krety_list(sql):
    """ get krety using sql query """
    krety = []
    if not sql:
        return krety
    for row in sql2table(sql):
        kret = KretyWaypoint()
        kret.waypoint = row[0]
        kret.count = row[3]
        kret.latitude = row[1]
        kret.longitude = row[2]
        kret.distance = row[4]
        krety.append(kret)
    return krety


import sublime
import sublime_plugin
import re
import http.client
import hashlib
import urllib
import random
import json
from .config import appid, secretKey

def baidu_translate(word):
    myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'

    from_lang = 'auto'
    to_lang = 'en'
    salt = random.randint(32768, 65536)
    sign = appid + word + str(salt) + secretKey
    sign = hashlib.md5(sign.encode(encoding="utf-8")).hexdigest()

    data = {
        'from': from_lang,
        'to': to_lang,
        'appid': appid,
        'salt': str(salt),
        'sign': sign,
        'q': word
    }
    data = urllib.parse.urlencode(data)
    url = '%s?%s' % (myurl, data)
    res = urllib.request.urlopen(url)
    result = str(res.read(), encoding='utf-8')
    result = json.loads(result)
    if result.get('error_code') is None:
        result_s = []
        for s in result['trans_result']:
            result_s.append(s['dst'])
        result_s = '\n'.join(result_s)
        return result_s
    elif result.get('error_code') == '52003':
        sublime.error_message('错误的appid')
    else:
        return None

class LineTranslatorCommand(sublime_plugin.TextCommand):
    print('translator正在将中文翻译为英文...')
    def is_chinese(self, ch):
        if type(ch) != str: return False
        return '\u4e00' <= ch <= '\u9fff'

    def check_key(self):
        if appid == '' or secretKey == '':
            sublime.error_message('请前往api.fanyi.baidu.com申请appid和secretKey,并添加在config.py')
            return False
        return True

    def translate(self, region, prefix, string):
       dst = baidu_translate(string)
       if dst:
          self.view.run_command('replace', {'region': (region.a, region.b), 'string': prefix + dst})

    def run(self, edit):
        if not self.check_key():
            return

        only_line = False

        choose_line = self.view.sel()[0]
        if choose_line.a == choose_line.b:
            only_line = True

        if only_line:
            region = self.view.line(choose_line)
            line_string = self.view.substr(region)
            for ch in line_string:
                if self.is_chinese(ch):
                    index = line_string.find(ch)
                    chinese_string = line_string[index:]
                    prefix = '' if index == 0 else line_string[0: index]
                    break
        else:
            region = choose_line
            chinese_string = self.view.substr(region)
            prefix = ''

        sublime.set_timeout_async(lambda :self.translate(region, prefix, chinese_string), 0)

class ReplaceCommand(sublime_plugin.TextCommand):
    def run(self, edit, region, string):
        region = sublime.Region(region[0], region[1])
        self.view.replace(edit, region, string)


import random

Bowser_is_best = ['Did your mother Chris Brown you as a baby? You fucking retard?', 'Your opinion is shit', 'Ding dong your opinion is wrong', 'Fucking kill yourself', 'Listen here you clueless shit where the fuckdoyouliveiwillcometoyourfuckinghouserightnowa-',\
                  'Go fuck yourself', 'You were adopted', 'Nobody loves you', 'You will die alone', 'Stop breathing']
Time = 2
while True:
    x = input ('Who in the SSBM cast is most DOPE?').lower()
    if Time == 0:
      print ('You are helpless. Goodbye')
      break
    Time -=1
    if x == "":
        break
    if x == 'bowser':
        print ('MY MAN!')
        break
    elif x == 'falco':
        print ('You aight')
        break
    elif x == 'ice climbers':
        print ('This isnt even funny at this point like seriously just go dive off of a cliff you filthy fucking degenerate')
        break
    else:
        print (random.choice(Bowser_is_best))


from typing import Tuple

import numpy as np
import torch
import PIL

from torchvision.transforms import transforms

from PIL import Image

from config.exception import InvalidImageModeException

class JitCycleGANModel:
    # i extract transform condition from original cycle gan repo
    transform = transforms.Compose([
        transforms.Resize((256, 256)),
        transforms.ToTensor(),
        transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
    ])

    # if you want to apply mlops, you need to get model from aws s3 or google drive
    jit_path = "./weight/jit_real_to_cartoon.pth"

    def __init__(self):
        self.model = torch.jit.load(self.jit_path)
        self.model.eval()

    @staticmethod
    def convert_pil_to_tensor(pil_image: PIL.Image.Image) -> Tuple[torch.Tensor, PIL.Image.Image]:

        if pil_image.mode == "RGB":
            pass
        elif pil_image.mode in ("L", "RGBA"):
            pil_image = pil_image.convert("RGB")
        else:
            raise InvalidImageModeException

        image: torch.Tensor = JitCycleGANModel.transform(pil_image)  # [3, 224, 224]
        return (image.unsqueeze(dim=0),  # [1, 3, 224, 224]
                pil_image)

    @staticmethod
    def convert_tensor_to_pil(tensor_image: torch.Tensor, origin_pil_image: PIL.Image.Image) -> PIL.Image.Image:
        # tensor_image : [1, 3, 256, 256]
        image_numpy = tensor_image[0].cpu().float().numpy()
        image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0  # post-processing: transpose and scaling
        generated_pil_image = Image.fromarray(image_numpy.astype(np.uint8))
        return generated_pil_image.resize(size=origin_pil_image.size)

    def inference(self, pil_image: PIL.Image.Image) -> PIL.Image.Image:
        (tensor_image, origin_pil_image) = self.convert_pil_to_tensor(pil_image)

        with torch.no_grad():
            output_tensor: torch.Tensor = self.model(tensor_image)  # [1, 3, 256, 256]

        return self.convert_tensor_to_pil(output_tensor, origin_pil_image)

if __name__ == '__main__':
    load_path = "./sample/a.png"
    output_path = "./sample/jit_cg_a.jpeg"
    input_pil_image = Image.open(load_path)

    jit_cg_model = JitCycleGANModel()
    output_pil_image = jit_cg_model.inference(input_pil_image)
    output_pil_image.save(output_path)


# ====================================================================
#
# Licensed under the GNU General Public License v3.0;
# you may not use this file except in compliance with the License.
#
# ====================================================================

from actor_logger import logger

class Action:
    STATUS_RUNNING = 'Running'
    STATUS_COMPLETED = 'Completed'
    STATUS_FAILED = 'Failed'

    def __init__(self, action_name, action_paras, action_type):
        self.action_output_summary = None
        self.action_output = None
        self.status = None
        self.name = action_name
        self.paras = action_paras
        self.type = action_type

    def action_running(self, task_id):
        self.status = Action.STATUS_RUNNING
        message = {"type": "action running", "id": task_id}
        action_res_all = "\n" + "Action <" + self.name + "> is running..."
        message['results'] = action_res_all
        return message

    def get_action_para(self, key):
        if key in self.paras.keys():
            return self.paras[key]
        else:
            return None

    def action_completed(self, task_id, action_output_summary, action_output):
        self.status = Action.STATUS_COMPLETED
        self.action_output_summary = action_output_summary
        self.action_output = action_output
        message = {"type": "action completed", "id": task_id}
        action_res_all = "Action <" + self.name + "> completed!"
        message['results'] = action_res_all
        message['output summary'] = action_output_summary
        #message['output'] = action_output
        return message

    def action_notfound(self, task_id, action_output_summary):
        self.status = Action.STATUS_FAILED
        self.action_output_summary = action_output_summary
        message = {"type": "action failed", "id": task_id}
        action_res_all = "Action <" + self.name + "> failed!"
        message['results'] = action_res_all
        message['output summary'] = action_output_summary
        return message

    # def set_exec_done(self, action_output_summary, action_output):
    #     self.status = Action.STATUS_COMPLETED
    #     self.action_output_summary = action_output_summary
    #     self.action_output = action_output
    #
    # def set_exec_failed_notfound(self, action_output_summary):
    #     self.status = Action.STATUS_FAILED
    #     self.action_output_summary = action_output_summary

class Task:
    STATUS_NEW = 'New'
    STATUS_PENDING = 'Pending'
    STATUS_RUNNING = 'Running'
    STATUS_COMPLETED = 'Completed'
    STATUS_CANCELLED = 'Cancelled'
    STATUS_QUIT_ERRORS = 'Quit with errors'

    def __init__(self, message):
        # The message from the server (in json) should have the following format:
        # {'name': task_name, 'id': task_id, 'actions': [{'name': action_name, 'paras': action_paras, 'type': action_type, }, {}, ... ]
        self.id = message['id']  # an ID generated by the server, not included in the test script.
        self.name = message['test_name']
        self.message = message
        self.actions = self.parse_actions()
        self.current = -1  # the current action index in the actions list
        self.actions_status = [None] * len(self.actions)
        self.task_status = Task.STATUS_NEW   # Task status taken from 'New', 'Pending', 'Running', 'Completed', 'Cancelled', 'Quit with errors'

    def parse_actions(self):
        action_list = []
        actions_msg = self.message['actions']
        for item in actions_msg:
            #action = Action(item['name'], item['paras'], item['type'])
            action = Action(item['name'], item['paras'], None)
            action_list.append(action)

        return action_list

    def first_five_actions_str(self):
        size = len(self.actions) if len(self.actions) < 5 else 5
        str_five = ""
        for i in range(size):
            str_five = str_five + self.actions[i].name + "; "
        return str_five

    def next_action(self):
        self.current = self.current + 1
        if self.current >= len(self.actions):
            return None
        else:
            return self.actions[self.current]

    def task_running(self):
        self.task_status = Task.STATUS_RUNNING
        message = {"type": "task running", "id": self.id}
        action_res_all = "Test task is now running..."
        message['results'] = action_res_all
        return message

    def task_completed(self):
        self.task_status = Task.STATUS_COMPLETED
        # TO DO: generate a report summarizing the test results to the server
        message = {"type": "task completed", "id": self.id}
        action_res_all = "\n" + "Test task completed!"
        # action_res_all = []
        # for action in self.actions:
        #     action_res = {'name': action.name, 'status': action.status, 'description': action.action_output_summary}
        #     action_res_all.append(action_res)
        message['results'] = action_res_all
        return message


#!/usr/bin/env python
# encoding=utf-8
# maintainer: rgaudin

import inspect

import reversion
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _

from bolibana.models import EntityType, Report, MonthPeriod

class MalariaReport(Report):

    """ Complies with bolibana.reporting.DataBrowser """

    YES = 'Y'
    NO = 'N'
    YESNO = ((YES, _(u"Yes")), (NO, _(u"No")))

    class Meta:
        app_label = 'pnlp_core'
        verbose_name = _(u"Malaria Report")
        verbose_name_plural = _(u"Malaria Reports")
        unique_together = ('period', 'entity', 'type')

    u5_total_consultation_all_causes = models.PositiveIntegerField( \
                                           _(u"Total Consultation All Causes"))
    u5_total_suspected_malaria_cases = models.PositiveIntegerField( \
                                           _(u"Total Suspected Malaria Cases"))
    u5_total_simple_malaria_cases = models.PositiveIntegerField( \
                                              _(u"Total Simple Malaria Cases"))
    u5_total_severe_malaria_cases = models.PositiveIntegerField( \
                                              _(u"Total Severe Malaria Cases"))
    u5_total_tested_malaria_cases = models.PositiveIntegerField( \
                                              _(u"Total Tested Malaria Cases"))
    u5_total_confirmed_malaria_cases = models.PositiveIntegerField( \
                                           _(u"Total Confirmed Malaria Cases"))
    u5_total_treated_malaria_cases = models.PositiveIntegerField( \
                                             _(u"Total Treated Malaria Cases"))
    u5_total_inpatient_all_causes = models.PositiveIntegerField( \
                                              _(u"Total Inpatient All Causes"))
    u5_total_malaria_inpatient = models.PositiveIntegerField( \
                                                 _(u"Total Malaria Inpatient"))
    u5_total_death_all_causes = models.PositiveIntegerField( \
                                                  _(u"Total Death All Causes"))
    u5_total_malaria_death = models.PositiveIntegerField( \
                                                     _(u"Total Malaria Death"))
    u5_total_distributed_bednets = models.PositiveIntegerField( \
                                               _(u"Total Distributed Bednets"))

    o5_total_consultation_all_causes = models.PositiveIntegerField( \
                                           _(u"Total Consultation All Causes"))
    o5_total_suspected_malaria_cases = models.PositiveIntegerField( \
                                           _(u"Total Suspected Malaria Cases"))
    o5_total_simple_malaria_cases = models.PositiveIntegerField( \
                                              _(u"Total Simple Malaria Cases"))
    o5_total_severe_malaria_cases = models.PositiveIntegerField( \
                                              _(u"Total Severe Malaria Cases"))
    o5_total_tested_malaria_cases = models.PositiveIntegerField( \
                                              _(u"Total Tested Malaria Cases"))
    o5_total_confirmed_malaria_cases = models.PositiveIntegerField( \
                                           _(u"Total Confirmed Malaria Cases"))
    o5_total_treated_malaria_cases = models.PositiveIntegerField( \
                                             _(u"Total Treated Malaria Cases"))
    o5_total_inpatient_all_causes = models.PositiveIntegerField( \
                                              _(u"Total Inpatient All Causes"))
    o5_total_malaria_inpatient = models.PositiveIntegerField( \
                                                 _(u"Total Malaria Inpatient"))
    o5_total_death_all_causes = models.PositiveIntegerField( \
                                                  _(u"Total Death All Causes"))
    o5_total_malaria_death = models.PositiveIntegerField( \
                                                     _(u"Total Malaria Death"))

    pw_total_consultation_all_causes = models.PositiveIntegerField( \
                                           _(u"Total Consultation All Causes"))
    pw_total_suspected_malaria_cases = models.PositiveIntegerField( \
                                           _(u"Total Suspected Malaria Cases"))
    pw_total_severe_malaria_cases = models.PositiveIntegerField( \
                                              _(u"Total Severe Malaria Cases"))
    pw_total_tested_malaria_cases = models.PositiveIntegerField( \
                                              _(u"Total Tested Malaria Cases"))
    pw_total_confirmed_malaria_cases = models.PositiveIntegerField( \
                                           _(u"Total Confirmed Malaria Cases"))
    pw_total_treated_malaria_cases = models.PositiveIntegerField( \
                                             _(u"Total Treated Malaria Cases"))
    pw_total_inpatient_all_causes = models.PositiveIntegerField( \
                                              _(u"Total Inpatient All Causes"))
    pw_total_malaria_inpatient = models.PositiveIntegerField( \
                                                 _(u"Total Malaria Inpatient"))
    pw_total_death_all_causes = models.PositiveIntegerField( \
                                                  _(u"Total Death All Causes"))
    pw_total_malaria_death = models.PositiveIntegerField( \
                                                     _(u"Total Malaria Death"))
    pw_total_distributed_bednets = models.PositiveIntegerField( \
                                               _(u"Total Distributed Bednets"))
    pw_total_anc1 = models.PositiveIntegerField(_(u"Total ANC1 Visits"))
    pw_total_sp1 = models.PositiveIntegerField(_(u"Total SP1 given"))
    pw_total_sp2 = models.PositiveIntegerField(_(u"Total SP2 given"))

    stockout_act_children = models.CharField(_(u"ACT Children"), \
                                             max_length=1, choices=YESNO)
    stockout_act_youth = models.CharField(_(u"ACT Youth"), \
                                          max_length=1, choices=YESNO)
    stockout_act_adult = models.CharField(_(u"ACT Adult"), \
                                          max_length=1, choices=YESNO)
    stockout_artemether = models.CharField(_(u"Artemether"), \
                                           max_length=1, choices=YESNO)
    stockout_quinine = models.CharField(_(u"Quinine"), \
                                        max_length=1, choices=YESNO)
    stockout_serum = models.CharField(_(u"Serum"), max_length=1, choices=YESNO)
    stockout_bednet = models.CharField(_(u"Bednets"), \
                                       max_length=1, choices=YESNO)
    stockout_rdt = models.CharField(_(u"RDTs"), max_length=1, choices=YESNO)
    stockout_sp = models.CharField(_(u"SPs"), max_length=1, choices=YESNO)

    sources = models.ManyToManyField('MalariaReport', \
                                     verbose_name=_(u"Sources"), \
                                     blank=True, null=True)

    @property
    def total_consultation_all_causes(self):
        return self.total_for_field(inspect.stack()[0][3])

    @property
    def total_suspected_malaria_cases(self):
        return self.total_for_field(inspect.stack()[0][3])

    @property
    def total_simple_malaria_cases(self):
        # no value for pregnant_women
        return self.u5_total_simple_malaria_cases \
               + self.o5_total_simple_malaria_cases

    @property
    def total_severe_malaria_cases(self):
        return self.total_for_field(inspect.stack()[0][3])

    @property
    def total_tested_malaria_cases(self):
        return self.total_for_field(inspect.stack()[0][3])

    @property
    def total_confirmed_malaria_cases(self):
        return self.total_for_field(inspect.stack()[0][3])

    @property
    def total_treated_malaria_cases(self):
        return self.total_for_field(inspect.stack()[0][3])

    @property
    def total_inpatient_all_causes(self):
        return self.total_for_field(inspect.stack()[0][3])

    @property
    def total_malaria_inpatient(self):
        return self.total_for_field(inspect.stack()[0][3])

    @property
    def total_death_all_causes(self):
        return self.total_for_field(inspect.stack()[0][3])

    @property
    def total_malaria_death(self):
        return self.total_for_field(inspect.stack()[0][3])

    @property
    def total_anc1(self):
        return self.total_for_field(inspect.stack()[0][3])

    @property
    def total_sp1(self):
        return self.total_for_field(inspect.stack()[0][3])

    @property
    def total_sp2(self):
        return self.total_for_field(inspect.stack()[0][3])

    def total_for_field(self, field):
        values = []
        for cat in ('u5', 'o5', 'pw'):
            fname = '%s_%s' % (cat, field)
            if hasattr(self, fname):
                values.append(getattr(self, fname))
        return sum(values)

    @property
    def mperiod(self):
        """ casted period to MonthPeriod """
        mp = self.period
        mp.__class__ = MonthPeriod
        return mp

    @classmethod
    def start(cls, period, entity, author, \
               type=Report.TYPE_SOURCE, *args, **kwargs):
        """ creates a report object with meta data only. Object not saved """
        report = cls(period=period, entity=entity, created_by=author, \
                     modified_by=author, _status=cls.STATUS_CREATED, \
                     type=type)
        for arg, value in kwargs.items():
            try:
                setattr(report, arg, value)
            except AttributeError:
                pass

        return report

    def add_underfive_data(self, total_consultation_all_causes, \
                                 total_suspected_malaria_cases, \
                                 total_simple_malaria_cases, \
                                 total_severe_malaria_cases, \
                                 total_tested_malaria_cases, \
                                 total_confirmed_malaria_cases, \
                                 total_treated_malaria_cases, \
                                 total_inpatient_all_causes, \
                                 total_malaria_inpatient, \
                                 total_death_all_causes, \
                                 total_malaria_death, \
                                 total_distributed_bednets):
        self.u5_total_consultation_all_causes = total_consultation_all_causes
        self.u5_total_suspected_malaria_cases = total_suspected_malaria_cases
        self.u5_total_simple_malaria_cases = total_simple_malaria_cases
        self.u5_total_severe_malaria_cases = total_severe_malaria_cases
        self.u5_total_tested_malaria_cases = total_tested_malaria_cases
        self.u5_total_confirmed_malaria_cases = total_confirmed_malaria_cases
        self.u5_total_treated_malaria_cases = total_treated_malaria_cases
        self.u5_total_inpatient_all_causes = total_inpatient_all_causes
        self.u5_total_malaria_inpatient = total_malaria_inpatient
        self.u5_total_death_all_causes = total_death_all_causes
        self.u5_total_malaria_death = total_malaria_death
        self.u5_total_distributed_bednets = total_distributed_bednets

    def add_overfive_data(self, total_consultation_all_causes, \
                                 total_suspected_malaria_cases, \
                                 total_simple_malaria_cases, \
                                 total_severe_malaria_cases, \
                                 total_tested_malaria_cases, \
                                 total_confirmed_malaria_cases, \
                                 total_treated_malaria_cases, \
                                 total_inpatient_all_causes, \
                                 total_malaria_inpatient, \
                                 total_death_all_causes, \
                                 total_malaria_death):
        self.o5_total_consultation_all_causes = total_consultation_all_causes
        self.o5_total_suspected_malaria_cases = total_suspected_malaria_cases
        self.o5_total_simple_malaria_cases = total_simple_malaria_cases
        self.o5_total_severe_malaria_cases = total_severe_malaria_cases
        self.o5_total_tested_malaria_cases = total_tested_malaria_cases
        self.o5_total_confirmed_malaria_cases = total_confirmed_malaria_cases
        self.o5_total_treated_malaria_cases = total_treated_malaria_cases
        self.o5_total_inpatient_all_causes = total_inpatient_all_causes
        self.o5_total_malaria_inpatient = total_malaria_inpatient
        self.o5_total_death_all_causes = total_death_all_causes
        self.o5_total_malaria_death = total_malaria_death

    def add_pregnantwomen_data(self, total_consultation_all_causes, \
                                 total_suspected_malaria_cases, \
                                 total_severe_malaria_cases, \
                                 total_tested_malaria_cases, \
                                 total_confirmed_malaria_cases, \
                                 total_treated_malaria_cases, \
                                 total_inpatient_all_causes, \
                                 total_malaria_inpatient, \
                                 total_death_all_causes, \
                                 total_malaria_death, \
                                 total_distributed_bednets, \
                                 total_anc1, \
                                 total_sp1, \
                                 total_sp2):
        self.pw_total_consultation_all_causes = total_consultation_all_causes
        self.pw_total_suspected_malaria_cases = total_suspected_malaria_cases
        self.pw_total_severe_malaria_cases = total_severe_malaria_cases
        self.pw_total_tested_malaria_cases = total_tested_malaria_cases
        self.pw_total_confirmed_malaria_cases = total_confirmed_malaria_cases
        self.pw_total_treated_malaria_cases = total_treated_malaria_cases
        self.pw_total_inpatient_all_causes = total_inpatient_all_causes
        self.pw_total_malaria_inpatient = total_malaria_inpatient
        self.pw_total_death_all_causes = total_death_all_causes
        self.pw_total_malaria_death = total_malaria_death
        self.pw_total_distributed_bednets = total_distributed_bednets
        self.pw_total_anc1 = total_anc1
        self.pw_total_sp1 = total_sp1
        self.pw_total_sp2 = total_sp2

    def add_stockout_data(self, stockout_act_children, \
                                stockout_act_youth, \
                                stockout_act_adult, \
                                stockout_artemether, \
                                stockout_quinine, \
                                stockout_serum, \
                                stockout_bednet, \
                                stockout_rdt, \
                                stockout_sp):
        self.stockout_act_children = stockout_act_children
        self.stockout_act_youth = stockout_act_youth
        self.stockout_act_adult = stockout_act_adult
        self.stockout_artemether = stockout_artemether
        self.stockout_quinine = stockout_quinine
        self.stockout_serum = stockout_serum
        self.stockout_bednet = stockout_bednet
        self.stockout_rdt = stockout_rdt
        self.stockout_sp = stockout_sp

    def fill_blank(self):
        self.add_underfive_data(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
        self.add_overfive_data(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
        self.add_pregnantwomen_data(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
        self.add_stockout_data(self.NO, self.NO, self.NO, self.NO, self.NO, \
                               self.NO, self.NO, self.NO, self.NO)

    def to_dict(self):
        d = {}
        for field in self._meta.get_all_field_names():
            try:
                if not field.split('_')[0] in ('u5', 'o5', 'pw', 'stockout'):
                    continue
            except:
                continue
            d[field] = getattr(self, field)
        return d

    @classmethod
    def generate_receipt(cls, instance):
        """ generates a reversable text receipt for a MalariaReport

        FORMAT:
            RR000/sss-111-D
            RR: region code on two letters
            000: internal report ID
            sss: entity slug
            111: sent day in year
            D: sent day of week """

        DOW = ['D', 'L', 'M', 'E', 'J', 'V', 'S']
        region_type = EntityType.objects.get(slug='region')

        def region_id(slug):
            return slug.upper()[0:2]

        region = 'ML'
        for ent in instance.entity.get_ancestors().reverse():
            if ent.type == region_type:
                region = region_id(ent.slug)
                break
        receipt = '%(region)s%(id)d/%(entity)s-%(day)s-%(dow)s' \
                  % {'day': instance.created_on.strftime('%j'), \
                     'dow': DOW[int(instance.created_on.strftime('%w'))], \
                     'entity': instance.entity.slug, \
                     'id': instance.id, \
                     'period': instance.period.id, \
                     'region': region}
        return receipt

    def get(self, slug):
        """ [data browser] returns data for a slug variable """
        return getattr(self, slug)

    def field_name(self, slug):
        """ [data browser] returns name of field for a slug variable """
        return self._meta.get_field(slug).verbose_name

    def validate(self):
        """ runs MalariaReportValidator """
        from pnlp_core.validators import MalariaReportValidator
        validator = MalariaReportValidator(self)
        validator.validate()
        return validator.errors

    @classmethod
    def create_aggregated(cls, period, entity, author, *args, **kwargs):
        agg_report = cls.start(period, entity, author, \
               type=Report.TYPE_AGGREGATED, *args, **kwargs)

        sources = MalariaReport.validated.filter(period=period, \
            entity__in=entity.get_children())

        if sources.count() == 0:
            agg_report.fill_blank()
            agg_report.save()

        for report in sources:
            for key, value in report.to_dict().items():
                pv = getattr(agg_report, key)
                if not pv:
                    nv = value
                elif pv in (cls.YES, cls.NO):
                    if pv == cls.YES:
                        nv = pv
                    else:
                        nv = value
                else:
                    nv = pv + value
                setattr(agg_report, key, nv)
            agg_report.save()

        for report in sources:
            agg_report.sources.add(report)

        with reversion.create_revision():
            agg_report.save()
            reversion.set_user(author.user)

        return agg_report

@receiver(pre_save, sender=MalariaReport)
def pre_save_report(sender, instance, **kwargs):
    """ change _status property of Report on save() at creation """
    if instance._status == instance.STATUS_UNSAVED:
        instance._status = instance.STATUS_CLOSED
    # following will allow us to detect failure in registration
    if not instance.receipt:
        instance.receipt = 'NO_RECEIPT'

@receiver(post_save, sender=MalariaReport)
def post_save_report(sender, instance, **kwargs):
    """ generates the receipt """
    if instance.receipt == 'NO_RECEIPT':
        instance.receipt = sender.generate_receipt(instance)
        instance.save()

reversion.register(MalariaReport)


import glob
import os
import pickle
import re
from typing import Dict

import matplotlib.pyplot as plt
import pandas as pd

def load_lasso_data(data_dir):
    if not data_dir.endswith("/"):
        data_dir += "/"
    input_files = glob.glob(data_dir + "log2*pkl")
    Abs = [os.path.split(i)[-1].split("_mic")[0] + "_mic" for i in input_files]
    data_dict = {}
    for i in range(len(Abs)):
        with open(input_files[i], "rb") as a:
            data_dict[Abs[i]] = pickle.load(a)
    return data_dict

def convert_to_dataframe_lasso(CV_results):
    """
    For formatting the output of the lasso model
    """

    df_dictionary = {
        "left_out_clade": [],
        "training_accuracy": [],
        "testing_accuracy": [],
        "validation_accuracy": [],
    }  # will be converted to df
    for left_out_clade, d in CV_results.items():
        d_val = {i: d[i]["validation_accuracy"] for i in d.keys()}
        k = max(d_val, key=d_val.get)  # key with max validation data accuracy
        df_dictionary["left_out_clade"].append(left_out_clade)
        df_dictionary["training_accuracy"].append(d[k]["training_accuracy"])
        df_dictionary["testing_accuracy"].append(d[k]["testing_accuracy"])
        df_dictionary["validation_accuracy"].append(d[k]["validation_accuracy"])

    return pd.DataFrame(df_dictionary)

def convert_to_dataframe(CV_results, SVR_data=False):
    df_dictionary = {
        "left_out_clade": [],
        "training_accuracy": [],
        "testing_accuracy": [],
        "validation_accuracy": [],
    }  # will be converted to df
    for left_out_clade, d in CV_results.items():
        df_dictionary["left_out_clade"].append(left_out_clade)
        if isinstance(d, Dict):
            if SVR_data:
                df_dictionary["training_accuracy"].append(
                    d["accuracies"]["training_accuracy"]
                )
                df_dictionary["testing_accuracy"].append(
                    d["accuracies"]["testing_accuracy"]
                )
                df_dictionary["validation_accuracy"].append(
                    d["accuracies"]["validation_accuracy"]
                )
            else:
                df_dictionary["training_accuracy"].append(
                    d["accuracies"][0]["training_accuracy"]
                )
                df_dictionary["testing_accuracy"].append(
                    d["accuracies"][0]["testing_accuracy"]
                )
                df_dictionary["validation_accuracy"].append(
                    d["accuracies"][0]["validation_accuracy"]
                )
        else:
            df_dictionary["training_accuracy"].append(d.training_accuracy)
            df_dictionary["testing_accuracy"].append(d.testing_accuracy)
            df_dictionary["validation_accuracy"].append(d.validation_accuracy)

    return pd.DataFrame(df_dictionary)

def _get_NN_results(data_dir, file_suffix=".tsv"):
    """
    Returns data from NN fitting metrics in form to be plotted with plot_results
    """
    if not data_dir.endswith("/"):
        data_dir += "/"

    input_files = glob.glob(data_dir + f"*{file_suffix}")
    Abs = [os.path.split(i)[-1].split("_mic")[0] + "_mic" for i in input_files]

    data_dict = {}
    for Ab in set(Abs):
        Ab_files = [i for i in input_files if i.startswith(data_dir + Ab)]
        Ab_accuracies = [None] * len(Ab_files)
        i = 0
        for f in Ab_files:
            left_out_clade = re.search(r"clade_(.*?)_left", f).group(1)
            last_line = pd.read_csv(Ab_files[0], sep="\t").iloc[-1]
            accuracies = last_line[
                [
                    "training_data_acc",
                    "testing_data_acc",
                    "validation_data_acc",
                ]
            ]
            accuracies["left_out_clade"] = int(left_out_clade)
            Ab_accuracies[i] = accuracies
            i += 1
        df = pd.concat(Ab_accuracies, axis=1).transpose()
        df.set_index("left_out_clade", inplace=True)
        df.columns = [
            "training_accuracy",
            "testing_accuracy",
            "validation_accuracy",
        ]
        data_dict[Ab] = df

    return data_dict

def get_SVR_results(dir_pattern):
    Abs = ["log2_azm_mic", "log2_cip_mic", "log2_cro_mic", "log2_cfx_mic"]

    input_files = [os.path.join(dir_pattern[0], Ab, dir_pattern[1]) for Ab in Abs]

    data_dict = {}
    for i in range(len(Abs)):
        with open(input_files[i], "rb") as a:
            data_dict[Abs[i]] = pickle.load(a)
    return data_dict

def density_plot(preds, labels, axs=None, axs_0=None, axs_1=None):
    df = pd.DataFrame({"Predictions": preds, "Truth": labels})
    if axs is not None:
        df.plot(kind="kde", ax=axs[axs_0, axs_1], legend=False)
        return axs
    else:
        df.plot(kind="kde")

def plot_train_preds_and_labels(data, Ab):
    fig, axs = plt.subplots(4, 3, sharex=True, sharey=True)
    n = 0
    m = 0
    for left_out_clade, d in data[Ab].items():
        axs = density_plot(
            d["model_outputs"]["training_predictions"],
            d["model_outputs"]["training_labels"],
            axs=axs,
            axs_0=n,
            axs_1=m,
        )

        # axs = density_plot(d['model_outputs']['testing_predictions'],
        #                     d['model_outputs']['testing_labels'],
        #                     axs = axs,
        #                     axs_0 = n,
        #                     axs_1 = 1)

        # axs = density_plot(d['model_outputs']['validation_predictions'],
        #                     d['model_outputs']['validation_labels'],
        #                     axs = axs,
        #                     axs_0 = n,
        #                     axs_1 = 2)

        if n > 0 and n % 3 == 0:
            n = 0
            m += 1
        else:
            n += 1
    fig.tight_layout()

def bar_plot_of_results(data, filename):
    fig, axs = plt.subplots(1, 4, sharey=True)
    width = 0.2
    n = 0
    for Ab in data.keys():
        df = data[Ab]
        axs[n].bar(
            df.index - width,
            df.training_accuracy,
            width,
            label="Training Data",
        )
        axs[n].bar(df.index, df.testing_accuracy, width, label="Testing Data")
        axs[n].bar(
            df.index + width,
            df.validation_accuracy,
            width,
            label="Validation Data",
        )
        axs[n].set_xticks(df.index)
        axs[n].set_title(Ab.upper().split("_")[1])
        n += 1

    axs[n - 1].legend(loc="lower right")
    fig.text(0.5, 0.04, "Left Out Clade", ha="center")
    fig.text(0.04, 0.5, "Prediction Accuracy (%)", va="center", rotation="vertical")

    fig.savefig(filename)

def rename_test_and_validate(df: pd.DataFrame) -> pd.DataFrame:
    return df.rename(
        columns={
            "validation_accuracy": "testing_accuracy",
            "testing_accuracy": "validation_accuracy",
        }
    )

def box_plot_of_results(data, filename):
    fig, axs = plt.subplots(1, 4, sharey=True)
    n = 0
    for Ab in data.keys():
        df = data[Ab]
        df.rename(
            columns={
                "training_accuracy": "Train",
                "testing_accuracy": "Test",
                "validation_accuracy": "Validate",
            },
            inplace=True,
        )
        df = df[["Train", "Validate", "Test"]]
        axs[n].boxplot(df, notch=False, labels=df.columns)
        axs[n].set_title(Ab.upper().split("_")[1])
        axs[n].set(ylim=(0, 100))
        axs[n].tick_params(labelrotation=90)
        n += 1

    fig.text(0, 0.5, "Mean Accuracy per MIC Bin", va="center", rotation="vertical")
    fig.tight_layout()

    fig.savefig(filename)

if __name__ == "__main__":
    data_dir = "lasso_model/results/linear_model_results/cross_validation_results/"  # noqa: E501
    data = load_lasso_data(data_dir)

    # svr results are stored within subdir with name of Ab,
    # unlike rest of results which are all stored in one dir
    # dir_pattern = (
    #     "kernel_learning",
    #     "cluster_wise_cross_validation/SVR_results/SVR_CV_results_mean_acc_per_bin.pkl",
    # )
    # data_dir = "."
    # data = get_SVR_results(dir_pattern)

    Abs = list(data.keys())
    Abs.sort()  # to maintain order
    accuracy_data = {Ab: convert_to_dataframe(data[Ab]) for Ab in Abs}
    accuracy_data = {
        Ab: df.set_index("left_out_clade") for Ab, df in accuracy_data.items()
    }
    accuracy_data = {k: rename_test_and_validate(v) for k, v in accuracy_data.items()}

    box_plot_of_results(accuracy_data, os.path.join(data_dir, "CV_accuracy.png"))


import discord
from discord.ext import commands
from datetime import datetime

intents = discord.Intents.all()
intents.members = True
bot = commands.Bot(command_prefix='!',intents=intents)

serverID = ""
with open('serverID.txt') as f:
    serverID = f.readline()
serverID = int(serverID)

bot.newChanBitrate = 9600
bot.oldFartServer = ""
bot.twosMakerChannel = ""
bot.threesMakerChannel = ""
bot.fourssMakerChannel = ""
bot.sixesMakerChannel = ""
bot.twosCategory = ""
bot.threesCategory = ""
bot.foursCategory = ""
bot.sixesCategory = ""
bot.lfgCategory = ""
bot.customCreators = []

@bot.event
async def on_ready():
    print(bot.user.name + " is Online...")
    print(datetime.now().strftime('%H:%M:%S %m-%d-%Y'))
    print('------')

    #get guild
    for g in bot.guilds:
        if g.id == serverID:
            print("Found server")
            bot.oldFartServer = g
            oldFartServer = bot.oldFartServer
            #set the new channel bitrate to whatever the max rate is for the server
            bot.newChanBitrate = int(oldFartServer.bitrate_limit)

    #create categories
    if not guild_has_category(oldFartServer, "2-MAX VOICE CHANNELS"):
        print("making 2v2 category...")
        await oldFartServer.create_category("2-MAX VOICE CHANNELS")

        bot.twosCategory = get_category(oldFartServer, "2-MAX VOICE CHANNELS")
         #create temp vc makers
        await oldFartServer.create_voice_channel("➕ Create 2's VC",category=bot.twosCategory)

    #create 3v3 category
    if not guild_has_category(oldFartServer, "3-MAX VOICE CHANNELS"):
        print("making 3v3 category...")
        await oldFartServer.create_category("3-MAX VOICE CHANNELS")

        bot.threesCategory = get_category(oldFartServer, "3-MAX VOICE CHANNELS")
         #create temp vc makers
        await oldFartServer.create_voice_channel("➕ Create 3's VC",category=bot.threesCategory)

    #create 4v4 category
    if not guild_has_category(oldFartServer, "4-MAX VOICE CHANNELS"):
        print("making 4v4 category...")
        await oldFartServer.create_category("4-MAX VOICE CHANNELS")

        bot.foursCategory = get_category(oldFartServer, "4-MAX VOICE CHANNELS")
         #create temp vc makers
        await oldFartServer.create_voice_channel("➕ Create 4's VC",category=bot.foursCategory)

    #create 6mans category
    if not guild_has_category(oldFartServer, "6-MAX VOICE CHANNELS"):
        print("making 6mans category...")
        await oldFartServer.create_category("6-MAX VOICE CHANNELS")

        bot.sixesCategory = get_category(oldFartServer, "6-MAX VOICE CHANNELS")
         #create temp vc makers
        await oldFartServer.create_voice_channel("➕ Create 6's VC",category=bot.sixesCategory)

    #get categories
    bot.twosCategory = get_category(oldFartServer, "2-MAX VOICE CHANNELS")
    bot.threesCategory = get_category(oldFartServer, "3-MAX VOICE CHANNELS")
    bot.foursCategory = get_category(oldFartServer, "4-MAX VOICE CHANNELS")
    bot.sixesCategory = get_category(oldFartServer, "6-MAX VOICE CHANNELS")
    #get creator channels
    for c in oldFartServer.channels:
        if c.name == "➕ Create 2's VC":
            bot.twosMakerChannel = c
        if c.name == "➕ Create 3's VC":
            bot.threesMakerChannel = c
        if c.name == "➕ Create 4's VC":
            bot.foursMakerChannel = c
        if c.name == "➕ Create 6's VC":
            bot.sixesMakerChannel = c

async def update_channels():
    print("update channels")
    try:
        await rename_and_reorder("2 Max", bot.twosMakerChannel.position +1)
    except Exception as e:
        print(e)
    try:
        await rename_and_reorder("3 Max", bot.threesMakerChannel.position +1)
    except Exception as e:
        print(e)
    try:
        await rename_and_reorder("4 Max", bot.foursMakerChannel.position +1)
    except Exception as e:
        print(e)
    try:
        await rename_and_reorder("6 Max", bot.sixesMakerChannel.position +1)
    except Exception as e:
        print(e)

@bot.event
async def on_voice_state_update(member, before, after):

    #delete any empty VCs that we are making
    if before.channel != None and "Max #" in before.channel.name:
        if len(before.channel.members) == 0:
            await before.channel.delete()
            await update_channels()

    if after.channel == bot.twosMakerChannel:
        #create 2 max VC
        cpos = bot.twosMakerChannel.position + 1
        await create_custom_channel("2 Max", cpos, bot.twosCategory,2,member)

    if after.channel == bot.threesMakerChannel:
        #create 3 max VC
        cpos = bot.threesMakerChannel.position + 1
        await create_custom_channel("3 Max", cpos, bot.threesCategory,3,member)

    if after.channel == bot.foursMakerChannel:
        #create 4 max VC
        cpos = bot.foursMakerChannel.position + 1
        await create_custom_channel("4 Max", cpos, bot.foursCategory,4,member)

    if after.channel == bot.sixesMakerChannel:
        #create 6 max VC
        cpos = bot.sixesMakerChannel.position + 1
        await create_custom_channel("6 Max", cpos, bot.sixesCategory,6,member)

async def create_custom_channel(cName, position, category, userLimit, player):
    cnum = 1
    cpos = position
    guild = bot.oldFartServer
    for c in guild.channels:
        if c != None and cName in c.name:
            await c.edit(name = cName +" #" + str(cnum))
            cnum = cnum+1
            cpos = cpos +1
    await guild.create_voice_channel(cName + " #" + str(cnum), position=cpos, category=category, bitrate = bot.newChanBitrate, user_limit=userLimit)
    #pull user into new VC
    for c in guild.channels:
        if c != None and c.name == cName + " #" + str(cnum):
            await player.move_to(c)

def guild_has_category(guild, cat):
    for c in guild.categories:
        if c.name == cat:
            return True
    print("didnt find it")
    return False

def get_category(guild, cat):
    for c in guild.categories:
        if c.name == cat:
            return c
    return

async def rename_and_reorder(cName, cPos):
    cnum = 1
    #for channel in server
    for c in bot.oldFartServer.channels:
        if c != None and cName in c.name:
            await c.edit(name = cName +" #" + str(cnum), position = cPos)
            cnum = cnum +1
            cPos = cPos +1

with open('token.txt') as f:
    TOKEN = f.readline()

bot.run(TOKEN)


from builtins import str
from builtins import object
from bson import json_util
from unicodecsv import DictWriter
from datetime import datetime
import json
import os

from ordered_set import OrderedSet

from mongoengine import Q
from mongoengine.fields import ReferenceField

from openelex import COUNTRY_DIR
from openelex.exceptions import UnsupportedFormatError
from openelex.lib import format_date, standardized_filename
from openelex.models import RawResult, Result, Contest, Candidate
from future.utils import with_metaclass

class FieldTransform(object):
    def __init__(self, doc, field_name, output_name=None):
        self.collection = doc._meta['collection']
        self.db_field = getattr(doc, field_name).db_field
        self.doc = doc
        self.output_name = output_name

    def transform(self, data):
        return data

class FieldNameTransform(FieldTransform):
    def transform(self, data):
        try:
            val = data[self.db_field]
            data[self.output_name] = val
            del data[self.db_field]
        except KeyError:
            data[self.output_name] = None

        return data

class FlattenFieldTransform(FieldTransform):
    def transform(self, data):
        try:
            data.update(data[self.db_field])
            del data[self.db_field]
        except KeyError:
            pass

        return data

class CalculatedField(object):
    def __init__(self, fn):
        self.fn = fn

    def apply(self, data):
        return self.fn(data)

class RollerMeta(type):
    """
    Metaclass for Roller that allows defining field name transformations
    in a declarative style.
    """
    def __new__(cls, name, bases, attrs):
        field_transforms = {}
        field_calculators = {}
        transformed_fields_ordered = []
        calculated_fields_ordered = []

        for k, v in list(attrs.items()):
            if isinstance(v, FieldTransform):
                transforms = field_transforms.setdefault(v.collection, {})
                transforms[v.db_field] = v
                # HACK Exclude flattened fields from the list of output fields.
                # The flattened fields' contents will get added, but the
                # original field shouldn't show up in the output.
                if not isinstance(v, FlattenFieldTransform):
                    if not v.output_name:
                        v.output_name = k
                    transformed_fields_ordered.append(v.output_name)

            elif isinstance(v, CalculatedField):
                field_calculators[k] = v.apply
                calculated_fields_ordered.append(k)

        attrs['field_transforms'] = field_transforms
        attrs['field_calculators'] = field_calculators
        attrs['transformed_fields_ordered'] = transformed_fields_ordered
        attrs['calculated_fields_ordered'] = calculated_fields_ordered

        return super(RollerMeta, cls).__new__(cls, name, bases, attrs)

class Roller(with_metaclass(RollerMeta, object)):
    """
    Filters and collects related data from document fields into a
    serializeable format.
    """

    def __init__(self):
        self._querysets = {}
        self._relationships = {}
        self._output_fields = []

        for coll in self.collections:
            name = coll._meta['collection']
            self._querysets[name] = getattr(coll, 'objects')
            if coll  == self.primary_collection:
                self._primary_queryset = self._querysets[name]

            self._contribute_fields(coll)

        self._output_fields.extend(self.calculated_fields_ordered)

    def _is_relationship_field(self, field):
        return isinstance(field, ReferenceField)

    def _contribute_fields(self, collection):
        is_primary = collection == self.primary_collection
        coll_name = collection._meta['collection']

        try:
            excluded_fields = list(self.excluded_fields[coll_name])
        except KeyError:
            excluded_fields = []
        excluded_fields.append('_id')
        excluded_field_set = set(excluded_fields)

        for field_name in collection._fields_ordered:
            field = collection._fields[field_name]
            db_field_name = field.db_field
            if db_field_name in excluded_field_set:
                continue

            if is_primary and self._is_relationship_field(field):
                # Track relationship fields but don't add them to the set of
                # output fields
                self._relationships[field.db_field] = field.document_type._meta['collection']
            else:
                output_field_name = self._transform_field_name(coll_name, db_field_name)
                if output_field_name:
                    self._output_fields.append(output_field_name)

    def _transform_field_name(self, collection_name, field_name):
        try:
            return self.field_transforms[collection_name][field_name].output_name
        except KeyError:
            return field_name

    @property
    def primary_collection_name(self):
        return self.primary_collection._meta['collection']

    def build_filters(self, **filter_kwargs):
        """
        Returns a dictionary of Q objects that will be used to limit the
        mapper querysets.

        This allows for translating arguments from upstream code to the
        filter format used by the underlying data store abstraction.

        This will build a set of filters common to all querysets and will call
        any build_filters_COLLECTION_NAME methods that have been implemented
        on this class.

        Arguments:

        * state: Required. Postal code for a state.  For example, "md".
        * datefilter: Date specified in "YYYY" or "YYYY-MM-DD" used to filter
          elections before they are baked.
        * election_type: Election type. For example, general, primary, etc.
        * reporting_level: Reporting level of the election results.  For example, "state",
          "county", "precinct", etc. Value must be one of the options specified
          in openelex.models.Result.REPORTING_LEVEL_CHOICES.

        """
        # TODO: Implement filtering by office, district and party after the
        # the data is standardized

        # By default, should filter to all state/contest-wide results for all
        # races when no filters are specified.
        filters= {}
        q_kwargs = {}

        q_kwargs['state'] = filter_kwargs['state'].upper()

        try:
            q_kwargs['election_id__contains'] = filter_kwargs['election_type']
        except KeyError:
            pass

        common_q = Q(**q_kwargs)

        # Merge in the date filters
        try:
            common_q &= self.build_date_filters(filter_kwargs['datefilter'])
        except KeyError:
            pass

        for collection_name in list(self._querysets.keys()):
            filters[collection_name] = common_q
            try:
                fn = getattr(self, 'build_filters_' + collection_name)
                collection_q = fn(**filter_kwargs)
                if collection_q:
                    filters[collection_name] &= collection_q
            except AttributeError:
                pass

        return filters

    @classmethod
    def build_date_filters(cls, datefilter):
        """
        Create a query object of filters based on a date string.

        Arguments:
            datefilter (string): String representation of date.

        Returns:
            Q object of filters based on date string.

        """
        filters = {}

        if not datefilter:
            return Q()

        # For now we filter on the date string in the election IDs
        # under the assumption that this will be faster than filtering
        # across a reference.
        filters['election_id__contains'] = format_date(datefilter)

        # Return a Q object rather than just a dict because the non-date
        # filters might also filter with a ``election_id__contains`` keyword
        # argument, clobbering the date filter, or vice-versa
        return Q(**filters)

    def build_filters_result(self, **filter_kwargs):
        try:
            return Q(reporting_level=filter_kwargs['reporting_level'])
        except KeyError:
            return None

    def apply_filters(self, **queries):
        """
        Filter querysets.
        """
        for collection_name, qs in list(self._querysets.items()):
            q = queries.get(collection_name)
            if q:
                self._querysets[collection_name] = qs(q)

    def build_fields(self, **filter_kwargs):
        """
        Returns a dictionary where the keys are the collection name and the
        values are lists of fields that will be included in the result or an
        empty list to include all fields.
        """
        return {}

    def build_exclude_fields(self, **filter_kwargs):
        return self.excluded_fields

    def apply_field_limits(self, fields={}, exclude_fields={}):
        """
        Limit the fields returned when evaluating the querysets.
        """
        for collection_name, flds in list(exclude_fields.items()):
            qs = self._querysets[collection_name].exclude(*flds)
            self._querysets[collection_name] = qs

        for collection_name, flds in list(fields.items()):
            qs = self._querysets[collection_name].only(*flds)
            self._querysets[collection_name] = qs

    def transform_fields(self, data, transforms):
        """Convert field names on a flat row of data"""
        for field_name, transform in list(transforms.items()):
            data = transform.transform(data)

        return data

    def get_calculated_fields(self, data):
        calculated_fields = {}
        for name, fn in list(self.field_calculators.items()):
            calculated_fields[name] = fn(data)
        return calculated_fields

    def flatten(self, primary, **related):
        """
        Returns a dictionary representing a single "row" of data, created by
        merging the fields from multiple mapper models/documents.
        """
        flat = {}
        # Remove id and reference id fields
        primary.pop('_id', None)
        for fname in list(self._relationships.keys()):
            primary.pop(fname, None)

        transforms = self.field_transforms.get(self.primary_collection_name)
        if transforms:
            primary = self.transform_fields(primary, transforms)

        # Merge in the related data
        for name, data in list(related.items()):
            # Prefix fields on related models for better readability in the
            # final output data, to prevent clobbering any duplicate keys
            # and to make the fields more accessible to our transformers
            # and calculators.
            data.pop('_id', None)
            transforms = self.field_transforms.get(name)
            if transforms:
                data = self.transform_fields(data, transforms)
            flat.update(data)

        flat.update(primary)
        flat.update(self.get_calculated_fields(flat))

        return flat

    def get_list(self, **filter_kwargs):
        """
        Returns a list of filtered, limited and flattened election results.
        """
        filters = self.build_filters(**filter_kwargs)
        fields = self.build_fields(**filter_kwargs)
        exclude_fields = self.build_exclude_fields(**filter_kwargs)
        self.apply_filters(**filters)
        self.apply_field_limits(fields, exclude_fields)
        # A list of encountered fields to accomodate dynamic document fields.
        # Start off with the list of known fields built in the constructor.
        self._fields = OrderedSet(self._output_fields)

        # It's slow to follow the referenced fields at the MongoEngine level
        # so just build our own map of related items in memory.
        #
        # We use as_pymongo() here, and below, because it's silly and expensive
        # to construct a bunch of model instances from the dictionary
        # representation returned by pymongo, only to convert them back to
        # dictionaries for serialization.
        related_map = {}
        for related_field, related_collection in list(self._relationships.items()):
            related_map[related_field] = {
                str(c['_id']):c for c
                in self._querysets[related_collection].as_pymongo()
            }

        # We'll save the flattened items as an attribute to support a
        # chainable interface.
        self._items = []
        primary_qs = self._querysets[self.primary_collection_name].as_pymongo()
        try:
            for primary in primary_qs:
                related = {}
                for fname, coll in list(self._relationships.items()):
                    related[fname] = related_map[coll][str(primary[fname])]

                flat = self.flatten(primary, **related)
                self._fields |= list(flat.keys())
                self._items.append(flat)
        except:
            pass

        return self._items

    def get_fields(self):
        """
        Returns a list of all fields encountered when building the flattened
        data with a call to get_list()

        This list is appropriate for writing a header row in a csv file
        using csv.DictWriter.
        """
        try:
            return list(self._fields)
        except AttributeError:
            return self._output_fields

class ResultRoller(Roller):
    collections = [
        Contest,
        Candidate,
        Result,
    ]
    """
    List of mapper document/model classes that will be queried and flattened.
    """

    primary_collection = Result
    """
    Mapper document/model class that will "receive" data from other collections.
    """

    # Field name transformations so output fields match the specs at
    # https://github.com/openelections/specs/wiki/Results-Data-Spec-Version-1
    # and
    # https://github.com/openelections/specs/wiki/Elections-Data-Spec-Version-2

    # HACK: election_id will get converted to 'id' in the final output.  Had to work around
    # the fact that id is a builtin in Python < 3
    election_id = FieldNameTransform(Result, 'election_id', output_name='id')
    first_name = FieldNameTransform(Candidate, 'given_name')
    last_name = FieldNameTransform(Candidate, 'family_name')
    middle_name = FieldNameTransform(Candidate, 'additional_name')
    votes = FieldNameTransform(Result, 'total_votes')
    division = FieldNameTransform(Result, 'ocd_id')
    updated_at = FieldNameTransform(Contest, 'updated')

    # Calculated fields to match specs.
    #
    # These are run after any of the field name transformations and
    # after data has been merged into a single dictionary from any related
    # documents. So the lambda functions should reference the new name in the
    # dictionary.
    year = CalculatedField(lambda d: d['start_date'].year)

    excluded_fields = {
        'result': ['candidate_slug', 'contest_slug', 'raw_result',],
        'candidate': [
            'contest',
            'contest_slug',
            'election_id',
            'parties',
            'source',
            'slug',
        ],
        'contest': ['election_id', 'party', 'source', 'slug',],
    }
    """
    Mongodb fields that should be excluded from output data.

    The excluded fields can be altered dynamically by overriding the
    ``build_excluded_fields()`` method.
    """

    def build_fields(self, **filter_kwargs):
        return {
            'result': [],
            'candidate': [],
            'contest': [],
        }

class RawResultRoller(Roller):
    collections = [
        RawResult,
    ]

    primary_collection = RawResult

    # Field name transformations so output fields match the specs at
    # https://github.com/openelections/specs/wiki/Results-Data-Spec-Version-1
    # and
    # https://github.com/openelections/specs/wiki/Elections-Data-Spec-Version-2

    # HACK: election_id will get converted to 'id' in the final output.  Had to work around
    # the fact that id is a builtin in Python < 3
    election_id = FieldNameTransform(RawResult, 'election_id', output_name='id')
    first_name = FieldNameTransform(RawResult, 'given_name')
    last_name = FieldNameTransform(RawResult, 'family_name')
    middle_name = FieldNameTransform(RawResult, 'additional_name')
    name_raw = FieldNameTransform(RawResult, 'full_name')
    division = FieldNameTransform(RawResult, 'ocd_id')
    updated_at = FieldNameTransform(RawResult, 'updated')
    vote_breakdowns = FlattenFieldTransform(RawResult, 'vote_breakdowns',
        output_name=None)

    # Calculated fields to match specs.
    #
    # These are run after any of the field name transformations and
    # after data has been merged into a single dictionary from any related
    # documents. So the lambda functions should reference the new name in the
    # dictionary.
    year = CalculatedField(lambda d: d['start_date'].year)

    excluded_fields = {
        'raw_result': [
            'contest_winner',
            'county_ocd_id',
            'created',
            'name_slug',
            'primary_party',
            'primary_type',
            'reporting_district',
            'reporting_level',
            'source',
            'state',
        ],
    }

    def build_fields(self, **filter_kwargs):
        return {
            'raw_result': [],
        }

    def build_filters_raw_result(self, **filter_kwargs):
        try:
            return Q(reporting_level=filter_kwargs['reporting_level'])
        except KeyError:
            return None

class BaseBaker(object):
    """Base class for classes that write election and candidate data to structured files"""

    timestamp_format = "%Y%m%dT%H%M%S"
    """
    stftime() format string used to format timestamps. Mostly used for
    creating filenames.

    Defaults to a version of ISO-8601 without '-' or ':' characters.
    """

    def __init__(self, **filter_kwargs):
        self.filter_kwargs = filter_kwargs

    def default_outputdir(self):
        """
        Returns the default path for storing output files.

        This will be used if a directory is not specifically passed to the
        constructor.  It's implemented as a method in case subclasses
        want to base the directory name on instance attributes.
        """
        return os.path.join(COUNTRY_DIR, 'bakery')

    @classmethod
    def filename(cls, fmt, timestamp=None, **filter_kwargs):
        """
        Generate a filename for the output file.

        Args:
            fmt (string): Output format of the results, usually corresponds
                to the filename extension.  For example, "csv" or "json".
            timestamp (datetime): Timestamp to be included in the filename.
                Default is value of ``datetime.now()``.
            **filter_kwargs (mixed): Keyword arguments used to select the
                results included in the output results file.  These will be
                used to construct the output filename.

        Returns:
            A string represneting the filename for the results file.
        """
        if timestamp is None:
            timestamp = datetime.now()

        state = filter_kwargs.get('state')
        return "%s_%s.%s" % (state.lower(),
            timestamp.strftime(cls.timestamp_format), fmt)

    @classmethod
    def manifest_filename(cls, timestamp, **filter_kwargs):
        """
        Returns the filename string for the manifest output file.
        """
        state = filter_kwargs.get('state')
        return "%s_%s_manifest.txt" % (state.lower(),
            timestamp.strftime(cls.timestamp_format))

    def collect_items(self):
        """
        Query the data store and retrieve a flattened, filtered list of
        election results.

        This should be implemented in a subclass.

        Returns:
            ``self``, allowing a chainable interface.

            Implementations of this method in subclasses should set the
            ``_items`` attribute of the class instance to a list of result
            dictionaries and the ``_fields`` attribute to a list of field names
            found in the result dictionaries.  Otherwise, subclasses will need
            to override the ``get_items()`` and ``get_fields()`` methods.

        """
        self._items = []
        self._fields = []
        return self

    def get_items(self):
        """
        Retrieve a flattened, filtered list of election results.

        Returns:
            A list of result dictionaries.  By default, this is the value of
            ``self._items`` which should be populated with a call to
            ``collect_items()``.

            If results need to be retrieved in some other way, this
            method should be overridden in a subclass.

        """
        try:
            return self._items
        except AttributeError:
            return []

    def get_fields(self):
        """
        Retrieve a list of fields found in result records.

        This facilitates writing the header row of CSV-formatted files.

        Returns:
            A list of field names. By default, this is the value of
            ``self._fields`` which should be populated with a call to
            ``collect_items()``.

            If the fields need to be retrieved in some other way, this
            method should be overridden in a subclass.

        """
        return self._fields

    def write(self, fmt='csv', outputdir=None, timestamp=None):
        """
        Writes collected data to a file.

        Arguments:

        * fmt: Output format. Either 'csv' or 'json'. Default is 'csv'.
        * outputdir: Directory where output files will be written. Defaults to
          "openelections/us/bakery"

        """
        try:
            fmt_method = getattr(self, 'write_' + fmt)
        except AttributeError:
            raise UnsupportedFormatError("Format %s is not supported" % (fmt))

        if outputdir is None:
            outputdir = self.default_outputdir()

        if not os.path.exists(outputdir):
            os.makedirs(outputdir)

        if timestamp is None:
            timestamp = datetime.now()

        return fmt_method(outputdir, timestamp)

    def write_csv(self, outputdir, timestamp, items=None):
        path = os.path.join(outputdir,
            self.filename('csv', timestamp, **self.filter_kwargs))

        if items is None:
            items = self.get_items()

        with open(path, 'w') as csvfile:
            writer = DictWriter(csvfile, self.get_fields())
            writer.writeheader()
            for row in items:
                writer.writerow(row)

        return self

    def write_json(self, outputdir, timestamp, items=None):
        path = os.path.join(outputdir,
            self.filename('json', timestamp, **self.filter_kwargs))

        if items is None:
            items = self.get_items()

        with open(path, 'w') as f:
            f.write(json.dumps(items, default=json_util.default))

        return self

    def write_manifest(self, outputdir=None, timestamp=None):
        """
        Writes a manifest file that describes collected results.
        """
        if outputdir is None:
            outputdir = self.default_outputdir()

        if not os.path.exists(outputdir):
            os.makedirs(outputdir)

        if timestamp is None:
            timestamp = datetime.now()

        path = os.path.join(outputdir,
            self.manifest_filename(timestamp, **self.filter_kwargs))

        # TODO: Decide on best format for manifest file.
        with open(path, 'w') as f:
            f.write("Generated on %s\n" %
                timestamp.strftime(self.timestamp_format))
            f.write("\n")
            f.write("Filters:\n\n")
            for k, v in list(self.filter_kwargs.items()):
                f.write("%s: %s\n" % (k, v))

        return self

class RawBaker(BaseBaker):
    """Writes filtered election results from RawResult records to structured files"""
    def collect_items(self):
        roller = RawResultRoller()
        self._items = roller.get_list(**self.filter_kwargs)
        self._fields = roller.get_fields()
        return self

    @classmethod
    def filename(cls, fmt, timestamp=None, **filter_kwargs):
        state = filter_kwargs.get('state')
        assert state is not None
        start_date = filter_kwargs.get('datefilter')
        assert start_date is not None
        start_date_s = start_date.replace('-', '')
        suffix_bits = ['raw']
        race_type = filter_kwargs.get('election_type')
        reporting_level = filter_kwargs.get('reporting_level')
        return standardized_filename(state=state, start_date=start_date_s,
            race_type=race_type, reporting_level=reporting_level,
            extension="."+fmt, suffix_bits=suffix_bits)

    def write_manifest(self, outputdir=None, timestamp=None):
        # Don't write a manifest with the raw baker
        pass

class Baker(BaseBaker):
    """Writes (filtered) election and candidate data to structured files"""
    def collect_items(self):
        roller = ResultRoller()
        self._items = roller.get_list(**self.filter_kwargs)
        self._fields = roller.get_fields()
        return self

def reporting_levels_for_election(state, election_date, election_type, raw=False):
    """
    Retrieve available reporting levels for an election.

    Args:
        state (string): State abbreviation.
        election_date (string): String representing election start date in
            format "YYYYMMDD".
        election_type: Election type. For example, general, primary, etc.
        raw: Consider available reporting levels for raw results.  The default
            is to consider standardized/cleaned results.

    Returns:
        A  list of available reporting levels.

    """
    if raw:
        result_class = RawResult
    else:
        result_class = Result

    q = (Q(election_id__contains=format_date(election_date)) &
         Q(election_id__contains=election_type))

    return result_class.objects.filter(state__iexact=state).filter(q).distinct('reporting_level')


# QUICK SORT ALGORITHM
# It is the fastest known algorithm .Also known as Partition Exchange Sort. Faster than Heap sort and merge sort.

# Algorithm's steps  :
# 1.select pivot element ==> list[first]
# 2.find the correct positon of pivot element ==> left = first +1 , right = last
    # a.left<=right
    # b. while list[left] < pivot , increment left by 1
    # c. while list[right] > pivot , decrement right by 1
    # d. if left < right , then swap left and right value else break
    # e. if right < left , then swap pivot or first value and right value
# 3.Sort the sublist recursively

# To get the correct position of the pivot elements
def pivot_position(mlist,first , last):
    pivot = mlist[first]
    left = first + 1
    right = last
    while True:
        while left <= right and mlist[left] <= pivot :
            left += 1
        while left <= right and mlist[right] >= pivot :
            right -= 1
        if right < left :
            break
        else:
            mlist[left],mlist[right] = mlist[right],mlist[left]
            # print("A: ",mlist)
    mlist[first],mlist[right] = mlist[right],mlist[first]
    # print("B: ",mlist)
    return right

def quickSort(mlist, first , last):
    # when a list contains single element then first = last ,so stops recursion
    if first < last:
        p = pivot_position(mlist, first , last)
        # print("position of pivot element : ",p)
        quickSort(mlist, first, p-1)
        quickSort(mlist, p+1 , last)

# main:
num = int(input("Enter the no of elements in the list: "))
list1 = [int(input()) for i in range(num)]
print("Unsorted list: ",list1)
quickSort(list1,0,len(list1)-1)
print("Sorted list: ",list1)