def prime(k):
    if k == 1:
        return False

    for i in range(2, k):
        if k % i == 0:
            return False
    return True

def invert(k):
    inv = 0
    while k > 0:
        inv = inv * 10 + k % 10
        k = k // 10
    return inv

######### Main #########
a, b = [int(el) for el in input().split()]
counter = 0
for i in range(a, b + 1):
    if prime(i) and prime(invert(i)):
        counter += 1
print(counter)


import datetime
import pandas_datareader.data as web
import matplotlib.pyplot as plt

from FileManipulation import SavingToFiles

class CompareCompetitors:

    __information_source = 'yahoo'
    __start_date = datetime.datetime(2010, 1, 11)
    __end_date = datetime.datetime(2021, 10, 28)
    __stock_type = 'Adj Close'

    def do_stuff(self, tickers):
        dataframe = self.get_competitors_stock_data(tickers)
        restcomp = self.get_correlation(dataframe)
        self.plot_returns_rate_and_risk(restcomp)

    def get_competitors_stock_data(self, tickers):
        try:
            print('getting competitors data...')
            dataframe = web.DataReader(tickers, self.__information_source, start=self.__start_date,
                                       end=self.__end_date)[self.__stock_type]
            print('saving to file')
            # psp.save_to_json(dataframe, 'competition_stocks.json')
            print(dataframe)
            return dataframe
        except Exception as e:
            print(f'error: {str(e)}')

    def get_correlation(self, dataframe):
        restcomp = dataframe.pct_change()
        correlation = restcomp.corr
        # psp.save_to_json(restcomp, 'percentage_change.json')
        print(restcomp)
        return restcomp

    def plot_returns_rate_and_risk(self, restcomp):
        plt.figure()
        plt.scatter(restcomp.mean(), restcomp.std())
        plt.xlabel('Expected returns')
        plt.ylabel('Risk')
        # plt.plot([-0.006, 0.006], [0.006, 0.024])
        for label, x, y in zip(restcomp.columns, restcomp.mean(), restcomp.std()):
            plt.annotate(
                label,
                xy=(x, y), xytext=(20, -20), textcoords='offset points', ha='right', va='bottom',
                bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
                arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
        saving_files = SavingToFiles.SaveToFiles()
        saving_files.save_graph_as_png('returns_rate_and_risk.png')


import random
import numpy as np
class Map(object):
    """
    A 2D map on which objects may be placed
    """

    def __init__(self, height, width):
        self.height = height
        self.width = width
        self.map = [["." for y in range(width)] for x in range(height)]
        symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@0\'&;:~]│─┌┐└┘┼┴┬┤├░▒≡± ⌠≈ · ■'
        sarray = np.array([ord(c) for c in symbols])
        self.s_mean = sarray.mean()
        self.s_std = sarray.std()
        self.set_spots()

    def set_spots(self):
        self.start = self.getRandomSpot()
        self.end = self.getRandomSpot()
        while self.start.all() == self.end.all():
            self.end = self.getRandomSpot()
        self.setCharacter('@', self.start)
        self.setCharacter('X', self.end)

    def Map(self):
        return self.map

    def getRandomSpot(self):
        x = random.randint(0, self.height - 1)
        y = random.randint(0, self.width - 1)
        return np.array((x,y), dtype=np.int32)

    def setCharacter(self,c,coord):
        self.map[coord[0]][coord[1]] = c

    def getDist(self, a, b):
        return np.linalg.norm(a - b)

    def display(self):
        for i in range(self.height):
            print("".join(self.map[i]))

    def angle(self, a, b):
        ang1 = np.arctan2(*a.tolist()[::-1])
        ang2 = np.arctan2(*b.tolist()[::-1])
        return (ang1 - ang2) % (2 * np.pi)

    def data(self):
        ords =[ord(item) for sublist in mx for item in sublist]
        #standard = [(o - self.s_mean)/self.s_std for o in ords]
        return ords

    def labels(self):
        labels = [self.getDist(self.start, self.end),
                self.angle(self.start, self.end)
                ]
        labels.extend(self.start.tolist())
        labels.extend(self.end.tolist())
        return labels

m = Map(15, 10)

mx = m.Map()
m.display()
print(m.data())
print(m.labels())


from web3 import Web3
import json
from flask import Flask, render_template, request, flash, redirect
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, IntegerField, FloatField, SubmitField
from wtforms.validators import DataRequired
import os
from datetime import date

# Ganache URL connection
ganache_url = "http://127.0.0.1:7545"
web3 = Web3(Web3.HTTPProvider(ganache_url))
print('Connection to node:', web3.isConnected())
ac_index = int(input('Enter default index of Ganache address:'))
web3.eth.defaultAccount = web3.eth.accounts[ac_index]

print(web3.eth.defaultAccount)

# Loading ABI from json
with open('abi.json') as f:
  abi = json.load(f)

# Loading deployed contract address and initating contract instance
with open('contract_details.json') as f1:
	contractdetails = json.load(f1)
contractadd = contractdetails['address']
contract=web3.eth.contract(address=contractadd, abi=abi)

# Form classes definition
class RegisrationForm(FlaskForm):
	username = StringField('Username', validators=[DataRequired()])
	submit = SubmitField('Register')
class BuySellForm(FlaskForm):
	amount = IntegerField('Amount', validators=[DataRequired()])
	submit = SubmitField('Submit')
class DonateForm(FlaskForm):
	address = StringField('Address', validators=[DataRequired()])
	amount = IntegerField('Amount', validators=[DataRequired()])
	submit = SubmitField('Donate')
class SetMarket(FlaskForm):
	supply = IntegerField('Total Supply', validators=[DataRequired()])
	price = FloatField('Price (ETH)', validators=[DataRequired()])
	validity = FloatField('Validity (days)', validators=[DataRequired()])
	sell_lock = FloatField('Duration of Sale Freeze (days)', validators=[DataRequired()])
	submit = SubmitField('Set Market')

# Functions
def terminalparams():
	name = contract.functions.myName().call()
	availableSupply = contract.functions.AvailableTokens().call()
	totalseconds = contract.functions.returnTimeRemaining().call()
	daysleft = int(float(totalseconds)/(60*60*24))
	hoursleft = int((totalseconds - (daysleft*24*60*60))/(60*60))
	minsleft = int((totalseconds - (daysleft*24*60*60) - (hoursleft*60*60))/(60))
	secsleft = int(totalseconds - (daysleft*24*3600) - (hoursleft*3600) - (minsleft*60))
	balance = contract.functions.returnBalance().call()
	price = contract.functions.price().call()
	price = web3.fromWei(price, 'ether')
	etherbal = web3.eth.getBalance(web3.eth.defaultAccount)
	etherbal = web3.fromWei(etherbal, 'ether')
	etheraccount = web3.eth.defaultAccount
	sell_lock = contract.functions.translock().call()
	if totalseconds > sell_lock:
		sale_status = 'Sale of tokens permitted'
	else:
		sale_status = 'No further sale of tokens permitted'
	return name, availableSupply, balance, daysleft, hoursleft, minsleft, secsleft, price, etherbal, etheraccount, sale_status

# Setting up flask protocols
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret420'

@app.route('/')
@app.route('/index')
def index():
	availableSupply = contract.functions.AvailableTokens().call()
	limit0 = contract.functions.returnTimeRemaining().call()
	limit0 = float(limit0/(24*60*60))
	price = contract.functions.price().call()
	price = web3.fromWei(price, 'ether')
	address_user = web3.eth.defaultAccount
	address_MM = contract.functions.marketmaker().call()
	if address_user == address_MM:
		return render_template('index_master.html', availableSupply=availableSupply, price=price, limit=limit0)
	else:
		return render_template('index.html', availableSupply=availableSupply, price=price)

@app.route('/register', methods=['GET', 'POST'])
def register():
	availableSupply = contract.functions.AvailableTokens().call()
	limit0 = contract.functions.returnTimeRemaining().call()
	limit0 = float(limit0/(24*60*60))
	price = contract.functions.price().call()
	price = web3.fromWei(price, 'ether')
	address_user = web3.eth.defaultAccount
	address_MM = contract.functions.marketmaker().call()
	if address_user == address_MM:
		return render_template('index_master.html', availableSupply=availableSupply, price=price, limit=limit0)
	else:
		form = RegisrationForm()
		status = contract.functions.isRegistered().call()
		regdict = contract.functions.regdict().call()
		regdict = regdict[:-1]
		if form.validate_on_submit():
			flash('Registration requested for user {}'.format(
				form.username.data))
			if status==False:
				today = date.today()
				todayd1 = today.strftime("%b-%d-%Y")
				entityinfo = {
					"name": form.username.data,
					"address": web3.eth.defaultAccount,
					"datejoined": todayd1
				}
				entityjson = json.dumps(entityinfo)
				regdict = regdict + entityjson + ', ]'
				contract.functions.register(form.username.data, regdict).transact()
				name, availableSupply, balance, daysleft, hoursleft, minsleft, secsleft, price, etherbal, etheraccount, sale_status = terminalparams()
				return render_template('terminal.html',
					availableSupply=availableSupply,
					balance=balance,
					name=name,
					daysleft=daysleft,
					hoursleft=hoursleft,
					minsleft=minsleft,
					secsleft=secsleft,
					price=price,
					etherbal=etherbal,
					etheraccount=etheraccount,
					sale_status=sale_status)
			else:
				availableSupply = contract.functions.AvailableTokens().call()
				price = contract.functions.price().call()
				price = web3.fromWei(price, 'ether')
				return render_template('index.html', availableSupply=availableSupply, price=price)
		return render_template('register.html', form=form)

@app.route('/terminal', methods=['GET', 'POST'])
def terminal():
	availableSupply = contract.functions.AvailableTokens().call()
	limit0 = contract.functions.returnTimeRemaining().call()
	limit0 = float(limit0/(24*60*60))
	price = contract.functions.price().call()
	price = web3.fromWei(price, 'ether')
	address_user = web3.eth.defaultAccount
	address_MM = contract.functions.marketmaker().call()
	if address_user == address_MM:
		return render_template('index_master.html', availableSupply=availableSupply, price=price, limit=limit0)
	else:
		status = contract.functions.isRegistered().call()
		if status:
			name, availableSupply, balance, daysleft, hoursleft, minsleft, secsleft, price, etherbal, etheraccount, sale_status = terminalparams()
			return render_template('terminal.html',
				availableSupply=availableSupply,
				balance=balance,
				name=name,
				daysleft=daysleft,
				hoursleft=hoursleft,
				minsleft=minsleft,
				secsleft=secsleft,
				price=price,
				etherbal=etherbal,
				etheraccount=etheraccount,
				sale_status=sale_status)
		else:
			availableSupply = contract.functions.AvailableTokens().call()
			price = contract.functions.price().call()
			price = web3.fromWei(price, 'ether')
			return render_template('index.html', availableSupply=availableSupply, price=price)

@app.route('/buy', methods=['GET', 'POST'])
def buy():
	availableSupply = contract.functions.AvailableTokens().call()
	limit0 = contract.functions.returnTimeRemaining().call()
	limit0 = float(limit0/(24*60*60))
	price = contract.functions.price().call()
	price = web3.fromWei(price, 'ether')
	address_user = web3.eth.defaultAccount
	address_MM = contract.functions.marketmaker().call()
	if address_user == address_MM:
		return render_template('index_master.html', availableSupply=availableSupply, price=price, limit=limit0)
	else:
		form = BuySellForm()
		name, availableSupply, balance, daysleft, hoursleft, minsleft, secsleft, price, etherbal, etheraccount, sale_status = terminalparams()
		time = contract.functions.returnTimeRemaining().call()
		if time > 0:
			if form.validate_on_submit():
				flash('Request to buy {}'.format(
					form.amount.data))
				price = contract.functions.price().call()
				weiamount = price*(form.amount.data)
				weibalance = web3.eth.getBalance(web3.eth.defaultAccount)
				gasprice = web3.toWei('50', 'gwei')
				gasamt = 2000000
				if weibalance < ((gasamt*gasprice)+weiamount):
					flash('Insufficient ether balance!')
					return render_template('buy.html', form=form)
				elif availableSupply < form.amount.data:
					flash('Insufficient token supply avaialble for purchase!')
					return render_template('buy.html', form=form)
				else:
					# Transaction dictionary
					nonce = web3.eth.getTransactionCount(web3.eth.defaultAccount)
					tx = {
					    'nonce': nonce,
					    'to': contractadd,
					    'value': weiamount,
					    'gas': gasamt,
					    'gasPrice': web3.toWei('50', 'gwei')
					}
					contract.functions.buy().transact(tx)
					#tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash)
					name, availableSupply, balance, daysleft, hoursleft, minsleft, secsleft, price, etherbal, etheraccount, sale_status = terminalparams()
					flash('Transaction successful!')
					return render_template('terminal.html',
						availableSupply=availableSupply,
						balance=balance,
						name=name,
						daysleft=daysleft,
						hoursleft=hoursleft,
						minsleft=minsleft,
						secsleft=secsleft,
						price=price,
						etherbal=etherbal,
						etheraccount=etheraccount,
						sale_status=sale_status)
		return render_template('buy.html', form=form)

@app.route('/sell', methods=['GET', 'POST'])
def sell():
	availableSupply = contract.functions.AvailableTokens().call()
	limit0 = contract.functions.returnTimeRemaining().call()
	limit0 = float(limit0/(24*60*60))
	price = contract.functions.price().call()
	price = web3.fromWei(price, 'ether')
	address_user = web3.eth.defaultAccount
	address_MM = contract.functions.marketmaker().call()
	if address_user == address_MM:
		return render_template('index_master.html', availableSupply=availableSupply, price=price, limit=limit0)
	else:
		sell_lock = contract.functions.translock().call()
		form = BuySellForm()
		if (limit0*24*3600) > sell_lock:
			if form.validate_on_submit():
				flash('Request to sell {}'.format(
					form.amount.data))
				name, availableSupply, balance, daysleft, hoursleft, minsleft, secsleft, price, etherbal, etheraccount, sale_status = terminalparams()
				if form.amount.data > balance:
					flash('You cannot sell more than what you have!')
					return render_template('sell.html', form=form)
				else:
					contract.functions.sell(form.amount.data).transact()
					name, availableSupply, balance, daysleft, hoursleft, minsleft, secsleft, price, etherbal, etheraccount, sale_status = terminalparams()
					flash('Transaction successful!')
					return render_template('terminal.html',
						availableSupply=availableSupply,
						balance=balance,
						name=name,
						daysleft=daysleft,
						hoursleft=hoursleft,
						minsleft=minsleft,
						secsleft=secsleft,
						price=price,
						etherbal=etherbal,
						etheraccount=etheraccount,
						sale_status=sale_status)
		return render_template('sell.html', form=form)

@app.route('/donate', methods=['GET', 'POST'])
def donate():
	availableSupply = contract.functions.AvailableTokens().call()
	limit0 = contract.functions.returnTimeRemaining().call()
	limit0 = float(limit0/(24*60*60))
	price = contract.functions.price().call()
	price = web3.fromWei(price, 'ether')
	address_user = web3.eth.defaultAccount
	address_MM = contract.functions.marketmaker().call()
	if address_user == address_MM:
		return render_template('index_master.html', availableSupply=availableSupply, price=price, limit=limit0)
	else:
		form = DonateForm()
		bal = contract.functions.returnTimeRemaining().call()
		if bal > 0:
			if form.validate_on_submit():
				flash('Request to donate {} to address {}'.format(
					form.amount.data, form.address.data))
				name, availableSupply, balance, daysleft, hoursleft, minsleft, secsleft, price, etherbal, etheraccount, sale_status = terminalparams()
				if form.amount.data > balance:
					flash('You cannot donate what you do not have!')
					return render_template('donate.html', form=form)
				else:
					contract.functions.donate(form.address.data, form.amount.data).transact()
					name, availableSupply, balance, daysleft, hoursleft, minsleft, secsleft, price, etherbal, etheraccount, sale_status = terminalparams()
					flash('The recipent thanks you for your kind gesture!')
					return render_template('terminal.html',
						availableSupply=availableSupply,
						balance=balance,
						name=name,
						daysleft=daysleft,
						hoursleft=hoursleft,
						minsleft=minsleft,
						secsleft=secsleft,
						price=price,
						etherbal=etherbal,
						etheraccount=etheraccount,
						sale_status=sale_status)
		return render_template('donate.html', form=form)

@app.route('/setmarket', methods=['GET', 'POST'])
def setmarket():
	availableSupply = contract.functions.AvailableTokens().call()
	limit0 = contract.functions.returnTimeRemaining().call()
	limit0 = float(limit0/(24*60*60))
	price = contract.functions.price().call()
	price = web3.fromWei(price, 'ether')
	address_user = web3.eth.defaultAccount
	address_MM = contract.functions.marketmaker().call()
	if address_user != address_MM:
		return render_template('index.html', availableSupply=availableSupply, price=price)
	else:
		form = SetMarket()
		if form.validate_on_submit():
			flash('Request to set up supply of {} CTs at {} ETH/CT, valid for {} days.'.format(
				form.supply.data, form.price.data, form.validity.data))
			# Resetting user balances to zero
			regdict = contract.functions.regdict().call()
			if len(regdict) > 2:
				regdict = regdict[:-3] + ']'
				reglist = json.loads(regdict)
				for reg in reglist:
					entity_add = reg['address']
					contract.functions.reset(entity_add).transact()
			weiprice = web3.toWei(form.price.data, 'ether')
			limit = int((form.validity.data)*24*3600)
			sell_lock = int((form.sell_lock.data)*24*3600)
			supply = form.supply.data
			tx_hash1 = contract.functions.setMarket(supply, weiprice, limit, sell_lock).transact()
			receipt1 = web3.eth.waitForTransactionReceipt(tx_hash1)
			availableSupply = contract.functions.AvailableTokens().call()
			price = contract.functions.price().call()
			price = web3.fromWei(price, 'ether')
			limit0 = contract.functions.returnTimeRemaining().call()
			limit0 = float(limit0/(24*60*60))
			return render_template('index_master.html', availableSupply=availableSupply, price=price, limit=limit0)
		return render_template('setmarket.html', form=form)

@app.route('/entities', methods=['GET', 'POST'])
def entities():
	availableSupply = contract.functions.AvailableTokens().call()
	limit0 = contract.functions.returnTimeRemaining().call()
	limit0 = float(limit0/(24*60*60))
	price = contract.functions.price().call()
	price = web3.fromWei(price, 'ether')
	address_user = web3.eth.defaultAccount
	address_MM = contract.functions.marketmaker().call()
	if address_user != address_MM:
		return render_template('index.html', availableSupply=availableSupply, price=price)
	else:
		regdict = contract.functions.regdict().call()
		if len(regdict)>2:
			timeleft = contract.functions.returnTimeRemaining().call()
			sell_lock = contract.functions.translock().call()
			regdict = regdict[:-3] + ']'
			reglist = json.loads(regdict)
			for reg in reglist:
				entity_add = reg['address']
				if timeleft == 0:
					contract.functions.reset(entity_add).transact()
				reg['ctbalance'] = contract.functions.retrieveBal(entity_add).call()
			return render_template('entities.html', reglist=reglist)
		else:
			flash('No entities have registered yet!')
			return render_template('index_master.html', availableSupply=availableSupply, price=price, limit=limit0)

if __name__ == '__main__':
	app.run(debug=True)


from pymavlink import mavutil

GPS_FIX_TYPE = {
    1: "GPS_NO_FIX",
    2: "GPS_2D_FIX",
    3: "GPS_3D_FIX",
    4: "GPS_FIX_TYPE_DGPS",
    5: "GPS_FIX_TYPE_RTK_FLOAT",
    6: "GPS_FIX_TYPE_RTK_FIXED",
    7: "GPS_FIX_TYPE_STATIC",
    8: "GPS_FIX_TYPE_PPP"
}
MAV_MODE = {
    0: "PREFLIGHT",
    80: "STABILIZE_DISARMED",
    208: "STABILIZE_ARMED",
    64: "MANUAL_DISARMED",
    192: "MANUAL_ARMED",
    88: "GUIDED_DISARMED",
    216: "GUIDED_ARMED",
    92: "DISARMED",
    220: "AUTO_ARMED",
    66: "TEST_DISARMED",
    194: "TEST_ARMED",
}
MAV_TYPE_MAP = {
    0: "GENERIC",
    1: "FIXED_WING",
    2: "QUADROTOR",
    3: "COAXIAL",
    4: "HELICOPTER",
    5: "ANTENNA_TRACKER",
    6: "GCS",
    7: "AIRSHIP",
    8: "FREE_BALLOON",
    9: "ROCKET",
    10: "ROVER",
    11: "BOAT",
    12: "SUBMARINE",
    13: "HEXAROTOR",
    14: "OCTOROTOR",
    15: "TRICOPTER",
    16: "FLAPPING_WING",
    17: "KITE",
    18: "ONBOARD_CONTROLLER",
    19: "VTOL_DUOROTOR",
    20: "VTOL_QUADROTOR",
    21: "VTOL_TILTROTOR",
    22: "VRTOL_RESERVED2",
    23: "VTOL_RESERVED3",
    24: "VTOL_RESERVED4",
    25: "VTOL_RESERVED5",
    26: "GIMBAL",
    27: "ADSB",
    28: "PARAFOIL",
    29: "DODECAROTOR",
    30: "CAMERA",
    31: "CHARING_STATION",
    32: "FLARM",
    33: "SERVO",
    34: "ODID",
    35: "DECAROTOR"
}

ORIENTATION_MESSAGE_NAME = 'ATTITUDE'
POWER_STATUS = 'POWER_STATUS'
GLOBAL_POSITION_INT = 'GLOBAL_POSITION_INT'
GPS_RAW_INT = 'GPS_RAW_INT'
GPS_RAW = 'GPS_RAW'
HEARTBEAT = "HEARTBEAT"
USEFUL_MESSAGES = [
    HEARTBEAT,
    ORIENTATION_MESSAGE_NAME,
    POWER_STATUS,
    GPS_RAW_INT,
]
MAVLINK_MSG_ID_SET_MODE = mavutil.mavlink.MAVLINK_MSG_ID_SET_MODE

AVAILABLE_TELEMETRY_DATA = {
    "GLOBAL_POSITION_INT": ["time_boot_ms", "lat", "lon", "alt", "relative_alt", "vx", "vy", "vz", "hdg"],
    "BATTERY_STATUS": ["id", "battery_function", "type", "temperature", "voltages", "current_battery",
                       "current_consumed", "energy_consumed", "battery_remaining", "time_remaining", "charge_state",
                       "voltages_ext", "mode", "fault_bitmask"],
    "SYS_STATUS": ["onboard_control_sensors_present", "onboard_control_sensors_enabled",
                   "onboard_control_sensors_health", "load", "voltage_battery", "current_battery", "battery_remaining",
                   "drop_rate_comm", "errors_comm", "errors_count1", "errors_count2", "errors_count3", "errors_count4"]
}


#! /usr/bin/env python

from mybigdft import Posinp, InputParams, Job, Logfile
from mybigdft.workflows import Geopt
from abipy.abio.outputs import AbinitOutputFile
from ase.io import read
from ase.calculators.abinit import Abinit
from shutil import rmtree, copyfile
from copy import deepcopy
import yaml
import numpy as np
import argparse
import os

def create_parser():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )

    parser.add_argument(
        "n_structs",
        type=int,
        help="Number of different structures to generate and calculate.",
    )
    runmode_subparser = parser.add_subparsers(
        dest="run_mode", help="Choose the DFT code to generate data."
    )

    # BigDFT parser
    bigdft_parser = runmode_subparser.add_parser(
        "bigdft",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        help="BigDFT calculations.",
    )

    bigdft_parser.add_argument("posinp", help="Name of the initial positions file.")
    bigdft_parser.add_argument(
        "--no_pseudos",
        help="Use pseudos for calculations",
        default=True,
        action="store_false",
    )
    bigdft_parser.add_argument(
        "--nmpi", help="Number of mpi processes", type=int, default=6
    )

    # Abinit parser
    abinit_parser = runmode_subparser.add_parser(
        "abinit",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        help="Abinit calculations.",
    )
    abinit_parser.add_argument(
        "positions", help="Name of the initial positions file(abinit format)"
    )
    abinit_parser.add_argument("input", help="Name of the yaml input file.")
    return parser

def main(args):
    # Create directories
    os.makedirs("run_dir/", exist_ok=True)
    os.makedirs("saved_results/", exist_ok=True)

    if args.run_mode == "bigdft":
        jobname = args.posinp.split(".")[0]
        initpos = Posinp.from_file(args.posinp)

        inputpar = InputParams()
        for filename in [f for f in os.listdir() if f.endswith(".yaml")]:
            try:
                inputpar = InputParams.from_file(filename)
                break
            except:
                continue

        os.chdir("run_dir/")
        for i in range(args.n_structs):
            try:
                os.makedirs("{}_{:06}".format(jobname, i))
                os.chdir("{}_{:06}".format(jobname, i))
                bigdft_run(i, initpos, args, jobname, inputpar, restart=False)
            except OSError:
                os.chdir("{}_{:06}".format(jobname, i))
                try:
                    log = Logfile.from_file("log-" + jobname + ".yaml")
                    print("Calculation {:06} was complete.\n".format(i))
                    os.chdir("../")
                except:
                    bigdft_run(i, initpos, args, jobname, inputpar, restart=True)
        os.chdir("../")

    elif args.run_mode == "abinit":
        jobname = args.positions.split(".")[0]
        initatoms = read(args.positions, format="abinit-in")
        with open(args.input, "r") as f:
            inputs = yaml.load(f, Loader=yaml.BaseLoader)
        calculator = Abinit(**inputs)

        os.chdir("run_dir/")
        for i in range(args.n_structs):
            try:
                os.makedirs("{}_{:06}".format(jobname, i))
                os.chdir("{}_{:06}".format(jobname, i))
                abinit_run(i, calculator, initatoms)
            except FileExistsError:
                os.chdir("{}_{:06}".format(jobname, i))
                try:
                    about = AbinitOutputFile("abinit.out")
                    if about.run_completed:
                        print("Calculation {:06} was complete.\n".format(i))
                        os.chdir("../")
                    else:
                        restart(i, calculator, initatoms)
                except:
                    restart(i, calculator, initatoms)
    else:
        raise ValueError("The run_mode argument should be abinit or bigdft.")

def bigdft_run(i, initpos, args, jobname, inputpar, restart=False):
    pos = bigdft_random_structure(initpos)
    job = Job(
        name=jobname,
        posinp=pos,
        inputparams=inputpar,
        pseudos=args.no_pseudos,
    )
    job.run(nmpi=args.nmpi, restart_if_incomplete=restart)
    copyfile(
        "forces_{}.xyz".format(jobname),
        "../../saved_results/{:06}.xyz".format(i),
    )
    os.chdir("../")

def bigdft_random_structure(initpos):
    pos = deepcopy(initpos)
    atoms_idx = np.arange(len(pos))
    n_translations = np.random.randint(len(pos)) + 1
    trans_idx = np.random.choice(atoms_idx, n_translations)
    for j in trans_idx:
        phi = 2 * np.pi * np.random.rand()
        theta = np.arccos(2 * np.random.rand() - 1)
        r = -0.1
        while r < 0:
            r = np.random.normal(scale=0.1)
        pos = pos.translate_atom(
            j,
            [
                r * np.sin(theta) * np.cos(phi),
                r * np.sin(theta) * np.sin(phi),
                r * np.cos(theta),
            ],
        )
    return pos

def restart(i, calculator, initatoms):
    for f in os.listdir():
        os.remove(f)
    abinit_run(i, calculator, initatoms)

def abinit_run(i, calculator, initatoms):
    at = abinit_random_structure(initatoms)
    at.set_calculator(calculator)
    at.get_forces()
    os.rename("abinit.txt", "abinit.out")
    copyfile("abinit.out", "../../saved_results/{:06}.out".format(i))
    for f in os.listdir():
        if f.startswith("abinito_"):
            os.remove(f)
    print("Calculation {:06} completed.\n".format(i))
    os.chdir("../")

def abinit_random_structure(initatoms):
    at = deepcopy(initatoms)
    atoms_idx = np.arange(len(at))
    n_translations = np.random.randint(len(at)) + 1
    trans_idx = np.random.choice(atoms_idx, n_translations)
    for j in trans_idx:
        phi = 2 * np.pi * np.random.rand()
        theta = np.arccos(2 * np.random.rand() - 1)
        r = -0.1
        while r < 0:
            r = np.random.normal(scale=0.1)
        at.positions[j] = at.positions[j] + np.array(
            [
                r * np.sin(theta) * np.cos(phi),
                r * np.sin(theta) * np.sin(phi),
                r * np.cos(theta),
            ]
        )
    return at

if __name__ == "__main__":
    parser = create_parser()
    args = parser.parse_args()
    main(args)


from ast import parse
from ast_graph_generator import AstGraphGenerator
import os
import gzip
import json
from tqdm import tqdm
import re
import pickle
import multiprocess as mp
import sys
from pathlib import Path
import codecs
home_path = str(Path.home())
sys.path.append(home_path + '/GitHub/graph-based-search/parsers/sourcecode/java/')
from build_java_graph import *
RAW_FILE = os.path.join(home_path, 'data/code_search_data/CodeSearchNet/resources/data/python/final/jsonl')
PYTHON_BASE = os.path.join(home_path,
                           'data/code_search_data/CodeSearchNet/resources/data/python_dedupe_definitions_v2.pkl')
BASE_GRAPH_FILE = os.path.join(home_path, 'data/code_search_data/CodeSearchNet/resources/data/python_base_gz')

def post_process():
    all_samples = load_data(RAW_FILE)
    process_list = []
    for key in all_samples.keys():
        process = mp.Process(target=single_post_process,
                             args=(key, all_samples[key]))
        process_list.append(process)
        process.start()
    for process in process_list:
        process.join()

def single_post_process(key, chunk):
    file_graph_name = os.path.join(os.path.join(RAW_FILE, key), 'graph_' + key + '_gnn.jsonl.gz')
    count = 0
    with gzip.GzipFile(file_graph_name, 'wb') as gnn_file:
        for raw_sample in tqdm(chunk):
            try:
                graph = build_python_graph(raw_sample['code'])
                if graph and len(graph['node_labels']) <= 200:
                    raw_sample['code_graph'] = normalize_graph(graph)
                else:
                    continue
                if raw_sample['docstring_tokens']:
                    doc_summary = ' '.join(re.sub(r'[^A-Za-z0-9 ]+', ' ',
                                                  ' '.join(raw_sample['docstring_tokens'])).split())
                    if doc_summary:
                        doc_graph = build_desc_graph(doc_summary)
                        raw_sample['doc_graph'] = normalize_des_graph(doc_graph)
                else:
                    raw_sample['doc_graph'] = {}
                if raw_sample['code_graph'] and raw_sample['doc_graph']:
                    save_sample_to_jsonl_gz(raw_sample, gnn_file)
                    count += 1
                del raw_sample
            except:
                continue
        print('there are %d samples have code graph and doc graph in %s' % (count, key))
        gnn_file.close()

def build_python_graph(code):
    try:
        visitor = AstGraphGenerator()
        visitor.visit(parse(code))
        edge_list = [(t, origin, destination)
                     for (origin, destination), edges
                     in visitor.graph.items() for t in edges]
        graph_node_labels = [label.strip() for (_, label) in sorted(visitor.node_label.items())]
        graph = {"edges": edge_list, "backbone_sequence": visitor.terminal_path, "node_labels": graph_node_labels}
    except:
        # print('sample %s build code graph failed' % index)
        graph = {}
    return graph

def subtokenizer(identifier):
    # Tokenizes code identifiers
    splitter_regex = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)')
    identifiers = re.split('[._\-]', identifier)
    subtoken_list = []

    for identifier in identifiers:
        matches = splitter_regex.finditer(identifier)
        for subtoken in [m.group(0) for m in matches]:
            subtoken_list.append(subtoken)

    return subtoken_list

def normalize_graph(graph):
    node_labels = graph['node_labels']
    backbone_sequence = graph['backbone_sequence']
    formatted_node_labels = []
    for index, node_label in enumerate(node_labels):
        formatted_node_labels.append({'id': index, 'contents': node_label, 'type': node_label})
    index = 0
    mapping = {}
    nodes_to_subtokenize = {}
    token_sequential_list = []
    seq_token_in_node = []
    method_nodes = []
    method_edges = []
    for i, sorted_node in enumerate(formatted_node_labels):
        if i in backbone_sequence:
            subtokens = subtokenizer(sorted_node['contents'])
            if len(subtokens) > 1:
                for subtoken in subtokens:
                    dummy_node = sorted_node.copy()
                    dummy_node['contents'] = subtoken
                    dummy_node['id_sorted'] = index
                    dummy_node['subtoken'] = True
                    dummy_node['ori_token'] = sorted_node['contents']
                    token_sequential_list.append(subtoken)
                    seq_token_in_node.append(index)
                    method_nodes.append(dummy_node)
                    if sorted_node['id'] not in mapping.keys():
                        mapping[sorted_node['id']] = index
                    if sorted_node['id'] not in nodes_to_subtokenize.keys():
                        nodes_to_subtokenize[sorted_node['id']] = [index]
                    else:
                        nodes_to_subtokenize[sorted_node['id']].append(index)
                    index += 1
            else:
                sorted_node['id_sorted'] = index
                sorted_node['subtoken'] = False
                method_nodes.append(sorted_node)
                mapping[sorted_node['id']] = index
                seq_token_in_node.append(index)
                token_sequential_list.append(sorted_node['contents'])
                index += 1
        else:
            sorted_node['id_sorted'] = index
            method_nodes.append(sorted_node)
            mapping[sorted_node['id']] = index
            index += 1
    edge_label_dict = {'child': 'AST_CHILD', 'NextToken': 'NEXT_TOKEN', 'computed_from': 'COMPUTED_FROM',
                       'last_use': 'LAST_USE', 'last_write': 'LAST_WRITE'}
    for edge in graph['edges']:
        if edge[0] in edge_label_dict.keys():
            method_edges.append({'type': edge_label_dict[edge[0]], 'sourceId': mapping[edge[1]], 'destinationId': mapping[edge[2]]})
    for key in nodes_to_subtokenize.keys():
        for index in range(1, len(nodes_to_subtokenize[key])):
            edge = {}
            edge['type'] = 'SUB_TOKEN'
            edge['sourceId'] = nodes_to_subtokenize[key][index-1]
            edge['destinationId'] = nodes_to_subtokenize[key][index]
            method_edges.append(edge)
    if not len(seq_token_in_node) == len(token_sequential_list):
        code_graph = {}
    else:
        code_graph = {'nodes': method_nodes, 'edges': method_edges, 'seq_token_in_node': seq_token_in_node,
                      'tokens': token_sequential_list}
    return code_graph

def load_data(file_folder):
    partition_folders = os.listdir(file_folder)
    all_samples = {}
    for folder in partition_folders:
        samples = []
        files = os.listdir(os.path.join(file_folder, folder))
        for file in files:
            if file.startswith('python') and file.endswith('.gz'):
                with gzip.open(os.path.join(file_folder, folder, file)) as f:
                    for line in f:
                        samples.append(json.loads(line.decode('utf-8')))
        all_samples[folder] = samples
    return all_samples

def build_python_base_graphs():
    definitions = pickle.load(open(PYTHON_BASE, 'rb'))
    chunk_samples = list(chunks(definitions, 100000))
    print('there are %d chunks' % len(chunk_samples))
    process_list = []
    for index in range(len(chunk_samples)):
        process = mp.Process(target=single_post_base_process,
                             args=(chunk_samples[index], index))
        process_list.append(process)
        process.start()
    for process in process_list:
        process.join()

def single_post_base_process(raw_samples, index):
    count = 0
    if not os.path.exists(BASE_GRAPH_FILE):
        os.makedirs(BASE_GRAPH_FILE)
    with gzip.GzipFile(os.path.join(BASE_GRAPH_FILE, 'base_graph_gnn_' + str(index) + '.jsonl.gz'), 'wb') as gnn_file:
        for raw_sample in tqdm(raw_samples):
            function = raw_sample['function']
            graph = build_python_graph(function)
            if graph and len(graph['node_labels']) <= 200:
                raw_sample['code_graph'] = normalize_graph(graph)
                if raw_sample['code_graph']:
                    save_sample_to_jsonl_gz(raw_sample, gnn_file)
                    count += 1
                del raw_sample
            else:
                continue
        print('there are %d samples in chunk %d' % (count, index))
        gnn_file.close()

def check_data(files):
    for file in files:
        samples = []
        with gzip.open(file) as f:
            for index, line in enumerate(f):
                print(index)
                raw_sample = json.loads(line.decode('utf-8'))
                if raw_sample['docstring_tokens']:
                    doc_summary = ' '.join(re.sub(r'[^A-Za-z0-9 ]+', ' ',
                                                  ' '.join(raw_sample['docstring_tokens'])).split())
                    if doc_summary:
                        doc_graph = build_desc_graph(doc_summary)
                        if doc_graph:
                            raw_sample['doc_graph'] = normalize_des_graph(doc_graph)
                            samples.append(raw_sample)
                        else:
                            continue
                else:
                    continue
        save_to_jsonl_gz(samples, file)

def save_to_jsonl_gz(functions, file_name):
    with gzip.GzipFile(file_name, 'wb') as out_file:
        writer = codecs.getwriter('utf-8')
        for entry in functions:
            writer(out_file).write(json.dumps(entry))
            writer(out_file).write('\n')

if __name__ == "__main__":
    post_process()
    build_python_base_graphs()


from django.core.management.base import BaseCommand
from gamezilla.settings import BASE_DIR
from game.models import Game
from django.core.files import File
import pathlib

class Command(BaseCommand):
    help = "Use for creating games"
    result = []
    path = str(pathlib.Path(__file__).parent.absolute())
    games = [
        {
            "name": "Snake And Ladder",
            "code": "SNL",
            "min_player": 2,
            "max_player": 4,
            "img": "snl.jpg",
        },
        {
            "name": "Tic Tac Toe",
            "code": "TAC",
            "min_player": 2,
            "max_player": 2,
            "img": "tac.png",
        },
    ]

    def handle(self, *args, **kwargs):
        for game in self.games:
            try:
                Game.objects.get(code=game["code"])
                self.result.append(game["name"] + " is already created")
            except:
                _game = Game(
                    game_name=game["name"],
                    code=game["code"],
                    min_player=game["min_player"],
                    max_player=game["max_player"],
                )
                _game.save()
                _game.img.save(
                    game["img"], File(open(self.path + "/" + game["img"], "rb"))
                )
                self.result.append(game["name"] + " created ")
        for msg in self.result:
            self.stdout.write(self.style.SUCCESS(msg))


import sympy as sp
A = sp.Matrix([
    [1],
    [2],
    [3]])
B = sp.Matrix([
    [4],
    [5],
    [6]])
print("A的模为：", A.norm())
print("A的模的浮点数为：", A.norm().evalf())
print("A的转置矩阵为：", A.T)
print("A和B的点乘为：", A.dot(B))
print("A和B的叉乘为：", A.cross(B))

3_python在高等数学和线性代数中的应用/3_6线性代数问题的符号解和数值解/3_6_1线性代数问题的符号解及解线性方程组/1_矩阵的运算.py


import requests
BASE = "http://127.0.0.1:5000/"
USER_NAME = "duc"
data = [{"call_duration": 300000},
        {"call_duration": 150000},
        {"call_duration": 142003}]

for i in range(len(data)):
    response = requests.put(BASE+"mobie/"+USER_NAME+"/call", data[i])
    print(response.json())

response = requests.get(BASE+"mobie/"+USER_NAME +
                        "/billing")
print(response.json())


from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter as DefsFormatter
from .proc_img import merge, Image
from .pathutil import dirname, get_ext, join as join_path
from . import Deg, __doc__ as desc  # get from __init__.py

DEF_OUT_FMT = "merged%s"
parser = ArgumentParser(
    prog=__package__, description=desc, formatter_class=DefsFormatter
)
parser.add_argument("file", action="store", nargs="+", help="image file to be merged")
parser.add_argument("-o", "--output", default=DEF_OUT_FMT,
    help="output file name format, %%s means .ext and defaults to the first image's ext",  # here %% -> %
)
parser.add_argument('-a', '--angle', type=Deg, default=0, help="rotate angle, 0 means the cut-off line is horizontal")
args = parser.parse_args()

fnames: list[str] = args.file
base_path = fnames[0]
ext = get_ext(base_path)
ofname: str = args.output
d = dirname(ofname) or dirname(base_path)
if "%s" in ofname: ofname = ofname % ext
opath = join_path(d, ofname)
# l=list(im for im in map(Image.open, fnames));print(l)
imgs = tuple(im for im in map(Image.open, fnames))
base_img = imgs[0]
rotate_ang: Deg = args.angle
om = merge(imgs, base_img, rotate=rotate_ang)
for i in imgs:
    i.close()
om.save(opath)


# -*- coding: utf-8 -*-
"""
Created on Wed May  6 02:12:07 2020

@author: rabia
"""

# -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 15:43:05 2020

@author: rabia
"""
#%%
import numpy as np
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5
from Crypto import Random
from base64 import b64encode, b64decode
from Crypto.Cipher import DES3
from Crypto.Cipher import AES
import os
import os.path
from os import listdir
from os.path import isfile, join
import time
import hashlib
##key = ''.join(chr(random.randint(0, 100)) for i in range(16))
##iv = ''.join([chr(random.randint(0, 100)) for i in range(16)])
##im = plt.imread('ex.jpg')
##plt.imshow(im)
##np.savetxt("im.txt", (im.shape[0],im.shape[1]), fmt="%s")

key = b'p2r5u8x/A?D(G+KbPeShVmYq3t6v9y$B'
keydes = b'mYq3t6w9z$C&F)J@'

class AESEncr:
    def __init__(self, key):
        self.key = key

    def pad(self, s):
        return s + b"\0" * (AES.block_size - len(s) % AES.block_size)

    def encrypt(self, message, key, key_size=256):
        message = self.pad(message)
        iv = Random.new().read(AES.block_size)
        encryptor = AES.new(key, AES.MODE_CBC, iv)
        return iv + encryptor.encrypt(message)

    def encryptFile(self, fileName):
        with open(fileName, 'rb') as f:
            plaintext = f.read()
        enc = self.encrypt(plaintext, self.key)
        with open(fileName + ".enc", 'wb') as f:
            f.write(enc)
        os.remove(fileName)

    def decrypt(self, ciphertext, key):
        iv = ciphertext[:AES.block_size]
        decryptor = AES.new(key, AES.MODE_CBC, iv)
        plaintext = decryptor.decrypt(ciphertext[AES.block_size:])
        return plaintext.rstrip(b"\0")

    def decryptFile(self, fileName):
        with open(fileName, 'rb') as f:
            ciphertext = f.read()
        dec = self.decrypt(ciphertext, self.key)
        with open(fileName[:-4], 'wb') as f:
            f.write(dec)
        os.remove(fileName)
class ThreeDES():
    def __init__(self):
        self.self=self

    def pad(self, s):
        return s + b"\0" * (DES3.block_size - len(s) % DES3.block_size)

    def ThreeDESEncrypt(self, message, key, key_size=192):
        message = self.pad(message)
        iv = Random.new().read(DES3.block_size)
        encryptor = DES3.new(key, DES3.MODE_CBC, iv)
        return iv + encryptor.encrypt(message)

    def ThreeDESEncryptFile(self, fileName):
        with open(fileName,'rb') as f:
            plaintext = f.read()
        enc = self.ThreeDESEncrypt(plaintext, keydes)
        with open(fileName+".enc",'wb') as f:
            f.write(enc)
        os.remove(fileName)

    def ThreeDESDecrypt(self,ciphertext, key):
        iv = ciphertext[:DES3.block_size]
        decryptor = DES3.new(keydes, DES3.MODE_CBC, iv)
        plaintext = decryptor.decrypt(ciphertext[DES3.block_size:])
        return plaintext.rstrip(b"\0")

    def ThreeDESDecryptFile(self, fileName):
        with open(fileName,'rb') as f:
            ciphertext = f.read()
        dec = self.ThreeDESDecrypt(ciphertext, keydes)
        with open(fileName[:-4],'wb') as f:
            f.write(dec)
        os.remove(fileName)

class RSAENC():
    def __init__(self,keypair,publicKey,privateKey):
        self.publicKey = publicKey
        self.privateKey = privateKey
        self.keypair = keypair

    def RSAEncrypt(self,message):
        encryptor = PKCS1_OAEP.new(self.publicKey)
        encrypted = encryptor.encrypt(message)
        return encrypted

    def RSAFileEncrypt(self,fileName):
        with open(fileName,'rb') as f:
            plaintext = f.read()
        enc = self.AESEncrypt(plaintext)
        with open(fileName+".enc",'wb') as f :
            f.write(enc)
        os.remove(fileName)

    def RSADecrypt(self,message):
        decryptor = PKCS1_OAEP.new(self.keypair)
        decrypted = decryptor.decrypt(message)
        return decrypted

    def RSAFileDecrypt(self,fileName):
        with open(fileName,'rb') as f:
            ciphertext = f.read()
        dec = self.AESDecrypt(ciphertext)
        with open(fileName[:-4],'wb') as f:
            f.write(dec)
        os.remove(fileName)

class Hash():
    def __init__(self):
        self.self = self

    def sha512enc(self,plaintext):
        res = hashlib.sha512(plaintext)
        return res.hexdigest()

    def sha512fileEncr(self,fileName):
        with open(fileName,'rb') as f:
            plaintext = f.read()
        dec = self.sha512enc(plaintext)
        with open(fileName+".enc",'w') as f:
            f.write(dec)
        os.remove(fileName)


class Blueprint:
        def __init__(self, line):
            #Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian.
            parts = line.split(':')
            self.id = int(parts[0].split(' ')[1].strip(':'))
            bot_costs = [s.strip() for s in parts[1].split('.')]
            self.ore_bot_cost = int(bot_costs[0].split(' ')[4])
            self.clay_bot_cost = int(bot_costs[1].split(' ')[4])
            self.obsidian_bot_cost_ore = int(bot_costs[2].split(' ')[4])
            self.obsidian_bot_cost_clay = int(bot_costs[2].split(' ')[7])
            self.geode_bot_cost_ore = int(bot_costs[3].split(' ')[4])
            self.geode_bot_cost_obsidian = int(bot_costs[3].split(' ')[7])

        def __str__(self):
            return f"Blueprint {self.id}: \n  Each ore robot costs {self.ore_bot_cost} ore.\n  Each clay robot costs {self.clay_bot_cost} ore.\n  Each obisidian robot costs {self.obsidian_bot_cost_ore} ore and {self.obsidian_bot_cost_clay} clay\n  Each geode robot costs {self.geode_bot_cost_ore} ore and {self.geode_bot_cost_obsidian} obsidian"

class MineState:
    def __init__(self, blueprint):
        self.geodes = 0
        self.ore = 0
        self.obsidian = 0
        self.clay = 0
        self.ore_bot_count = 1
        self.clay_bot_count = 0
        self.obsidian_bot_count = 0
        self.geode_bot_count = 0
        self.blueprint = blueprint
        self.building_ore_bot = False
        self.building_clay_bot = False
        self.building_obsidian_bot = False
        self.building_geode_bot = False

    def copy_values(self, copy_from):
        self.geodes = copy_from.geodes
        self.ore = copy_from.ore
        self.obsidian = copy_from.obsidian
        self.clay = copy_from.clay
        self.ore_bot_count = copy_from.ore_bot_count
        self.clay_bot_count = copy_from.clay_bot_count
        self.obsidian_bot_count = copy_from.obsidian_bot_count
        self.geode_bot_count = copy_from.geode_bot_count
        self.blueprint = blueprint
        self.building_ore_bot = copy_from.building_ore_bot
        self.building_clay_bot = copy_from.building_clay_bot
        self.building_obsidian_bot = copy_from.building_obsidian_bot
        self.building_geode_bot = copy_from.building_geode_bot

    def full_state_hash_key(self):
        return f"{self.ore},{self.obsidian},{self.clay},{self.bot_state_hash_key()}"

    def bot_state_hash_key(self):
        return f"{self.ore_bot_count}-{self.building_ore_bot},{self.clay_bot_count}-{self.building_clay_bot},{self.obsidian_bot_count}-{self.building_obsidian_bot},{self.geode_bot_count}-{self.building_geode_bot}"

    def can_manufacture_ore_bot(self):
        return self.ore >= self.blueprint.ore_bot_cost

    def can_manufacture_clay_bot(self):
        return self.ore >= self.blueprint.clay_bot_cost

    def can_manufacture_obsidian_bot(self):
        return self.ore >= self.blueprint.obsidian_bot_cost_ore and self.clay >= self.blueprint.obsidian_bot_cost_clay

    def can_manufacture_geode_bot(self):
        return self.ore >= self.blueprint.geode_bot_cost_ore and self.obsidian >= self.blueprint.geode_bot_cost_obsidian

    def manufacture_ore_bot(self):
        self.ore -= self.blueprint.ore_bot_cost
        self.building_ore_bot = True

    def manufacture_clay_bot(self):
        self.ore -= self.blueprint.clay_bot_cost
        self.building_clay_bot = True

    def manufacture_obsidian_bot(self):
        self.ore -= self.blueprint.obsidian_bot_cost_ore
        self.clay -= self.blueprint.obsidian_bot_cost_clay
        self.building_obsidian_bot = True

    def manufacture_geode_bot(self):
        self.ore -= self.blueprint.geode_bot_cost_ore
        self.obsidian -= self.blueprint.geode_bot_cost_obsidian
        self.building_geode_bot = True

    def mine(self):
        self.ore += self.ore_bot_count
        self.clay += self.clay_bot_count
        self.obsidian += self.obsidian_bot_count
        self.geodes += self.geode_bot_count
        if self.building_ore_bot:
            self.ore_bot_count += 1
            self.building_ore_bot = False
        if self.building_clay_bot:
            self.clay_bot_count += 1
            self.building_clay_bot = False
        if self.building_obsidian_bot:
            self.obsidian_bot_count += 1
            self.building_obsidian_bot = False
        if self.building_geode_bot:
            self.geode_bot_count += 1
            self.building_geode_bot = False

def check_branches(mine_state, branch_hashes):
    new_states = []
    if mine_state.can_manufacture_geode_bot():
        new_state = MineState(mine_state.blueprint)
        new_state.copy_values(mine_state)
        new_state.manufacture_geode_bot()
        if (new_state.full_state_hash_key() not in branch_hashes):
            branch_hashes.add(new_state.full_state_hash_key())
            new_states.append(new_state)
    if mine_state.can_manufacture_obsidian_bot():
        new_state = MineState(mine_state.blueprint)
        new_state.copy_values(mine_state)
        new_state.manufacture_obsidian_bot()
        if (new_state.full_state_hash_key() not in branch_hashes):
            branch_hashes.add(new_state.full_state_hash_key())
            new_states.append(new_state)
    if mine_state.can_manufacture_ore_bot():
        new_state = MineState(mine_state.blueprint)
        new_state.copy_values(mine_state)
        new_state.manufacture_ore_bot()
        if (new_state.full_state_hash_key() not in branch_hashes):
            branch_hashes.add(new_state.full_state_hash_key())
            new_states.append(new_state)
    if mine_state.can_manufacture_clay_bot():
        new_state = MineState(mine_state.blueprint)
        new_state.copy_values(mine_state)
        new_state.manufacture_clay_bot()
        if (new_state.full_state_hash_key() not in branch_hashes):
            branch_hashes.add(new_state.full_state_hash_key())
            new_states.append(new_state)

    return new_states

def prune_poor_branches(active_branches, min_geodes):
    result = []
    for branch in active_branches:
        if branch.geodes >= min_geodes:
            result.append(branch)
    return result

def run_simulation(blueprint, minutes, trim_offset):
    start_state = MineState(blueprint)
    branch_hashes = set()
    active_branches = [start_state]
    branch_hashes.add(start_state.bot_state_hash_key())
    for time in range(minutes):
        max_geodes = 0
        for branch in active_branches:
            if branch.geodes > max_geodes:
                max_geodes = branch.geodes
        print("Max geodes: " + str(max_geodes))
        active_branches = prune_poor_branches(active_branches, max_geodes - trim_offset)
        for branch in active_branches.copy():
            new_branches = check_branches(branch, branch_hashes)
            for new_branch in new_branches:
                new_branch.mine()
            branch.mine()
            if len(new_branches) > 0:
                active_branches.extend(new_branches)
        print(f"Minute {time}, {len(active_branches)} branches")
    max_geodes = 0
    for branch in active_branches:
        if branch.geodes > max_geodes:
            max_geodes = branch.geodes
    return max_geodes

file = open('day19_input.txt', 'r')
blueprints = [Blueprint(s.strip('\n')) for s in file.readlines()]

id_geodes = {}
for blueprint in blueprints:
    max_geodes = run_simulation(blueprint, 24, 0)
    id_geodes[blueprint.id] = max_geodes
    print(f"Blueprint {blueprint.id} can produce {max_geodes} geodes")

total_quality_level = 0
for blueprint in blueprints:
    blueprint_quality = blueprint.id * id_geodes[blueprint.id]
    total_quality_level += blueprint_quality

print(f"Answer 1: {total_quality_level}")

id_geodes = {}
total_quality_level = 1
for blueprint in blueprints[:3]:
    max_geodes = run_simulation(blueprint, 32, 2)
    total_quality_level *= max_geodes
    print(f"Blueprint {blueprint.id} can produce {max_geodes} geodes")

print(f"Answer 2: {total_quality_level}")


# -*- coding: utf-8 -*-
import unittest

class Bot():

    def __init__(self, owner_name):
        self.owner_name = name

    def reply(self, call):
        if self.owner_name in call:
            return "Hello my Boss!"
        else:
            return "Hello"

class TestBot(unittest.TestCase):

    def test_bot_reply(self):
        bot = Bot("Angy")
        self.assertEqual("Hello", bot.reply("Hi, I'm Bill.'"))
        self.assertEqual("Hello my Boss!", bot.reply("Hi, I'm Angy."))

if __name__ == "__main__":
    unittest.main()


from constant import BASE_URL

def _get_semester_info(tr):
    td = tr.find_all("td")[0]
    return td.find_all("b")[0].text

def _course_result(tr):
    tds = tr.find_all("td")
    return {
        'course_code': tds[0].text,
        'course_name': tds[1].text,
        'credit': int(tds[3].text),
        'grade': tds[4].text
    }

def _scrap_table(table):
    trs = table.find_all("tr")
    semester = _get_semester_info(trs[1])
    result = []
    for tr in trs[2:]:
        result.append(_course_result(tr))
    return semester, result

POINT_SCHEME = {
    "A": 10,
    "B": 8,
    "C": 6,
    "D": 4,
    "F": 0
}

def _semester_aggregate_info(result):
    credits_earned = 0
    points_earned = 0
    for subject in result:
        credits_earned += subject["credit"]
        points_earned += POINT_SCHEME.get(subject["grade"], 0) * subject["credit"]
    total_points = credits_earned * 10
    sgpa = points_earned / total_points * 10

    return {
        'credits_earned': credits_earned,
        'points_earned': points_earned,
        'total_points': total_points,
        'sgpa': f"{sgpa:.2f}"
    }

def _get_aggregate_info(result):
    total_points = 0
    total_earned_points = 0
    total_credits = 0
    for key, value in result.items():
        try:
            _ = int(key)  # check it's semester number
            total_credits += value["aggregate_info"]["credits_earned"]
            total_earned_points += value["aggregate_info"]["points_earned"]
            total_points += value["aggregate_info"]["total_points"]
        except:
            pass
    cgpa = total_earned_points / total_points * 10
    return {
        'total_points': total_points,
        'total_earned_points': total_earned_points,
        'total_credits': total_credits,
        'cgpa': f"{cgpa:.2f}"
    }

def transcript(browser):
    url = f"{BASE_URL}/transcript.do"
    browser.open(url)

    tables = browser.find_all("table")

    _transcript = {}
    semester_number = 1
    for table in tables[:-3]:
        sem, result = _scrap_table(table)
        _transcript[str(semester_number)] = {
            "semester": sem,
            "result": result,
            "aggregate_info": _semester_aggregate_info(result)
        }
        semester_number += 1

    _transcript["aggregate"] = _get_aggregate_info(_transcript)

    return _transcript


#!/usr/bin/python3
'''define class'''

class Square:
    '''square attributes'''

    def __init__(self, size=0):
        '''init square'''
        if type(size) is int:
            if size < 0:
                raise ValueError('size must be >= 0')
            else:
                self.__size = size
        else:
            raise TypeError('size must be an integer')


import argparse
import logging

from discord.ext import commands

import tekinbot.utils.db as du
from tekinbot.comms import tekin_extensions
from tekinbot.utils.config import tekin_secrets

log = logging.getLogger(__name__)

def tekin_args():
    parser = argparse.ArgumentParser(
        description='TekinBot Server'
    )
    parser.add_argument(
        '--dry-run', dest='dry_run', action='store_true',
        help=('set up Tekin for dry running; Tekin will print all '
              'posting actions to stdout, instead of sending Requests'
              ),
    )
    parser.add_argument(
        '--no-db', dest='nodb', action='store_true',
        help=('tekin will not read or write anything to database, '
              'everything will be performed either in a dry run fashion '
              'or in memory'
              ),
    )
    return parser.parse_args()

class TekinBot(commands.Bot):

    description = (
        "TaaD: Tekin (a knowledgeable and possibly friendly professor) "
        "as a DiscordBot"
    )

    def __init__(self, args):
        super().__init__(
            command_prefix=commands.when_mentioned,
            description=self.description,
        )
        # set up db here
        du.tekin_db_init(args.nodb)

        self.token = tekin_secrets('discord.bot_token')

        self.theme = None

        for ext in tekin_extensions:
            self.load_extension(ext)

    def run(self):
        super().run(self.token, reconnect=True)

if __name__ == '__main__':
    args = tekin_args()
    tekinbot = TekinBot(args)
    tekinbot.run()


#!/usr/bin/python
import requests
import pytest
import sys
import json
import pytest

def main(argv):
 testCountry()
 testCountry2()

def getCapital(country):
 url = "https://restcountries.eu/rest/v2/name/{country}".format(country=country)
 response = requests.get(url)
 json_data = response.json()
 if (len(json_data)) >= 2:
  return json_data[1][u'capital']
 else:
  return json_data[0][u'capital']

def testCountry():
    assert getCapital("india") == "New Delhi"
    assert getCapital("pakistan") == "Islamabad"

def testCountry2():
    assert getCapital("america") != "Washington"
    assert getCapital("an") != "Islamabad"

if __name__  == "__main__":
 main()


import glob
import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
import networkx as nx
import os
import queue
import re

from datetime import datetime
from threading import Lock, Thread

def _extract(g, lk, trd_cnt, prt):
    sd = 'graph' if os.getenv('MD', 'G') == 'G' else 'sample'
    st_tm = datetime.strptime(os.getenv('ST_TM', ''), '%Y-%m-%d-%H')
    sp_tm = datetime.strptime(os.getenv('SP_TM', ''), '%Y-%m-%d-%H')
    for fn in glob.glob(f'./data/{sd}/*.txt'):
        fn_tm = datetime.strptime(fn, f'./data/{sd}/%Y-%m-%d-%H.txt')
        if fn_tm < st_tm or fn_tm > sp_tm or fn_tm.timetuple().tm_yday % trd_cnt != prt:
            continue
        with open(fn, 'r') as fr:
            for l in fr.readlines():
                v1, v2, r, _ = l.split('\t')
                with lk:
                    if v1 not in g:
                        g[v1] = set()
                    g[v1].add(v2)

                    # NOTE: To find nodes with the most interactions
                    if v2 not in g:
                        g[v2] = set()
                    g[v2].add(v1)

def extract():
    g = {}
    lk = Lock()
    trd_cnt = int(os.getenv('TRD_CNT', '8'))
    ts = []
    for i in range(0, trd_cnt):
        t = Thread(target=_extract, args=(g, lk, trd_cnt, i))
        t.start()
        ts.append(t)
    for t in ts:
        t.join()
    return g

def _transform(tg, g, gk, lk, trd_cnt, prt):
    for i, v in enumerate(gk):
        if i % trd_cnt != prt:
            continue
        tp_rx = re.compile(r'/(.*)/.*')
        tp = re.findall(tp_rx, v)[0]
        nv = len(g[v])
        with lk:
            if tp not in tg:
                tg[tp] = set()
            tg[tp].add((nv, v))

def transform(g):
    tg = {}
    lk = Lock()
    gk = sorted(g.keys())
    trd_cnt = int(os.getenv('TRD_CNT', '8'))
    ts = []
    for i in range(0, trd_cnt):
        t = Thread(target=_transform, args=(tg, g, gk, lk, trd_cnt, i))
        t.start()
        ts.append(t)
    for t in ts:
        t.join()
    return tg

def _bfs(viz_g, g, viz_pl, viz_d, trd_cnt, prt):
    for i, (dx, x) in enumerate(viz_pl):
        if i % trd_cnt != prt:
            continue
        tp_rx = re.compile(r'/(.*)/(.*)')
        tp, pk = re.findall(tp_rx, x)[0]

        vs = set()
        mk = set()
        q = queue.Queue()
        mk.add(x)
        q.put((x, 0))
        while not q.empty():
            v, d = q.get()
            if d > viz_d:
                continue
            vs.add(v)
            for n in g[v] - mk:
                mk.add(n)
                q.put((n, d + 1))

        k = f'{dx}_{tp}_{pk}'
        for v in vs:
            if k not in viz_g:
                viz_g[k] = set()
            for u in (vs & g[v]):
                # NOTE: To reduce memory footprint
                viz_g[k].add((max(v, u), min(v, u)))

def bfs(g, tg):
    viz_cnt = int(os.getenv('VIZ_CNT', '10'))
    viz_pl = []
    for k, v in tg.items():
        sv = sorted(v, reverse=True)
        viz_pl += sv[-viz_cnt:]
        viz_pl += sv[(len(sv) - viz_cnt) // 2:(len(sv) - viz_cnt) // 2 + viz_cnt]
        viz_pl += sv[:viz_cnt]

    viz_g = {}
    lk = Lock()
    viz_d = int(os.getenv('VIZ_D', '3'))
    trd_cnt = int(os.getenv('TRD_CNT', '8'))
    ts = []
    for i in range(0, trd_cnt):
        t = Thread(target=_bfs, args=(viz_g, g, viz_pl, viz_d, trd_cnt, i))
        t.start()
        ts.append(t)
    for t in ts:
        t.join()
    return viz_g

def _build(plt_g, viz_g, viz_gk, cm, lk, trd_cnt, prt):
    for i, k in enumerate(viz_gk):
        if i % trd_cnt != prt:
            continue

        tp_rx = re.compile(r'/(.*)/.*')

        vs = []
        for v in set(itertools.chain.from_iterable(viz_g[k])):
            tp = re.findall(tp_rx, v)[0]
            vs.append((v, {'color': cm[tp]}))

        es = []
        for v, u in viz_g[k]:
            tp = re.findall(tp_rx, v)[0]
            es.append((v, u, {'color': cm[tp]}))

        net = nx.Graph()
        net.add_nodes_from(vs)
        net.add_edges_from(es)

        plt_g.append((net, k))

def build(viz_g):
    from configs.graph import schema as cfg_schema

    cm = {}
    cp = ['#f0134d', '#ffcc00', '#f5f0e3', '#c0ffb3', '#05dfd7', '#d89cf6', '#ffb6b9', '#ff4d00', '#be7575']
    for i, tp in enumerate(sorted(cfg_schema.schema.keys())):
        cm[tp] = cp[i]

    plt_g = []
    lk = Lock()
    viz_gk = sorted(viz_g.keys())
    trd_cnt = int(os.getenv('TRD_CNT', '8'))
    ts = []
    for i in range(0, trd_cnt):
        t = Thread(target=_build, args=(plt_g, viz_g, viz_gk, cm, lk, trd_cnt, i))
        t.start()
        ts.append(t)
    for t in ts:
        t.join()
    return plt_g, cm

def plot(plt_g, cm):
    for net, k in sorted(plt_g, key=lambda x: x[0].number_of_nodes()):
        tp_rx = re.compile(r'([^_]*)_(.*)_([^_]*)')
        d, tp, pk = re.findall(tp_rx, k)[0]

        dir_pth = f'./results/visualizations/local/{tp}'

        if os.path.exists(f'{dir_pth}/{d}_{pk}.png'):
            continue

        if not os.path.isdir(dir_pth):
            os.mkdir(dir_pth)

        fig = plt.figure(figsize=(100, 100))
        ax = fig.add_subplot(111)
        ax.set_facecolor('black')

        nc = [d['color'] for _, d in net.nodes(data=True)]
        ec = [d['color'] for _, _, d in net.edges(data=True)]
        pos = nx.fruchterman_reingold_layout(net)
        nx.draw_networkx(net,
                         pos,
                         node_size=600,
                         node_color=nc,
                         edgecolors='white',
                         linewidths=2.0,
                         edge_color=ec,
                         width=2.0,
                         with_labels=False)

        plt.legend(framealpha=0.5,
                   loc='upper left',
                   prop={'size': 48},
                   handles=[mpl.lines.Line2D([], [], linewidth=20, label=k, color=v) for k, v in cm.items()])

        plt.tight_layout()
        plt.savefig(f'{dir_pth}/{d}_{pk}.png', format='PNG')
        plt.close(fig)

def main():
    g = extract()
    tg = transform(g)
    viz_g = bfs(g, tg)
    plt_g, cm = build(viz_g)
    plot(plt_g, cm)

if __name__ == '__main__':
    main()


import logging
from typing import Dict, Optional
from urllib.parse import parse_qs, urlparse

import httpx
from bs4 import BeautifulSoup
from httpcore import ConnectError

logger = logging.getLogger("audible.localization")

LOCALE_TEMPLATES = {
    "germany": {
        "country_code": "de",
        "domain": "de",
        "market_place_id": "AN7V1F1VY261K"
    },
    "united_states": {
        "country_code": "us",
        "domain": "com",
        "market_place_id": "AF2M0KC94RCEA"
    },
    "united_kingdom": {
        "country_code": "uk",
        "domain": "co.uk",
        "market_place_id": "A2I9A3Q2GNFNGQ"
    },
    "france": {
        "country_code": "fr",
        "domain": "fr",
        "market_place_id": "A2728XDNODOQ8T"
    },
    "canada": {
        "country_code": "ca",
        "domain": "ca",
        "market_place_id": "A2CQZ5RBY40XE"
    },
    "italy": {
        "country_code": "it",
        "domain": "it",
        "market_place_id": "A2N7FU2W2BU2ZC"
    },
    "australia": {
        "country_code": "au",
        "domain": "com.au",
        "market_place_id": "AN7EY7DTAW63G"
    },
    "india": {
        "country_code": "in",
        "domain": "in",
        "market_place_id": "AJO3FBRUE6J4S"
    },
    "japan": {
        "country_code": "jp",
        "domain": "co.jp",
        "market_place_id": "A1QAP3MOU4173J"
    },
    "spain": {
        "country_code": "es",
        "domain": "es",
        "market_place_id": "ALMIKO4SZCSAR"
    }
}

def search_template(key: str, value: str) -> Optional[Dict[str, str]]:
    for country in LOCALE_TEMPLATES:
        locale = LOCALE_TEMPLATES[country]
        if locale[key] == value:
            logger.debug(f"found locale for {country}")
            return locale

    logger.info(f"don\'t found {value} in {key}")
    return None

def autodetect_locale(domain: str) -> Dict[str, str]:
    """Try to automatically detect correct settings for marketplace.

    Needs the top level domain of the audible page to continue with
    (e.g. co.uk, co.jp) and returns results found.

    Args:
        domain: The top level domain for the Audible marketplace to
            detect settings for (e.g. com).

    Returns:
        The settings for the found Audible marketplace.
    """

    domain = domain.lstrip(".")
    site = f"https://www.audible.{domain}"
    params = {"ipRedirectOverride": True, "overrideBaseCountry": True}

    try:
        resp = httpx.get(site, params=params)
    except ConnectError as e:
        logger.warning(f"site {site} doesn\'t exists or Network Error occours")
        raise e

    soup = BeautifulSoup(resp.text, "html.parser")

    login_link = soup.find("a", class_="ui-it-sign-in-link")["href"]
    parsed_link = urlparse(login_link)
    query_string = parse_qs(parsed_link.query)
    market_place_id = query_string['marketPlaceId'][0]
    country_code = query_string['pageId'][0].split("_")[-1]

    return {
        "country_code": country_code,
        "domain": domain,
        "market_place_id": market_place_id
    }

class Locale:
    """
    Adjustments for the different marketplaces who are provided by Audible.

    You can try to ``autodetect_locale`` if your marketplace is
    not in templates`.

    """

    def __init__(
            self,
            country_code: Optional[str] = None,
            domain: Optional[str] = None,
            market_place_id: Optional[str] = None) -> None:

        if not all([country_code, domain, market_place_id]):
            locale = None
            if country_code:
                locale = search_template("country_code", country_code)
            elif domain:
                locale = search_template("domain", domain)

            if locale is None:
                raise Exception("can\'t find locale")

        self._country_code = country_code or locale["country_code"]
        self._domain = domain or locale["domain"]
        self._market_place_id = market_place_id or locale["market_place_id"]

    def __repr__(self):
        return (
            f"Locale class for domain: {self.domain}, "
            f"marketplace: {self.market_place_id}"
        )

    def to_dict(self) -> Dict[str, str]:
        return {
            "country_code": self.country_code,
            "domain": self.domain,
            "market_place_id": self.market_place_id
        }

    @property
    def country_code(self) -> str:
        return self._country_code

    @property
    def domain(self) -> str:
        return self._domain

    @property
    def market_place_id(self) -> str:
        return self._market_place_id


import openpyxl
import sys
import json
import os

# Help information
def PrintHelp():
    print("ISA Excel file analysis tool.")
    print("Usage:")
    print("  -v")
    print("  --version    Show tool current version.")
    print("  -V")
    print("  --verbose    Show more debug information.")
    print("  -c")
    print("  --check      Print encoding information with lit check prefix.")
    print("  -C=filename")
    print("  --configs=filename    Indicate the custom configuration file.")
    print("  -h")
    print("  --help       Show help infomation")

# Parse arguments
isVerbose = False
printLitCheck = False
customConfigs = ""
if len(sys.argv) != 1:
    for index,arg in enumerate(sys.argv[1:]):
        if arg == "-V" or arg == "--verbose":
            isVerbose = True
        elif arg == "-c" or arg == "--check":
            printLitCheck = True
        elif arg == "-v" or arg == "--version":
            print("ISA Excel file analysis tool.")
            print("Version : 0.2")
            exit(0)
        elif arg.startswith("-C=") or arg.startswith("--configs="):
            customConfigs = arg[arg.find("=")+1:]
            print(customConfigs)
        elif arg == "-h" or arg == "--help":
            PrintHelp()
            exit(0)
        else:
            PrintHelp()
            exit(0)

# Open configuration file
if os.path.exists("configs.json"):
    cfgFile = open("configs.json", 'r')
elif customConfigs:
    try:
        cfgFile = open(customConfigs, 'r')
    except FileNotFoundError as err:
        print("Error: Can not find configuration file: " + customConfigs)
        exit(-1)
else:
    print("Error: Can not find configuration file")
    exit(-1)
cfgs = json.loads(cfgFile.read())
cfgFile.close()

register = cfgs['register']
operandsEncode = cfgs['operandsEncode']
excelFile = cfgs['excelFileName']

# Open ISA excel file
try:
    xml = openpyxl.load_workbook(excelFile)
    sheets = xml.sheetnames
except FileNotFoundError as err:
    print("Error: Can not find ISA file: " + excelFile)
    exit(-1)

# Interactive instruction check
# Select excel sheet
print("Sheets:")
for index,names in enumerate(sheets):
    print(names + " --- " + str(index))
selectSheet = input("Select sheet: ")
table = xml[sheets[int(selectSheet)]]

max_row = table.max_row
instrFormat = []
encode = []
instrEncode = []

for r in table.rows:
    instrFormat.append(r[2].value)
    for i in range(3, 3+31):
        v = r[i].value
        t = i
        while v == None:
            t = t - 1
            v = r[t].value
        f = str(v).find('_')
        if f != -1:
            v = v[0:f]

        encode.append(v)
    instrEncode.append(encode)
    encode = []

oldInputIndex = 0
while True:
    print("========")
    searchIndex = input("Input a line number(Enter to next, Q/q to quit): ")
    space = searchIndex.find(" ")
    if searchIndex == 'q' or searchIndex == 'Q':
        exit(0)
    elif space != -1:
        beginIndex = int(searchIndex[:space])
        endIndex = int(searchIndex[space+1:])
    elif not searchIndex:
        beginIndex = oldInputIndex + 1
        endIndex = beginIndex
    else:
        beginIndex = int(searchIndex)
        endIndex = beginIndex
    oldInputIndex = endIndex

    searchEncode = []
    illegal = False
    for index in range(beginIndex, endIndex+1):
        if index > max_row:
            print("Error: input index is out of range of the table.")
            illegal = True
            break
        searchEncode.append(list(instrEncode[int(index)-1]))
        print("InstrFormat: " + instrFormat[int(index)-1])
    if isVerbose:
        print("Description Encode: " + str(searchEncode))

    if illegal:
        continue

    encodeOut = []
    # here come input searchEncode
    for encode in searchEncode:
        i = 31
        pre = []
        bins = ''
        binEncode = []
        illegal = False
        while i > 0:
            i = i - 1
            e = encode[i]
            if len(bins) > 8:
                binEncode.append(bins[-8:])
                bins = bins[:-8]

            if e == 'x':
                print("Warning: Illegal encoding bit: '" + e + "' in " + str(30-i))
                illegal = True
                break

            if e != 0 and e != 1:

                if e in operandsEncode:
                    if e in pre:
                        encode[i] = 0
                        bins = str(0) + bins
                        continue

                    op = operandsEncode[e]
                    if isVerbose:
                        print("Value of operand " + e + " is " + str(op))
                    while True:
                        if encode[i] != e:
                            print("Error: Operand encoding out of range")
                            exit(1)

                        if (op & 0b1) == 0b1:
                            encode[i] = 1
                            bins = str(1) + bins
                        else:
                            encode[i] = 0
                            bins = str(0) + bins
                        op = op >> 1
                        if op == 0:
                            break
                        i = i - 1
                    pre.append(e)
                    continue

                else:
                    print("Error: Unknown operand key")
                    illegal = True
                    break

            bins = str(e) + bins

        if illegal:
            continue

        binEncode.append(bins)

        hexEncode = []
        for e in binEncode:
            hexEncode.append('0x%02X' % int(e, 2))#hex(int(e, 2)))

        if isVerbose:
            print("Binary Encode:")
            print(encode)
        if printLitCheck:
            encodeStr = ""
            for e in hexEncode:
                encodeStr = encodeStr + "," + e
            encodeStr = encodeStr[1:].lower()
            #  print("# CHECK: " + encodeStr)
            encodeOut.append("# CHECK: " + encodeStr)
        else:
            #  print(hexEncode)
            encodeOut.append(hexEncode)

    print("Hexadecimal Encode:")
    for encode in encodeOut:
        print(encode)


#!/usr/bin/env python3

# ---<=> MODULOS <=>---
import requests
from bs4 import BeautifulSoup

# ---<=> FUNCIONES <=>---
def get_soup(url: str) -> BeautifulSoup:
    response = requests.get(url)
    return BeautifulSoup(response.content, "html.parser")

def wiki():
    soup = get_soup("https://en.wikipedia.org/wiki/List_of_states_of_Mexico")
    rows = soup.find_all("table")[0].find_all("tr")
    file = open('Scrapping.txt', "a")
    for row in rows:
        columns = row.find_all("td")
        t = [ele.text.strip() for ele in columns]
        file.write(f"{t}\n")
    file.close()

if __name__ == "__main__":
    wiki()


"""
https://quera.org/problemset/102256/
Author: https://github.com/smh997/
"""
n = int(input())
li = map(int, input().split())
k = int(input())
mod = 1000000007
ml = []
mp = {}
for amount in li:
    if amount not in mp:
        ml.append(amount)
        mp[amount] = 0
    mp[amount] += 1
ml.sort(reverse=True)
res = 0
for i, amount in enumerate(ml):
    nxt_am = ml[i + 1] if i < len(ml) - 1 else 0
    if nxt_am != amount - 1:
        tedad = mp[amount]
        rng = (amount - nxt_am) * tedad
        if k > rng:
            res = (res + (((amount * (amount + 1) // 2) - (nxt_am * (nxt_am + 1) // 2)) * tedad) % mod) % mod
            k -= rng
            mp[nxt_am] += tedad
        else:
            myrng = k // tedad
            rem = k % tedad
            nxt_am = amount - myrng
            res = (res + (((amount * (amount + 1) // 2) - (nxt_am * (nxt_am + 1) // 2)) * tedad) % mod) % mod
            res = (res + (nxt_am * rem) % mod) % mod
            k = 0
            break
    else:
        tedad = mp[amount]
        if k >= tedad:
            res = (res + (tedad * amount) % mod) % mod
            k -= tedad
            mp[amount - 1] += tedad
        else:
            res = (res + (k * amount) % mod) % mod
            k = 0
            break
print(int(res))


import webapp2
import jinja2
from google.appengine.api import users
from google.appengine.ext import ndb
import os

from myuser import MyUser
from userModel import UserModel

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True
)

class UserSignUp(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'

        user = users.get_current_user()
        logout = users.create_logout_url('/')

        myuser_key = ndb.Key('MyUser', user.user_id())
        myuser = myuser_key.get()

        actual_username = myuser.username

        template_values = {'actual_username' : actual_username, 'logout' : logout}

        template = JINJA_ENVIRONMENT.get_template('userSignUp.html')
        self.response.write(template.render(template_values))

    def post(self):
        self.response.headers['Content-Type'] = 'text/html'

        logout = users.create_logout_url('/')

        action=self.request.get('button')

        if action == 'Submit':
            user = users.get_current_user()
            myuser_key = ndb.Key('MyUser', user.user_id())
            myuser = myuser_key.get()

            username = self.request.get('username')
            actual_username = myuser.username

            if username != actual_username:
                self.response.write('***Incorrect Username!***')

            else:
                self.redirect('/userProfile?username='+username)

        if action == 'Create':
            user = users.get_current_user()
            myuser_key = ndb.Key('MyUser', user.user_id())
            myuser = myuser_key.get()

            username = self.request.get('username')
            name = self.request.get('name')
            actual_username = myuser.username

            query_username = MyUser.query(MyUser.username == username)

            unique_key = ndb.Key('UserModel', username)
            unique_user = unique_key.get()

            if query_username.count() == 0:
                if myuser.username == None:
                    myuser.username = username
                    myuser.put()

                    unique_user = UserModel(id = username,
                                            email = user.email(),
                                            username = username,
                                            name = name,)
                    unique_user.put()

                    self.redirect('/userProfile?username='+username)
            else:
                self.response.write('***Username Exists. Please choose another!***')

        template_values = {'username' : username,
                            'actual_username' : actual_username,
                            'logout' : logout}

        template = JINJA_ENVIRONMENT.get_template('userSignUp.html')
        self.response.write(template.render(template_values))