from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
from past.builtins import *
standard_library.install_aliases()
from builtins import *
import json
import re

from ojai.Document import Document

from ojai.types.ODate import ODate
from ojai.types.OInterval import OInterval
from ojai.types.OTime import OTime
from ojai.types.OTimestamp import OTimestamp

from mapr.ojai.ojai import document_utils
from mapr.ojai.ojai_utils.ojai_dict import OJAIDict
from mapr.ojai.ojai_utils.ojai_list import OJAIList
from mapr.ojai.ojai.document_utils import merge_two_dicts, parse_field_path, replacer

class OJAIDocument(Document):
    __json_stream_document_reader = None
    __regex = re.compile(r"""(["']).*?\1|(?P<dot>\.)""")
    __list_regex = re.compile(r"\[(\w+)\]")

    def __init__(self, json_value=None):
        self.__internal_dict = {}
        self.json_value = json_value

    def set_id(self, _id):
        """Set _id field into the Document. _id field required for each document in MapR-DB
        :param _id: type should be binary or str"""
        if not isinstance(_id, (basestring, bytearray)):
            raise TypeError
        self.set(field_path="_id", value=_id)
        return self

    def get_id(self):
        return self.__internal_dict['_id']

    def size(self):
        return len(self.__internal_dict)

    def empty(self):
        return self.size() == 0

    def clear(self):
        self.__internal_dict = {}

    def set(self, field_path, value):
        if field_path == '_id' and isinstance(value, (basestring, bytearray)):
            self.__internal_dict[field_path] = value
        elif self.__list_regex.search(field_path):
            self.__set_list_element(field_path=field_path, value=value)
        elif isinstance(value, OJAIDocument):
            self.__set_document(field_path=field_path, value=value)
        elif value is None:
            self.__set_none(field_path=field_path)
        else:
            self.__set_dispatcher(field_path=field_path, value=value)

        return self

    def __get_index_and_stored_value(self, field_path):
        index = int(self.__list_regex.search(field_path).group(1))
        stored_value = self.get(re.sub(self.__list_regex, '', field_path))
        return index, stored_value

    def __set_list_element(self, field_path, value):
        index, stored_value = self.__get_index_and_stored_value(field_path=field_path)

        if isinstance(stored_value, list):
            if len(stored_value) < index:
                while len(stored_value) < index:
                    stored_value.append(None)
                stored_value.append(value)
            else:
                stored_value[index] = value

    def parse_dict(self, dictionary):
        if not isinstance(dictionary, dict):
            raise TypeError("parse_dict allows only dict as input param.")
        self.__internal_dict = dictionary
        return self

    def as_dictionary(self):
        return self.__internal_dict

    def __set_str(self, field_path, value):
        self.__internal_dict = merge_two_dicts(self.__internal_dict,
                                               parse_field_path(field_path=field_path,
                                                                value=value))

    def __set_boolean(self, field_path, value):
        self.__internal_dict = merge_two_dicts(self.__internal_dict,
                                               parse_field_path(field_path=field_path,
                                                                value=value))

    def __set_long(self, field_path, value):
        self.__internal_dict = merge_two_dicts(self.__internal_dict,
                                               parse_field_path(field_path=field_path,
                                                                value=value,
                                                                ))

    def __set_float(self, field_path, value):
        self.__internal_dict = merge_two_dicts(self.__internal_dict,
                                               parse_field_path(field_path=field_path,
                                                                value=value,
                                                                ))

    def __set_time(self, field_path, value):
        self.__internal_dict = merge_two_dicts(self.__internal_dict,
                                               parse_field_path(field_path=field_path,
                                                                value=value,
                                                                ))

    def __set_date(self, field_path, value):
        self.__internal_dict = merge_two_dicts(self.__internal_dict,
                                               parse_field_path(field_path=field_path,
                                                                value=value,
                                                                ))

    def __set_timestamp(self, field_path, value):
        self.__internal_dict = merge_two_dicts(self.__internal_dict,
                                               parse_field_path(field_path=field_path,
                                                                value=value,
                                                                ))

    def __set_interval(self, field_path, value):
        self.__internal_dict = merge_two_dicts(self.__internal_dict,
                                               parse_field_path(field_path=field_path,
                                                                value=value,
                                                                ))

    def __set_byte_array(self, field_path, value):
        self.__internal_dict = merge_two_dicts(self.__internal_dict,
                                               parse_field_path(field_path=field_path,
                                                                value=value,
                                                                ))

    def __set_dict(self, field_path, value):
        value = OJAIDict.parse_dict(value)
        if self.get(field_path) is not None:
            self.delete(field_path)
        self.__internal_dict = merge_two_dicts(self.__internal_dict,
                                               parse_field_path(field_path=field_path,
                                                                value=value))

    def __set_document(self, field_path, value):
        self.__internal_dict = merge_two_dicts(self.__internal_dict,
                                               parse_field_path(field_path=field_path,
                                                                value=value.as_dictionary()))

    def __set_array(self, field_path, value):
        list_value = OJAIList.set_list(value=value)
        if self.get(field_path) is not None:
            self.delete(field_path)
        self.__internal_dict = merge_two_dicts(self.__internal_dict,
                                               parse_field_path(field_path=field_path,
                                                                value=list_value))

    def __set_none(self, field_path):
        self.__internal_dict = merge_two_dicts(self.__internal_dict,
                                               parse_field_path(field_path=field_path,
                                                                value=None))

    __dispatcher = (
        (basestring, __set_str),
        (bool, __set_boolean),
        (int, __set_long),
        (float, __set_float),
        (OTime, __set_time),
        (OTimestamp, __set_timestamp),
        (ODate, __set_date),
        (OInterval, __set_interval),
        (list, __set_array),
        (dict, __set_dict),
        (bytearray, __set_byte_array),
        (None, __set_none),
    )

    def __set_dispatcher(self, field_path, value):
        for (t, m) in OJAIDocument.__dispatcher:
            if isinstance(value, t):
                return m(self, field_path, value)

    def delete(self, field_path):
        if self.__list_regex.search(field_path):
            index, stored_value = \
                self.__get_index_and_stored_value(field_path=field_path)
            del stored_value[index]
        else:
            split_path = [part.strip("'").strip('"')
                          for part in self.__regex.sub(replacer,
                                                       field_path)
                              .split("pass") if part]
            try:
                e = self.__internal_dict
                for k in split_path[:-1]:
                    e = e[k]
                del e[split_path[-1]]
            except KeyError:
                pass
        return self

    def get(self, field_path):
        value = None
        index = None
        if self.__list_regex.search(field_path):
            index = int(self.__list_regex.search(field_path).group(1))
            field_path = re.sub(self.__list_regex, '', field_path)

        split_path = [part.strip("'").strip('"') for part in self.__regex.sub(replacer,
                                                                              field_path).split("pass") if part]
        try:
            tmp_dict = self.__internal_dict
            for k in split_path[:-1]:
                tmp_dict = tmp_dict[k]
            value = tmp_dict[split_path[-1]]
        except KeyError:
            pass
        if index is not None and value is not None and isinstance(value, list):
            try:
                value = value[index]
            except IndexError:
                value = None
        return value

    def get_str(self, field_path):
        value = self.get(field_path=field_path)
        if isinstance(value, basestring):
            return value
        else:
            return None

    def get_boolean(self, field_path):
        value = self.get(field_path=field_path)
        if isinstance(value, bool):
            return value
        else:
            return None

    def get_int(self, field_path):
        value = self.get(field_path=field_path)
        if isinstance(value, int) and not isinstance(value, bool):
            return value
        else:
            return None

    def get_long(self, field_path):
        return self.get_int(field_path=field_path)

    def get_float(self, field_path):
        value = self.get(field_path=field_path)
        if isinstance(value, float):
            return value
        else:
            return None

    def get_time(self, field_path):
        value = self.get(field_path=field_path)
        if isinstance(value, OTime):
            return value
        else:
            return None

    def get_date(self, field_path):
        value = self.get(field_path=field_path)
        if isinstance(value, ODate):
            return value
        else:
            return None

    def get_timestamp(self, field_path):
        value = self.get(field_path=field_path)
        if isinstance(value, OTimestamp):
            return value
        else:
            return None

    def get_binary(self, field_path):
        value = self.get(field_path=field_path)
        if isinstance(value, bytearray):
            return value
        else:
            return None

    def get_interval(self, field_path):
        value = self.get(field_path=field_path)
        if isinstance(value, OInterval):
            return value
        else:
            return None

    def get_dictionary(self, field_path):
        value = self.get(field_path=field_path)
        if isinstance(value, dict):
            return value
        else:
            return None

    def get_list(self, field_path):
        value = self.get(field_path=field_path)
        result = []
        if isinstance(value, list):
            for element in value:
                if isinstance(element, dict):
                    result.append(list(element.values())[0])
                else:
                    result.append(element)
            return result
        else:
            return None

    def from_dict(self, document_dict):
        self.__internal_dict = document_dict
        return self

    def as_json_str(self, with_tags=True):
        if with_tags:
            from mapr.ojai.ojai.OJAITagsBuilder import OJAITagsBuilder
            return json.dumps(OJAITagsBuilder().set('tmp', self.__internal_dict).as_dictionary()['tmp'],
                              default=document_utils.type_serializer)
        else:
            return json.dumps(self.__internal_dict, default=document_utils.type_serializer)


#!/usr/bin/python
import os,sys
DGCNN_DIR = os.path.dirname(os.path.abspath(__file__))
DGCNN_DIR = os.path.dirname(DGCNN_DIR)
sys.path.insert(0,DGCNN_DIR)
from dgcnn import DGCNN_FLAGS

def main():
  flags = DGCNN_FLAGS()
  flags.parse_args()

if __name__ == '__main__':
  main()


#@sureshkrishna
import pygame
import sys
import time
import random

pygame.init()
pygame.mixer.init(frequency= 44100,size=-16,channels=2,buffer=512)
clock=pygame.time.Clock()

#------------------GameVariables-----------------------------
ScreenX=500
ScreenY=500
x,y=100,200
width,height=20,20
speed=5
DirX=0
DirY=0
FoodX,FoodY=0,0
SnakeLength=1
SnakeList=[]
FScore=0
GameOverSrc=pygame.image.load('assests/gameover.png')
GOrect=GameOverSrc.get_rect(center=(ScreenX/2,ScreenY/2-50))
GAMEOVER=False
#------ColorVariables-------
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
WHITE=(255,255,255)
BLACK=(0,0,0)
#------------------------------------------------------------
#-----------------Game Functions-----------------------------
def Food():
    FoodX=random.randint(0,ScreenX)
    FoodY=random.randint(0,ScreenY)
    return FoodX,FoodY

#-----------------------------------------
flap=pygame.mixer.Sound('assests/sfx_wing.wav')
hit=pygame.mixer.Sound('assests/sfx_hit.wav')
points=pygame.mixer.Sound('assests/sfx_point.wav')
die=pygame.mixer.Sound('assests/sfx_die.wav')
pygame.mixer.music.load('assests/pubg.mp3')
pygame.mixer.music.play(-1)

Screen=pygame.display.set_mode((ScreenX,ScreenX))
pygame.display.set_caption('SnakeGame')
font=pygame.font.SysFont(None,20)
Screen.fill(WHITE)

FoodX,FoodY=Food()

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_UP and GAMEOVER==False:
                flap.play()
                DirY=0
                DirY-=speed
                DirX=0
            if event.key==pygame.K_DOWN and GAMEOVER==False:
                flap.play()
                DirY=0
                DirY+=speed
                DirX=0
            if event.key==pygame.K_RIGHT and GAMEOVER==False:
                flap.play()
                DirX=0
                DirX+=speed
                DirY=0
            if event.key==pygame.K_LEFT and GAMEOVER==False:
                flap.play()
                DirX=0
                DirX-=speed
                DirY=0
            if event.key==pygame.K_SPACE and GAMEOVER==True:
                GAMEOVER=False
    x+=DirX
    y+=DirY
    if x>ScreenX:
        x=0
    elif x<0:
        x=ScreenX
    elif y>ScreenY:
        y=0
    elif y<0:
        y=ScreenY
    #-----------------

    Screen.fill(WHITE)
    if GAMEOVER==False:
        for x1,y1 in SnakeList:
           SnakeBox=pygame.draw.rect(Screen,(255,0,0),(x1,y1,width,height))
           FoodBox=pygame.draw.circle(Screen,GREEN,(FoodX,FoodY),8)

           if SnakeBox.colliderect(FoodBox):
                points.play()
                FoodX,FoodY=Food()
                SnakeLength+=10
        SnakeList.append([x,y])
        if len(SnakeList)>SnakeLength:
           SnakeList.pop(0)
        if SnakeList[-1] in SnakeList[:-1]:
            GAMEOVER=True
            die.play()
            FScore=SnakeLength
            SnakeList.clear()
            SnakeLength=1
        Score=font.render(f"Score-{SnakeLength-1}",True,BLACK)
        Screen.blit(Score,(20,10))
    else:
        FinalScore=font.render(f'Score : {FScore-1}',True,BLACK)
        FSrect=FinalScore.get_rect(center=(ScreenX/2,250))
        ResumeText=font.render('Press Space to Start...',True,BLACK)
        RTrect=ResumeText.get_rect(center=(ScreenX/2,400))
        DevBy=font.render('Devloped By Sureshkrishna',True,RED)
        DevByrect=DevBy.get_rect(center=(ScreenX/2,480))

        Screen.blit(GameOverSrc,GOrect)
        Screen.blit(FinalScore,FSrect)
        Screen.blit(ResumeText,RTrect)
        Screen.blit(DevBy,DevByrect)

    clock.tick(120)
    pygame.display.update()

#@sureshkrishna


from typing import Callable, Tuple
import sys
import numpy as np
import matplotlib.pyplot as plt

def ukf(
    f: Callable[[np.ndarray], np.ndarray],
    h: Callable[[np.ndarray], np.ndarray],
    B: np.ndarray,
    Q: np.ndarray,
    R: np.ndarray,
    y: np.ndarray,
    xhat: np.ndarray,
    P: np.ndarray,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    # reshape to col vector
    xhat = xhat.reshape(-1, 1)
    y = y.reshape(-1, 1)
    # a preori
    xhatm, Pm, _ = u_transform(f, xhat, P)
    Pm = Pm + B.dot(Q.dot(B.T))
    yhatm, Pyy, Pxy = u_transform(h, xhatm, Pm)
    # kalman gain
    G = Pxy / (Pyy + R)
    # a preori
    xhat_new = xhatm + G * (y - yhatm)
    P_new = Pm - G * Pxy.T

    return xhat_new, P_new, G

def u_transform(
    f: Callable[[np.ndarray], np.ndarray],
    xm: np.ndarray,
    Pxx: np.ndarray,
) -> Tuple[np.ndarray, np.ndarray]:
    xm = xm.reshape(-1, 1)
    n_dim = xm.shape[0]
    kappa = 3 - n_dim
    w0 = kappa / (n_dim + kappa)
    wi = 1 / (2 * (n_dim + kappa))
    w_diag = np.array([w0] + [wi] * (2*n_dim))
    W = np.diag(w_diag)

    L = np.linalg.cholesky(Pxx)
    X = np.concatenate((
        xm,
        np.ones((n_dim, 1)).dot(xm.T) + np.sqrt(n_dim + kappa) * L,
        np.ones((n_dim, 1)).dot(xm.T) - np.sqrt(n_dim + kappa) * L,
    ))
    Y = np.apply_along_axis(f, 0, X)
    ym = np.sum(W.dot(Y)).T
    Pyy = (Y - ym).T.dot(W.dot((Y - ym)))
    Pxy = (X - xm).T.dot(W.dot((Y - ym)))

    return ym , Pyy, Pxy

def experiment(
    dim: int,
    f: Callable[[np.ndarray], np.ndarray],
    h: Callable[[np.ndarray], np.ndarray],
    B: np.ndarray,
    Q: np.ndarray,
    R: np.ndarray,
    # y: np.ndarray,
    xhat_0: np.ndarray,
    P_0: np.ndarray,
    N: int,
    figname: str,
) -> np.ndarray:
    v = np.random.randn(N, 1) * np.sqrt(Q)
    w = np.random.randn(N, 1) * np.sqrt(R)
    x = np.zeros((N, dim))
    y = np.zeros((N, 1))
    x[0] = xhat_0
    y[0] = h(x[0])
    for k in range(1, N):
        x[k] = f(x[k-1]) + B.dot(v[k-1])
        y[k] = h(x[k]) + w[k]

    xhat = np.zeros((N, dim))
    P = P_0
    xhat[0] = xhat_0.reshape(-1)
    for k in range(1, N):
        xhat_new, P, G = ukf(
            f, h, B, Q, R, y[k], xhat[k-1], P,
        )
        xhat[k] = xhat_new.reshape(-1)

    fig, axes = plt.subplots(dim, 1)
    if dim == 1:
        axes.plot(np.arange(0, N), y[:, 0], c="orange", linestyle="-", label="observation")
        axes.plot(np.arange(0, N), x[:, 0], c="gray", linestyle="--", label="ground truth")
        axes.plot(np.arange(0, N), xhat[:, 0], c="purple", linestyle="-.", label="state estimation")
        axes.legend()
    else:
        for i in range(dim):
            axes[i].plot(np.arange(0, N), y[:, 0], c="orange", linestyle="-", label="observation")
            axes[i].plot(np.arange(0, N), x[:, i], c="gray", linestyle="--", label="ground truth")
            axes[i].plot(np.arange(0, N), xhat[:, i], c="purple", linestyle="-.", label="state estimation")
            axes[i].legend()

    plt.savefig(figname)
    plt.show()

def main():
    figname = sys.argv[1]
    # parametrers
    f = lambda x: 0.2*x + 25*x/(1+x**2) + 10*np.cos(x/10) + 0.01 * np.exp(-x)
    h = lambda x: 1/20*(x**2)
    b = np.array([[1.0]])
    N = 50
    Q = np.array([[1.0]])
    R = np.array([[3.0]])
    xhat_0 = np.array([[0.0]])
    gamma = 10.0
    P_0 = gamma * np.identity(1)
    experiment(
        1, f, h, b, Q, R, xhat_0, P_0, N, figname
    )

if __name__ == "__main__":
    main()


lines = open("input.txt").read().splitlines()

x, y = 0, 0
wx, wy = 1, 10
for line in lines:
    action = line[0]
    value = int(line[1:])
    if action=="N":
        wx += value
    if action=="S":
        wx -= value
    if action=="E":
        wy += value
    if action=="W":
        wy -= value
    while value and action=="L":
        if (wx >= 0 <= wy): # northeast -> northwest
            wx, wy = abs(wy), -1 * abs(wx)
        elif (wx >= 0 >= wy): # northwest -> southwest
            wx, wy = -1 * abs(wy), -1 * abs(wx)
        elif (wx <= 0 >= wy): # southwest -> southeast
            wx, wy = -1 * abs(wy), abs(wx)
        elif (wx <= 0 <= wy): # southeast -> northeast
            wx, wy = abs(wy), abs(wx)
        value -= 90
    while value and action=="R":
        if (wx >= 0 <= wy): # northeast -> southeast
            wx, wy = -1 * abs(wy), abs(wx)
        elif (wx <= 0 <= wy): # southeast -> southwest
            wx, wy = -1 * abs(wy), -1 * abs(wx)
        elif (wx <= 0 >= wy): # southwest -> northwest
            wx, wy = abs(wy), -1 * abs(wx)
        elif (wx >= 0 >= wy): # northwest -> northeast
            wx, wy = abs(wy), abs(wx)
        value -= 90
    if action=="F":
        x += value * wx
        y += value * wy

print('    ', f"x:{x} y:{y} wx:{wx} wy:{wy}, {abs(x)+abs(y)}")


"""empty message

Revision ID: 12c1db213a78
Revises: 13027de93606
Create Date: 2017-05-18 00:46:39.026539

"""

# revision identifiers, used by Alembic.
revision = '12c1db213a78'
down_revision = '13027de93606'

from alembic import op
import sqlalchemy as sa

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('activ',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('created_at', sa.DateTime(), nullable=False),
    sa.Column('value', sa.Integer(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('activ')
    # ### end Alembic commands ###


# 2021/07/13 23:43
# https://www.acmicpc.net/source/30985626

n, k = map(int, input().split())
coin = []
cnt = 0

for _ in range(n) :
    coin.append(int(input()))
coin.sort(reverse = True)

for i in coin :
    if k < i : continue
    tgt = (k//i)*i
    cnt += k//i
    k -= tgt

print(cnt)


import argparse
import cv2
from image_masking import *

def inpaint(imagePath, maskPath, method="telea", radius=3):
    flags=cv2.INPAINT_TELEA
    if method=="ns":
        flags=cv2.INPAINT_NS
    image=cv2.imread(imagePath)
    mask=cv2.imread(maskPath)
    if mask is None or mask.shape != image.shape:
        print("The given mask is not applicable. Please create a new mask.")
        maskImage().process(imagePath, maskPath)
        mask=cv2.imread(maskPath)
    mask=cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
    output=cv2.inpaint(image, mask, radius, flags=flags)
    return output

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('inputPath', help='Input original image')
    parser.add_argument('maskPath', help='Mask image')
    parser.add_argument('outputPath', help='Restored image')
    parser.add_argument('method', choices=["telea", "ns"], default="telea", help="Inpainting algorithm to use")
    args = parser.parse_args()
    output = inpaint(args.inputPath, args.maskPath, args.method)
    cv2.imwrite(args.outputPath, output)


from cart import forms
from django import forms

class QtyForm(forms.Form):

    product_id = forms.CharField(widget=forms.HiddenInput())

    qty = forms.IntegerField(
        min_value = 0,
        max_value = 99,
        widget = forms.TextInput(attrs={'class': 'form-control qty',
                                        'type': 'hidden',
                                      'style': 'text-align: center; color: #705737; background-color: #f3eae0; width: 40px',
                                      'readonly': 'readonly'}),
        required = True
    )


from __future__ import print_function

import os
import sys
import signal
import re
import time

from os.path import dirname
from fnmatch import fnmatch
from shutil import rmtree
from argparse import ArgumentTypeError
from subprocess import Popen, PIPE

class DependencyError(Exception):
    """raised when dependency not found"""
class KilledError(Exception):
    """raised when process killed"""
class NotFromCDError(Exception):
    """raised when encountering track that has number of samples
    not divisible by 588"""
class AccurateripError(Exception):
    """raised when there's a problem parsing accuraterip data"""
class SubprocessError(Exception):
    """raised when a subprocess has a nonzero return code"""
class NetworkError(Exception):
    """raised when problem connecting to accuraterip database"""

STATUSES = ['[+----]',
            '[-+---]',
            '[--+--]',
            '[---+-]',
            '[----+]',
            '[---+-]',
            '[--+--]',
            '[-+---]',
            ]
STATUS_INDEX = 0

def which(name, flags=os.X_OK, additional_paths=[]):
    """Search PATH for executable files with the given name.

    On newer versions of MS-Windows, the PATHEXT environment variable will be
    set to the list of file extensions for files considered executable. This
    will normally include things like ".EXE". This fuction will also find files
    with the given name ending with any of these extensions.

    On MS-Windows the only flag that has any meaning is os.F_OK. Any other
    flags will be ignored.

    @type name: C{str}
    @param name: The name for which to search.

    @type flags: C{int}
    @param flags: Arguments to L{os.access}.

    @rtype: C{list}
    @param: A list of the full paths to files found, in the
    order in which they were found.
    """
    result = []
    exts = filter(None, os.environ.get('PATHEXT', '').split(os.pathsep))
    path = os.environ.get('PATH', None)

    if path is None:
        return []
    paths = os.environ.get('PATH', '').split(os.pathsep) + additional_paths
    for p in paths:
        p = os.path.join(p, name)
        if os.access(p, flags):
            result.append(p)
        for e in exts:
            pext = p + e
            if os.access(pext, flags):
                result.append(pext)
    return result

def isfile(value):
    if not os.path.isfile(value):
        raise ArgumentTypeError('%s is not a file' % value)

    return value

def check_dependencies(BIN, REQUIRED):
    for dep in BIN:
        value = which(dep, additional_paths=[dirname(sys.argv[0])])
        altdep = BIN[dep]
        altvalue = which(altdep, additional_paths=[dirname(sys.argv[0])]) \
            if altdep else None
        if not value and not altvalue:
            if dep in REQUIRED:
                raise DependencyError("%s required\n" % dep)
        else:
            BIN[dep] = altvalue[0] if altvalue else value[0]

def add_common_arguments(parser, version):
    parser.add_argument("-v", "--verbose",
                        help="enable verbose output",
                        action='store_true',
                        default=False,
                        )
    parser.add_argument('--version', action='version', version='%%(prog)s %s' %
                        version)
    parser.add_argument("-w", "--wait",
                        action='store_true',
                        default=False,
                        help=("wait for [ENTER] key press before exiting"),
                        )

def show_status(msg, *args):
    global STATUS_INDEX
    status = STATUSES[STATUS_INDEX%len(STATUSES)]
    msg = msg % args
    msg = '\r'+msg+' %s   ' % status
    sys.stderr.write(msg)
    sys.stderr.flush()
    time.sleep(0.25)
    STATUS_INDEX += 1

def finish_status(msg=''):
    sys.stderr.write('\n')

def get_num_samples(BIN, path):
    devnull = open(os.devnull, 'w')
    if fnmatch(path.lower(), '*.flac') and BIN['metaflac']:
        p = Popen([BIN['metaflac'], '--show-total-samples', path], stdout=PIPE)
        out, err = p.communicate()
        num_samples = int(out.strip())
    else:
        p = Popen([BIN['ffprobe'], '-show_streams', path], stdout=PIPE,
                  stderr=devnull)
        out, err = p.communicate()
        try:
            dur = float(re.search(b'duration=([0-9.]+)', out).group(1))
        except:
            dur = 0
        num_samples = int(round(dur*44100))

    devnull.close()

    return num_samples

def abort(*args):
    raise KilledError

def execute(main, process_arguments, processes, tempfiles=[], tempdirs=[]):
    options = None
    try:
        SIGS = [getattr(signal, s, None) for s in
                "SIGINT SIGTERM SIGHUP".split()]
        for sig in filter(None, SIGS):
            signal.signal(sig, abort)
        options = process_arguments()
        exitcode = main(options)
    except KilledError:
        exitcode = 1
    except (DependencyError, AccurateripError, SubprocessError,
            NotFromCDError, NetworkError) as e:
        print(e, file=sys.stderr)
        sys.stderr.write('%s\n' % e)
        exitcode = 2
    finally:
        for t in tempfiles:
            try: os.unlink(t)
            except OSError: pass
        for d in tempdirs:
            try: rmtree(d)
            except OSError: pass
        for p in processes:
            try: p.kill()
            except OSError: pass

    if options.wait:
        try:
            raw_input('Press [ENTER] to exit')
        except:
            pass

    sys.exit(exitcode)


#16
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

dp = [None]*(N+1)
dp[1] = 0
dp[2] = A[0]

for i in range(3, N+1):
    dp[i] = min(dp[i-1]+A[i-2], dp[i-2]+B[i-3])

print(dp[N])

#17
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

dp = [None]*(N+1)
dp[1] = 0
dp[2] = A[0]

for i in range(3, N+1):
    dp[i] = min(dp[i-1]+A[i-2], dp[i-2]+B[i-3])

Ans = []
P = N
while True:
    Ans.append(P)
    if P == 1:
        break

    if dp[P] == dp[P-1] + A[P-2]:
        P = P-1
    else:
        P = P-2
Ans.reverse()

print(len(Ans))
for i in range(len(Ans)):
    print(Ans[i], end=" ")
print("")

#18
N, S = map(int, input().split())
A = list(map(int, input().split()))

dp = [[None]*(S+1) for _ in range(N+1)]
dp[0][0] = True
for i in range (1, S+1):
    dp[0][i] = False

for i in range(1, N+1):
    for j in range(0, S+1):

        if j < A[i-1]:
            if dp[i-1][j] == True:
                dp[i][j] = True
            else:
                dp[i][j] = False

        else:
            if dp[i-1][j] == True or dp[i-1][j-A[i-1]] == True:
                dp[i][j] = True
            else:
                dp[i][j] = False

if dp[N][S] == True:
    print("Yes")
else:
    print("No")

#19
N, W = map(int, input().split())
w = [None]*(N+1)
v = [None]*(N+1)
for i in range(1, N+1):
    w[i], v[i] = map(int, input().split())

dp = [[0]*(W+1) for _ in range(N+1)]
dp[0][0] = 0
for i in range (1, N+1):
    for j in range (1, W+1):
        if j < w[i]:
            dp[i][j] = dp[i-1][j]
        else:
            dp[i][j] = max(dp[i-1][j], dp[i-1][j-w[i]]+v[i])

print(max(dp[N]))

#20
S = input()
T = input()
N = len(S)
M = len(T)

dp = [[None]*(M+1) for _ in range(N+1)]
dp[0][0] = 0
for i in range (N+1):
    for j in range (M+1):
        if i>=1 and j>=1 and S[i-1]==T[j-1]:
            dp[i][j] = max(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]+1)
        elif i>=1 and j>=1:
            dp[i][j] = max(dp[i][j-1], dp[i-1][j])
        elif j>=1:
            dp[i][j] = dp[i][j-1]
        elif i>=1:
            dp[i][j] = dp[i-1][j]

print(dp[N][M])

#21
N = int(input())
P = [None]*(N+1)
A = [None]*(N+1)
for i in range(1, N+1):
    P[i], A[i] = map(int, input().split())

dp = [[None]*(N+1) for _ in range (N+1)]
dp[1][N] = 0

for LEN in range(N-2, -1, -1):
    for l in range(1, N-LEN+1):
        r = l + LEN

        score_l = 0
        if l>=2 and l<=P[l-1] and P[l-1]<=r:
            score_l = A[l-1]

        score_r = 0
        if r<=N-1 and l<=P[r+1] and P[r+1]<=r:
            score_r = A[r+1]

        if l==1:
            dp[l][r] = dp[l][r+1] + score_r
        elif r==N:
            dp[l][r] = dp[l-1][r] + score_l
        else:
            dp[l][r] = max(dp[l-1][r] + score_l, dp[l][r+1] + score_r)

Ans = 0
for i in range(1, N+1):
    Ans = max(Ans, dp[i][i])
print(Ans)

#22
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

dp = [-10**10]*(N+1)
dp[1] = 0
for i in range(1, N):
    dp[A[i-1]] = max(dp[A[i-1]], dp[i]+100)
    dp[B[i-1]] = max(dp[B[i-1]], dp[i]+150)

print(dp[N])

#23
N, M = map(int, input().split())
A = [None]*(M)
for i in range(M):
    A[i] = list(map(int, input().split()))

dp = [[10**5]*(2**N) for _ in range(M+1)]
dp[0][0] = 0

for i in range(1, M+1):
    for j in range(0, 2**N):
        free = [None]*N
        for k in range(0, N):
            if (j//(2**k))%2 == 0:
                free[k] = 0
            else:
                free[k] = 1
        v = 0
        for k in range(0, N):
            if free[k]==1 or A[i-1][k]==1:
                v += 2**k

        dp[i][j] = min(dp[i][j], dp[i-1][j])
        dp[i][v] = min(dp[i][v], dp[i-1][j]+1)

if dp[M][2**N-1] == 10**5:
    print(-1)
else:
    print(dp[M][2**N-1])

#24
import bisect
N = int(input())
A = list(map(int, input().split()))

LEN = 0
L = []
dp = [0]*N

for i in range(N):
    pos = bisect.bisect_left(L, A[i])
    dp[i] = pos

    if dp[i] >= LEN:
        L.append(A[i])
        LEN += 1
    else:
        L[dp[i]] = A[i]
print(LEN)

#25
H, W = map(int, input().split())
c = [None]*H
for i in range(H):
    c[i] = input()

dp = [[0]*(W+1) for _ in range(H+1)]
for i in range(1, H+1):
    for j in range(1, W+1):
        if i==1 and j==1:
            dp[i][j] = 1
        else:
            if i>=2 and c[i-2][j-1]=='.':
                dp[i][j] += dp[i-1][j]
            if j>=2 and c[i-1][j-2]=='.':
                dp[i][j] += dp[i][j-1]

print(dp[H][W])

## 25'
H, W = map(int, input().split())
c = [None]*H
for i in range(H):
    c[i] = input()

dp = [[0]*(W) for _ in range(H)]
dp[0][0] = 1
for i in range(H):
    for j in range(W):
        if i>=1 and c[i-1][j]=='.':
            dp[i][j] += dp[i-1][j]
        if j>=1 and c[i][j-1]=='.':
            dp[i][j] += dp[i][j-1]

print(dp[H-1][W-1])


import math

def get_points(filename):
    with open(filename, 'r') as f:
        data = f.read().split()
        pointA = (float(data[1]), float(data[2]))
        pointB = (float(data[4]), float(data[5]))
    return pointA, pointB

def calculate_distance(point1, point2):
    return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)

def output(pointA, pointB, filename='output.txt'):
    distance = calculate_distance(pointA, pointB)
    with open(filename, 'w') as f:
        f.write(f"A({pointA[0]}, {pointA[1]}) B({pointB[0]}, {pointB[1]}) AB = {round(distance, 2)}")

pointA, pointB = get_points('input.txt')
output(pointA, pointB)


import pygame
import pygame_gui

from . import constants

class GameMenu(pygame_gui.UIManager):

    def __init__(self, game):
        super().__init__((game.width, game.height))
        self.game = game
        button_width = 300
        button_height = 100
        center_x = game.width // 2
        center_y = game.width // 2

        self.return_button = pygame_gui.elements.UIButton(
            relative_rect=pygame.Rect(
                (center_x - button_width // 2, center_y - button_height // 2 - 300),
                (button_width, button_height)),
            text=constants.RETURN_TO_GAME,
            manager=self
        )
        self.reset_level_button = pygame_gui.elements.UIButton(
            relative_rect=pygame.Rect(
                (center_x - button_width // 2, center_y - button_height // 2 - 200),
                (button_width, button_height)),
            text=constants.RESET_LEVEL,
            manager=self
        )
        self.exit_button = pygame_gui.elements.UIButton(
            relative_rect=pygame.Rect(
                (center_x - button_width // 2, center_y - button_height // 2 - 100),
                (button_width, button_height)),
            text=constants.EXIT_GAME,
            manager=self
        )

    def process_events(self, event: pygame.event.Event):
        super().process_events(event)

        if event.type != pygame.USEREVENT or event.user_type != pygame_gui.UI_BUTTON_PRESSED:
            return

        if event.ui_element == self.exit_button:
            self.game.exit_game()
        elif event.ui_element == self.reset_level_button:
            if self.game.current_level is not None:
                self.game.start_level()
                self.game.toggle_pause()
        elif event.ui_element == self.return_button:
            self.game.toggle_pause()

    def draw_ui(self, window_surface: pygame.surface.Surface):
        super().draw_ui(window_surface)

        if self.game.player.alive:
            self.return_button.show()
        else:
            self.return_button.hide()


class EarlyStopper:
    """
        Implements early stopping with patience.
    """

    def __init__(self, patience=5):
        self.patience = patience
        self.violations = 0
        self.min_val = float("inf")

    def check_stop_training(self, metric):

        if metric < self.min_val:
            self.violations = 0
            self.min_val = metric
            return False

        elif self.violations == self.patience:
            return True

        else:
            self.violations += 1
            return False


import requests
import re
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

from db_conn import *

"""
    id int auto_increment primary key,
    m_id int,
    point int, -- 평점
    user_id varchar(20), -- 닉네임 * 포함
    short_review varchar(300), -- 한줄평
    review_date datetime, -- 작성 날짜

"""

def crawl_short_review(num, rows, m_id):
    num += 1

    m_id = int(m_id)
    print("m_id:", m_id)
    try:
        totalgradeNum = 0
        nowgradecnt = 0
        pageNum = 1

        while (True):
            movie_url = "https://movie.naver.com/movie/point/af/list.naver?st=mcode&sword=" + str(m_id) + "&target=after&page=" + str(pageNum)
            movieDetail = requests.get(movie_url)
            gradeDetailPage = BeautifulSoup(movieDetail.content, 'html.parser')

            print()

            short_reviews = gradeDetailPage.select_one("#old_content")

            # 총 평점 수
            if pageNum == 1:
                totalgradeNum = int(short_reviews.select_one("h5 > div > strong").string)
                print("totalgradeNum:", totalgradeNum)
                print()

                # 평점 없는 경우 생략
                if totalgradeNum == 0:
                    break

            short_reviewsList = short_reviews.find('table', {'class': "list_netizen"})
            short_reviewsList = short_reviewsList.select('tbody > tr')

            for gradeTemp in short_reviewsList:
                # 평점
                point = int(gradeTemp.select_one("td.title > div > em").string)
                print("point:", point)

                # 닉네임
                user_id = gradeTemp.select_one("td:nth-child(3) > a").string
                print("user_id:", user_id)

                # 내용
                short_review = list(gradeTemp.select_one("td.title"))[6].replace("\n", "").replace("\t", "").strip()
                if len(short_review) > 300:
                    short_review = short_review[:300]
                elif len(short_review.strip()) < 1:
                    print("too short to save")
                    print()
                    continue
                print("short_review:", short_review)

                # 작성일
                review_date = "20" + list(gradeTemp.select_one("td:nth-child(3)"))[2].strip().replace(".", "-")
                print("review_date:", review_date)

                nowgradecnt += 1
                print("nowgradecnt", nowgradecnt)
                print()

                row = (m_id, point, user_id, short_review, review_date)
                rows.append(row)

                if nowgradecnt >= totalgradeNum:
                    break
                if nowgradecnt >= 100:
                    break
            if nowgradecnt >= 100:
                break
            pageNum += 1

    except:
        print("data 가져올 수 없음. continue")

def get_movie_url_from_db():
    conn, cur = open_db()
    conn2, cur2 = open_db()

    truncate_sql = """truncate table movie_short_review;"""
    cur.execute(truncate_sql)
    conn.commit()

    getmcodesql = "select m_id from naver_top_ranked_movie_list order by m_rank"
    cur.execute(getmcodesql)

    # 결과 하나씩(tuple) 가져오기
    movie_id = cur.fetchone()

    num = 0
    rows = []

    insert_sql= "insert into movie_short_review(m_id, point, user_id, short_review, review_date) values (%s, %s, %s, %s, %s);"
    number=0

    while movie_id:
        num+=1

        number+=1
        print("number:", number)

        movie_id = movie_id['m_id']
        print("m_id:", movie_id)
        print()

        crawl_short_review(num, rows, str(movie_id))

        if num%10 == 0:
            print()
            print()
            print("--------------------------------------------------------------")
            print()
            print()
            print("DB에 데이터 넣기")

            cur2.executemany(insert_sql, rows)
            conn2.commit()

            rows = []
            num = 0

        movie_id = cur.fetchone()
        print()
        print()
        print("--------------------------------------------------------------")
        print()
        print()
        '''if number == 10:
            break/'''
        continue

    close_db(conn, cur)

if __name__ == '__main__':
    get_movie_url_from_db()
    print()
    print()
    print("============================== 영화 short_review 가져오기 완료 ==============================")

5. Web Data Collection/소스코드/crawl_review.py


import os
import logging
import numpy as np
import multiprocessing as mp
os.environ['CUDA_VISIBLE_DEVICES']=''
import tensorflow as tf
import inteF_env as env
import a3c_interF
import load_trace

S_INFO = 6  # Inter Frame: choose features 3-4 and 6-9 in Table I
S_LEN = 4  # take how many frames in the past
QP_VALUE = [xi for xi in xrange(52)]  # QP
A_DIM = 52
ACTOR_LR_RATE = 0.0001
CRITIC_LR_RATE = 0.001
NUM_AGENTS = 10
TRAIN_SEQ_LEN = 100  # take as a train batch
MODEL_SAVE_INTERVAL = 100
CHUNK_TIL_VIDEO_END_CAP = 48.0
M_IN_K = 1000.0
ALPHA_PENALTY = 1
BETA_PENALTY = 1
GAMMA_PENALTY = 1
DEFAULT_QP = np.random.randint(13,41)  # default video QP without agent
RANDOM_SEED = 42
RAND_RANGE = 1000
SUMMARY_DIR = './results'
LOG_FILE = './results/log'
TEST_LOG_FOLDER = './test_results/'
TRAIN_DATAS = './training_traces/'
# NN_MODEL = './results/pretrain_linear_reward.ckpt'
NN_MODEL = None

def testing(epoch, nn_model, log_file):
    # clean up the test results folder
    os.system('rm -r ' + TEST_LOG_FOLDER)
    os.system('mkdir ' + TEST_LOG_FOLDER)
    # run test script
    os.system('python rl_test.py ' + nn_model)
    # append test performance to the log
    rewards = []
    test_log_files = os.listdir(TEST_LOG_FOLDER)
    for test_log_file in test_log_files:
        reward = []
        with open(TEST_LOG_FOLDER + test_log_file, 'rb') as f:
            for line in f:
                parse = line.split()
                try:
                    reward.append(float(parse[-1]))
                except IndexError:
                    break
        rewards.append(np.sum(reward[1:]))

    rewards = np.array(rewards)

    rewards_min = np.min(rewards)
    rewards_5per = np.percentile(rewards, 5)
    rewards_mean = np.mean(rewards)
    rewards_median = np.percentile(rewards, 50)
    rewards_95per = np.percentile(rewards, 95)
    rewards_max = np.max(rewards)

    log_file.write(str(epoch) + '\t' +
                   str(rewards_min) + '\t' +
                   str(rewards_5per) + '\t' +
                   str(rewards_mean) + '\t' +
                   str(rewards_median) + '\t' +
                   str(rewards_95per) + '\t' +
                   str(rewards_max) + '\n')
    log_file.flush()

def central_agent(net_params_queues, exp_queues):

    assert len(net_params_queues) == NUM_AGENTS
    assert len(exp_queues) == NUM_AGENTS

    logging.basicConfig(filename=LOG_FILE + '_central',
                        filemode='w',
                        level=logging.INFO)

    with tf.Session() as sess, open(LOG_FILE + '_test', 'wb') as test_log_file:

        actor = a3c.ActorNetwork(sess,
                                 state_dim=[S_INFO, S_LEN], action_dim=A_DIM,
                                 learning_rate=ACTOR_LR_RATE)
        critic = a3c.CriticNetwork(sess,
                                   state_dim=[S_INFO, S_LEN],
                                   learning_rate=CRITIC_LR_RATE)

        summary_ops, summary_vars = a3c.build_summaries()

        sess.run(tf.global_variables_initializer())
        writer = tf.summary.FileWriter(SUMMARY_DIR, sess.graph)  # training monitor
        saver = tf.train.Saver()  # save neural net parameters
        # restore neural net parameters
        nn_model = NN_MODEL
        if nn_model is not None:  # nn_model is the path to file
            saver.restore(sess, nn_model)
            print("Model restored.")

        epoch = 0

        while True:

            actor_net_params = actor.get_network_params()
            critic_net_params = critic.get_network_params()
            for i in xrange(NUM_AGENTS):
                net_params_queues[i].put([actor_net_params, critic_net_params])

            total_batch_len = 0.0
            total_reward = 0.0
            total_td_loss = 0.0
            total_entropy = 0.0
            total_agents = 0.0

            # assemble experiences from the agents
            actor_gradient_batch = []
            critic_gradient_batch = []

            for i in xrange(NUM_AGENTS):
                s_batch, a_batch, r_batch, terminal, info = exp_queues[i].get()

                actor_gradient, critic_gradient, td_batch = \
                    a3c.compute_gradients(
                        s_batch=np.stack(s_batch, axis=0),
                        a_batch=np.vstack(a_batch),
                        r_batch=np.vstack(r_batch),
                        terminal=terminal, actor=actor, critic=critic)

                actor_gradient_batch.append(actor_gradient)
                critic_gradient_batch.append(critic_gradient)

                total_reward += np.sum(r_batch)
                total_td_loss += np.sum(td_batch)
                total_batch_len += len(r_batch)
                total_agents += 1.0
                total_entropy += np.sum(info['entropy'])

            # compute aggregated gradient
            assert NUM_AGENTS == len(actor_gradient_batch)
            assert len(actor_gradient_batch) == len(critic_gradient_batch)

            for i in xrange(len(actor_gradient_batch)):
                actor.apply_gradients(actor_gradient_batch[i])
                critic.apply_gradients(critic_gradient_batch[i])

            # log training information
            epoch += 1
            avg_reward = total_reward  / total_agents
            avg_td_loss = total_td_loss / total_batch_len
            avg_entropy = total_entropy / total_batch_len

            logging.info('Epoch: ' + str(epoch) +
                         ' TD_loss: ' + str(avg_td_loss) +
                         ' Avg_reward: ' + str(avg_reward) +
                         ' Avg_entropy: ' + str(avg_entropy))

            summary_str = sess.run(summary_ops, feed_dict={
                summary_vars[0]: avg_td_loss,
                summary_vars[1]: avg_reward,
                summary_vars[2]: avg_entropy
            })

            writer.add_summary(summary_str, epoch)
            writer.flush()

            if epoch % MODEL_SAVE_INTERVAL == 0:
                # Save the neural net parameters to disk.
                save_path = saver.save(sess, SUMMARY_DIR + "/nn_model_ep_" +
                                       str(epoch) + ".ckpt")
                logging.info("Model saved in file: " + save_path)
                testing(epoch,
                    SUMMARY_DIR + "/nn_model_ep_" + str(epoch) + ".ckpt",
                    test_log_file)

def agent(agent_id, all_cooked_time, all_cooked_bw, net_params_queue, exp_queue):

    net_env = env.Environment(all_cooked_time=all_cooked_time,
                              all_cooked_bw=all_cooked_bw,
                              random_seed=agent_id)

    with tf.Session() as sess, open(LOG_FILE + '_agent_' + str(agent_id), 'wb') as log_file:
        actor = a3c.ActorNetwork(sess,
                                 state_dim=[S_INFO, S_LEN], action_dim=A_DIM,
                                 learning_rate=ACTOR_LR_RATE)
        critic = a3c.CriticNetwork(sess,
                                   state_dim=[S_INFO, S_LEN],
                                   learning_rate=CRITIC_LR_RATE)

        # initial synchronization of the network parameters from the coordinator
        actor_net_params, critic_net_params = net_params_queue.get()
        actor.set_network_params(actor_net_params)
        critic.set_network_params(critic_net_params)

        last_QP = DEFAULT_QP
        select_QP = DEFAULT_QP

        action_vec = np.zeros(A_DIM)
        action_vec[select_QP] = 1

        s_batch = [np.zeros((S_INFO, S_LEN))]
        a_batch = [action_vec]
        r_batch = []
        entropy_record = []

        time_stamp = 0
        while True:  # experience video coding forever

            f_ALPHA, f_BETA, f_GAMMA, fs1, fs2, fs3, \
            fs4, fs5, fs6, fs7, fs8, fs9, \
            end_of_video, video_frame_remain = \
                net_env.encode_video_frame(select_QP)

            time_stamp += delay  # in ms
            time_stamp += sleep_time  # in ms

            reward = ALPHA_PENALTY * f_ALPHA \
                    * BETA_PENALTY * f_BETA \
                    * GAMMA_PENALTY * f_GAMMA

            r_batch.append(reward)

            last_QP = select_QP

            # retrieve previous state
            if len(s_batch) == 0:
                state = [np.zeros((S_INFO, S_LEN))]
            else:
                state = np.array(s_batch[-1], copy=True)

            # dequeue history record
            state = np.roll(state, -1, axis=1)

            # this should be S_INFO number of terms
            state[0, -1] = fs3
            state[1, -1] = fs4
            state[2, -1] = fs6
            state[3, -1] = fs7
            state[4, -1] = fs8
            state[5, -1] = fs9

            # compute action probability vector
            action_prob = actor.predict(np.reshape(state, (1, S_INFO, S_LEN)))
            action_cumsum = np.cumsum(action_prob)
            select_QP = (action_cumsum > np.random.randint(1, RAND_RANGE) / float(RAND_RANGE)).argmax()

            entropy_record.append(a3c.compute_entropy(action_prob[0]))

            log_file.write(str(time_stamp) + '\t' +
                           str(QP_VALUE[select_QP]) + '\t' +
                           str(f_ALPHA) + '\t' +
                           str(f_BETA) + '\t' +
                           str(f_GAMMA) + '\t' +
                           str(reward) + '\n')
            log_file.flush()

            # report experience to the coordinator
            if len(r_batch) >= TRAIN_SEQ_LEN or end_of_video:
                exp_queue.put([s_batch[1:],  # ignore the first chuck
                               a_batch[1:],  # since we don't have the
                               r_batch[1:],  # control over it
                               end_of_video,
                               {'entropy': entropy_record}])

                # synchronize the network parameters from the coordinator
                actor_net_params, critic_net_params = net_params_queue.get()
                actor.set_network_params(actor_net_params)
                critic.set_network_params(critic_net_params)

                del s_batch[:]
                del a_batch[:]
                del r_batch[:]
                del entropy_record[:]

                log_file.write('\n')  # so that in the log we know where video ends

            # store the state and action into batches
            if end_of_video:
                last_QP = DEFAULT_QP
                select_QP = np.random.randint(13,40)  # use the random action to start here

                action_vec = np.zeros(A_DIM)
                action_vec[select_QP] = 1

                s_batch.append(np.zeros((S_INFO, S_LEN)))
                a_batch.append(action_vec)

            else:
                s_batch.append(state)

                action_vec = np.zeros(A_DIM)
                action_vec[select_QP] = 1
                a_batch.append(action_vec)

def main():

    np.random.seed(RANDOM_SEED)
    assert len(QP_VALUE) == A_DIM

    # create result directory
    if not os.path.exists(SUMMARY_DIR):
        os.makedirs(SUMMARY_DIR)

    # inter-process communication queues
    net_params_queues = []
    exp_queues = []
    for i in xrange(NUM_AGENTS):
        net_params_queues.append(mp.Queue(1))
        exp_queues.append(mp.Queue(1))

    # create a coordinator and multiple agent processes
    # (note: threading is not desirable due to python GIL)
    coordinator = mp.Process(target=central_agent,
                             args=(net_params_queues, exp_queues))
    coordinator.start()

    all_cooked_time, all_cooked_bw, _ = load_trace.load_trace(TRAIN_DATAS)
    agents = []
    for i in xrange(NUM_AGENTS):
        agents.append(mp.Process(target=agent,
                                 args=(i, all_cooked_time, all_cooked_bw,
                                       net_params_queues[i],
                                       exp_queues[i])))
    for i in xrange(NUM_AGENTS):
        agents[i].start()

    # wait unit training is done
    coordinator.join()

if __name__ == '__main__':
    main()


budget = float(input())
count_actors = int(input())
price_per_costume = float(input())

decor = budget * 0.10
clothes_price = count_actors * price_per_costume

if count_actors > 150:
    clothes_price = clothes_price * 0.9

total_sum = decor + clothes_price
diff = abs(total_sum - budget)

if total_sum <= budget:
    print("Action!")
    print(f"Wingard starts filming with {diff:.2f} leva left.")
else:
    print("Not enough money!")
    print(f"Wingard needs {diff:.2f} leva more.")

Programming Basics with Python/02. Conditional-Statements/02.Conditional-Statements-Exercise/godzilla_vs._kong.py


import pygame as pg
import random as rand

# Application
appDim = (1200,675)
backgroundColor = (15,15,20)
caption = "Collisions"

# Functional
app = pg.display.set_mode(appDim)
pg.display.set_caption(caption)
EXIT = False


"""A file merging script."""
__author__ = "Martin Lacayo-Emery <popanalyst@gmail.com>"

import sys
import os
import arcgisscripting

if __name__=="__main__":
    #create geoprocessor object
    gp = arcgisscripting.create()

    #store parameters
    inFolder=sys.argv[1]
    outName=sys.argv[2]
    if sys.argv[3]=="true":
        header=True
    else:
        header=False

    outFile=open(outName,"w")

    #if file header, pick longest
    finalHeader=""
    if header:
        gp.addwarning("The longest header is being selected for the final ouput.")
        for name in os.listdir(inFolder):
            inName=inFolder+"\\"+name
            inFile=open(inName)
            tempHeader=inFile.readline()
            if len(tempHeader)>len(finalHeader):
                finalHeader=tempHeader
            inFile.close()
        outFile.write(finalHeader)

    #read in each file and write to output
    for name in os.listdir(inFolder):
        inName=inFolder+"\\"+name
        gp.AddMessage("Processing "+inName)
        inFile=open(inName)
        #skip header line if present
        if header:
            inFile.readline()
        #end each sequence with a end of line, otherwise TraMineR parse warnings
        outFile.write(inFile.read().strip()+"\n")
        inFile.close()

    outFile.close()


import os
import pickle

import tweepy

def get_twitter_oauth_handler():
    if not os.path.exists("secrets.pickle"):
        api_key = input("Twitter API Key: ")
        secret_key = input("Twitter API Key Secret: ")
        with open("secrets.pickle", "wb") as pickle_file:
            pickle.dump(
                {"api_key": api_key, "api_key_secret": secret_key, "accounts": {}},
                pickle_file,
            )
    with open("secrets.pickle", "rb") as pickle_file:
        secrets = pickle.load(pickle_file)
        return (
            tweepy.OAuth1UserHandler(secrets["api_key"], secrets["api_key_secret"], callback="oob"),
            secrets["accounts"],
        )

def log_in_to_twitter(account_name):
    auth, account_secrets = get_twitter_oauth_handler()
    if account_name not in account_secrets:
        redirect_url = auth.get_authorization_url()
        print(f"Go to {redirect_url} as {account_name}")
        verifier = input("Twitter Verifier PIN: ")
        access_token, access_token_secret = auth.get_access_token(verifier)
        account_secrets[account_name] = {
            "access_token": access_token,
            "access_token_secret": access_token_secret,
        }
        with open("secrets.pickle", "wb") as pickle_file:
            pickle.dump(
                {
                    "consumer_key": auth.consumer_key,
                    "consumer_secret": auth.consumer_secret,
                    "accounts": account_secrets,
                },
                pickle_file,
            )
    auth.set_access_token(
        account_secrets[account_name]["access_token"],
        account_secrets[account_name]["access_token_secret"],
    )
    return auth