import os
import sys

COMPILER_OPTIONS ={'COMPILER_OPTIMIZATION':'-O2','COMPILER_WARNING':'-Wall'}
LINKER_OPTIONS ={'LINKFLAGS':'-fopenmp'} # some systems don't need it, but ubuntu does
GFORTRANFLAGS = ['-ffixed-line-length-none' ,'-fno-second-underscore',    '-fPIC','-fno-range-check']
GCCFLAGS = ['-fPIC']
if 'DEVELOPER' in os.environ:
    GFORTRANFLAGS.append('-fbounds-check')
    GCCFLAGS.append('-fbounds-check')
class SconsConfig(object):
    def __init__(self):
        self.dir = None
        self.file = None
        return
sconsConfig = SconsConfig()

def readConfigFile(fileName):

    fin = open(fileName)
    allLines = fin.readlines()
    retDict = {}
    for line in allLines:
        if line.startswith('#'):#remove comments at the beginning of a line
            continue

        if line.find('#'):# remove comments at the end of a line
            indx = line.find('#')
            line = line[0:indx]

        line = substitute_env(line)   #replace '$VAR' string swith their value from the environment

        lineS =line.split('=')
        if len(lineS) == 1:#variable not defined
            continue

        key = lineS[0].strip()
        valueS = lineS[1].split()
        retDict[key] = valueS[0] if (len(valueS)==1) else valueS

    return retDict

def substitute_env(s):
    import re
    import os

    envs = re.findall(r"\$(\w*)",s)
    for x in envs:
        if x in os.environ.keys():
            s = s.replace("$"+x,os.environ[x])
        else:
            print(" ")
            print("Variable, $%s, used in the configuration file\n\n%s\n\nis not defined in the shell environment." % (x,os.path.join(sconsConfig.dir,sconsConfig.file)))
            print("Please correct this situation and try again.")
            print("(Either add that variable to the environment or edit the\nconfiguration file to use a variable in the environment\nor no variable at all).")
            print(" ")
            sys.exit(1)

    return s

def newList(lizt):
    #scons may add its CLVar to the list, which has base class UserList
    from collections import UserList
    rLizt = []
    if isinstance(lizt,list):
        rLizt.extend(lizt)
    elif isinstance(lizt,UserList):
        rLizt.extend(lizt)
    elif isinstance(lizt,str):
        rLizt.extend(lizt.split())
    else:
        print("ERROR: unexpected list type in newList")

    return rLizt

def mergeLists(list1,list2):
    retList = newList(list1)
    otherList = newList(list2)

    for el2 in otherList:
        if not retList.count(el2):
           retList.append(el2)

    return retList

def initCompilerFlags(flag,initDict,dict):

    if 'C' in flag:
        dkey = 'CCFLAGS'
    elif 'FORT' in flag:
        dkey = 'FORTRANFLAGS'
    elif 'LINK' in flag:
        dkey = 'LINKFLAGS'

    coList = []
    for cokey in initDict.keys():
        coList.append(initDict[cokey])

    if dkey in dict:
        if(dict[dkey]):#make sure that there is something otherwise newList in mergeLists fails
            return mergeLists(coList,dict[dkey])
        else:
            return coList
    else:
        return coList

def setupSunOs(dict):

        dict['LINKFLAGS'] = initCompilerFlags('LINKFLAGS',LINKER_OPTIONS,dict)
        dict['FORTRANFLAGS'] = initCompilerFlags('FORTRANFLAGS',COMPILER_OPTIONS,dict)
        dict['CCFLAGS'] = initCompilerFlags('CCFLAGS',COMPILER_OPTIONS,dict)
        dict['CCFLAGS'] = mergeLists(dict['CCFLAGS'],GCCFLAGS)

        if os.path.basename(dict['FORTRAN']).count('gfortran'):

            dict['LINKFLAGS'] = mergeLists(dict['LINKFLAGS'],'--allow-shlib-undefined')
            dict['FORTRANFLAGS'] = mergeLists(dict['FORTRANFLAGS'],GFORTRAN_COMPILE_FLAGS)
            dict['LIBS'] = ['gfortran']
            dict['FORTRANMODDIRPREFIX'] = '-J'

        dict['LIBS'] = mergeLists(dict['LIBS'], ['m'])
        if not 'STDCPPLIB' in dict:
            if not 'LIBPATH' in dict:
                print("Missing information. Either the variable STDC++LIB has to be set in the SConfig file or the LIBPATH needs to be set to be  \
                      able to deduce the right stdc++ library. Try to look for libstdc++*.so in the /usr/lib directory.")
                raise Exception
            else:# try to guess stdc++ from LIBPATH
                libstd = ''
                found = False
                libpath = dict['LIBPATH']
                if(isinstance(libpath,str)):
                    libpath = [libpath]
                for dir in libpath:
                    if not os.path.exists(dir):
                        continue
                    listDir = os.listdir(dir)
                    for file in listDir:
                        if file.startswith('libstdc++'):
                            libstd = 'stdc++'
                            found = True
                            break
                    if found:
                        break

                if not found:
                    print("Error. Cannot locate the stdc++ library in the directories specified by LIBPATH in the SConfig file.")
                    raise Exception
                dict['LIBS'] = mergeLists(dict['LIBS'],[libstd])
        else:
            dict['LIBS'] = mergeLists(dict['LIBS'],[dict['STDCPPLIB']])

        return dict

def setupLinux(dict):

        dict['LINKFLAGS'] = initCompilerFlags('LINKFLAGS',LINKER_OPTIONS,dict)
        dict['FORTRANFLAGS'] = initCompilerFlags('FORTRANFLAGS',COMPILER_OPTIONS,dict)
        dict['CCFLAGS'] = initCompilerFlags('CCFLAGS',COMPILER_OPTIONS,dict)
        dict['CCFLAGS'] = mergeLists(dict['CCFLAGS'],GCCFLAGS)

        if os.path.basename(dict['FORTRAN']).count('gfortran'):

            dict['LINKFLAGS'] = mergeLists(dict['LINKFLAGS'],'-Wl,-undefined,suppress')
            dict['FORTRANFLAGS'] = mergeLists(dict['FORTRANFLAGS'],GFORTRANFLAGS)
            dict['LIBS'] = ['gfortran']
            dict['FORTRANMODDIRPREFIX'] = '-J'

        dict['LIBS'] = mergeLists(dict['LIBS'], ['m'])
        if not 'STDCPPLIB' in dict:
            if not 'LIBPATH' in dict:
                print("Missing information. Either the variable STDC++LIB has to be set in the SConfig file or the LIBPATH needs to be set to be  \
                      able to deduce the right stdc++ library. Try to look for libstdc++*.so in the /usr/lib directory.")
                raise Exception
            else:# try to guess stdc++ from LIBPATH
                libstd = ''
                found = False
                libpath = dict['LIBPATH']
                if(isinstance(libpath,str)):
                    libpath = [libpath]
                for dir in libpath:
                    if not os.path.exists(dir):
                        continue
                    listDir = os.listdir(dir)
                    for file in listDir:
                        if file.startswith('libstdc++'):
                            libstd = 'stdc++'
                            found = True
                            break
                    if found:
                        break

                if not found:
                    print("Error. Cannot locate the stdc++ library in the directories specified by LIBPATH in the SConfig file.")
                    raise Exception
                dict['LIBS'] = mergeLists(dict['LIBS'],[libstd])
        else:
            dict['LIBS'] = mergeLists(dict['LIBS'],[dict['STDCPPLIB']])

        return dict

def setupDarwin(dict):

        dict['LINKFLAGS'] = initCompilerFlags('LINKFLAGS',LINKER_OPTIONS,dict)
        dict['FORTRANFLAGS'] = initCompilerFlags('FORTRANFLAGS',COMPILER_OPTIONS,dict)
        dict['CCFLAGS'] = initCompilerFlags('CCFLAGS',COMPILER_OPTIONS,dict)
        dict['CCFLAGS'] = mergeLists(dict['CCFLAGS'],GCCFLAGS)

        if os.path.basename(dict['FORTRAN']).count('gfortran'):

            dict['LINKFLAGS'] = mergeLists(dict['LINKFLAGS'],'-Wl,-undefined,dynamic_lookup')
            dict['FORTRANFLAGS'] = mergeLists(dict['FORTRANFLAGS'],GFORTRANFLAGS)
            dict['LIBS'] = ['gfortran']
            dict['FORTRANMODDIRPREFIX'] = '-J'

        dict['LIBS'] = mergeLists(dict['LIBS'], ['m'])
        if not 'STDCPPLIB' in dict:
            if not 'LIBPATH' in dict:
                print("Missing information. Either the variable STDC++LIB has to be set in the SConfig file or the LIBPATH needs to be set to be  \
                      able to deduce the right stdc++ library. Try to look for libstdc++*.dylib in the /usr/lib directory.")
                raise Exception
            else:# try to guess stdc++ from LIBPATH
                libstd = ''
                found = False
                libpath = dict['LIBPATH']
                if(isinstance(libpath,str)):
                    libpath = [libpath]
                for dir in libpath:
                    if not os.path.exists(dir):
                        continue
                    listDir = os.listdir(dir)
                    for file in listDir:
                        if file.startswith('libstdc++') and file.endswith('.dylib'):
                            libstd = file[3:(len(file) - 6)]
                            found = True
                            break
                    if found:
                        break

                if not found:
                    print("Error. Cannot locate the stdc++ library in the directories specified by LIBPATH in the SConfig file.")
                    raise Exception
                dict['LIBS'] = mergeLists(dict['LIBS'],[libstd])
        else:
            dict['LIBS'] = mergeLists(dict['LIBS'],[dict['STDCPPLIB']])

        return dict

def setupCompilers(dict):
    dict['LDMODULEPREFIX'] = ''
    if dict['SYSTEM_TYPE'].lower() == 'darwin':
        dict = setupDarwin(dict)
    elif dict['SYSTEM_TYPE'].lower() == 'linux':
        dict = setupLinux(dict)
    elif dict['SYSTEM_TYPE'].lower() == 'sunos':
        dict = setupSunOs(dict)
    else:
        print('System not supported. Supported ones are Darwin, Linux and SunOs. Use uname to find out the system type.')
        raise Exception

    if 'CPPDEFINES'  in dict:
        dict['CPPDEFINES'] = mergeLists(dict['CPPDEFINES'], ['NEEDS_F77_TRANSLATION', 'F77EXTERNS_LOWERCASE_TRAILINGBAR'])
    else:
        dict['CPPDEFINES'] = ['NEEDS_F77_TRANSLATION', 'F77EXTERNS_LOWERCASE_TRAILINGBAR']

    dict['F90FLAGS'] = []
    for val in dict['FORTRANFLAGS']:
        if val == '-ffixed-line-length-none':
            val = '-ffree-line-length-none'
        dict['F90FLAGS'].append(val)

    return dict

def setupArchitecture(dict):
    import platform as PL
    platform = PL.architecture()
    flag = ''
    if (platform[0] == '64bit'):
        flag = '-m64'
    elif (platform[0] == '32bit'):
        flag = '-m32'
    listKeys = ['CCFLAGS','FORTRANFLAGS','LINKFLAGS','F90FLAGS']
    for key in listKeys:
        if dict[key].count('-m32') or dict[key].count('-m64'):
            if dict[key].count('-m32'):#if choice if different from user's warn but leave the way it is
                if not (flag == '-m32'):
                    print('################################################################################')
                    print('Warning. The software will be compiled as 32 bit on a 64 bit machine. Most likely will not work. Change the flag to -m64 or comment out this flag and let the system figure it out.')
                    print('################################################################################')
            else:
                if not (flag == '-m64'):
                    print('################################################################################')
                    print('Warning. The software will be compiled as 64 bit on a 32 bit machine. Most likely will not work. Change the flag to -m32 or comment out this flag and let the system figure it out.')
                    print('################################################################################')
        else:#flag not present, add it
            dict[key].append(flag)

def setupScons(env,fileName = None):

    envDictionary = env.Dictionary()
    if 'SCONS_CONFIG_DIR' in os.environ:
        sconsConfigDir = os.environ['SCONS_CONFIG_DIR']
    else:
        print("Error. Need to set the variable SCONS_CONFIG_DIR in the shall environment")
        raise Exception
    if fileName == None:
        fileName = 'SConfig'

    sconsConfig.dir = sconsConfigDir
    sconsConfig.file = fileName

    retDict = readConfigFile(sconsConfigDir + '/' + fileName)
    if not  'SYSTEM_TYPE' in retDict:
        retDict['SYSTEM_TYPE'] = os.uname()[0]
    if  'FORTRAN' not  in retDict:#if not present then use default
        retDict['FORTRAN'] = env['FORTRAN']

    if  'F77' not  in retDict:#if not present then use default
        retDict['F77'] = retDict['FORTRAN']
    if  'F90' not  in retDict:#if not present then use default
        retDict['F90'] = retDict['FORTRAN']
    if  'F95' not  in retDict:#if not present then use default
        retDict['F95'] = retDict['FORTRAN']
    #if CXX is not explicitly defined, but CC is, then assume that CXX is in the same dir
    #unfortunatelly one cannot just use gcc to compile cpp code, since it generates that right obj code, but does not link the g++ libraries

    if (('CC'  in retDict) and ('CXX' not  in retDict)):# use g++ in the same directory where CC was defined.
        (head,tail) = os.path.split(retDict['CC'])
        slash = ''
        if not (head == ''):
            slash = '/'
        gpp = head + slash + 'g++'
        retDict['CXX']= gpp

    if ('CXX' not  in retDict):#if not present then use default
        retDict['CXX']= env['CXX']

    if ('CC' not  in retDict):#if not present then use default
        retDict['CC']= env['CC']

    for key, val in COMPILER_OPTIONS.items():
        if key not in retDict: #key not in SConfig file
            if key in env: #get value from environment if it is defined there
               retDict[key] = env[key]
            else: #or else use default defined at top of this file
               retDict[key] = val

    for key, val in LINKER_OPTIONS.items():
        if key not in retDict: #key not in SConfig file
            if key in env: #get value from environment if it is defined there
               retDict[key] = env[key]
            else: #or else use default defined at top of this file
               retDict[key] = val

    retDict = setupCompilers(retDict)
    setupArchitecture(retDict)
    for key in retDict.keys():
            if isinstance(retDict[key],list):
                for value in retDict[key]:
                    exec('env.AppendUnique(' + key + ' = [\'' + value + '\'])')

            else:# assume is a string
                exec('env.Replace(' + key + ' = \'' + retDict[key] + '\')')
    return env


import torch
import torch.nn as nn

from models.feature_net import get_senet, get_resnet50
from models.graph_layers import GraphLinear, GraphResBlock
from models.transformer import Transformer
from utils import Mesh

class GraphFormer(nn.Module):
    def __init__(self, A, template_vertices, num_layers=5, num_channels=256):
        super(GraphFormer, self).__init__()

        self.A = A
        # t, s =  A._indices().detach().cpu().numpy(), A._values().detach().cpu().numpy()
        self.template_vertices = template_vertices
        self.feature_net = get_resnet50(pretrained=True)
        layers = [GraphLinear(3 + 2048, 2 * num_channels), GraphResBlock(2 * num_channels, num_channels, A)]
        for i in range(num_layers):
            layers.append(GraphResBlock(num_channels, num_channels, A))
        self.shape = nn.Sequential(GraphResBlock(num_channels, 64, A),
                                   GraphResBlock(64, 32, A),
                                   nn.GroupNorm(32 // 8, 32),
                                   nn.ReLU(inplace=True),
                                   GraphLinear(32, 3))
        self.gc = nn.Sequential(*layers)
        self.camera_fc = nn.Sequential(nn.GroupNorm(num_channels // 8, num_channels),
                                       nn.ReLU(inplace=True),
                                       GraphLinear(num_channels, 1),
                                       nn.ReLU(inplace=True),
                                       nn.Linear(A.shape[0], 3))
        # self.vfomer = Transformer(dim=template_vertices.shape[1], depth=1, heads=6, dim_head=16, mlp_dim=2048)

    def forward(self, image):
        batch_size = image.shape[0]
        template_vertices = self.template_vertices[None, :, :].expand(batch_size, -1, -1)
        feature = self.feature_net(image)
        image_enc = feature.view(batch_size, 2048, 1).expand(-1, -1, template_vertices.shape[-1])
        x = torch.cat([template_vertices, image_enc], dim=1)
        x = self.gc(x)
        shape = self.shape(x)
        camera = self.camera_fc(x).view(batch_size, 3)
        # shape = self.vfomer(shape)
        return shape, camera

def graphformer(mesh):
    model = GraphFormer(mesh.adjmat, mesh.ref_vertices.t())
    return model


import socket
from datetime import datetime

class UDPServer:
    ''' A simple UDP Server '''

    def __init__(self, host, port):
        self.host = host    # Host address
        self.port = port    # Host port
        self.sock = None    # Socket
        ##Información dict es : [Codigo, DNS, u disponibles, precio x unidad]
        self.invent = {'vodka': [1, 'ru', 100, 72000]} ##Se utiliza como clave el nombre en minuscula del licor por facilidad

    def printwt(self, msg):
        ''' Print message with current date and time '''

        current_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print(f'[{current_date_time}] {msg}')

    def configure_server(self):
        ''' Configure the server '''

        # create UDP socket with IPv4 addressing
        self.printwt('Creating socket...')
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.printwt('Socket created')

        # bind server to the address
        self.printwt(f'Binding server to {self.host}:{self.port}...')
        self.sock.bind((self.host, self.port))
        self.printwt(f'Server binded to {self.host}:{self.port}')

    def get_phone_no(self, name):
        ''' Get phone no for a given name '''

        phonebook = {'Alex': '1234567890', 'Bob': '1234512345', 'Dylan': '1234'}
        for i in phonebook.keys():
            if i == name[0:-1]:
                return f"{name[0:-1]}'s phone number is {phonebook[name[0:-1]]}"
        return f"No records found for {name[0:-1]}"
    def get_inventory(self):
        return f"Inventory: {self.inventory}"
    def handle_request(self, data, client_address):
        ''' Handle the client '''

        # handle request
        name = data.decode('utf-8')
        resp = self.get_phone_no(name)
        self.printwt(f'[ REQUEST from {client_address} ]')
        print('\n', name, '\n')

        # send response to the client
        self.printwt(f'[ RESPONSE to {client_address} ]')
        self.sock.sendto(resp.encode('utf-8'), client_address)
        print('\n', resp, '\n')
    def buy_drink(self, drink, quant, creds):
        # Se esta haciendo la conexion con el servidor banco
        drink = drink.lower()
        msgFromClient="WIT, "+str(creds[0])+", "+str(creds[1])[0:-1]+", "+str(self.invent[drink][3])+"\n"
        print(msgFromClient)
        bytesToSend = str.encode(msgFromClient)
        bufferSize          = 1024
        serverAddressPort   = ("127.0.0.2", 5555)
        UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
        UDPClientSocket.sendto(bytesToSend, serverAddressPort)
        msgFromServer = UDPClientSocket.recvfrom(bufferSize)
        msg = "Message from Bank {}".format(msgFromServer[0])
        print(msg)
        if drink in self.invent.keys() and int(quant)<= self.invent[drink][2]:
            self.invent[drink][2] = self.invent[drink][2] - int(quant)
            return f"Succesful purchase you got {quant}: {drink}s \n"
        else:
            return f"Unsuccesful purchase \n"

    def wait_for_client(self):
        ''' Wait for a client '''

        try:
            # receive message from a client
            data, client_address = self.sock.recvfrom(1024)

            # handle client's request
            self.handle_request(data, client_address)

        except OSError as err:
            self.printwt(err)

    def shutdown_server(self):
        ''' Shutdown the UDP server '''

        self.printwt('Shutting down server...')
        self.sock.close()

def main():
    ''' Create a UDP Server and respond to a client's resquest '''

    udp_server = UDPServer('127.0.0.1', 4444)
    udp_server.configure_server()
    udp_server.wait_for_client()
    udp_server.shutdown_server()

if __name__ == '__main__':
    main()


import argparse
import os.path
import sys
import subprocess
import platform

parser = argparse.ArgumentParser(description="Changes the file permission for device clock setting on Android")
parser.add_argument("-t", "--target", required=True, help="IP address of Android device")
parser.add_argument("-d", "--device", help="adb device ID, as seen in 'adb devices'. This or -i must be specified when multiple devices are available.")
parser.add_argument("-i", "--infer", action="store", metavar="PORT", nargs="?", const="5555", help="Specify this when using ADB over TCP/IP, to infer the -d argument from the -t one. This option saves you from having to specify the device IP address twice. Port 5555 is used if no port is specified. This or -d must be specified when multiple devices are available.")
args = parser.parse_args()

# Check that we have adb in PATH, that it sees a device and the device is
# in a usable state
proc = subprocess.Popen(["adb", "--help"], stdout=subprocess.DEVNULL)
proc.communicate()
if proc.returncode != 0:
    sys.stderr.write("Error: adb not in PATH\n")
    exit(1)

proc = subprocess.Popen(["adb", "devices"], stdout=subprocess.PIPE)
output = proc.communicate()[0].decode()
if proc.returncode != 0:
    sys.stderr.write("Error: unexpected error querying adb devices\n")
    exit(1)

lines = output.strip().splitlines()
if lines[0] != "List of devices attached":
    sys.stderr.write("Error: unexpected output from 'adb devices'\n")
    exit(1)

if len(lines) > 2 and not (args.device or args.infer):
    sys.stderr.write("Error: Multiple Android devices available; must specify one with -d or -i\n")
    for line in lines[1:]:
        sys.stderr.write("   {}\n".format(line))
    exit(1)

device = args.device
if device is None and args.infer:
    device = args.target + ":" + args.infer

if device is None:
    proc = subprocess.Popen(["adb", "get-serialno"], stdout=subprocess.PIPE)
    device = proc.communicate()[0].decode().strip()

proc = subprocess.Popen(["adb", "-s", device, "get-state"], stdout=subprocess.PIPE)
output = proc.communicate()[0].decode().strip()
if proc.returncode != 0:
    # No need for explicit message; adb already reported device not found
    exit(1)
if output != "device":
    sys.stderr.write("Error: adb device is not in a usable state\n")
    exit(1)

# sysfs permission needs to be changed:
subprocess.call(["adb", "-s", device, "shell", "su", "root", "chmod", "766", "/sys/class/drm/card0/device/power_dpm_force_performance_level"])


#!/usr/bin/env python

import io
import os
import string
import typing

import gym
import numpy as np
from PIL import Image
from playwright.sync_api import sync_playwright

cur_path_dir = os.path.dirname(os.path.realpath(__file__))
webtasks_dir = os.path.join(cur_path_dir, "webtasks")

# Generate an index mapped character list: ["NOKEY", A, B, C, ... X, Y, Z, " "]
ACTION_KEY_MAP = {
    i: x for (i, x) in enumerate(["NOKEY"] + list(string.ascii_uppercase + " "))
}

class PlaywrightEnv(gym.Env):
    def __init__(self, env_config: typing.Dict = {}):
        self.env_config = env_config
        self.base_url = env_config.get("url", f"file://{webtasks_dir}/login-user.html")
        self.obs_im_shape = env_config.get(
            "obs_im_shape", {"width": 160, "height": 260}
        )
        self.obs_im_channels = 3
        self.reward_elem_name = self.env_config.get("reward_elem_name", "reward")
        self.step_num = 0
        self.max_step_num = self.env_config.get("max_step_num", 100)
        self.num_allowed_chars = len(ACTION_KEY_MAP) - 1
        self.observation_space = gym.spaces.Box(
            0,
            255,
            (
                self.obs_im_shape["width"],
                self.obs_im_shape["height"],
                self.obs_im_channels,
            ),
            dtype=int,
        )
        # Action: [x, y, character]
        self.action_space = gym.spaces.Box(
            low=np.array([0, 0, 0]),
            high=np.array(
                [
                    self.obs_im_shape["width"],
                    self.obs_im_shape["height"],
                    self.num_allowed_chars,
                ]
            ),
            shape=(3,),
            dtype=np.float32,  # minval for tf.random.uniform for int is expected to be scalar :?;https://github.com/tensorflow/tensorflow/issues/39814
        )
        self.headless = self.env_config.get("headless", True)
        self.playwright = sync_playwright().start()
        self.browser = self.playwright.chromium.launch(headless=self.headless)
        self.page = self.browser.new_page()
        self.page.set_viewport_size(self.obs_im_shape)
        self.page.set_default_navigation_timeout(1000)

    def _get_screenshot(self) -> np.ndarray:
        screenshot_bytes = self.page.screenshot()
        screenshot = np.array(Image.open(io.BytesIO(screenshot_bytes)).convert("RGB"))
        return screenshot

    def reset(self) -> np.ndarray:
        self.page.goto(self.base_url)
        self.obs = self._get_screenshot()
        self.step_num = 0
        self.done = False
        return self.obs

    def _clamp(self, action, low, high):
        low_x, low_y, low_char_idx = low
        high_x, high_y, high_char_idx = high
        return (
            max(low_x, min(action[0], high_x)),
            max(low_y, min(action[1], high_y)),
            max(low_char_idx, min(action[2], high_char_idx)),
        )

    def step(self, action):
        # action: [click_x, click_y, press_key]
        if not self.done:
            clamped_action = self._clamp(
                action, self.action_space.low, self.action_space.high
            )
            click_x, click_y, press_key_id_float = clamped_action
            press_key_id = int(press_key_id_float)  # Using integer part; No ceil/floor
            press_key = ACTION_KEY_MAP.get(press_key_id, "")
            self.page.mouse.click(float(click_x), float(click_y))
            if not (press_key in ["NOKEY", ""]):  # Skip NOKEY, ""
                self.page.keyboard.press(press_key)
            self.obs = self._get_screenshot()
            self.step_num += 1

            self.done = self.page.evaluate("done")
            # Reward is +1 on task completion; -1 otherwise
            self.reward = self.page.evaluate("reward")
            if self.step_num >= self.max_step_num:
                self.done = True
            self.info = {}
            return self.obs, self.reward, self.done, self.info
        else:
            raise (ValueError("Episode done. Call reset()"))

    def close(self):
        self.browser.close()
        self.playwright.stop()
        super().close()

if __name__ == "__main__":
    env_config = {}
    env = PlaywrightEnv(env_config=env_config)
    done = False
    obs = env.reset()
    step_num = 0
    while not done:
        action = env.action_space.sample()
        next_obs, reward, done, info = env.step(action)
        print(
            f"Step#:{step_num} obs.shape:{next_obs.shape} Action:{action} Reward:{reward} Done:{done} Info:{info}"
        )
        step_num += 1
        # Debug:
        # Image.fromarray(next_obs).show()
        # input()
    env.close()


# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 15:11:10 2019

@author: Aspire E15
"""

import csv

def modelistcsv():
    with open('hasil1.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        for row in csv_reader:
            print(row[0], row[1], row[2], row[3])

def modediccsv():
    with open('hasil1.csv', mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        for row in csv_reader:
            print(row['nama'], row['npm'], row['kelas'], row['tanggal lahir'])

def menuliscsv():
    data = {
    ('Ramadhan', '1174072', 'D4TI2C'),
    ('Ade','1174073','D4TI2C')
    }
    data_file = open('hasil3.csv', 'w')
    w = csv.writer(data_file)
    w.writerow(('nama','npm','kelas'))
    for s in data:
        w.writerow(s)


# Method-1 Using Stack

def decodeString(s):
    length = len(s)
    stack = []

    for i in range(length):
        if s[i] != ']':
            stack.append(s[i])
        else:
            substr = ''
            while stack[-1] != '[':
                substr = stack.pop() + substr
            stack.pop()

            digit = ''
            while stack and stack[-1].isdigit():
                digit = stack.pop() + digit
            stack.append(int(digit) * substr )
    return ''.join(stack)

# Time and Space Complexity depends
# on the input


import copy
import os
from typing import Any, Dict, List, cast

from tfx import types
from tfx.dsl.components.base import base_beam_executor
from tfx.dsl.components.base import base_executor
from tfx.dsl.components.base import executor_spec
from tfx.orchestration.config import base_component_config
from tfx.orchestration.launcher import base_component_launcher

class InProcessComponentLauncher(base_component_launcher.BaseComponentLauncher):
  """Responsible for launching a python executor.

  The executor will be launched in the same process of the rest of the
  component, i.e. its driver and publisher.
  """

  @classmethod
  def can_launch(
      cls, component_executor_spec: executor_spec.ExecutorSpec,
      component_config: base_component_config.BaseComponentConfig) -> bool:
    """Checks if the launcher can launch the executor spec."""
    if component_config:
      return False

    return isinstance(component_executor_spec, executor_spec.ExecutorClassSpec)

  def _run_executor(self, execution_id: int,
                    input_dict: Dict[str, List[types.Artifact]],
                    output_dict: Dict[str, List[types.Artifact]],
                    exec_properties: Dict[str, Any]) -> None:
    """Execute underlying component implementation."""
    executor_class_spec = cast(executor_spec.ExecutorClassSpec,
                               self._component_executor_spec)

    if issubclass(executor_class_spec.executor_class,
                  base_beam_executor.BaseBeamExecutor):
      executor_context = base_beam_executor.BaseBeamExecutor.Context(
          beam_pipeline_args=self._beam_pipeline_args,
          tmp_dir=os.path.join(self._pipeline_info.pipeline_root, '.temp', ''),
          unique_id=str(execution_id))
    else:
      executor_context = base_executor.BaseExecutor.Context(
          extra_flags=self._beam_pipeline_args,
          tmp_dir=os.path.join(self._pipeline_info.pipeline_root, '.temp', ''),
          unique_id=str(execution_id))

    # Type hint of component will cause not-instantiable error as
    # component.executor is Type[BaseExecutor] which has an abstract function.
    executor = executor_class_spec.executor_class(
        executor_context)  # type: ignore

    # Make a deep copy for input_dict and exec_properties, because they should
    # be immutable in this context.
    # output_dict can still be changed, specifically properties.
    executor.Do(
        copy.deepcopy(input_dict), output_dict, copy.deepcopy(exec_properties))


from tkinter import *
from PIL import Image , ImageTk

def createfullarray(createlittlearray, i):
    if (len(createlittlearray) == o):
        feasible.append(createlittlearray)
        print(createlittlearray)
    if (i not in [_[0] for _ in createlittlearray]):
        for j in range(1, u+1):
            if (j not in [_[1] for _ in createlittlearray]):
                if len([0 for p in createlittlearray if abs(p[0]-i) == abs(p[1]-j)]) == 0:
                    createfullarray(createlittlearray+[[i, j]], i+1)

def start(n, k):
    global feasible, u, o
    u = n
    o = k
    feasible = []
    createfullarray([], 1)
    return feasible

start(8, 8)

def next_button():
    global z
    canvas_chessFlat.delete("all")
    z += 1
    layout_chess(z)

def previos_button():
    global z
    canvas_chessFlat.delete("all")
    z -= 1
    layout_chess(z)

def reset_button():
    global z
    canvas_chessFlat.delete("all")
    z = 0
    layout_chess(z)

chessFlat = Tk()
chessFlat.geometry("600x670")
chessFlat.maxsize(600,670)
chessFlat.title("Chess")
canvas_chessFlat = Canvas(chessFlat, width=560, height=560)
image_chess_flat = ImageTk.PhotoImage(Image.open("chessflat.png"))
image_queen = ImageTk.PhotoImage(Image.open("queen.png"))

def layout_chess(z):
    canvas_chessFlat.create_image(280,280,image=image_chess_flat)
    for y in range(8):
        for x in range(8):
            if (feasible[z][y][1] == x+1):
                canvas_chessFlat.create_image( 35+(x*70) , 35+((y)*70) ,image=image_queen)
    Label(chessFlat, font=('arial', 13, 'bold'), text="level: " + str(z+1), fg="black").place(relx=0.03, rely=0.85, height=30, width=70)
    Button(chessFlat, padx=10, pady=16, font=('arial', 11), fg='black', bg='#04AA6D', text='Next >', command=next_button).place(relx=0.83, rely=0.9, height=50, width=80)
    Button(chessFlat, padx=10, pady=16, font=('arial', 11), fg='black', bg='#3d30ff', text='< previos', command=previos_button).place(relx=0.03, rely=0.9, height=50, width=80)
    Button(chessFlat, padx=10, pady=16, font=('arial', 11), fg='black', bg='#ff4c4c', text='Reset', command=reset_button).place(relx=0.43, rely=0.9, height=50, width=80)

z = 0
layout_chess(z)
canvas_chessFlat.pack()
chessFlat.mainloop()


# -*- coding: utf-8 -*-
# __author__ = 'shicaiping'

import os
import re
import argparse

parser = argparse.ArgumentParser(description='repeat比对统计')
parser.add_argument('-i', '--xls', help='input repeat blast table', required=True)
parser.add_argument('-o', '--detail', help='output repeat detail table', required=True)
parser.add_argument('-f', '--gff', help='repeat annotation file', required=True)

args = vars(parser.parse_args())
blast = args['xls']
detail = args['detail']
gff = args['gff']

ssr = {}
with open(gff, "r") as f:
    head = f.readline()
    for line in f:
        items = line.strip().split("\t")
        info = re.search(r'ID=(\S+);.*;Class=(\S+).*;PercDiv=.*', items[8])
        ID = info.group(1)
        CLASS = info.group(2).split("/")[0]
        ssr[ID] = CLASS

query = {}
columns = []
with open(blast, "r") as f, open (detail ,"w") as w:
    head = f.readline()
    w.write("query_name\tHit\tEvalue\tIdentity\tClass\n")
    for line in f:
        items = line.strip().split("\t")
        if not query.has_key(items[5]):
            query[items[5]] = 1
            columns = [items[5], items[10], items[1], items[3], ssr[items[10]]]
            w.write("\t".join(columns) + "\n")
        else:
            pass


#{
 # Driver Code Starts
#Initial Template for Python 3

import atexit
import io
import sys

# } Driver Code Ends

class Solution:
    def combinationalSum(self,A, B):
        def combinationSum(A, B, i, sum_arr, result):
            if B == 0:
                sum_arr.sort()
                result.append(sum_arr)
                return

            for j in range(i, len(A)):
                if A[j] > 0:
                    if j > i and A[j] == A[j - 1]: continue
                    if A[j] > B: break
                    combinationSum(A, (B - A[j]), j, sum_arr + [A[j]], result)
        result = []
        combinationSum(sorted(A), B, 0, [], result)
        result.sort()
        return result
        # code here

#{
 # Driver Code Starts.

if __name__ == '__main__':
    test_cases = int(input())
    for cases in range(test_cases):
        n = int(input())
        a = list(map(int,input().strip().split()))
        s = int(input())
        ob = Solution()
        result = ob.combinationalSum(a,s)
        if(not len(result)):
            print("Empty")
            continue
        for i in range(len(result)):
            print("(", end="")
            size = len(result[i])
            for j in range(size - 1):
                print(result[i][j], end=" ")
            if (size):
                print(result[i][size - 1], end=")")
            else:
                print(")", end="")
        print()

# } Driver Code Ends

Combination Sum - GFG/combination-sum.py


# -*- coding: utf-8 -*-
"""
Created on Sun Jan  1 02:06:15 2017

@author: LLH
"""
import numpy as np
import matplotlib.pyplot as plot

### Project 5
class proj_5:
    ##[Monte Carlo]
    def q1_1():
        # K=50 runs of Pi-estimations with n=100 samples
        pi_est=[]
        for k in range(50):
            s=np.random.rand(100,2)
            count=0
            for i in s:
                if i[0]**2+i[1]**2<=1:
                    count+=1
            pi_est.append(count/100)
        plot.hist(pi_est)
        plot.xlabel("Pi")
    def q1_2():
        # Using different n, plot variance of estimations
        n=100
        v=[]
        while 1:
            pi_est2=[]
            for k in range(50):
                s=np.random.rand(n,2)
                count=0
                for i in s:
                    if i[0]**2+i[1]**2<=1:
                        count+=1
                pi_est2.append(count/n)
            v.append(np.var(pi_est2))
            if n==1000:
                plot.plot(np.arange(100,1100,100),v)
                plot.xlabel("number of samples",fontsize=13)
                plot.ylabel("Variance",fontsize=13)
                break
            else:
                n+=100
    def q1_3():
        # introduction use
        from mpl_toolkits.mplot3d import Axes3D
        x=np.arange(0,1.005,0.005)
        y=np.arange(0,1.005,0.005)
        X,Y=np.meshgrid(x,y)
        G=np.abs(4*X-2)*np.abs(4*Y-2)
        n=100
        s=np.random.rand(n,3)
        s[:,2]=4*s[:,2]
        fig=plot.figure()
        ax=fig.add_subplot(111, projection='3d')
        ax.scatter3D(s[:,0],s[:,1],s[:,2],c='blue',s=50)
        ax.plot_surface(X,Y,G,color='yellow')
        # the 1st way
        inte=[];stder=[]
        n=100
        while 1:
            sample=[]
            for j in range(50):
                s=np.random.rand(n,3)
                s[:,2]=4*s[:,2]
                count=0
                for i in s:
                    if i[2]<=np.abs(4*i[0]-2)*np.abs(4*i[1]-2):
                        count+=1
                sample.append(count/n*4)
            inte.append(np.mean(sample))
            stder.append(np.std(sample))
            if n==10000:
                print('the 1st way:')
                print('integral=',inte)
                print('standard error=',stder,'\n')
                break
            else:
                n=n*10
        # the 2nd way
        n=100
        inte2=[];stder2=[]
        while 1:
            ss=np.random.rand(n,2)
            GG=np.abs(4*ss[:,0]-2)*np.abs(4*ss[:,1]-2)
            inte2.append(np.mean(GG))
            stder2.append(np.sqrt((np.sum((GG-np.mean(GG))**2)/(n-1)/n)))
            if n==10000:
                print('the 2nd way:')
                print('integral=',inte2)
                print('standard error=',stder2)
                break
            else:
                n=n*10
    ##[Variance Reduction Methods for Monte Carlo]
    def q2():
        #draw the functions
        from mpl_toolkits.mplot3d import Axes3D
        x=np.arange(0,1.005,0.005)
        y=np.arange(0,1.005,0.005)
        X,Y=np.meshgrid(x,y)
        G1=np.exp(5*np.abs(X-0.5)+5*np.abs(Y-0.5))
        G3=np.abs(4*X-2)*np.abs(4*Y-2)
        fig=plot.figure()
        ax=fig.add_subplot(111, projection='3d')
        ax.plot_surface(X,Y,G1,color='yellow')
        fig=plot.figure()
        ax=fig.add_subplot(111, projection='3d')
        ax.plot_surface(X,Y,G3,color='green')
        xx=np.arange(-1,1.005,0.005)
        yy=np.arange(-1,1.005,0.005)
        XX,YY=np.meshgrid(xx,yy)
        G2=np.cos(np.pi+5*XX+5*YY)
        fig=plot.figure()
        ax=fig.add_subplot(111, projection='3d')
        ax.plot_surface(XX,YY,G2,color='blue')
        #stratification: 4 subintervals
        #a,c
        def iv_a(n_acin,n_acout):
            sub_in=np.exp(5*np.abs(n_acin[:,0]-0.5)+5*np.abs(n_acin[:,1]-0.5))
            sub_out=np.exp(5*np.abs(n_acout[:,0]-0.5)+5*np.abs(n_acout[:,1]-0.5))
            itg_a=0.25*np.sum(sub_in)/np.shape(sub_in)[0]+0.75*np.sum(sub_out)/np.shape(sub_out)[0]
            var_a=1/16*np.var(sub_in)/(np.shape(sub_in)[0]-1)+\
            9/16*np.var(sub_out)/(np.shape(sub_out)[0]-1)
            return itg_a,var_a
        def iv_c(n_acin,n_acout):
            sub_in=np.abs(4*n_acin[:,0]-2)*np.abs(4*n_acin[:,1]-2)
            sub_out=np.abs(4*n_acout[:,0]-2)*np.abs(4*n_acout[:,1]-2)
            itg_c=0.25*np.sum(sub_in)/np.shape(sub_in)[0]+0.75*np.sum(sub_out)/np.shape(sub_out)[0]
            var_c=1/16*np.var(sub_in)/(np.shape(sub_in)[0]-1)+\
            9/16*np.var(sub_out)/(np.shape(sub_out)[0]-1)
            return itg_c,var_c
        sample_ac=np.random.rand(1000,2)
        suba=np.exp(5*np.abs(sample_ac[:,0]-0.5)+5*np.abs(sample_ac[:,1]-0.5))
        itg_sa=np.mean(suba)
        var_sa=np.var(suba)/(np.shape(suba)[0]-1)
        subc=np.abs(4*sample_ac[:,0]-2)*np.abs(4*sample_ac[:,1]-2)
        itg_sc=np.mean(subc)
        var_sc=np.var(subc)/(np.shape(subc)[0]-1)
        n_acin=[]
        n_acout=[]
        for i in sample_ac:
            if ((i[0]>0.25)&(i[0]<0.75))&((i[1]>0.25)&(i[1]<0.75)):
                n_acin.append(i)
            else:
                n_acout.append(i)
        n_acin=np.array(n_acin)
        n_acout=np.array(n_acout)
        ra=iv_a(n_acin,n_acout)
        rc=iv_c(n_acin,n_acout)
        print('result_a=',ra)
        print('result_c=',rc)
        #b
        def iv_b(n_bin,n_bout):
            sub_in=np.cos(np.pi+5*n_bin[:,0]+5*n_bin[:,1])
            sub_out=np.cos(np.pi+5*n_bout[:,0]+5*n_bout[:,1])
            itg_c=1*np.sum(sub_in)/np.shape(sub_in)[0]+3*np.sum(sub_out)/np.shape(sub_out)[0]
            var_c=1/16*np.var(sub_in)/(np.shape(sub_in)[0]-1)+\
            9/16*np.var(sub_out)/(np.shape(sub_out)[0]-1)
            return itg_c,var_c
        sample_b=2*np.random.rand(1000,2)-1
        subb=np.cos(np.pi+5*sample_b[:,0]+5*sample_b[:,1])
        itg_sb=np.mean(subb)*4
        var_sb=np.var(subb)/(np.shape(subb)[0]-1)
        n_bin=[]
        n_bout=[]
        for i in sample_b:
            if ((i[0]>-0.5)&(i[0]<0.5))&((i[1]>-0.5)&(i[1]<0.5)):
                n_bin.append(i)
            else:
                n_bout.append(i)
        n_bin=np.array(n_bin)
        n_bout=np.array(n_bout)
        rb=iv_b(n_bin,n_bout)
        print('result_b=',rb)

        #importance sampling

    ##[MCMC for Optimization]
    def q3_1():
        #2 dimension case
        x=np.arange(-500,503,2)
        y=np.arange(-500,503,2)
        X,Y=np.meshgrid(x,y)
        f=418.9829*2-(X*np.sin(np.sqrt(np.abs(X)))+
        Y*np.sin(np.sqrt(np.abs(Y))))
        plot.contour(X,Y,f)
        plot.colorbar()
        plot.xticks(np.arange(-500,600,100))
        plot.yticks(np.arange(-500,600,100))
    def q3_2(s,tstep):
        # simulated annealing
        from random import random as rd
        from random import choice
        from scipy.constants import k
        def cost(s):
            c=418.9829*2-(s[0]*np.sin(np.sqrt(np.abs(s[0])))+
            s[1]*np.sin(np.sqrt(np.abs(s[1]))))
            return c
        def neighbor(s,c):
            ax=choice([-5,0,5])
            ay=choice([-5,0,5])
            nx=s[0]+ax
            ny=s[1]+ay
            if np.abs(nx)>500:
                nx=nx/np.abs(nx)*500
            if np.abs(ny)>500:
                ny=ny/np.abs(ny)*500
            if cost([nx,ny])-c<5:
                return np.round(1000*np.random.rand(2)-500)
            else:
                return np.array([nx,ny])
        def accept_prob(c,n_c,T,k):
            a=min([1,np.exp((n_c-c)/(k*T))])
            return a
        def cooling(T,t):
            return T*0.9*np.exp(-t)  #exponential
#            return 1/2*t**(-2)+1/2*t**(-1)  #polynomial
#            return T/(1+5*np.log(1+t))  #logarithmic
        T=1.0
        c=cost(s)
        past=np.array([s])
        T=cooling(T,tstep)
        i=1
        while i<=100:
            n_s=neighbor(s,c)
            n_c=cost(n_s)
            ap=accept_prob(c,n_c,T,k)
            if ap>rd():
                past=np.append(past,[s],axis=0)
                s=n_s
                c=n_c
            i+=1
#        return c # used for q3_3
        return past # used for q3_4
    def q3_3():
        r20=[]
        for i in range(20):
            r20.append(proj_5.q3_2([0,0],i+1))
        plot.subplot(2,2,1)
        plot.hist(r20)
        plot.title('t=20')
        r50=[]
        for i in range(50):
            r50.append(proj_5.q3_2([0,0],i+1))
        plot.subplot(2,2,2)
        plot.hist(r50)
        plot.title('t=50')
        r100=[]
        for i in range(100):
            r100.append(proj_5.q3_2([0,0],i+1))
        plot.subplot(2,2,3)
        plot.hist(r100)
        plot.title('t=100')
        r1000=[]
        for i in range(1000):
            r1000.append(proj_5.q3_2([0,0],i+1))
        plot.subplot(2,2,4)
        plot.hist(r1000)
        plot.title('t=1000')
    def q3_4():
        fp=proj_5.q3_2([0,0],1)
        proj_5.q3_1()
        plot.scatter(fp[:,0],fp[:,1])


import datetime
import httpx
import requests
import bs4
from colorama import Fore

global loop

async def get_html(episode_number: int) -> str:
    print(Fore.YELLOW + f"Getting HTML for episode {episode_number}", flush=True)

    url = f'https://talkpython.fm/{episode_number}'

    async with httpx.AsyncClient() as client:
        resp = await client.get(url)  #this assigns tasks and for each co-routines
        resp.raise_for_status()
        return resp.text

def get_title(html: str, episode_number: int) -> str:
    print(Fore.CYAN + f"Getting TITLE for episode {episode_number}", flush=True)
    soup = bs4.BeautifulSoup(html, 'html.parser')
    header = soup.select_one('h1')
    if not header:
        return "MISSING"
    return header.text.strip()

def main():
    t0 = datetime.datetime.now()
    get_title_range()
    dt = datetime.datetime.now() - t0
    print(f"Done in {dt.total_seconds():.2f} sec")

def get_title_range():
    for n in range(270, 280):
        html = get_html(n)
        title = get_title(html, n)
        print(Fore.WHITE + f"Title found: {title}", flush=True)

if __name__ == '__main__':
    main()


import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtUiTools import QUiLoader
from setting import Setting

class GeneralSettingWidget(QDialog):

    def __init__(self, parent = None, generalSetting = {}, shortcutSetting = {}):
        super(GeneralSettingWidget, self).__init__(parent)

        self.tempGeneralSetting = generalSetting
        self.tempShortcutSetting = shortcutSetting

        self.ui = QUiLoader().load("./generalSetting.ui")
        self.setupUi()

        self.ui.shortcutTreeWidget.currentItemChanged.connect(lambda:  self.setupUiShortcutDetail(self.ui.shortcutTreeWidget.currentItem()))
        self.slot1 = lambda: self.updateShortcutPropertyItem(key = self.ui.shortcutEdit.text(), folderPath = self.ui.folderPathEdit.text())
        self.ui.shortcutEdit.textChanged.connect(self.slot1)
        self.ui.folderPathEdit.textChanged.connect(self.slot1)

        self.ui.shortcutNewButton.clicked.connect(lambda: self.insertShortcutSetting(index = self.ui.shortcutTreeWidget.indexOfTopLevelItem(self.ui.shortcutTreeWidget.currentItem())))
        self.ui.shortcutCopyButton.clicked.connect(lambda: self.insertShortcutSetting(index = self.ui.shortcutTreeWidget.indexOfTopLevelItem(self.ui.shortcutTreeWidget.currentItem()),
                                                                                shortcutProperty = self.ui.shortcutTreeWidget.currentItem().clone()))
        self.ui.shortcutUpButton.clicked.connect(lambda: self.moveTreeWidgetItem(index = self.ui.shortcutTreeWidget.indexOfTopLevelItem(self.ui.shortcutTreeWidget.currentItem()),
                                                                                direction = -1))
        self.ui.shortcutDownButton.clicked.connect(lambda: self.moveTreeWidgetItem(index = self.ui.shortcutTreeWidget.indexOfTopLevelItem(self.ui.shortcutTreeWidget.currentItem()),
                                                                                direction = +1))
        self.ui.shortcutSortButton.clicked.connect(lambda: self.ui.shortcutTreeWidget.sortItems(0, Qt.AscendingOrder))
        self.ui.shortcutDeleteButton.clicked.connect(lambda: self.deleteShortcutSetting(index = self.ui.shortcutTreeWidget.indexOfTopLevelItem(self.ui.shortcutTreeWidget.currentItem())))
        self.ui.folderSelectDialogButton.clicked.connect(lambda: self.openFolderSelectDialog(self.ui.folderPathEdit.text()))

    def setupUi(self):
        self.ui.font1ComboBox.setCurrentFont(QFont(self.tempGeneralSetting["font1"]))
        self.ui.font2ComboBox.setCurrentFont(QFont(self.tempGeneralSetting["font2"]))

        self.ui.fontSizeSpinBox.setDecimals(1)
        self.ui.fontSizeSpinBox.setValue(self.tempGeneralSetting["fontSize"])

        self.ui.shortcutTreeWidget.setHeaderLabels(["Shortcut", "Folder path"])

        for key in sorted(self.tempShortcutSetting):
            self.ui.shortcutTreeWidget.addTopLevelItem(self.getShortcutPropertyItem(key))

    def setupUiShortcutDetail(self, shortcutProperty):
        if shortcutProperty:
            self.ui.shortcutEdit.textChanged.disconnect(self.slot1)
            self.ui.folderPathEdit.textChanged.disconnect(self.slot1)

            self.ui.shortcutEdit.setText(shortcutProperty.text(0))
            self.ui.folderPathEdit.setText(shortcutProperty.text(1))

            self.ui.shortcutEdit.textChanged.connect(self.slot1)
            self.ui.folderPathEdit.textChanged.connect(self.slot1)

    def getShortcutPropertyItem(self, key = None):
        shortcutPropertyItem = QTreeWidgetItem()

        if key is not None:
            shortcutPropertyItem.setText(0, key)
            shortcutPropertyItem.setText(1, self.tempShortcutSetting[key])
        elif key is None:
            key = "sample"
            shortcutPropertyItem.setText(0, key)
            shortcutPropertyItem.setText(1, Setting().getInitSettings()["shortcut"][key])

        return shortcutPropertyItem

    def updateShortcutPropertyItem(self, key = "", folderPath = 0):
        if self.ui.shortcutTreeWidget.currentItem():
            shortcutProperty = self.ui.shortcutTreeWidget.currentItem()
            shortcutProperty.setText(0, key)
            shortcutProperty.setText(1, folderPath)

    def checkDuplicationShortcutKey(self):
        index = 0
        shortcutList = list()
        duplicateItemIndexList = list()

        while index < self.ui.shortcutTreeWidget.topLevelItemCount():
            if self.ui.shortcutTreeWidget.topLevelItem(index).text(0) in shortcutList:
                duplicateItemIndexList.append(index)
                if shortcutList.index(self.ui.shortcutTreeWidget.topLevelItem(index).text(0)) not in duplicateItemIndexList:
                    duplicateItemIndexList.append(shortcutList.index(self.ui.shortcutTreeWidget.topLevelItem(index).text(0)))

            shortcutList.append(self.ui.shortcutTreeWidget.topLevelItem(index).text(0))

            self.ui.shortcutTreeWidget.topLevelItem(index).setBackground(0, QBrush(Qt.transparent))

            index += 1

        for i in duplicateItemIndexList:
            self.ui.shortcutTreeWidget.topLevelItem(i).setBackground(0, QBrush(Qt.red))

    def openFolderSelectDialog(self, dir):
        self.ui.shortcutEdit.textChanged.disconnect(self.slot1)
        self.ui.folderPathEdit.textChanged.disconnect(self.slot1)

        dialog = QFileDialog(directory = dir)
        dialog.setFileMode(QFileDialog.Directory);
        dialog.setOption(QFileDialog.ShowDirsOnly, True);
        if dialog.exec():
            folderPath = dialog.selectedFiles()[0]
            folderPath = folderPath.replace('/', '\\')
            self.ui.folderPathEdit.setText(folderPath)

            self.updateShortcutPropertyItem(key = self.ui.shortcutEdit.text(), folderPath = self.ui.folderPathEdit.text())

        self.ui.shortcutEdit.textChanged.connect(self.slot1)
        self.ui.folderPathEdit.textChanged.connect(self.slot1)

    def getCurrentGeneralSetting(self):
        generalSetting = dict()
        generalSetting["font1"] = self.ui.font1ComboBox.currentFont().family()
        generalSetting["font2"] = self.ui.font2ComboBox.currentFont().family()
        generalSetting["fontSize"] = self.ui.fontSizeSpinBox.value()

        return generalSetting

    def getCurrentShortcutSettings(self):
        shortcutSettings  = dict()

        i = 0
        while i < self.ui.shortcutTreeWidget.topLevelItemCount():
            key = self.ui.shortcutTreeWidget.topLevelItem(i).text(0)
            shortcutSettings[key] = self.ui.shortcutTreeWidget.topLevelItem(i).text(1)

            i += 1

        return shortcutSettings

    def insertShortcutSetting(self, index = -1, shortcutProperty = None):
        if shortcutProperty is None:
            shortcutProperty = self.getShortcutPropertyItem()

        if index != -1:
            self.ui.shortcutTreeWidget.insertTopLevelItem(index + 1, shortcutProperty)
        else:
            self.ui.shortcutTreeWidget.addTopLevelItem(shortcutProperty)

        self.checkDuplicationShortcutKey()

    def moveTreeWidgetItem(self, index = 0, direction = 0):
        if index == 0 and direction == -1:
            return
        if index == self.ui.shortcutTreeWidget.topLevelItemCount() - 1 and direction == +1:
            return

        item = self.ui.shortcutTreeWidget.takeTopLevelItem(index)
        self.ui.shortcutTreeWidget.insertTopLevelItem(index + direction, item)
        self.ui.shortcutTreeWidget.setCurrentItem(item)

    def deleteShortcutSetting(self, index = -1):
        item = self.ui.shortcutTreeWidget.takeTopLevelItem(index)
        del item
        self.checkDuplicationShortcutKey()


#!/usr/bin/env python3
from mechanize import Browser;  # for making requests
from bs4 import BeautifulSoup;  # for parsing html

# this is the global browser for this program
bro = Browser();
bro.set_handle_robots(False)
bro.set_handle_refresh(False)
bro.set_cookiejar(None)

"""
Get a list of courses from the catalog
@param url: the basename url to the catalog for a course
@param catoid: the catalog id
@param coid_begin: the course id for the first course in the catalog
@param coid_end: the course id for the last course in the catalog
@return a list of json courses
"""
def web_parse(url, catoid, coid_begin, coid_end):
    courses = []
    coid = coid_begin
    while coid <= coid_end:
        # get html
        html = bro.open(url+"?catoid="+str(catoid)+"&coid="+str(coid)).get_data()
        # leech the course information from the html
        course = process_request(html)
        if course:                 # if it was a course page
            courses.append(course) # add the course
        coid += 1                  # go the the next course page
    return courses

"""
get the course information from the html page
@return a course json
"""
def process_request(html):
    # TODO: beautiful soup probably
    print("TODO")

"""
connect to a page. if connection times out, rety indefinitly
@param bro: the mechanize browser object
@param url: the url to connect to
"""
def connect_nofail(url):
    # never fail to access the link
    connected = False
    while not connected:
        try:
            bro.open(url)
            connected = True
        except:
            print(".", end='',flush=True)

def get_last_coid(url):
    # page with list of courses: southern methodist university catalog uniform resource locator
    ### find the last courses id
    coid_end = 0;               # will set later
    connect_nofail(url)
    # find the link to get to the last page of courses
    links = list(bro.links())
    for i in range(len(links)-1, 0, -1):
        text = links[i].text
        if(text == "Forward 10"):
            # the link after this one is the link to the last page
            connect_nofail(links[i+1].url) # we are going to the last page
            break
    # now being on the last page of courses, we can start from the back again and find the last course
    links = list(bro.links())
    for i in range(len(links)-1, 0, -1):
        text = links[i].text
        if(text == "1"):         # this is the link right after the last course
            # get the course id of the last course
            text = links[i-1].url # the previous link on the page should be the last course
            url_parts = text.split('=')
            coid_end = int(url_parts[-1]) # the last element is the coid
            break
    return coid_end

### Main ###
"""
get any user input and get initial information like the last course id

"""
def main():
    # for unt
    # catoid = 22
    # navoid = 2372
    # school = "unt"
    catoid = 40
    navoid = 3146
    school = "smu"
    smu_cat_url = "https://catalog."+school+".edu/content.php?catoid="+str(catoid)+"&navoid="+str(navoid)

    coid_begin = 144004         # hopefuly this stays the same forever
    coid_end = get_last_coid(smu_cat_url)
    # we got the course ids, now we leave the rest of the work to web_parse()
    courses = web_parse("https://catalog.smu.edu/preview_course_nopop.php", catoid, coid_begin, coid_end)
    # I guess we just print them out for now
    print(courses);

if __name__ == '__main__':
    main()


import os

# External imports:
from dotenv import dotenv_values
import requests

# Dev: Test with the development server.
BASE = 'http://127.0.0.1:8000/api'

# Production: Uncomment to test with the production server once published.
# BASE = 'https://cannlytics.com/api'

# Load your API key to pass in the authorization header as a bearer token.
config = dotenv_values('../../.env')
API_KEY = config['CANNLYTICS_API_KEY']

# === Tests ===
if __name__ == '__main__':

    # Authentication a session.
    session = requests.Session()
    session.headers.update({'Authorization': f'Bearer {API_KEY}'})

    # [✓] Get information about Cannlytics AI.
    response = session.get(f'{BASE}/ai')
    assert response.status_code == 200
    print('AP live.')

    # [✓] Create a recipe.
    print('Creating a recipe...')
    data = {
      'image_type': '',
      'ingredients': ['coffee', 'milk', 'butter'],
      'product_name': 'Infused cannabis coffee',
      'doses': None,
      'special_instructions': None,
      'creativity': 0.420,
      'total_thc': 800,
      'total_cbd': 0,
      'public': True,
    }
    response = session.post(f'{BASE}/ai/recipes', json=data)
    assert response.status_code == 200
    print('Created a recipe.')

    # [✓] Generate a color from text.
    data = {'text': 'Moonshine Haze'}
    response = session.post(f'{BASE}/ai/color', json=data)
    assert response.status_code == 200
    print('Generated color from text.')

    # [✓] Generate an emoji from text.
    data = {'text': 'Moonshine Haze'}
    response = session.post(f'{BASE}/ai/emoji', json=data)
    assert response.status_code == 200
    print('Generated emoji from text.')

    # [✓] Get a user's recipes.
    response = session.get(f'{BASE}/ai/recipes')
    assert response.status_code == 200
    print('Found user recipes.')

    # [✓] Get a recipe using its ID.
    uid = response.json()['data'][0]['id']
    response = session.get(f'{BASE}/ai/recipes/{uid}')
    assert response.status_code == 200
    print('Found user recipe by ID.')

    # [ ] Get public recipes.
    params = {'public': True}
    response = session.get(f'{BASE}/ai/recipes', params=params)
    assert response.status_code == 200
    print('Found public recipes.')

    # [ ] Search public / user recipes:
    # - limit
    # - order_by
    # - desc
    # - filters:
    # available_filters = [
    #     {'key': 'product_name', 'type': 'str'},
    #     {'key': 'product_subtype', 'type': 'str'},
    #     {'key': 'title', 'type': 'str'},
    #     {'key': 'total_thc', 'type': 'float'},
    #     {'key': 'total_cbd', 'type': 'float'},
    #     {'key': 'serving_cbd', 'type': 'float'},
    #     {'key': 'number_of_servings', 'type': 'number_of_servings'},
    #     {'key': 'created_at_min', 'type': 'datetime'},
    #     {'key': 'created_at_max', 'type': 'datetime'},
    #     {'key': 'updated_at_min', 'type': 'datetime'},
    #     {'key': 'updated_at_max', 'type': 'datetime'},
    # ]

    # [ ] Update a recipe.
    data = {
      'ingredients': [],
      'title': '',
      'doses': None,
      'instructions': '',
      'special_instructions': None,
      'creativity': 0.420,
      'change_recipe': True,
      'change_image': True,
      'change_title': True,
      'public': True,
    }

    # [ ] Update a recipe's image.

    # [ ] Delete a recipe.

    # [ ] Give feedback on a recipe.
    data = {
        'feedback': 'Simply delightful.',
        'like': True,
        'uid': '<recipe_id>',
    }
    params = {'action': 'feedback'}
    url = f'{BASE}/ai/recipes'
    response = session.post(url, json=data, params=params)
    assert response.status_code == 200
    print('Created a recipe.')

    # [ ] Review a public recipe.
    data = {
        'review': "A baker's dozen!",
        'rating': 0.420,
    }
    params = {'action': 'review'}


import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from main import Ui_Narrator
from ans1 import Ui_Stanley
from ans2 import Ui_People
from ans3 import Ui_Robot
from last import Ui_Dialog

app = QtWidgets.QApplication(sys.argv)

Narrator = QtWidgets.QMainWindow()
ui = Ui_Narrator()
ui.setupUi(Narrator)
Narrator.show()

def openStanley():
	global Stanley
	Stanley = QtWidgets.QDialog()
	ui = Ui_Stanley()
	ui.setupUi(Stanley)
	Narrator.close()
	Stanley.show()

	def openDialog():
		global Dialog
		Dialog = QtWidgets.QDialog()
		ui = Ui_Dialog()
		ui.setupUi(Dialog)
		Stanley.close()
		Dialog.show()

	ui.pushButton.clicked.connect(openDialog)

ui.pushButton.clicked.connect(openStanley)

def openPeople():
	global People
	People = QtWidgets.QDialog()
	ui = Ui_People()
	ui.setupUi(People)
	Narrator.close()
	People.show()

	def returnTomain():
		People.close()
		Narrator.show()

	ui.pushButton.clicked.connect(returnTomain)

ui.pushButton_2.clicked.connect(openPeople)

def openRobot():
	global Robot
	Robot = QtWidgets.QDialog()
	ui = Ui_Robot()
	ui.setupUi(Robot)
	Narrator.close()
	Robot.show()

	def returnTomain():
		Robot.close()
		Narrator.show()

	ui.pushButton_4.clicked.connect(returnTomain)

ui.pushButton_3.clicked.connect(openRobot)

sys.exit(app.exec_())


from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _

from viewshare.apps.vendor.friends.models import *

from viewshare.apps.vendor.notification import models as notification

class UserForm(forms.Form):

    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(UserForm, self).__init__(*args, **kwargs)

class InviteFriendForm(UserForm):

    to_user = forms.CharField(widget=forms.HiddenInput)
    message = forms.CharField(label="Message", required=False, widget=forms.Textarea(attrs = {'cols': '20', 'rows': '5'}))

    def clean_to_user(self):
        to_username = self.cleaned_data["to_user"]
        try:
            User.objects.get(username=to_username)
        except User.DoesNotExist:
            raise forms.ValidationError(_(u"Unknown user."))

        return self.cleaned_data["to_user"]

    def clean(self):
        to_user = User.objects.get(username=self.cleaned_data["to_user"])
        previous_invitations_to = FriendshipInvitation.objects.invitations(to_user=to_user, from_user=self.user)
        if previous_invitations_to.count() > 0:
            raise forms.ValidationError(_(u"Already requested friendship with %s") % to_user.username)
        # check inverse
        previous_invitations_from = FriendshipInvitation.objects.invitations(to_user=self.user, from_user=to_user)
        if previous_invitations_from.count() > 0:
            raise forms.ValidationError(_(u"%s has already requested friendship with you") % to_user.username)
        return self.cleaned_data

    def save(self):
        to_user = User.objects.get(username=self.cleaned_data["to_user"])
        message = self.cleaned_data["message"]
        invitation = FriendshipInvitation(from_user=self.user, to_user=to_user, message=message, status="2")
        invitation.save()
        if notification:
            notification.send([to_user], "friends_invite", {"invitation": invitation})
            notification.send([self.user], "friends_invite_sent", {"invitation": invitation})
        return invitation


import sys, os
import logging
import json
from typing import List
import inspect
import flask
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import cross_origin
from pathlib import Path
from server import models as m
from server.api import helper as h

logging.basicConfig(level=logging.DEBUG, filename='api.log', encoding='utf-8')

app = flask.Flask(__name__)

outputPath = str(Path(__file__).parent)

AllModels = m.AllModels.items()

def Setup(port: int):
    logging.info('starting application on port: ' + str(port))
    success = False
    attempts = 0
    while success == False and attempts < 5:
        try:
            app.run(port=port)
            success = True
        except OSError as ose:
            logging.error(ose)
            logging.error('Failed to launch api. Retry attempt ' + str(attempts+1))
            __shutdown_server__()
        except:
            raise RuntimeError('Failed to launch api')
        finally:
            attempts += 1

@app.errorhandler(404)
def page_not_found(e):
    return "
404

The resource could not be found.
", 404

@app.errorhandler(500)
def invalid_request(e):
    return e, 500

@app.route('/api/models', methods=['GET'])
@cross_origin()
def getAllModels():
    logging.info('retrieving all models')

    j = list({
        'id': key,
        'value': item.ModelSchema.Description,
        'parameters': item.ModelSchema.ToJson()
        }
        for key, item in AllModels)

    logging.info('models found: ' + str(j))

    return jsonify(j)

@app.route('/api/models/<path:modelName>', methods=['GET'])
@cross_origin()
def getModelDefinition(modelName):
    return __runModel__(modelName, request.query_string.decode(), False)

@app.route('/api/models3d/<path:modelName>', methods=['GET'])
@cross_origin()
def getModelDefinition3d(modelName):
    return __runModel__(modelName, request.query_string.decode(), True)

@app.route('/ping', methods=['GET'])
def ping():
    return 'Server is running...'

@app.route('/shutdown', methods=['GET'])
def shutdown():
    __shutdown_server__()
    return 'Server shutting down...'

def __runModel__(modelName: str, queryString: str, is3d: bool):
    try:
        parameters = h.ParseQueryString(queryString)

        model = dict(AllModels)[modelName]()

        if model is None:
            raise ModuleNotFoundError(name=modelName)

        graphJson = model.Run(is3d, 'Api', parameters)

        return json.dumps(graphJson)
    except Exception as e:
        return 'failed to run: ' + modelName + '\r\n\t [Trace]: \r\n\t' + str(e), 500

def __shutdown_server__():
    logging.info('attempting to shutdown server')
    try:
        func = request.environ.get('werkzeug.server.shutdown')
        if func is not None:
            func()

    except RuntimeError as e:
        logging.error(e)

if __name__ == '__main__':
    Setup(1400)


from array import array

from bs4 import BeautifulSoup
import urllib.request

if __name__ == '__main__':
    url = 'https://www.thegioididong.com/dtdd/samsung-galaxy-a51/danh-gia?s=1&p=1'
    page = urllib.request.urlopen(url)
    soup = BeautifulSoup(page, 'html.parser')
    file1= open(r"D:\GITHUB\Khoa_Luan\Classification\Draw_data\TieuCuc_00.txt","a",encoding='utf-8')
    arr_comments=[]
    comments=[]

    new_feeds = soup.find_all(
        'li', class_='par')

    for feed in new_feeds:
        if(feed.find('div', class_='rh').find('label')):
            comment = feed.find('div', class_='rc').find_all('i')[5].get_text().replace('?','. ')
            comments.append(comment)
    for string in comments:
        comment=string.split('.')
        if arr_comments==[]:
            for i in comment:
                arr_comments.append(i)
        else:
            flag=0
            for i in arr_comments:
                for j in comment:
                    if i==j:
                        flag=1
                        break
            if flag==0:
                for j in comment:
                    arr_comments.append(j)

    count=0
    for i in arr_comments:
        print(i)
        file1.write(i.strip()+'\n')
        count+=1
    file1.close()
    print(str(count)+' câu')


import numpy as np
import pandas as pd

# Pandas is a python library...
# Pandas made data framing......

mydata = {
    'car':["volvo","vr","audy"],
    'price':[222,444,555]
}

myvar = pd.DataFrame(mydata)
print(myvar)

# A Pandas Series is like a column in a table.
data = [1,3,5,6]
mydata = pd.Series(data,index=["a","b","c","d"])
print(mydata)

data1 = {
    "name":["Abir","Asik","Onik"],
    "age":[32,22,55],
    "address":["Dhaka","Rajshai","Sylhet"]
}

mydata1 = pd.DataFrame(data1,index=["name","age","address"])
print(mydata1.loc["age"])

# A Pandas DataFrame is a 2 dimensional data structure like a 2 dimensional array, or a table with rows and columns.
df = pd.read_csv('data.csv')
print(df.to_string())
print(df.head(10))

# df = pd.read_json('data.json')
# print(df.to_string())

json_data = {
  "Duration":{
    "0":60,
    "1":60,
    "2":60,
    "3":45,
    "4":45,
    "5":60
  },
  "Pulse":{
    "0":110,
    "1":117,
    "2":103,
    "3":109,
    "4":117,
    "5":102
  },
  "Maxpulse":{
    "0":130,
    "1":145,
    "2":135,
    "3":175,
    "4":148,
    "5":127
  },}

myjason=pd.DataFrame(json_data)
print(myjason)