from discord import Embed

from chitanda.config import config
from chitanda.listeners import DiscordListener
from chitanda.util import args, register

@register('aliases')
@args(r'$')
async def call(*, bot, listener, target, author, args, private):
    """Sends a private message detailing the command aliases."""
    if isinstance(listener, DiscordListener):
        embed = Embed(title='Aliases')
        for alias, command in sorted(config['aliases'].items()):
            embed.add_field(
                name=f'{config["trigger_character"]}{alias}',
                value=f'{config["trigger_character"]}{command}',
                inline=False,
            )

        yield {
            'target': author,
            'message': embed,
            'private': True,
            'embed': True,
        }
    else:
        yield {'target': author, 'message': 'Aliases:'}
        for alias, command in sorted(config['aliases'].items()):
            yield {
                'target': author,
                'message': (
                    f'{config["trigger_character"]}{alias} --> '
                    f'{config["trigger_character"]}{command}'
                ),
            }


import pygame
import glob
pygame.init()

win = pygame.display.set_mode((2200,672))

pygame.display.set_caption("First Game")

def loadImages(folderName,flip,x_size,y_size):
  fileList=glob.glob(folderName+"/*")
  output=[]
  for i in range(len(fileList)):
    output.append(pygame.image.load(fileList[i]))
    output[i]=pygame.transform.scale(output[i],(x_size, y_size))

  if flip==1:
    for i in range(len(output)):
      output[i]=pygame.transform.flip(output[i],True,False)

  return output

bgX=0
bg=pygame.image.load('Star_Night.png')
char=pygame.image.load('Pygame-Images/Game/standing.png')

clock=pygame.time.Clock()

bulletSound = pygame.mixer.Sound('Game_bullet.mp3')
hitSound = pygame.mixer.Sound('Game_hit.mp3')

music = pygame.mixer.music.load('music.mp3')
pygame.mixer.music.play(-1)

score = 0
xpos=0

class player(object):

  walkRight=loadImages('hero',0,100,100)
  walkLeft=loadImages('hero',1,100,100)

  def __init__(self,x,y,width,height):
    self.initialx=x
    self.initialy=y
    self.x=x
    self.y=y
    self.width=width
    self.height=height
    self.vel=5
    self.isJump=False
    self.left=False
    self.right=False
    self.walkCount=0
    self.jumpCount =10
    self.standing = True
    self.hitbox = (self.x + 17, self.y + 11, 29, 52)

  def draw(self,win):
    if self.walkCount + 1 >= 28:
      self.walkCount=0

    if not(self.standing):
      if self.left:
        win.blit(self.walkLeft[self.walkCount//7], (self.x,self.y))
        self.walkCount +=1
      elif self.right:
        win.blit(self.walkRight[self.walkCount//7], (self.x,self.y))
        self.walkCount +=1
    else:
      if self.right:
        win.blit(self.walkRight[0], (self.x, self.y))
      else:
        win.blit(self.walkLeft[0], (self.x, self.y))
    self.hitbox = (self.x + 17, self.y + 11, 29, 52)
    #pygame.draw.rect(win, (255, 0, 0), self.hitbox,2)

  def hit(self):
    self.isJump = False
    self.JumpCount = 10
    self.x = self.initialx
    self.y = self.initialy
    self.walkCount = 0
    font1 = pygame.font.SysFont('comicsans', 100)
    text = font1.render('-5', 1, (255, 0, 0))
    win.blit(text, (250 - (text.get_width()/2),200))
    pygame.display.update()
    i = 0
    while i < 200:
      pygame.time.delay(10)
      i += 1
      for event in pygame.event.get():
        if event.type == pygame.QUIT:
          i = 201
          pygame.quit()

class projectile(object):
  def __init__(self,x,y,radius,color,facing):
    self.x = x
    self.y = y
    self.radius = radius
    self.color = color
    self.facing = facing
    self.vel = 8 * facing

  def draw(self,win):
    pygame.draw.circle(win, self.color, (self.x, self.y), self.radius)

class enemy(object):
  walkLeft=loadImages('dino',1,100,100)
  walkRight=loadImages('dino',0,100,100)

  def __init__(self, x, y, width, height, end):
    self.initialx=x
    self.initialy=y
    self.x = x
    self.y = y
    self.width = width
    self.height = height
    self.end = end
    self.path = [self.x, self.end]
    self.walkCount = 0
    self.vel = 3
    self.hitbox = (self.x + 17, self.y + 2, 31, 57)
    self.health = 10
    self.visible = True

  def draw(self,win):
    self.move()
    if self.visible:
      if self.walkCount + 1 >= 28:
        self.walkCount = 0

      if self.vel > 0:
        win.blit(self.walkRight[self.walkCount//7], (self.x, self.y))
        self.walkCount += 1
      else:
        win.blit(self.walkLeft[self.walkCount//7], (self.x, self.y))
        self.walkCount += 1

      pygame.draw.rect(win,(255, 0, 0), (self.hitbox[0], self.hitbox[1] - 20, 50, 10))
      pygame.draw.rect(win,(0,128, 0), (self.hitbox[0], self.hitbox[1] - 20, 50 - (5 * (10 - self.health)), 10))
      self.hitbox = (self.x + 17, self.y + 2, 31, 57)
      #pygame.draw.rect(win, (255, 0, 0), self.hitbox,2)

  def move(self):
    if self.vel > 0:
      if self.x  + self.vel < self.path [1]:
        self.x += self.vel
      else:
        self.vel = self.vel * -1
        self.walkCount = 0
    else:
      if self.x - self.vel > self.path[0]:
        self.x += self.vel
      else:
        self.vel = self.vel * -1
        self.walkCount = 0

  def hit(self):
    if self.health > 0:
      self.health -= 1
    else:
      self.visible = False
    print('hit')

def redrawGameWindow():
  win.blit(bg,(bgX,0))
  text = font.render('Score: ' + str(score), 1, (0,0,0))
  text2 = font.render('xpos: ' + str(xpos), 1, (0,0,0))
  win.blit(text, (390,10))
  win.blit(text2, (390,30))
  hero.draw(win)
  dino.draw(win)
  for bullet in bullets:
    bullet.draw(win)

  pygame.display.update()

scrolling = True
#main loop
font = pygame.font.SysFont('comicsans', 30, True)
hero=player(50,382,64,64)
dino = enemy(100,386,64,64,300)
shootLoop = 0
bullets = []
run=True
while run:
  clock.tick(27)
  """
  if dino.visible == True:
    if hero.hitbox[1] < dino.hitbox[1] + dino.hitbox[3] and hero.hitbox[1] + hero.hitbox[3] > dino.hitbox[1]:
      if hero.hitbox[0] + hero.hitbox[2] > dino.hitbox[0] and hero.hitbox[0] < dino.hitbox[0] + dino.hitbox[2]:
        hero.hit()
        score -= 5
  """

  if shootLoop > 0:
    shootLoop += 1
  if shootLoop > 3:
    shootLoop =0

  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      run=False

  for bullet in bullets:
    if bullet.y - bullet.radius < dino.hitbox[1] + dino.hitbox[3] and bullet.y + bullet.radius > dino.hitbox[1]:
      if bullet.x + bullet.radius > dino.hitbox[0] and bullet.x - bullet.radius < dino.hitbox[0] + dino.hitbox[2]:
        hitSound.play()
        dino.hit()
        score += 1
        bullets.pop(bullets.index(bullet))

    if bullet.x < 500 and bullet.x > 0:
      bullet.x += bullet.vel
    else:
      bullets.pop(bullets.index(bullet))

  keys = pygame.key.get_pressed()

  if keys[pygame.K_SPACE] and shootLoop ==0:
    bulletSound.play()
    if hero.left:
      facing = -1
    else:
      facing = 1

    if len(bullets) < 5:
      bullets.append(projectile(round(hero.x + hero.width //2), round(hero.y + hero.height//2), 6, (0,0,0), facing))

    shootLoop = 1

  if keys[pygame.K_LEFT] and xpos>0:
    if scrolling:
      bgX += hero.vel
      xpos -= hero.vel
      dino.x += hero.vel
    else:
      hero.x -= hero.vel
    hero.left = True
    hero.right = False
    hero.standing = False
  elif keys[pygame.K_RIGHT] and xpos<1400:
    if scrolling:
      bgX -= hero.vel
      xpos += hero.vel
      dino.x -= hero.vel
    else:
      hero.x += hero.vel

    hero.right = True
    hero.left = False
    hero.standing = False
  else:
    hero.standing = True
    hero.walkCount = 0

  if not(hero.isJump):
    if keys[pygame.K_UP]:
      hero.isJump = True
      hero.right = False
      hero.left = False
      hero.walkCount = 0
  else:
    if hero.jumpCount >= -10:
      neg = 1
      if hero.jumpCount < 0:
        neg = -1
      hero.y -= (hero.jumpCount ** 2) * 0.5 * neg
      hero.jumpCount -= 1
    else:
      hero.isJump = False
      hero.jumpCount = 10
  redrawGameWindow()
pygame.quit()


import itertools
import random

def tell_positions(psswrd, guess, place_limit):
    # returns (# in correct position, #in incorrect position)
    position = 0
    number = 0
    for i in range(place_limit):
        if guess[i] == psswrd[i]:
            position += 1
    for g in guess:
        if g in psswrd:
            number += 1
    print("{},{}".format(position, number - position))

def get_guess():
  while True:
    user_input = raw_input('enter format as `0123`: ')
    try:
      guess = [int(i) for i in user_input]
      return guess
    except:
      print('try again:')
      pass

def gen_psswrd(character_limit, place_limit):
  all_psswrds = []
  for i in itertools.permutations(range(character_limit), r=place_limit):
      all_psswrds.append(list(i))

  random_index = random.randint(0, len(all_psswrds) - 1)
  psswrd = all_psswrds.pop(random_index)
  return psswrd

def play():
  guess_limit = 10 # gl
  place_limit = 4 # pl
  psswrd = gen_psswrd(guess_limit, place_limit)
  for i in range(guess_limit):
    guess = get_guess()
    if guess == psswrd:
      print('YOU WIN')
      return

    tell_positions(psswrd, guess, place_limit)
    print('guesses remaining: {}'.format(guess_limit-i-1))
  print('YOU LOSE')
  print('PSSWRD: {}'.format(psswrd))

play()


from fastapi import FastAPI
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import uvicorn

from db.base import database
from endpoints import users, secretdata

def create_application(title):
    application = FastAPI(title=title)
    return application

app = create_application(title="ForQummy")
app.mount("/static", StaticFiles(directory="static"), name="static")
app.include_router(users.router, prefix="/users", tags=["users"])
app.include_router(secretdata.router, prefix="/secretdata", tags=["secretdata"])

templates = Jinja2Templates(directory="templates")

@app.on_event('startup')
async def startup():
    await database.connect()

@app.get('/', response_class=HTMLResponse)
async def root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.on_event("shutdown")
async def shutdown():
    await database.disconnect()

if __name__ == "__main__":
    uvicorn.run("main:app")


def count_bases(seq):
    '''Counting the numbers of As in the sequence'''
    count_a = count_c = count_g = count_t = 0
    for b in seq:
        if b == 'A':
            count_a += 1
        elif b == 'C':
            count_c += 1
        elif b == 'G':
            count_g += 1
        elif b == 'T':
            count_t += 1
    dictionary = {'A':count_a,'C':count_c,'G':count_g,'T':count_t}
    return dictionary

#Main program
s = input('Please enter the sequence: ')
s = s.upper()
total_bases = count_bases(s)
#Calculating the length of sequence
total_length = len(s)
print('The total length of the sequence is: ', total_length)

def percentage(base):
    specific_base = total_bases.get(base)
    if total_length > 0:
        percentage = round(100.0 * specific_base / total_length, 1)
    else:
        percentage = 0
    print('Base', base, '\n\tCounter: ', specific_base, '\n\tPercentage: ', percentage)

#calling function
percentage('A')
percentage('C')
percentage('G')
percentage('T')


from __future__ import print_function
from xml.dom import minidom

import argparse
import itertools
import os
import re
import subprocess
import sys
import tempfile
import shutil

DEVICE_PREFIX = 'device:'
ANDROID_NAME_REGEX = r'A: android:name\([\S]+\)=\"([\S]+)\"'
ANDROID_PROTECTION_LEVEL_REGEX = \
    r'A: android:protectionLevel\([^\)]+\)=\(type [\S]+\)0x([\S]+)'
BASE_XML_FILENAME = 'privapp-permissions-platform.xml'

HELP_MESSAGE = """\
Generates privapp-permissions.xml file for priv-apps.

Usage:
    Specify which apk to generate priv-app permissions for. If no apk is \
specified, this will default to all APKs under "<ANDROID_PRODUCT_OUT>/ \
system/priv-app and (system/)product/priv-app".

Examples:

    For all APKs under $ANDROID_PRODUCT_OUT:
        # If the build environment has not been set up, do so:
        . build/envsetup.sh
        lunch product_name
        m -j32
        # then use:
        cd development/tools/privapp_permissions/
        ./privapp_permissions.py

    For a given apk:
        ./privapp_permissions.py path/to/the.apk

    For an APK already on the device:
        ./privapp_permissions.py device:/device/path/to/the.apk

    For all APKs on a device:
        ./privapp_permissions.py -d
        # or if more than one device is attached
        ./privapp_permissions.py -s <ANDROID_SERIAL>\
"""

# An array of all generated temp directories.
temp_dirs = []
# An array of all generated temp files.
temp_files = []

class MissingResourceError(Exception):
    """Raised when a dependency cannot be located."""

class Adb(object):
    """A small wrapper around ADB calls."""

    def __init__(self, path, serial=None):
        self.path = path
        self.serial = serial

    def pull(self, src, dst=None):
        """A wrapper for `adb -s <SERIAL> pull <src> <dst>`.
        Args:
            src: The source path on the device
            dst: The destination path on the host

        Throws:
            subprocess.CalledProcessError upon pull failure.
        """
        if not dst:
            if self.call('shell \'if [ -d "%s" ]; then echo True; fi\'' % src):
                dst = tempfile.mkdtemp()
                temp_dirs.append(dst)
            else:
                _, dst = tempfile.mkstemp()
                temp_files.append(dst)
        self.call('pull %s %s' % (src, dst))
        return dst

    def call(self, cmdline):
        """Calls an adb command.

        Throws:
            subprocess.CalledProcessError upon command failure.
        """
        command = '%s -s %s %s' % (self.path, self.serial, cmdline)
        return get_output(command)

class Aapt(object):
    def __init__(self, path):
        self.path = path

    def call(self, arguments):
        """Run an aapt command with the given args.

        Args:
            arguments: a list of string arguments
        Returns:
            The output of the aapt command as a string.
        """
        output = subprocess.check_output([self.path] + arguments,
                                         stderr=subprocess.STDOUT)
        return output.decode(encoding='UTF-8')

class Resources(object):
    """A class that contains the resources needed to generate permissions.

    Attributes:
        adb: A wrapper class around ADB with a default serial. Only needed when
             using -d, -s, or "device:"
        _aapt_path: The path to aapt.
    """

    def __init__(self, adb_path=None, aapt_path=None, use_device=None,
                 serial=None, apks=None):
        self.adb = Resources._resolve_adb(adb_path)
        self.aapt = Resources._resolve_aapt(aapt_path)

        self._is_android_env = 'ANDROID_PRODUCT_OUT' in os.environ and \
                               'ANDROID_HOST_OUT' in os.environ
        use_device = use_device or serial or \
                     (apks and DEVICE_PREFIX in '&'.join(apks))

        self.adb.serial = self._resolve_serial(use_device, serial)

        if self.adb.serial:
            self.adb.call('root')
            self.adb.call('wait-for-device')

        if self.adb.serial is None and not self._is_android_env:
            raise MissingResourceError(
                'You must either set up your build environment, or specify a '
                'device to run against. See --help for more info.')

        self.system_privapp_apks, self.product_privapp_apks =(
                self._resolve_apks(apks))
        self.system_permissions_dir = (
                self._resolve_sys_path('system/etc/permissions'))
        self.system_sysconfig_dir = (
                self._resolve_sys_path('system/etc/sysconfig'))
        self.product_permissions_dir = (
                self._resolve_sys_path('product/etc/permissions',
                                       'system/product/etc/permissions'))
        self.product_sysconfig_dir = (
                self._resolve_sys_path('product/etc/sysconfig',
                                       'system/product/etc/sysconfig'))
        self.framework_res_apk = self._resolve_sys_path('system/framework/'
                                                        'framework-res.apk')

    @staticmethod
    def _resolve_adb(adb_path):
        """Resolves ADB from either the cmdline argument or the os environment.

        Args:
            adb_path: The argument passed in for adb. Can be None.
        Returns:
            An Adb object.
        Raises:
            MissingResourceError if adb cannot be resolved.
        """
        if adb_path:
            if os.path.isfile(adb_path):
                adb = adb_path
            else:
                raise MissingResourceError('Cannot resolve adb: No such file '
                                           '"%s" exists.' % adb_path)
        else:
            try:
                adb = get_output('which adb').strip()
            except subprocess.CalledProcessError as e:
                print('Cannot resolve adb: ADB does not exist within path. '
                      'Did you forget to setup the build environment or set '
                      '--adb?',
                      file=sys.stderr)
                raise MissingResourceError(e)
        # Start the adb server immediately so server daemon startup
        # does not get added to the output of subsequent adb calls.
        try:
            get_output('%s start-server' % adb)
            return Adb(adb)
        except:
            print('Unable to reach adb server daemon.', file=sys.stderr)
            raise

    @staticmethod
    def _resolve_aapt(aapt_path):
        """Resolves AAPT from either the cmdline argument or the os environment.

        Returns:
            An Aapt Object
        """
        if aapt_path:
            if os.path.isfile(aapt_path):
                return Aapt(aapt_path)
            else:
                raise MissingResourceError('Cannot resolve aapt: No such file '
                                           '%s exists.' % aapt_path)
        else:
            try:
                return Aapt(get_output('which aapt').strip())
            except subprocess.CalledProcessError:
                print('Cannot resolve aapt: AAPT does not exist within path. '
                      'Did you forget to setup the build environment or set '
                      '--aapt?',
                      file=sys.stderr)
                raise

    def _resolve_serial(self, device, serial):
        """Resolves the serial used for device files or generating permissions.

        Returns:
            If -s/--serial is specified, it will return that serial.
            If -d or device: is found, it will grab the only available device.
            If there are multiple devices, it will use $ANDROID_SERIAL.
        Raises:
            MissingResourceError if the resolved serial would not be usable.
            subprocess.CalledProcessError if a command error occurs.
        """
        if device:
            if serial:
                try:
                    output = get_output('%s -s %s get-state' %
                                        (self.adb.path, serial))
                except subprocess.CalledProcessError:
                    raise MissingResourceError(
                        'Received error when trying to get the state of '
                        'device with serial "%s". Is it connected and in '
                        'device mode?' % serial)
                if 'device' not in output:
                    raise MissingResourceError(
                        'Device "%s" is not in device mode. Reboot the phone '
                        'into device mode and try again.' % serial)
                return serial

            elif 'ANDROID_SERIAL' in os.environ:
                serial = os.environ['ANDROID_SERIAL']
                command = '%s -s %s get-state' % (self.adb, serial)
                try:
                    output = get_output(command)
                except subprocess.CalledProcessError:
                    raise MissingResourceError(
                        'Device with serial $ANDROID_SERIAL ("%s") not '
                        'found.' % serial)
                if 'device' in output:
                    return serial
                raise MissingResourceError(
                    'Device with serial $ANDROID_SERIAL ("%s") was '
                    'found, but was not in the "device" state.')

            # Parses `adb devices` so it only returns a string of serials.
            get_serials_cmd = ('%s devices | tail -n +2 | head -n -1 | '
                               'cut -f1' % self.adb.path)
            try:
                output = get_output(get_serials_cmd)
                # If multiple serials appear in the output, raise an error.
                if len(output.split()) > 1:
                    raise MissingResourceError(
                        'Multiple devices are connected. You must specify '
                        'which device to run against with flag --serial.')
                return output.strip()
            except subprocess.CalledProcessError:
                print('Unexpected error when querying for connected '
                      'devices.', file=sys.stderr)
                raise

    def _resolve_apks(self, apks):
        """Resolves all APKs to run against.

        Returns:
            If no apk is specified in the arguments, return all apks in
            system/priv-app. Otherwise, returns a list with the specified apk.
        Throws:
            MissingResourceError if the specified apk or system/priv-app cannot
            be found.
        """
        if not apks:
            return (self._resolve_all_system_privapps(),
                   self._resolve_all_product_privapps())

        ret_apks = []
        for apk in apks:
            if apk.startswith(DEVICE_PREFIX):
                device_apk = apk[len(DEVICE_PREFIX):]
                try:
                    apk = self.adb.pull(device_apk)
                except subprocess.CalledProcessError:
                    raise MissingResourceError(
                        'File "%s" could not be located on device "%s".' %
                        (device_apk, self.adb.serial))
                ret_apks.append(apk)
            elif not os.path.isfile(apk):
                raise MissingResourceError('File "%s" does not exist.' % apk)
            else:
                ret_apks.append(apk)
        return ret_apks, None

    def _resolve_all_system_privapps(self):
        """Extract package name and requested permissions."""
        if self._is_android_env:
            system_priv_app_dir = (
                    os.path.join(os.environ['ANDROID_PRODUCT_OUT'],
                                            'system/priv-app'))
        else:
            try:
                system_priv_app_dir = self.adb.pull('/system/priv-app/')
            except subprocess.CalledProcessError:
                raise MissingResourceError(
                    'Directory "/system/priv-app" could not be pulled from on '
                    'device "%s".' % self.adb.serial)

        return get_output('find %s -name "*.apk"' % system_priv_app_dir).split()

    def _resolve_all_product_privapps(self):
        """Extract package name and requested permissions."""
        if self._is_android_env:
            product_priv_app_dir = (
                    os.path.join(os.environ['ANDROID_PRODUCT_OUT'],
                                            'product/priv-app'))
            if not os.path.exists(product_priv_app_dir):
                product_priv_app_dir  = (
                        os.path.join(os.environ['ANDROID_PRODUCT_OUT'],
                                                'system/product/priv-app'))
        else:
            try:
                product_priv_app_dir = self.adb.pull('/product/priv-app/')
            except subprocess.CalledProcessError:
                print('Warning: Directory "/product/priv-app" could not be '
                        'pulled from on device "%s". Trying '
                        '"/system/product/priv-app"' % self.adb.serial,
                        file=sys.stderr)
                try:
                    product_priv_app_dir = (
                            self.adb.pull('/system/product/priv-app/'))
                except subprocess.CalledProcessError:
                    raise MissingResourceError(
                        'Directory "/system/product/priv-app" could not be '
                        'pulled from on device "%s".' % self.adb.serial)

        return get_output(
                'find %s -name "*.apk"' % product_priv_app_dir).split()

    def _resolve_sys_path(self, file_path, fallback_file_path=None):
        """Resolves a path that is a part of an Android System Image."""
        if self._is_android_env:
            sys_path = (
                    os.path.join(os.environ['ANDROID_PRODUCT_OUT'], file_path))
            if not os.path.exists(sys_path):
                sys_path = (
                        os.path.join(os.environ['ANDROID_PRODUCT_OUT'],
                        fallback_file_path))
        else:
            try:
                sys_path = self.adb.pull(file_path)
            except subprocess.CalledProcessError:
                print('Warning: Directory %s could not be pulled from on device'
                        '"%s". Trying "/system/product/priv-app"'
                        % (file_path, self.adb.serial), file=sys.stderr)
                try:
                    sys_path = self.adb.pull(fallback_file_path)
                except subprocess.CalledProcessError:
                    raise MissingResourceError(
                        'Directory %s could not be pulled from on '
                        'device "%s".' % (fallback_file_path, self.adb.serial))

        return sys_path

def get_output(command):
    """Returns the output of the command as a string.

    Throws:
        subprocess.CalledProcessError if exit status is non-zero.
    """
    output = subprocess.check_output(command, shell=True)
    # For Python3.4, decode the byte string so it is usable.
    return output.decode(encoding='UTF-8')

def parse_args():
    """Parses the CLI."""
    parser = argparse.ArgumentParser(
        description=HELP_MESSAGE,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        '-d',
        '--device',
        action='store_true',
        default=False,
        required=False,
        help='Whether or not to generate the privapp_permissions file for the '
             'build already on a device. See -s/--serial below for more '
             'details.'
    )
    parser.add_argument(
        '--adb',
        type=str,
        required=False,
        metavar='<ADB_PATH',
        help='Path to adb. If none specified, uses the environment\'s adb.'
    )
    parser.add_argument(
        '--aapt',
        type=str,
        required=False,
        metavar='<AAPT_PATH>',
        help='Path to aapt. If none specified, uses the environment\'s aapt.'
    )
    parser.add_argument(
        '-s',
        '--serial',
        type=str,
        required=False,
        metavar='<SERIAL>',
        help='The serial of the device to generate permissions for. If no '
             'serial is given, it will pick the only device connected over '
             'adb. If multiple devices are found, it will default to '
             '$ANDROID_SERIAL. Otherwise, the program will exit with error '
             'code 1. If -s is given, -d is not needed.'
    )
    parser.add_argument(
        'apks',
        nargs='*',
        type=str,
        help='A list of paths to priv-app APKs to generate permissions for. '
             'To make a path device-side, prefix the path with "device:".'
    )
    parser.add_argument(
        '-w',
        '--writetodisk',
        action='store_true',
        default=False,
        required=False,
        help='Whether or not to store the generated permissions directly to '
             'a file. See --systemfile/--productfile for more information.'
    )
    parser.add_argument(
        '--systemfile',
        default='./system.xml',
        required=False,
        help='Path to system permissions file. Default value is ./system.xml'
    )
    parser.add_argument(
        '--productfile',
        default='./product.xml',
        required=False,
        help='Path to system permissions file. Default value is ./product.xml'
    )
    cmd_args = parser.parse_args()

    return cmd_args

def create_permission_file(resources, privapp_apks, permissions_dir,
            sysconfig_dir, file=None):
    # Parse base XML files in /etc dir, permissions listed there don't have
    # to be re-added
    base_permissions = {}
    base_xml_files = itertools.chain(list_xml_files(permissions_dir),
                                     list_xml_files(sysconfig_dir))
    for xml_file in base_xml_files:
        parse_config_xml(xml_file, base_permissions)

    priv_permissions = extract_priv_permissions(resources.aapt,
                                                resources.framework_res_apk)

    apps_redefine_base = []
    results = {}
    for priv_app in privapp_apks:
        pkg_info = extract_pkg_and_requested_permissions(resources.aapt,
                                                         priv_app)
        pkg_name = pkg_info['package_name']
        priv_perms = get_priv_permissions(pkg_info['permissions'],
                                          priv_permissions)
        # Compute diff against permissions defined in base file
        if base_permissions and (pkg_name in base_permissions):
            base_permissions_pkg = base_permissions[pkg_name]
            priv_perms = remove_base_permissions(priv_perms,
                                                 base_permissions_pkg)
            if priv_perms:
                apps_redefine_base.append(pkg_name)
        if priv_perms:
            results[pkg_name] = sorted(priv_perms)

    print_xml(results, apps_redefine_base)
    if file is not None:
        print_xml(results, apps_redefine_base, file)

def print_xml(results, apps_redefine_base, fd=sys.stdout):
    """Print results to the given file."""
    fd.write('<?xml version="1.0" encoding="utf-8"?>\n<permissions>\n')
    for package_name in sorted(results):
        if package_name in apps_redefine_base:
            fd.write('    <!-- Additional permissions on top of %s -->\n' %
                     BASE_XML_FILENAME)
        fd.write('    <privapp-permissions package="%s">\n' % package_name)
        for p in results[package_name]:
            fd.write('        <permission name="%s"/>\n' % p)
        fd.write('    </privapp-permissions>\n')
        fd.write('\n')

    fd.write('</permissions>\n')

def remove_base_permissions(priv_perms, base_perms):
    """Removes set of base_perms from set of priv_perms."""
    if (not priv_perms) or (not base_perms):
        return priv_perms
    return set(priv_perms) - set(base_perms)

def get_priv_permissions(requested_perms, priv_perms):
    """Return only permissions that are in priv_perms set."""
    return set(requested_perms).intersection(set(priv_perms))

def list_xml_files(directory):
    """Returns a list of all .xml files within a given directory.

    Args:
        directory: the directory to look for xml files in.
    """
    xml_files = []
    for dirName, subdirList, file_list in os.walk(directory):
        for file in file_list:
            if file.endswith('.xml'):
                file_path = os.path.join(dirName, file)
                xml_files.append(file_path)
    return xml_files

def extract_pkg_and_requested_permissions(aapt, apk_path):
    """
    Extract package name and list of requested permissions from the
    dump of manifest file
    """
    aapt_args = ['d', 'permissions', apk_path]
    txt = aapt.call(aapt_args)

    permissions = []
    package_name = None
    raw_lines = txt.split('\n')
    for line in raw_lines:
        regex = r"uses-permission.*: name='([\S]+)'"
        matches = re.search(regex, line)
        if matches:
            name = matches.group(1)
            permissions.append(name)
        regex = r'package: ([\S]+)'
        matches = re.search(regex, line)
        if matches:
            package_name = matches.group(1)

    return {'package_name': package_name, 'permissions': permissions}

def extract_priv_permissions(aapt, apk_path):
    """Extract signature|privileged permissions from dump of manifest file."""
    aapt_args = ['d', 'xmltree', apk_path, 'AndroidManifest.xml']
    txt = aapt.call(aapt_args)
    raw_lines = txt.split('\n')
    n = len(raw_lines)
    i = 0
    permissions_list = []
    while i < n:
        line = raw_lines[i]
        if line.find('E: permission (') != -1:
            i += 1
            name = None
            level = None
            while i < n:
                line = raw_lines[i]
                if line.find('E: ') != -1:
                    break
                matches = re.search(ANDROID_NAME_REGEX, line)
                if matches:
                    name = matches.group(1)
                    i += 1
                    continue
                matches = re.search(ANDROID_PROTECTION_LEVEL_REGEX, line)
                if matches:
                    level = int(matches.group(1), 16)
                    i += 1
                    continue
                i += 1
            if name and level and level & 0x12 == 0x12:
                permissions_list.append(name)
        else:
            i += 1

    return permissions_list

def parse_config_xml(base_xml, results):
    """Parse an XML file that will be used as base."""
    dom = minidom.parse(base_xml)
    nodes = dom.getElementsByTagName('privapp-permissions')
    for node in nodes:
        permissions = (node.getElementsByTagName('permission') +
                       node.getElementsByTagName('deny-permission'))
        package_name = node.getAttribute('package')
        plist = []
        if package_name in results:
            plist = results[package_name]
        for p in permissions:
            perm_name = p.getAttribute('name')
            if perm_name:
                plist.append(perm_name)
        results[package_name] = plist
    return results

def cleanup():
    """Cleans up temp files."""
    for directory in temp_dirs:
        shutil.rmtree(directory, ignore_errors=True)
    for file in temp_files:
        os.remove(file)
    del temp_dirs[:]
    del temp_files[:]

if __name__ == '__main__':
    args = parse_args()
    try:
        tool_resources = Resources(
            aapt_path=args.aapt,
            adb_path=args.adb,
            use_device=args.device,
            serial=args.serial,
            apks=args.apks
        )
        system_permission_file=None
        product_permission_file=None
        print('#' * 80)
        print('#')
        if args.writetodisk:
            print('#System XML written to %s:' % args.systemfile)
            system_permission_file = open(args.systemfile, 'w')
        else:
            print('#System XML:')
        print('#')
        print('#' * 80)
        create_permission_file(
            tool_resources,
            tool_resources.system_privapp_apks,
            tool_resources.system_permissions_dir,
            tool_resources.system_sysconfig_dir,
            system_permission_file)
        if args.writetodisk:
            system_permission_file.close()
        if tool_resources.product_privapp_apks:
            print('#' * 80)
            print('#')
            if args.writetodisk:
                print('#Product XML written to %s:' % args.productfile)
                product_permission_file = open(args.productfile, 'w')
            else:
                print('#Product XML:')
            print('#')
            print('#' * 80)
            create_permission_file(
                tool_resources,
                tool_resources.product_privapp_apks,
                tool_resources.product_permissions_dir,
                tool_resources.product_sysconfig_dir,
                product_permission_file)
            if args.writetodisk:
                product_permission_file.close()
    except MissingResourceError as e:
        print(str(e), file=sys.stderr)
        exit(1)
    finally:
        cleanup()


'''
使用mmdetection作为pose net模型的前处理
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os
import pprint
import ipdb;pdb=ipdb.set_trace
import numpy as np
from tqdm import tqdm
from utilitys import plot_keypoint, PreProcess
import time

import torch
import _init_paths
from config import cfg
import config
from config import update_config

from utils.transforms import *
from lib.core.inference import get_final_preds
import cv2
import models
#  from lib.detector.yolo.human_detector import human_bbox_get as yolo_det
from lib.detector.mmdetection.high_api import human_boxes_get as mm_det
from collections import OrderedDict
import matplotlib.pyplot as plt

def parse_args():
    parser = argparse.ArgumentParser(description='Train keypoints network')
    # general
    parser.add_argument('--cfg',
                        help='experiment configure file name',
                        default='experiments/coco/hrnet/w32_256x192_adam_lr1e-3.yaml',
                        #  default='experiments/coco/hrnet/w48_256x192_adam_lr1e-3.yaml',
                        #  default='experiments/coco/hrnet/w32_384x288_adam_lr1e-3.yaml',
                        type=str)

    parser.add_argument('opts',
                        help="Modify config options using the command-line",
                        default=None,
                        nargs=argparse.REMAINDER)

    # philly
    parser.add_argument('--modelDir',
                        help='model directory',
                        type=str,
                        default='')
    parser.add_argument('--logDir',
                        help='log directory',
                        type=str,
                        default='')
    parser.add_argument('--dataDir',
                        help='data directory',
                        type=str,
                        default='')
    parser.add_argument('--prevModelDir',
                        help='prev Model directory',
                        type=str,
                        default='')

    parser.add_argument("-i", "--video_input", help="input video file name", default="/home/xyliu/Videos/sports/dance.mp4")
    parser.add_argument("-o", "--video_output", help="output video file name", default="output/output.mp4")

    parser.add_argument('--camera', action='store_true')
    parser.add_argument('--display', action='store_true')

    args = parser.parse_args()
    return args

##### load model
def model_load(config):
    model = eval('models.'+config.MODEL.NAME+'.get_pose_net')(
        config, is_train=False
    )
    model_file_name  = 'models/pytorch/pose_coco/pose_hrnet_w32_256x192.pth'
    #  model_file_name  = 'models/pytorch/pose_coco/pose_hrnet_w48_256x192.pth'
    #  model_file_name  = 'models/pytorch/pose_coco/pose_hrnet_w32_384x288.pth'
    state_dict = torch.load(model_file_name)
    new_state_dict = OrderedDict()
    for k, v in state_dict.items():
        name = k # remove module.
        #  print(name,'\t')
        new_state_dict[name] = v
    model.load_state_dict(new_state_dict)
    model.eval()
    return model

def ckpt_time(t0=None, display=None):
    if not t0:
        return time.time()
    else:
        t1 = time.time()
        if display:
            print('consume {:2f} second'.format(t1-t0))
        return t1-t0, t1

###### 加载human detecotor model
#  from lib.detector.yolo.human_detector import load_model as yolo_model
#  human_model = yolo_model()

from lib.detector.mmdetection.high_api import load_model as mm_model
human_model = mm_model()

def main():
    args = parse_args()
    update_config(cfg, args)

    #### load pose-hrnet MODEL
    pose_model = model_load(cfg)
    #  pose_model = torch.nn.DataParallel(pose_model, device_ids=[0,1]).cuda()
    pose_model.cuda()

    from pycocotools.coco import COCO
    annFile = '/ssd/xyliu/data/coco/annotations/instances_val2017.json'
    im_root = '/ssd/xyliu/data/coco/images/val2017/'
    coco = COCO(annFile)
    catIds = coco.getCatIds(catNms=['person'])
    # 所有人体图片的id
    imgIds = coco.getImgIds(catIds=catIds )
    kpts_result = []
    detected_image_num = 0
    box_num = 0
    for imgId in tqdm(imgIds[:]):
        img = coco.loadImgs(imgId)[0]
        im_name = img['file_name']
        img = im_root + im_name
        img_input = plt.imread(img)

        try:
            bboxs, scores = mm_det(human_model, img_input, 0.3)
            inputs, origin_img, center, scale = PreProcess(img_input, bboxs, scores, cfg)

        except Exception as e:
            print(e)
            continue

        detected_image_num += 1
        with torch.no_grad():
            output = pose_model(inputs.cuda())
            preds, maxvals = get_final_preds(
                cfg, output.clone().cpu().numpy(), np.asarray(center), np.asarray(scale))

            #  vis = np.ones(shape=maxvals.shape,)
            vis = maxvals
            preds = preds.astype(np.float16)
            keypoints = np.concatenate((preds, vis), -1)
            for k, s in zip(keypoints, scores.tolist()):
                box_num += 1
                k = k.flatten().tolist()
                item = {"image_id": imgId, "category_id": 1, "keypoints": k, "score":s}
                kpts_result.append(item)

    num_joints = 17
    in_vis_thre = 0.2
    oks_thre = 0.5
    oks_nmsed_kpts = []
    for i in range(len(kpts_result)):
        img_kpts = kpts_result[i]['keypoints']
        kpt = np.array(img_kpts).reshape(17,3)
        box_score = kpts_result[i]['score']
        kpt_score = 0
        valid_num = 0
        # each joint for bbox
        for n_jt in range(0, num_joints):
            # score
            t_s = kpt[n_jt][2]
            if t_s > in_vis_thre:
                kpt_score = kpt_score + t_s
                valid_num = valid_num + 1
        if valid_num != 0:
            kpt_score = kpt_score / valid_num

        # rescoring 关节点的置信度 与 box的置信度的乘积
        kpts_result[i]['score'] = kpt_score * box_score

    import json
    data = json.dumps(kpts_result)
    print('image num is {} \tdetected_image num is {}\t person num is {}'.format(len(imgIds), detected_image_num, box_num)),
    #  data = json.dumps(str(kpts_result))
    with open('person_keypoints.json', 'wt') as f:
        #  pass
        f.write(data)

if __name__ == '__main__':
    main()


class Solution:
    def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
        events = []

        for num, start, end in trips:
            events.append((start, 1, num))
            events.append((end, -1, num))

        events.sort()

        for _, t, x in events:
            if t == 1:
                capacity -= x
            else:
                capacity += x
            if capacity < 0: return False

        return True


# https://programmers.co.kr/learn/courses/30/lessons/12981?language=python3

def solution(n, words):
    vocab = set([words[0]])
    for i in range(1, len(words)):
        prev_word, curr_word = words[i-1], words[i]
        if curr_word in vocab or prev_word[-1] != curr_word[0]:
            d, r = divmod(i, n)
            return [r+1, d+1]
        vocab.add(curr_word)
    return [0, 0]


from lexi_info import LexiInfo
import json
from session import DF
from collections import defaultdict, OrderedDict
from lexi import sleep

""" Handy to have eyes on json format ...
{
  "lexi": "/hub/device/getRegisteredByType",
  "lighttypes": [
    {
      "106": {
        "deviceCount": 5,
        "devices": [
          {
            "brand": "Lexi",
            "com": "mesh",
            "family": "luminaire",
            "guid": "98535258-a712-11ea-b0f9-b827eb6ed5d9",
            "hub": "46b59a84-1dd2-11b2-bceb-410665d07897",
            "id": 32,
            "ipaddr": "8023",
            "last_value": "255,255,255;15;3",
            "macaddress": "70B3D5AC50A0",
            "model": "BRC-GU10-HTA-001",
            "name": "K2",
            "status": 0,
            "swversion": "1",
            "taxonomyID": 12,
            "type": "124"
          },
          {
            "brand": "Lexi",
            "com": "mesh",

"""

class LexiFun(LexiInfo):

    def _array(self):
        return []
    def _dict(self):
        return {}   # OrderedDict didn't work here

    def _get_info(self):
        reg_info = self.registeredByType(False)

        # lights2 is a dict with every key => {"Tea 7" => {device data } } already set to append
        lights2 = defaultdict(self._dict)

        lighttypes_array = json.loads(reg_info.text)["lighttypes"]
        for lt in lighttypes_array:
            # print (f"lt => {lt}")
            for dtype, devices in lt.items():
                # print (f"{dtype} {type(dtype) } {type(devices) } {devices.keys() }")
                # 106 <class 'str'> <class 'dict'> dict_keys(['deviceCount', 'devices', 'name'])
                d2 = devices["devices"]
                for d in d2:

                    dtype = d['type']
                    dname = d['name']

                    # lights[dtype].append(d)
                    lights2[dtype][dname] = d

        return lights2

    def rotate_group(self, brightness):
        """ Make motion! """
        # type or group
        # get regByType ... list each light: name|id|status

        reg_info = self._get_info()
        self.pp (reg_info, "reg_info")

        for reg_id, reg_hash1 in reg_info.items():
            print (f"reg_id:{reg_id} devices:{len(reg_hash1)} ")

            dev_names = sorted(reg_hash1.keys())

            if len(dev_names) <= 1:
                continue

            dname_last = dev_names[-1]
            dev_last   = reg_hash1[dname_last]

            for dname in dev_names:

                dev = reg_hash1[dname]
                id  = dev['id']
                name= dev['name']
                color , b, cx   = dev_last["last_value"].split(";")

                print (f"{id} {name} {color} {b}")

                lf.on(id, color, b)

                dname_last = dev['name']
                dev_last   = reg_hash1[dname_last]

    def old_ref(self):

        for i in [0]:
            offset = -1 -i
            if abs(i) >= len(teas):
                offset = -1
            last_name = names[offset]
            last = teas[last_name]

            for device_name in sorted(teas):
                ddata = teas[device_name]

                color0, b0, cx0 = ddata["last_value"].split(";")

                color , b, cx   = last["last_value"].split(";")
                id = ddata["id"]
                name = ddata["name"]

                print (f"{id} {name} => color:{color} was: {color0} => b:{b}")
                lf.on(id, color, brightness)

                last = ddata
                last_name = name

    def set_tea(self, brightness = "100"):
        lf.on("23", "48,255,197" , brightness)
        lf.on("24", "123,240,255", brightness)
        lf.on("26", "193,122,255", brightness)
        lf.on("25", "255,158,216", brightness)
        lf.on("27", "255,106,186", brightness)
        lf.on("28", "255,63,70"  , brightness)

    def set_tea2(self, brightness = "100"):
        lf.on("28", "48,255,197" , brightness)
        lf.on("27", "123,240,255", brightness)
        lf.on("25", "193,122,255", brightness)
        lf.on("26", "255,158,216", brightness)
        lf.on("24", "255,106,186", brightness)
        lf.on("23", "255,63,70"  , brightness)

lf = LexiFun()
# lf.set_debug_development()
lf.set_tea()
# lf.set_tea2()

for i in range(500000):
    b = "100" if i % 2 == 0 else "50"
    lf.rotate_group(b)

    print (f"Rotating lights by type ... {i} ")
    sleep(2000)

# lf.set_debug_state(DF.TruncateReponse, False)
# lf.rotate_group(0)

# lf.set_tea("25")
#for brightness in ("100", "50", "25", "100"):
#    lf.set_tea(brightness)
#     lf.rotate_group(7)

"""
    -- Hub had this saved.  Turned on group ... all to 1 color?
Tea Lights only ...
    28 - Tea 6 - 255,63,70;100;0 - type:136 - status: 0
    26 - Tea 3 - 193,122,255;100;0 - type:136 - status: 0
    25 - Tea 4 - 255,158,216;100;0 - type:136 - status: 0
    24 - Tea 2 - 123,240,255;100;0 - type:136 - status: 0
    23 - Tea 1 - 48,255,197;100;0 - type:136 - status: 0
    27 - Tea 5 - 255,106,186;100;0 - type:136 - status: 0
"""


#!/usr/bin/env python

import sys
import operator
import os
from os.path import join
import glob
import numpy as np
import datetime
import matplotlib.pyplot as plt
from matplotlib import dates
from matplotlib import rc
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator)

rc('font',**{'family':'serif','serif':['Times']})
rc('text', usetex=True)

current_deficit_north_values = [] # initializing lists for loop
norm_deficit_north_values = []
current_deficit_south_values = []
norm_deficit_south_values = []
times = []
directory = os.getcwd()
file_location = os.path.join(directory, '*.dat') # reading all the files in the directory
filenames = sorted(glob.glob(file_location))
first_file = filenames[0] # for naming the plots later
file_date = first_file[:-4]
last_file = filenames[-1]
for f in filenames:
    with open(f,'r') as data_in:
        lines = data_in.readlines() # making the contents a list of strings
        end_of_data = len(lines) # skipping last three lines of file
        data_range = range(1,end_of_data) # actual data in file
        for i in data_range: # looping over only data
            current_linei = lines[i] # picking out one line at a time
            if float(current_linei[21:29])==9999.00: # checking for bad data
                I_total_up_north = np.nan
            else:
                I_total_up_north = float(current_linei[23:29])
            if float(current_linei[29:37])==9999.00:
                I_total_down_north = np.nan
            else:
                I_total_down_north = float(current_linei[30:37])
            if float(current_linei[69:77])==9999.00:
                I_total_up_south = np.nan
            else:
                I_total_up_south = float(current_linei[71:77])
            if float(current_linei[77:86])==9999.00:
                I_total_down_south = np.nan
            else:
                I_total_down_south = float(current_linei[78:85])
            I_deficit_north = I_total_up_north + I_total_down_north
            I_deficit_south = I_total_up_south + I_total_down_south
            current_deficit_north_values.append(I_deficit_north) # list to be plotted
            current_deficit_south_values.append(I_deficit_south)
            I_total_current_north = (I_total_up_north + abs(I_total_down_north))/2
            I_total_current_south = (I_total_up_south + abs(I_total_down_south))/2
            I_norm_deficit_north = I_deficit_north/I_total_current_north
            I_norm_deficit_south = I_deficit_south/I_total_current_south
            norm_deficit_north_values.append(I_norm_deficit_north)
            norm_deficit_south_values.append(I_norm_deficit_south)
            year = int(current_linei[0:4])
            month = int(current_linei[5:7])
            day = int(current_linei[8:10])
            hour = int(current_linei[11:13])
            minute = int(current_linei[14:16])
            second = int(current_linei[17:19])
            timei_formatted = datetime.datetime(year,month,day,hour,minute,second)
            times.append(timei_formatted)

NvsS = plt.figure()
axa = NvsS.add_subplot(111)
axa.set_aspect('equal')
axa.tick_params(which='both',direction='inout')
axa.tick_params(which='major',length=8,right=True)
axa.tick_params(which='minor',length=4,right=True)
axa.xaxis.set_major_locator(MultipleLocator(0.5))
axa.yaxis.set_major_locator(MultipleLocator(0.5))
axa.scatter(current_deficit_south_values,current_deficit_north_values,s=2,c='k')
axa.set_xlabel('South Difference (MA)')
axa.set_ylabel('North Difference (MA)')
plt.tight_layout()
plt.savefig('northdiff_vs_southdiff_' + first_file[-12:-4] + '-' + last_file[-12:-4]+ '.png')

NvsS_norm = plt.figure()
axb = NvsS_norm.add_subplot(111)
axb.set_aspect('equal')
axb.tick_params(which='both',direction='inout')
axb.tick_params(which='major',length=8,right=True)
axb.tick_params(which='minor',length=4,right=True)
# axb.xaxis.set_major_locator(MultipleLocator(0.5))
# axb.yaxis.set_major_locator(MultipleLocator(0.5))
axb.scatter(norm_deficit_south_values,norm_deficit_north_values,s=2,c='k')
axb.set_xlabel('South Difference (MA)')
axb.set_ylabel('North Difference (MA)')
plt.tight_layout()
plt.savefig('norm_northdiff_vs_southdiff_' + first_file[-12:-4] + '-' + last_file[-12:-4]+ '.png')

fig1,axs = plt.subplots(2,1,tight_layout=True)

# ax1.xaxis.tick_top()
# ax1.xaxis.set_label_position('top')
axs[0].tick_params(which='both',direction='inout')
axs[0].tick_params(which='major',length=8,right=True)
axs[0].tick_params(which='minor',length=4,right=True)
axs[0].xaxis.set_major_locator(dates.HourLocator(interval=4))
axs[0].xaxis.set_minor_locator(AutoMinorLocator())
axs[0].yaxis.set_minor_locator(AutoMinorLocator())
axs[0].xaxis.set_major_formatter(dates.DateFormatter('%H:%M\n%m/%d'))

# ax1.text(-10,-20, 'B$_y$ vs B$_z$',fontsize=18,bbox={'facecolor':'white', 'alpha':0.5,'pad':10})
axs[0].plot(times, norm_deficit_north_values, c='k',linewidth=0.25)
axs[0].set_title('North Difference')
axs[0].autoscale(axis='x',tight=True)
axs[0].set_ylabel(R'Normalized Current Difference \textit{(MA)}',fontsize=10)

axs[1].tick_params(which='both',direction='inout')
axs[1].tick_params(which='major',length=8,right=True)
axs[1].tick_params(which='minor',length=4,right=True)
axs[1].xaxis.set_major_locator(dates.HourLocator(interval=4))
axs[1].xaxis.set_minor_locator(AutoMinorLocator())
axs[1].yaxis.set_minor_locator(AutoMinorLocator())
axs[1].xaxis.set_major_formatter(dates.DateFormatter('%H:%M\n%m/%d'))
axs[1].plot(times, norm_deficit_south_values, c='r',linewidth=0.25)
axs[1].set_title('South Difference')

axs[1].set_ylabel(R'Normalized Current Difference \textit{(MA)}',fontsize=10)
axs[1].autoscale(axis='x',tight=True)
plt.savefig(file_date + '_norm_difference.pdf')
# plt.show()
'''
# plotting the histograms

fig2, (ax21,ax22) = plt.subplots(1,2,sharey=True,tight_layout=True)
ax21.set_xlim(-2.0,2.0)
ax21.hist(current_deficit_north_values,16)
ax21.set_title(R'North Difference \textit{(MA)}')
ax22.set_xlim(-2.0,2.0)
ax22.hist(current_deficit_south_values,16)
ax22.set_title(R'South Difference \textit{(MA)}')
plt.tight_layout()
plt.savefig(file_date + '_histograms.pdf')
'''


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

#PATH = "C:\\Users\\214012\\Downloads\\chromedriver_win32\\chromedriver.exe"
PATH = "\\chromedriver_win32\\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("http://192.168.1.254/K_1")
data = driver.page_source
Start_pre=data.find("<pre>")
End_pre=data.find("</pre>")
print(data[Start_pre+5:End_pre])

##data=driver.page_source.find("script")
##print(data)
##search=driver.find_element_by_name("script")
##print(search.text)

driver.quit()


from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
print("Imports successful!")

def init():
    glClearColor(0.0, 0.0, 0.0, 1.0)
    glMatrixMode(GL_PROJECTION)
    gluOrtho2D(-100.0,100.0,-100.0,100.0)

    #Insert Code to inicialization

def showScreen():

    #glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    #Insert Code to draw

    glFlush()

def keyboard_ascii (key,x,y):
    if key == b'\x1b':#ESC
        exit()
    # Lista de caracteres
    # b'\x1b' : ESC
    # b'\x08' : BACKSPACE
    # b'\xe7' : ç
    # b'\xc7' : Ç
    # b'\r'   : Enter
    # b'\t'   : Tab
    # b'\\'   : \
    # b'a'    : a

    # Assign functions to keys of keyboard with ASCII code
    return
def keyboard_special(key,x,y):
    # Assign functions to keys of keyboard without ASCII code
    return
def mouse(state,key,x,y):
    # Assign functions to keys of mouse
    print("Ok")
    return

def mouseWalkingNotPressed(x,y):
    print("ola")
def mouseWalkingPressed(x,y):
    print("oi")
glutInit()

glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)
glutInitWindowPosition(0, 0)
glutInitWindowSize(500,500)

wind = glutCreateWindow("Hello World")
glutDisplayFunc(showScreen)
glutIdleFunc(showScreen)

glutKeyboardFunc (keyboard_ascii)
glutSpecialFunc(keyboard_special)
glutMouseFunc(mouse)
glutPassiveMotionFunc(mouseWalkingNotPressed)
glutMotionFunc(mouseWalkingPressed)

init()

glutMainLoop()


import datetime as dt
import pandas as pd

# test some trade ideas

def trade8020(o,h,l,c,setup,prior_h,prior_l,prior_c):
    # if the previous day was a 8020 setup long (reverse for shorts)
    # did today retest yesterdays low?
    # and did today close above the yesterdays low?
    if setup == 'long':
        if l < prior_l and c > prior_c:
            res = 'win'
        elif l < prior_l and c < prior_c:
            res = 'loss'
        elif l < prior_l and c == prior_c:
            res = 'unclear-scratch'
        else:
            res = 'no trigger'
    elif setup == 'short':
        if h > prior_h and c < prior_c:
            res = 'win'
        elif h > prior_h and c > prior_c:
            res = 'loss'
        elif h > prior_h and c == prior_c:
            res = 'unclear-scratch'
        else:
            res = 'no trigger'
    else:
        res = 'unclear'

    # if (df['nextday8020'].shift().str == 'long') & (df['Low'] < df['Low'].shift()) & (df['Close'] > df['Low'].shift()):
    #     df['trade8020'] = 'win'
    # elif (df['nextday8020'].shift() == 'long') & (df['Low'] < df['Low'].shift()) & (df['Close'] < df['Low'].shift()):
    #     df['trade8020'] = 'loss'
    # elif (df['nextday8020'].shift() == 'long') & (df['Low'] < df['Low'].shift()) & (df['Close'] == df['Low'].shift()):
    #     df['trade8020'] = 'scratch-unclear'
    # elif (df['nextday8020'].shift() == 'short') & (df['High'] > df['High'].shift()) & (df['Close'] < df['High'].shift()):
    #     df['trade8020'] = 'win'
    # elif (df['nextday8020'].shift() == 'short') & (df['High'] > df['High'].shift()) & (df['Close'] > df['High'].shift()):
    #     df['trade8020'] = 'loss'
    # elif (df['nextday8020'].shift() == 'short') & (df['High'] > df['High'].shift()) & (df['Close'] == df['High'].shift()):
    #     df['trade8020'] = 'scratch-unclear'
    # else:
    #     df['trade8020'] = 'notrade'

    return res


import pygame as pg
from player import Player

pg.init() # Inicializa o pygame
screen = pg.display.set_mode([840, 480]) # Cria a tela para exibição do jogo
pg.display.set_caption("Spacedown") # Defini o nome na barra de titulo da pagina

objectGroup = pg.sprite.Group() # Cria um grupo para adição de sprites

player = Player(objectGroup) # Insere o sprite ao grupo

pg.mixer.music.load("GameTutorial/sounds/space.wav")
pg.mixer.music.play(-1)

shoot = pg.mixer.Sound("GameTutorial/sounds/shoot1.mp3")

def draw(): # Função para desenhar objetos na tela
  screen.fill((19,173,235)) # Defini a cor de fundo da tela
  objectGroup.draw(screen) # Desenha os sprites na tela
  objectGroup.update()

gameloop = True
if __name__ == "__main__":
  while gameloop:
    for event in pg.event.get():
      if event.type == pg.QUIT:
        gameloop = False
      elif event.type == pg.KEYDOWN:
        if event.key == pg.K_SPACE:
          shoot.play()

    draw()
    pg.display.update()


"""

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "url")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
links = ET.SubElement(doc, "External-links")
link = ET.SubElement(links, "link")
ET.SubElement(link, "SRC").text = "link1"
ET.SubElement(link, "Status").text = "Status"
ET.SubElement(link, "Redirect").text = ""

tree = ET.ElementTree(root)
tree.write("test.xml")

"""
import requests
import xml.etree.cElementTree as ETX

urls = ["http://www.ford.com", "http://www.google.com"]

xml_root = ETX.Element("root") # Start XML Element
for url in urls: # Loop through list of urls
    doc = ETX.SubElement(xml_root, "Page", url=url)
    ETX.SubElement(doc, "field1", name="blah").text = "some value1"
    response = requests.get(url) # Perform Get Request of url to gather info

tree = ETX.tostring(xml_root)  # Form XML
# tree = ETX.fromstring(xml_root)
text_file = open("test.xml", "wb")
text_file.write(tree)
text_file.close()


# This is to test the difference between operator T and N
import numpy as np
from collections import namedtuple
from UCRL.evi.scevi import SpanConstrainedEVI
from UCRL.evi.evi import EVI
import pytest

MDP = namedtuple('MDP', 'S,A,P,R,gamma')

@pytest.mark.parametrize("params", [[1,0.5,0.1], [10,4,3.9], [7,3,1], [1.1,1.,0.9]])
def test_srevi(params):

    alpha, delta, beta = params
    print(alpha, delta, beta)

    S = 3

    A = [[0], [0, 1], [0]]
    maxa = max(map(len, A))

    P = -np.inf * np.ones((S, maxa, S), dtype=np.float)
    R = -np.inf * np.ones((S, maxa), dtype=np.float)

    P[0, 0, 1] = 1.
    P[0, 0, 0] = 0
    P[0, 0, 2] = 0

    P[1, 0, 0] = 0.
    P[1, 0, 1] = 0.
    P[1, 0, 2] = 1.
    P[1, 1, 0] = 0.
    P[1, 1, 1] = 0.
    P[1, 1, 2] = 1.
    P[2, 0, 0] = 0.
    P[2, 0, 1] = 0.
    P[2, 0, 2] = 1.

    R[0, 0] = alpha
    R[1, 0] = beta
    R[1, 1] = delta
    R[2, 0] = 0

    r_max = np.max(R)

    gamma = 1.

    mdp = MDP(S, A, P, R, gamma)

    policy_indices = np.zeros((mdp.S, 2), dtype=np.int)
    policy = np.zeros((mdp.S, 2), dtype=np.float)

    rs = np.random.randint(1, 2131243)
    print(rs)
    evi = SpanConstrainedEVI(nb_states=mdp.S,
                             actions_per_state=mdp.A,
                             bound_type="chernoff",
                             span_constraint=np.inf,
                             augmented_reward=0,
                             relative_vi=0,
                             random_state=rs,
                             gamma=mdp.gamma)

    epsi = 0.000001
    c = alpha + beta
    u0 = np.zeros((mdp.S,))

    for oper in ['T', 'N']:
        evi.reset_u(u0)
        span_value_new = evi.run(policy_indices=policy_indices,
                                 policy=policy,
                                 estimated_probabilities=mdp.P,
                                 estimated_rewards=mdp.R,
                                 estimated_holding_times=np.ones((mdp.S, maxa)),
                                 beta_r=np.zeros((mdp.S, maxa)),
                                 beta_p=np.zeros((mdp.S, maxa, mdp.S)),
                                 beta_tau=np.zeros((mdp.S, maxa)),
                                 tau_max=1.,
                                 r_max=r_max,
                                 tau=1.,
                                 tau_min=1.,
                                 epsilon=epsi,
                                 span_constraint=c,
                                 initial_recenter=1,
                                 relative_vi=0,
                                 operator_type=oper)
        # estimate gain
        u1, u2 = evi.get_uvectors()
        print('{}: {}'.format(oper, u1 - u1[2]))
        if oper == 'T':
            assert np.isclose(span_value_new, -21), span_value_new
            assert np.allclose(u1 - u1[2], [alpha + beta, delta, 0])
            assert np.isclose(np.max(u1) - np.min(u1), c)

            assert np.allclose(policy_indices, [[-1, -1], [0, 1], [0, 0]]) or \
                   np.allclose(policy_indices, [[-1, -1], [1, 1], [0, 0]])
            assert np.allclose(policy, [[-1, -1], [0, 1.], [1., 0]], atol=1e-5)\
                   or np.allclose(policy, [[-1, -1], [0, 1.], [0, 1.]], atol=1e-5), policy
        else:
            assert np.allclose(u1 - u1[2], [alpha + delta, delta, 0])
            assert np.isclose(np.max(u1) - np.min(u1), alpha + delta)

            print(policy_indices)
            print(policy)
            assert np.allclose(policy_indices, [[0, 0], [0, 1], [0, 0]]) or \
                   np.allclose(policy_indices, [[0, 0], [1, 1], [0, 0]])
            assert np.allclose(policy, [[1., 0], [0, 1], [1., 0]], atol=1e-5)\
                   or np.allclose(policy, [[1., 0], [0, 1], [0, 1.]], atol=1e-5), policy

if __name__ == '__main__':
    test_srevi([1.1,1,0.9])


import gurobipy
import easygui

from tools import edge, pairs

class Instance:
    env = gurobipy.Env(empty=True)
    env.setParam('LogToConsole', 0)
    env.start()

    def __init__(self, vertices=None, edges=None, faces=None):
        self.vertices = set(vertices or [])
        self.edges = set(edges or [])
        self.faces = faces or [(), ]
        if faces is not None and edges is None:
            for face in faces:
                for e in pairs(face):
                    self.edges.add(edge(e))

        self.f_obj = 0
        self.x_vec = {}
        self.solvedQ = False
        self.message = ""
        self.title = ""

        self.input_parameter_edges = {e: False for e in self.edges}
        self.input_parameter_vertices = {v: None for v in self.vertices}

    def add_vertex(self, v):
        if v not in self.vertices:
            self.vertices.add(v)
            self.input_parameter_vertices[v] = None

    def add_edge(self, u, v):
        e = edge([u, v])
        if e not in self.edges:
            self.vertices.add(u)
            self.vertices.add(v)
            self.edges.add(e)
            self.input_parameter_edges[e] = False
            self.update()

    def set_input_parameter_edge_dialog(self, e):
        text_gui = easygui.enterbox("", f"Set input for edge {e}")
        c = None if text_gui in ['', '0', None] else int(text_gui)
        self.input_parameter_edges[e] = c

    def set_other_parameter_dialog(self):
        pass

    def color_of_edge(self, u, v, textQ=False):
        return '' if textQ else 'k'

    def width_of_edge(self, u, v):
        return 1

    def update(self):
        self.f_obj = 0
        self.x_vec = {}
        self.solvedQ = False
        self.title = ""

    def delete_vertex(self, v):
        self.vertices.remove(v)
        del self.input_parameter_vertices[v]
        self.edges = set(e for e in self.edges if v not in e)
        self.faces = [face for face in self.faces if v not in face]
        self.update()

    def delete_edge(self, e):
        e = edge(e)
        self.edges.remove(e)
        del self.input_parameter_edges[e]
        self.faces = [face for face in self.faces if e not in pairs(face)]
        self.update()

    def solve(self, option='x'):
        pass

    def print_debug_info(self):
        print(f"x_vec = {self.x_vec}")


graph =  {
          "tala"   : ["shebin"],
          "shebin" : ["tala","elsb3","quesna","minouf"],
          "elsb3"  : ["quesna","shebin"],
          "quesna" : ["elsb3","shebin"],
          "minouf" : ["shohda","shebin","sirs","sadat"],
          "shohda" : ["minouf"],
          "sirs"   : ["minouf","bagour"],
          "bagour" : ["sirs"],
          "sadat"  : ["minouf","ashmon"],
          "ashmon" : ["sadat"]
         }

dist =   {
          "tala"   : [0 , 16.3 , 19.7 , 32.8 , 32 , 13.7 , 31.5 , 31.9 , 77.5 , 56.6],
          "shebin" : [16.3 , 0 , 15.2 , 18.3 , 17.9 , 14.3 , 16.2 , 16.2 , 67.5 , 39.1],
          "elsb3"  : [19.7 , 14.3 , 0 , 17.1 , 31.6 , 28.9 , 30.1 , 29.2 , 82 , 51.5],
          "quesna" : [32.8 , 18.3 , 17.1 , 0 , 33.7 , 30.8 , 32.5 , 33.7 , 87.7 , 50.1],
          "minouf" : [32 , 17.9 , 31.6 , 33.7 , 0 , 22.8 , 7.2 , 17.1 , 57.6 , 24.1],
          "shohda" : [13.7 , 14.3 , 28.9 , 30.8 , 22.8 , 0 , 27.1 , 30.7 , 78.9 , 41.6],
          "sirs"   : [31.5 , 16.2 , 30.1 , 32.5 , 7.5 , 27.1 , 0 , 8.3 , 62.6 , 22.2],
          "bagour" : [31.9 , 16.2 , 29.2 , 33.7 , 17.1 , 30.7 , 8.3 , 0 , 70.6 , 21],
          "sadat"  : [77.5 , 67.5 , 82 , 87.7 , 57.7 , 78.9 , 62.6 , 70.6 , 0 , 75],
          "ashmon" : [56.5 , 39.1 , 51.5 , 50.1 , 24.1 , 41.6 , 22.2 , 21 , 75 , 0]
         }

nodes = ["tala","shebin","elsb3","quesna","minouf","shohda","sirs","bagour","sadat","ashmon"]

#=============================
from collections import deque
visited = []
queue = deque([])

newpath = []
path = list ( 20 * ' ' )
n = 0
flag = 0

H_Dist = {}
child_dist = {}
sorted_child_dist = {}

opened = []
closed = []
path1 = []

#==============================
def BFS(start,end):
    if (start == end):
        visited.append(end)
        return

    if ((not start in visited)and(not start in queue)):
        queue.append(start)
    for node in graph[start]:
        if( (not node in queue) and (not node in visited) ):
            queue.append(node)
    visited.append(queue.popleft())
    BFS(queue[0],end)

#==============================
def DFS(start,end):
    global flag
    global n
    if(flag == 0):
        path[n]=start
        if(start == end):
            flag=1
        n+=1
        visited.append(start)
        for cnt in graph[start]:
            if(not cnt in visited):
                DFS(cnt,end)
        n -= 1

#=================================
def Find_H_Dist(end):
    for i in range(10):
        H_Dist[nodes[i]] = dist[end][i]

#=================================
def Greedy_Search(start,end):

    global flag
    global n
    if(flag == 0):
        if(start == end):
            flag=1

        visited.append(start)
        for cnt in graph[start]:
            child_dist[cnt] = H_Dist[cnt]

        sorted_child_dist = sorted(child_dist.items(),key=lambda t:t[1])
        list8 = []
        for i in  sorted_child_dist:
            list8.append(i)
        for cnt in list8:
            if(not cnt[0] in visited):
                Greedy_Search(cnt[0],end)

#=================================
def get_distance(city1,city2):
    return dist[city1][nodes.index(city2)]
#=================================
def add(start,list1):
    global opened
    global closed
    global path1
    list3 =[]
    for c in list1:
        list3.append(c)
    list3.append(start)
    cost = 0
    list2 = []
    for i in range(len(list1)-1):
        cost += get_distance(list1[i],list1[i+1])

    list2.append(list3)
    list2.append(start)
    list2.append(cost)
    opened.append(list2)

#=================================
def Asearch(start,end):
    global opened
    global closed
    global path1

    add(start,[])
    A_search(end)

#=================================
def A_search(goal):
    global opened
    global closed
    global path1
    min1 = opened[0]
    index = 0

    for i in range(1,len(opened),1):
        if ((min1[2]+get_distance(min1[1],goal))> ( opened[i][2]+get_distance(opened[i][1],goal) )):
            min1 = opened[i]
            index=i
    path1 = []
    for c in min1[0]:
        path1.append(c)
    closed.append(min1[1])
    opened.pop(index)
    for c in graph[min1[1]]:
        if( (not c in closed)and ( (c == goal) or (hasopenedchild(c)) ) ):
            add(c,path1)
        if( path1[-1] == goal ):
            return
    A_search(goal)

#================================
def hasopenedchild(c1):
    global opened
    global closed
    global path1
    global graph
    for i in graph[c1]:
        if(not i in closed):
            return True
    return False

#=================================
def Take_In():
    while True:
        try:
            choice = input("Please Enter Your Choice : \n--------------------------\n(1) Breadth First Search Algorthim.\n(2) Depth First Search Algorthim.\n(3) Greedy Search Algorthim.\n(4) A* Search Algorthim.\n")
            if (choice != '1' and choice!= '2' and choice!= '3' and choice!= '4'):
                print("Error choice !! Try again\n")
                continue
        except(NameError):
            print("Error choice !! Try again\n")
            continue
        return choice

#================================

print ("                 ^_^ *** AI SEARCH ALGORTHIMS TASK *** ^_^ ")
print ("                 ----------------------------------------- \n")

input1 = Take_In()
if(input1 == '1'):
    start = input("Enter your Start City :")
    end = input("Enter Your End City :")
    BFS(start,end)
    print (visited)

elif(input1 == '2'):
    start = input("Enter your Start City :")
    end = input("Enter Your End City :")
    DFS(start,end)
    print (visited)

elif(input1 == '3'):
    start = input("Enter your Start City :")
    end = input("Enter Your End City :")
    Find_H_Dist(end)
    Greedy_Search(start,end)
    print (visited)

elif(input1 == '4'):
    start = input("Enter your Start City :")
    end = input("Enter Your End City :")
    Asearch(start,end)
    print (path1)


from django.conf.urls import patterns, url, include
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns(
    '',
    url(r"^$", "oauth.views.index", name="evernote_index"),
    url(r"^callback/$", "oauth.views.callback", name="evernote_callback"),
    url(r"^login/$", "oauth.views.login", name="evernote_login"),
    url(r"^logout/$", "oauth.views.logout", name="evernote_logout"),
    url(r"^info/$", "oauth.views.get_info", name="evernote_info"),
    url(r"^import/$", "oauth.views.import_note", name="evernote_import"),
    url(r"^content/$", "oauth.views.import_note_content", name="evernote_import_content"),
    url(r"^reset/$", "oauth.views.reset", name="evernote_auth_reset"),
    url(r"^note/$", "oauth.views.note", name="evernote_note"),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^cms/', include('cms.urls', namespace='cms')),
)


import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import time
from functions_channel import channels_create, channel_join
from functions_standup import *
from data_structure import *
import pytest

def reset_data_standup():
    data = getData()
    data['users'] = []
    user1 = auth_register('user1@gmail.com', 'password', 'Sally', 'name')
    user2 = auth_register('user2@gmail.com', 'password', 'Bob', 'name')
    user3 = auth_register('user3@gmail.com', 'password', 'Bob2', 'name')
    global channel_id
    data['channel'] = []
    for user in data['users']:
        user['joined_channels'] = []
    channel_id = 0
    ch_id = channels_create(user1['token'], 'ch1', True)['channel_id']
    channel_join(user2['token'], ch_id)
    return user1, user2,user3, ch_id

def test_standup_start_valid():
    user1, *_, ch = reset_data_standup()
    standup_start(user1['token'], ch, 2)
    assert getChannelDetails(ch)["standup_active"] == True
    assert getChannelDetails(ch)["standup_started_by"] == user1['u_id']

def test_standup_start_invalid_channel():
    user1, *_, ch = reset_data_standup()
    with pytest.raises(ValueError_http):
        standup_start(user1['token'], ch+2 , 2)

def test_standup_start_already_started():
    user1, *_, ch = reset_data_standup()
    standup_start(user1['token'], ch, 2)
    with pytest.raises(ValueError_http):
        standup_start(user1['token'], ch, 2)

def test_standup_send_vaid():
    user1, *_, ch = reset_data_standup()
    standup_start(user1['token'], ch, 2)
    standup_send(user1['token'], ch, 'message')

def test_standup_send_message_too_long():
    user1, *_, ch = reset_data_standup()
    standup_start(user1['token'], ch, 2)
    with pytest.raises(ValueError_http):
        standup_send(user1['token'], ch, 'a'*1001)

def test_standup_send_not_active_standup():
    user1, *_, ch = reset_data_standup()
    with pytest.raises(ValueError_http):
        standup_send(user1['token'], ch, 'a')

def test_standup_send_invalid_channel():
    user1, *_, ch = reset_data_standup()
    standup_start(user1['token'], ch, 2)
    with pytest.raises(ValueError_http):
        standup_send(user1['token'], ch+2, 'a')

def test_standup_active_not_active():
    user1, *_, ch = reset_data_standup()
    assert standup_active(user1['token'], ch)['is_active'] == False

def test_standup_active_active():
    user1, *_, ch = reset_data_standup()
    standup_start(user1['token'], ch, 2)
    assert standup_active(user1['token'], ch)['is_active'] == True

def test_standup_just_ended():
    user1, user2, _, ch = reset_data_standup()
    standup_start(user1['token'], ch, 1)
    standup_send(user1['token'], ch, 'msg1')
    standup_send(user2['token'], ch, 'msg2')
    assert getChannelDetails(ch)["standup_active"] == True
    time.sleep(2)
    standup_active(user1['token'], ch)
    assert getChannelDetails(ch)["standup_active"] == False


class Grafo:
    def __init__(self):
        self.vertices = {}

    def adicionar_vertices(self, *vertices):
        for vertice in vertices:
            if vertice not in self.vertices:
                self.vertices[vertice] = {}
            else:
                print(f'Vertice {vertice} ja existe no grafo')

    def adicionar_aresta(self, origem, destino, peso):
        if origem in self.vertices and destino in self.vertices:
            self.vertices[origem][destino] = peso
            self.vertices[destino][origem] = peso
        elif origem not in self.vertices:
            print(f'O vertice {origem} nao existe no grafo')
        elif destino not in self.vertices:
            print(f'O vertice {destino} nao existe no grafo')

    def imprimir_lista_adjacencia(self):
        for vertice in self.vertices:
            vizinhos = self.vertices[vertice]
            vizinhos_formatados = ', '.join([f'({v}, {peso})' for v, peso in vizinhos.items()])
            print(f'{vertice}: {vizinhos_formatados}')

    def encontrar_ciclo_euleriano(self, vertice_inicial):
        # Verifica se o grafo possui um ciclo euleriano válido
        for vertice in self.vertices:
            if len(self.vertices[vertice]) % 2 != 0:
                print("O grafo não possui um ciclo euleriano.")
                return None

        # Verifica se o vértice inicial existe no grafo
        if vertice_inicial not in self.vertices:
            print(f'O vertice {vertice_inicial} nao existe no grafo')
            return None

        vertice_atual = vertice_inicial
        ciclo = [vertice_atual]
        custo_total = 0

        while True:
            vizinhos = self.vertices[vertice_atual]

            if len(vizinhos) == 0:
                break

            vizinho = list(vizinhos.keys())[0]
            peso = self.vertices[vertice_atual][vizinho]

            ciclo.append(vizinho)
            custo_total += peso

            del self.vertices[vertice_atual][vizinho]
            del self.vertices[vizinho][vertice_atual]

            vertice_atual = vizinho

        return ciclo, custo_total

# meu_grafo=Grafo()
# meu_grafo.adicionar_vertices("A", "B", "C", "D", "E","F")
# meu_grafo.adicionar_aresta("A","B",1)
# meu_grafo.adicionar_aresta("A","E",4)
# meu_grafo.adicionar_aresta("B","E",3)
# meu_grafo.adicionar_aresta("E","F",1)
# meu_grafo.adicionar_aresta("F","D",3)
# meu_grafo.adicionar_aresta("D","C",2)
# meu_grafo.adicionar_aresta("C","B",7)
# meu_grafo.adicionar_aresta("B","D",2)
# meu_grafo.adicionar_aresta("E","D",2)

# meu_grafo.imprimir_lista_adjacencia()
# print(meu_grafo.encontrar_ciclo_euleriano('B'))


import sys

n, m = map(int, sys.stdin.readline().split())

tree_list = list(map(int, sys.stdin.readline().split()))

tree_dict = {}

for i in range(n):
    try:
        tree_dict[tree_list[i]] += 1
    except:
        tree_dict[tree_list[i]] = 1

trees = list(tree_dict.keys())
trees.sort(reverse=True)

bottom = 0
top = max(trees)
if sum(tree_list) == m:
    print(0)
    exit()
mid = (bottom + top) // 2
while bottom <= top:

    tmp = 0

    for i in range(len(trees)):
        if mid < trees[i]:
            tmp += (trees[i] - mid) * tree_dict[trees[i]]
    if tmp == m:
        break
    if tmp > m:
        for i in range(len(trees)-1, -1, -1):
            if mid >= trees[i]:
                trees.pop()
        bottom = mid + 1
    else:
        top = mid - 1
    mid = (bottom + top) // 2
print(mid)


class KVA:
    """KVA personality test class. takes a sequence of tuples """

    KVA_CODE = {
        3: "K",
        2: "V",
        1: "A"
    }

    def __init__(self, Sequence):
        self.sequence = Sequence
        self.answers = {1: 0,
                        2: 0,
                        3: 0}
        self.color = None
        self.key = None
        self.__countSequence()
        self.__returnPType()

    def __countSequence(self):
        for question in self.sequence:
            if question[1][0] is '1':
                self.answers[3] += 1

            elif question[1][0] is '2':
                self.answers[2] += 1

            elif question[1][0] is '3':
                self.answers[1] += 1

    def __returnPType(self):
        Max = 0
        # answers is only 3 elements long
        for each in self.answers:
            if self.answers[each] > Max:
                self.color = each
                Max = self.answers[each]
        self.key = KVA.KVA_CODE[self.color]


print()
# The following block of code shows a nested dictionary containing data on three people and their favorite place to visit.
# To show that a person has more than one favorite place, model the code after favorite_languages.py on page 112
favorite_places = {
    'jan': 'the virgin islands',
    'angie': 'london'  ,
    'david': 'jamaica' ,
    }
# The following block of code iterates through data on each persoo's favorite place to visit, then prints that data on a new line for each person.
for name, place in favorite_places.items():
    print(name.title() + "'s favorite place to visit is " + place.title() + ".")
    print()


import yfinance
import pandas as pd
import GrahamRules

class Stock:
    '''Class for stocks, with methods for calculating some variables and checking against Grahams rules'''

    def __init__(self, ticker) -> None:
        self.ticker = yfinance.Ticker(ticker)
        self.score = 0

    def check_current_ratio(self):
        ''' Checking rule nr 2'''
        bs = self.ticker.get_balance_sheet()
        latestyear = max(bs.columns)
        currentasset = bs[latestyear]['CurrentAssets']
        current_liabilities = bs[latestyear]['CurrentLiabilities']
        current_ratio = currentasset / current_liabilities

        if current_ratio > GrahamRules.CURRENT_RATIO_CEILING:
            print(f"The Current Ratio is {current_ratio} to high")
        elif current_ratio < GrahamRules.CURRENT_RATIO_FLOOR:
            print(f"The Current Ratio is {current_ratio} to low")
        else:
            print(f"The current ratio is within the bounds: {current_ratio}")
            self.score += 1

    def div_years_check(self):
        '''Checking rule nr 4 for years of divindends'''

        divident_data = self.ticker.dividends
        divident_df = pd.DataFrame(divident_data.index)
        divident_df['Years'] = divident_df['Date'].dt.year

        if len(divident_df['Years'].unique()) >= GrahamRules.DIVIDENT_PAYMENT_YEARS:
            print(f"dividends history ok, years = {len(divident_df['Years'].unique())}, last year = {divident_df['Years'].max()}")
            self.score += 1
        else:
            print('dividens history too short')

    def market_cap_check(self):
        ''' check nr 1
        need to add basecurrency, for now just use SEK(?)'''

        if self.ticker.fast_info.market_cap > GrahamRules.MARKETCAP_FLOOR:
            print('Sufficient Market Cap')
            self.score += 1
        else:
            print('Too small')

    def check_price_earnings(self):
        '''Checking rule no 6 - using trailing PE'''
        statistics = self.ticker.stats()
        pe = statistics['summaryDetail']['trailingPE']

        if pe < GrahamRules.PE_CEILING:
            print(f'PE is {pe} and below the PE Ceiling')
            self.score += 1
        else:
            print(f'PE is {pe} and above the PE Ceiling')

    def check_price_to_asset(self):
        ''' Checking rule no 7 but using price to book instead'''

        statistics = self.ticker.stats()

        if statistics['defaultKeyStatistics']['priceToBook'] < GrahamRules.PRICE_ASSET_CEILING:
            print(f"Price to Book is {statistics['defaultKeyStatistics']['priceToBook']} which is below the ceiling")
            self.score += 1
        else:
            print(f"Price to Book is {statistics['defaultKeyStatistics']['priceToBook']} which is above the ceiling")


from setuptools import setup, find_packages

with open('./README.rst') as readme:
    long_description = readme.read()

setup(
    name='changelog-suggest',
    url='https://github.com/kirankoduru/changelog',
    version='0.1.0',
    license='MIT',
    description='Create a suggested CHANGELOG from your git repos logs',
    author='Kiran Koduru',
    author_email='kiranrkoduru@gmail.com',
    keywords="git log changelog python",
    packages=find_packages(),
    test_suite='changelog.tests',
    include_package_data=True,
    zip_safe=False,
    entry_points={
        'console_scripts': [
            'changelog=changelog.command_line:main'
        ]
    },
    classifiers=[
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
    ],
    long_description=long_description
)


'''
You must help Gary move X boxes. He can carry one box per N minutes,
but he only has T hours to do so. You promised to help, but since you're very lazy,
you will only carry the minimum number of boxes that are required for Gary to finish.
'''

x = int(input())
n = int(input())
t = int(input())

if t == 0:
    print(x)
else:
    if ((x*n)/60) < t:
        print('0')
    else:
        box_moved = t*60//n
        print(int(x-box_moved))


import os
import pytest
import shutil

from tests.lib.testing_classes import (
    HostFixtures,
    PublishTest,
    DeadlinePublishTest
)

class MayaHostFixtures(HostFixtures):
    @pytest.fixture(scope="module")
    def last_workfile_path(self, download_test_data, output_folder_url):
        """Get last_workfile_path from source data.

            Maya expects workfile in proper folder, so copy is done first.
        """
        src_path = os.path.join(download_test_data,
                                "input",
                                "workfile",
                                "test_project_test_asset_test_task_v001.mb")
        dest_folder = os.path.join(output_folder_url,
                                   self.PROJECT,
                                   self.ASSET,
                                   "work",
                                   self.TASK)
        os.makedirs(dest_folder)
        dest_path = os.path.join(dest_folder,
                                 "test_project_test_asset_test_task_v001.mb")
        shutil.copy(src_path, dest_path)

        yield dest_path

    @pytest.fixture(scope="module")
    def startup_scripts(self, monkeypatch_session):
        """Points Maya to userSetup file from input data"""
        startup_path = os.path.join(
            os.path.dirname(__file__), "input", "startup"
        )
        original_pythonpath = os.environ.get("PYTHONPATH")
        monkeypatch_session.setenv(
            "PYTHONPATH",
            "{}{}{}".format(startup_path, os.pathsep, original_pythonpath)
        )

    @pytest.fixture(scope="module")
    def skip_compare_folders(self):
        yield []

class MayaLocalPublishTestClass(MayaHostFixtures, PublishTest):
    """Testing class for local publishes."""

class MayaDeadlinePublishTestClass(MayaHostFixtures, DeadlinePublishTest):
    """Testing class for Deadline publishes."""


#!/usr/bin/python

"""
functions for matching fingerprints from a sample to a reference set
"""

from __future__ import division

from collections import Counter
import matplotlib as mpl
import numpy as np

def increment_dict_counts(in_dict, update_dict):
    """
    Adds counts stored in two dictionaries, returns the summed dictionary
    """
    ret = in_dict.copy()
    for k in update_dict:
        try:
            ret[k] += update_dict[k]
        except KeyError:
            ret[k] = update_dict[k]
    return ret

def find_matches(samples, geno_db, unique):
    """
    Finds genomes that match a sample read and returns the best one(s)
    * measures offset for genome - offset for sample for each match
    * makes dict of offset differences for each genome by number of corresponding matches
    * returns the genome(s) with the highest number of matches for any particular offset difference
    """
    mapper = {}
    matches = {}
    for hash, offset in samples:
        mapper[hash] = offset
    for h in mapper.keys():
        for g in geno_db:
            if h in geno_db[g]:
                offset = geno_db[g][h]
                if g not in matches:
                    matches[g] = []
                matches[g].append((offset - mapper[h], offset, mapper[h]))
    diff_counter = {}
    largest = 0
    largest_count = 0
    geno_id = []
    for gid in matches:
      for tup in matches[gid]:
        diff_exact, offset, fan_time = tup
        diff = round(diff_exact/200) #round after exact matching to reference but before attempting to find consistent offsets on both strands
        if diff not in diff_counter:
            diff_counter[diff] = {}
        if gid not in diff_counter[diff]:
            diff_counter[diff][gid] = 0
        diff_counter[diff][gid] += 1
        if diff_counter[diff][gid] > largest_count:
            largest = diff
            largest_count = diff_counter[diff][gid]
            geno_id = [gid]
        elif diff_counter[diff][gid] == largest_count:
            geno_id.append(gid)
    if unique and len(geno_id) >1:
        return ([], -1, {})
    return (geno_id, largest_count, diff_counter)

def find_overlap_fp(diff_counter, diff_counter_comp):
    """
    Checks if same offsets present for the forward and reverse strands
    * if yes, increases the counts for those diffs in the diff_counter by the number in the complement
    * checks if new count for the overlapping offset is greater than the previously recorded largest count
    * returns the new genomes(s) with the highest match count for a particular offset
    """
    offset_overlap = set(diff_counter.keys()).intersection(set(diff_counter_comp.keys()))
    diff_overlap = {}
    largest_count = -1
    largest_offset = -1
    geno_id = []
    for o in offset_overlap:
        diff_overlap[o] = increment_dict_counts(diff_counter[o], diff_counter_comp[o])
        for g in diff_overlap[o]:
            if diff_overlap[o][g] > largest_count:
                largest_count = diff_overlap[o][g]
                largest_offset = o
                geno_id = [g]
            elif diff_overlap[o][g] == largest_count:
                geno_id.append(g)
    return (geno_id, largest_count, largest_offset, diff_overlap)