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

# # Lab 3: Bayes Classifier and Boosting

import numpy as np
from scipy import misc
from imp import reload
from labfuns import *
import random, math

# ------- DEFINITIONS OF FUNCTIONS -------

# in:      X - N x d matrix of N data points
#     labels - N vector of class labels
# out:    mu - C x d matrix of class means (mu[i] - class i mean)
#      sigma - C x d x d matrix of class covariances (sigma[i] - class i sigma)
def mlParams(X, y, W=None):
    assert(X.shape[0]==y.shape[0])
    Npts,Ndims = np.shape(X)
    classes = np.unique(y)
    Nclasses = np.size(classes)

    if W is None:
        W = np.ones((Npts,1))/float(Npts)

    mu = np.zeros((Nclasses,Ndims))
    S = np.zeros((Nclasses,Ndims,Ndims))

    for k,c in enumerate(classes):
        i = y == c                  # return True/False length of labels
        Xk = X[i,:]                 # the X with class c
        NkW = sum((i*W.T).T)        # ADDED

        Wk = W[i,:]                 # ADDED
        XkW = np.multiply(Wk,Xk)    # ADDED

        mukW = sum(XkW)/NkW
        xicW = Xk - mukW            # ADDED

        S[k,:,:] = np.diag(sum(Wk*xicW*xicW))/NkW  # ADDED Naive, (S(m,n) = 0, n != m)
        mu[k,:] = mukW

    return mu, S

# in: labels - N vector of class labels
# out: prior - C x 1 vector of class priors
def computePrior(y, W=None):
    N = y.shape[0]

    if W is None:
        W = np.ones((N,1))/N
    else:
        assert(W.shape[0] == N)

    classes = list(np.unique(y))
    yW = y*W.T
    #yOLD = list(y)

    #priorOLD = [yOLD.count(x)/float(N) for x in classes]
    #priorOLD = np.matrix(priorOLD).reshape((len(classes),1))

    prior = np.zeros((len(classes),1))
    for c in classes:
        #numerator = sum(((y == c)*W.T).T)
        #denominator = sum(W)
        #denominatorn ska inte behövas om vi vet att sum(W) alltid blir 1...
        #prior[c] = numerator/denominator
        prior[c] = sum(((y == c)*W.T).T)

    # TODO snygga till det här och ta bort lite joks

    return prior

# Bayes classifier functions to implement
# The lab descriptions state what each function should do.

# in:      X - N x d matrix of M data points
#      prior - C x 1 matrix of class priors
#         mu - C x d matrix of class means (mu[i] - class i mean)
#      sigma - C x d x d matrix of class covariances (sigma[i] - class i sigma)
# out:     h - N vector of class predictions for test points
def classifyBayes(X, prior, mu, S):

    N = X.shape[0]                          # no of points
    Ncl,Ndim = np.shape(mu)                 # no of classes and features
    logProb = np.zeros((Ncl, N))

    for k in range(Ncl):
        Sk = S[k,:,:]
        mmu = mu[k,:]

        priorK = prior[k,:]

        SdetDiag = np.prod(np.diag(Sk))
        SinvDiag = np.diag(1.0/np.diag(Sk))     # to avoid division by zero of diag elem.

        d1 = -0.5*math.log(SdetDiag)
        d2 = -0.5*sum(np.multiply((X-mmu).dot(SinvDiag),(X-mmu)).T)
        d3 = math.log(priorK)

        logProb[k,:] = d2+d1+d3

    h = np.argmax(logProb,axis=0)
    return h

# The implementd functions can now be summarized into the `BayesClassifier`
# class, which we will use later to test the classifier,
# no need to add anything else here:
# NOTE: no need to touch this
class BayesClassifier(object):
    def __init__(self):
        self.trained = False

    def trainClassifier(self, X, y, W=None):
        rtn = BayesClassifier()
        rtn.prior = computePrior(y, W)
        rtn.mu, rtn.S = mlParams(X, y, W)
        rtn.trained = True
        return rtn

    def classify(self, X):
        return classifyBayes(X, self.prior, self.mu, self.S)

# ## Boosting functions to implement
#
# The lab descriptions state what each function should do.

# in: base_classifier - a classifier of the type that we will boost, e.g. BayesClassifier
#                   X - N x d matrix of N data points
#              labels - N vector of class labels
#                   T - number of boosting iterations
# out:    classifiers - (maximum) length T Python list of trained classifiers
#              alphas - (maximum) length T Python list of vote weights
def trainBoost(base_classifier, X, y, T=10):
    # these will come in handy later on
    Npts,Ndims = np.shape(X)

    classifiers = []    # append new classifiers to this list
    alphas = []         # append the vote weight of the classifiers to this list

    # The weights for the first iteration
    wCur = np.ones((Npts,1))/float(Npts)
    #print 'init wCur= ', wCur

    for i_iter in range(T):
        # a new classifier can be trained like this, given the current weights
        classifiers.append(base_classifier.trainClassifier(X, y, wCur))

        # do classification for each point
        #vote = classifiers[-1].classify(X) # RENAMED
        ht = classifiers[-1].classify(X)

        # TODO : Fill in the rest, construct the alphas etc.
        # ==========================

        # compute priors w.r.t. current weight wCur:
        pk = computePrior(y, wCur)
        # compute errors w.r.t. current weight wCur (step 2):
        i = ht == y # i is zero if ht != ci
        et = sum((wCur.T*(1-i)).T)
        et = max(et,1e-9)           # TODO RIKTIGT FULHAXX!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        # compute alphas w.r.t. current weight wCur (step 3):
        alphat = 0.5*(math.log(1-et)-math.log(et))
        # update weights (step 4):
        wCurUN1 = i*wCur.T*math.exp(-alphat) # if ht = ci
        wCurUN2 = (1-i)*wCur.T*math.exp(alphat) # if ht != ci
        wCurUN = np.array([sum(x) for x in zip(wCurUN1, wCurUN2)])
        # normalize:
        wCur = (wCurUN/sum(wCurUN.T)).T
        alphas.append(alphat) # you will need to append the new alpha
        # ==========================

    return classifiers, alphas

# in:       X - N x d matrix of N data points
# classifiers - (maximum) length T Python list of trained classifiers as above
#      alphas - (maximum) length T Python list of vote weights
#    Nclasses - the number of different classes
# out:  yPred - N vector of class predictions for test points
def classifyBoost(X, classifiers, alphas, Nclasses):
    Npts = X.shape[0]
    Ncomps = len(classifiers)

    # if we only have one classifier, we may just classify directly
    if Ncomps == 1:
        return classifiers[0].classify(X)
    else:
        votes = np.zeros((Npts,Nclasses))

        for c in range(Nclasses):
            suM = np.zeros((Npts,1))
            for t in range(Ncomps):
                ht = classifiers[t].classify(X)
                delta = ht == c*np.ones((1,Npts))
                suM += alphas[t]*delta.reshape((Npts,1))
            votes[:,c] = suM.reshape((1,Npts))

        # one way to compute yPred after accumulating the votes
        return np.argmax(votes,axis=1)

# The implemented functions can now be summarized another classifer,
# the `BoostClassifier` class. This class enables boosting different
# types of classifiers by initializing it with the `base_classifier`
# argument. No need to add anything here.

# NOTE: no need to touch this
class BoostClassifier(object):
    def __init__(self, base_classifier, T=10):
        self.base_classifier = base_classifier
        self.T = T
        self.trained = False

    def trainClassifier(self, X, y):
        rtn = BoostClassifier(self.base_classifier, self.T)
        rtn.nbr_classes = np.size(np.unique(y))
        rtn.classifiers, rtn.alphas = trainBoost(self.base_classifier, X, y, self.T)
        rtn.trained = True
        return rtn

    def classify(self, X):
        return classifyBoost(X, self.classifiers, self.alphas, self.nbr_classes)


import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import websysconf

sys.path.append(websysconf.UTIL_PATH)
import util
import bsb64

import userman
import sessionman
import authman

root_path = ''
query = None

encryption = True
LOCK_FILE_PATH = websysconf.LOCK_FILE_PATH

#----------------------------------------------------------
# set root path
#----------------------------------------------------------
def set_root_path(path):
    global root_path
    root_path = path

#-----------------
# WebContext Class
#-----------------
class WebContext:
    def __init__(self):
        self.status = ''
        self.session_info = None
        self.user_info = None
        self.authorized = False

    def get_status(self):
        return self.status

    def set_status(self, status):
        self.status = status

    def is_authorized(self):
        return self.authorized

    def set_authorized(self, authorized):
        self.authorized = authorized

    def get_session_info(self):
        return self.session_info

    def set_session_info(self, session_info):
        self.session_info = session_info

    #------------------------------------------------------
    # get_user_info
    #
    # Returns:
    # user: {
    #   "uid": "root",
    #   "name": "root",
    #   "local_name": "root_L",
    #   "is_admin": true,
    #   "group": "GROUP1 GROUP2",
    #   "privs": "PRIVILEGE1 PRIVILEGE2",
    #   "desc": "Description",
    #   "status": 0,
    #   "created_at": 1667047612.967891,
    #   "updated_at": 1667047612.967891,
    #   "pw_changed_at": 1667047612.967891
    # }
    #
    # users_guest: {
    #   "uid": "123456",
    #   "name": "GUEST",
    #   "local_name": "GUEST_L",
    #   "group": "GROUP1",
    #   "privs": "",
    #   "desc": "Description",
    #   "is_guest": true,
    #   "status": 0,
    #   "created_at": 1667047612.967891,
    #   "updated_at": 1667047612.967891,
    #   "pw_changed_at": 1667047612.967891,
    #   "expires_at": 1571476916.59936
    # }
    #
    # or None
    #------------------------------------------------------
    def get_user_info(self):
        return self.user_info

    def set_user_info(self, user_info):
        self.user_info = user_info

    def get_session_id(self):
        session_info = self.session_info
        if session_info is not None and 'sid' in session_info:
            return session_info['sid']
        return None

    def get_user_id(self):
        user_info = self.user_info
        if user_info is not None and 'uid' in user_info:
            return user_info['uid']
        return None

    def get_user_name(self):
        user_info = self.user_info
        if user_info is not None and 'name' in user_info:
            return user_info['name']
        return ''

    def get_user_local_name(self):
        user_info = self.user_info
        if user_info is not None and 'local_name' in user_info:
            return user_info['local_name']
        return ''

    def is_admin(self):
        user_info = self.user_info
        if user_info is not None:
            if 'is_admin' in user_info and user_info['is_admin']:
                return True
        return False

    # group_name: case-insensitive
    def is_member_of(self, group_name):
        user_info = self.user_info
        if user_info is None:
            return False
        return userman.is_member_of(user_info, group_name)

    def get_groups(self):
        user_info = self.user_info
        if user_info is None:
            return []

        if 'group' not in user_info:
            return []

        groups = user_info['group']
        group_list = groups.split(' ')
        return group_list

    # priv_name: case-insensitive
    def has_privilege(self, priv_name):
        user_info = self.user_info
        if user_info is None:
            return False
        return userman.has_privilege(user_info, priv_name)

    # Returns if the user has privilege in privileges or groups
    # priv_name: case-insensitive
    def has_permission(self, priv_name):
        if self.has_privilege(priv_name):
            return True

        groups = self.get_groups()
        for i in range(len(groups)):
            gid = groups[i]
            if userman.has_privilege_in_group(gid, priv_name):
                return True

        return False

    def get_user_description(self):
        user_info = self.user_info
        if user_info is not None and 'desc' in user_info:
            return user_info['desc']
        return ''

    def is_guest(self):
        session_info = self.session_info
        if session_info is not None:
            if 'is_guest' in session_info and session_info['is_guest']:
                return True
        return False

#----------------------------------------------------------
# on access
#----------------------------------------------------------
def on_access(allow_guest=True):
    #context = {
    #    'status': '',
    #    'session_info': None,
    #    'user_info': None,
    #    'authorized': False
    #}

    context = WebContext()

    if synchronize_start():
        context = _on_access(context, allow_guest)
        context.set_status('OK')
        synchronize_end()
    else:
        context.set_status('SYSTEM_BUSY')

    return context

def _on_access(context, allow_guest):
    sid = util.get_cookie_val('sid')
    session_info = None
    user_info = None

    sessions = sessionman.get_all_sessions_info()
    if sessions is None:
        return context

    sessions = sessionman.clear_expired_sessions(sessions)
    sessionman.update_last_accessed_info(sessions, sid)

    if sid in sessions:
        session_info = sessions[sid]

    if session_info is None:
        return context

    uid = session_info['uid']
    user_info = userman.get_user_info(uid)

    sessionman.set_current_session_info(session_info)
    authorized = authman.auth(allow_guest)

    context.set_session_info(session_info)
    context.set_user_info(user_info) # see userman.create_user() for object fields
    context.set_authorized(authorized)

    return context

#----------------------------------------------------------
# Get Request Param
#----------------------------------------------------------
def get_request_param(key=None, default=None):
    q = util.get_query()
    if q is None or util.typename(q) == 'FieldStorage':
        return default

    if encryption:
        q = util.replace(q, '&?_trcid=.+', '')
        try:
            q = bsb64.decode_string(q, 1)
        except:
            pass

    if key is not None:
        if q == '':
            q = None
        else:
            q = util.get_query_value(q, key)

    if q is None:
        q = default
    else:
        q = util.decode_uri(q)

    return q

def get_raw_request_param(key=None, default=None):
    return get_request_param(key, default)

#----------------------------------------------------------
# build logout cookies
#----------------------------------------------------------
def build_logout_cookies():
    cookie1 = util.build_cookie_for_clear('sid', path='/', http_only=True)
    cookies = []
    cookies.append({'Set-Cookie': cookie1})
    return cookies

#----------------------------------------------------------
# build session cookie
#----------------------------------------------------------
def build_session_cookie(session_info):
    cookies = None
    if session_info is not None:
        sid = session_info['sid']
        uid = session_info['uid']
        session_timeout = sessionman.get_session_timeout_value()
        cookie1 = util.build_cookie('sid', sid, max_age=str(session_timeout), path='/', http_only=True)
        cookies = []
        cookies.append({'Set-Cookie': cookie1})

    return cookies

#----------------------------------------------------------
# get ip addr
#----------------------------------------------------------
def get_ip_addr():
    addr = util.get_ip_addr()
    return addr

#----------------------------------------------------------
# get host name
#----------------------------------------------------------
def get_host_name():
    if websysconf.USE_HOSTNAME:
        host = util.get_host_name()
    else:
        host = ''
    return host

#----------------------------------------------------------
# send response
#----------------------------------------------------------
def send_response(result, type, headers=None, encoding=None):
    if headers is None:
        session_info = sessionman.get_current_session_info()
        cookies = build_session_cookie(session_info)
        headers = cookies
    _send_response(result, type, headers, encoding)

def _send_response(result, type, headers=None, encoding=None):
    if type == 'application/json' and util.typename(result) != 'str':
        result = util.to_json(result)

    if type == 'text/html':
        content = result
    else:
        if encryption:
            content = bsb64.encode_string(result, 7)
            type = 'text/plain'
        else:
            content = result

    util.send_response(content, type, headers=headers)

#----------------------------------------------------------
def send_result_json(status, body=None, headers=None, http_headers=None):
    result = util.build_result_object(status, body, headers)
    content = util.to_json(result)
    send_response(content, 'application/json', headers=http_headers)

#----------------------------------------------------------
# Blue Screen
def blue_screen(msg=None):
    if msg is None:
        msg = 'FORBIDDEN'
    html = '''<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>ERROR</title>
<style>
body, pre {
  background: #fff;
  color: #000;
  font-size: 14px;
  font-family: Consolas;
}
</style>
</head>
<body>
<pre>''' +  msg + '''</pre>
</body>
</html>'''
    send_response(html, 'text/html')

#----------------------------------------------------------
# Auth Redirection
def redirect_auth_screen():
    global root_path
    html = '''<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
'''
    html += '<script src="' + root_path + 'libs/util.js"></script>\n'
    html += '<script src="' + root_path + 'websys/websys.js"></script>\n'
    html += '<script>\n'
    html += 'onLoad = function() {\n'
    html +='  websys.init(\'' + root_path + '\');\n'
    html += 'websys.authRedirection(location.href);';
    html += '};\n'
    html += '''window.addEventListener('load', onLoad, true);
</script>
</head>
<body>
</body>
</html>'''
    send_response(html, 'text/html')

#----------------------------------------------------------
def get_user_name(uid, default=None):
    user_name = default
    if default is None:
        user_name = uid
    user_info = userman.get_user_info(uid)
    if user_info is not None and 'name' in user_info:
        user_name = user_info['name']
    return user_name

def get_user_local_name(uid, default=None):
    user_local_name = default
    if default is None:
        user_local_name = uid
    user_info = userman.get_user_info(uid)
    if user_info is not None and 'local_name' in user_info:
        user_local_name = user_info['local_name']
    return user_local_name

#----------------------------------------------------------
def synchronize_start():
    if util.file_lock(LOCK_FILE_PATH, 25, 0.2):
        return True
    return False

def synchronize_end():
    util.file_unlock(LOCK_FILE_PATH)


from datetime import datetime

import click
import geopandas as gpd
import pandas as pd
from loguru import logger

from src.config import settings
from src.data_processing import admin_bounds, feature_collection_pipeline

@click.command()
@click.option(
    "--locations-csv",
    default=settings.DATA_DIR / "2022-04-29-air4thai-th-stations.csv",
    help="Path to the CSV file containing the locations for which to generate data.",
)
@click.option(
    "--ground-truth-csv",
    help="Path to the CSV file containing the locations for which to generate data.",
)
@click.option(
    "--admin-bounds-shp",
    help="If provided, the script will identify the admin bounds of the locations of interest."
    "This is used primarily for spatial cross-validation during model training and evaluation.",
)
@click.option(
    "--id-col",
    default="station_code",
    help="Primary Key to uniquely identify entries in the locations CSV. If ground truth CSV is provided, this should be present in that file as well.",
)
@click.option(
    "--hrsl-tif",
    default=settings.DATA_DIR / "tha_general_2020.tif",
    help="Path to the HRSL tif file containing the population counts for the country.",
)
@click.option(
    "--start-date",
    default="2021-01-01",
    help="Date to start collecting data",
)
@click.option(
    "--end-date",
    default="2021-12-31",
    help="Date to end collecting data",
)
@click.option(
    "--debug",
    is_flag=True,
    default=False,
    help="If true, will run only on 2 locations just to check if the whole script will run.",
)
def main(
    locations_csv,
    ground_truth_csv,
    admin_bounds_shp,
    hrsl_tif,
    id_col,
    start_date,
    end_date,
    debug,
):
    BBOX_SIZE_KM = 1

    # Read in desired AOI locations
    # Assumed that the CSV has an id column, latitude, and longitude at the minimum.
    locations_df = pd.read_csv(locations_csv)
    if debug:
        logger.warning("Running in debug mode. Trying out with 2 locations only.")
        locations_df = locations_df[:2]
    assert {id_col, "latitude", "longitude"} <= set(locations_df.columns.tolist())

    # Create base DF from the locations, date range, and features (HRSL + GEE data)
    base_df = feature_collection_pipeline.collect_features_for_locations(
        locations_df, start_date, end_date, id_col, hrsl_tif, bbox_size_km=BBOX_SIZE_KM
    )

    # Join ground truth if any
    if ground_truth_csv:
        logger.info(f"Generating dataset with ground truth from {ground_truth_csv}")
        ground_truth_df = pd.read_csv(ground_truth_csv)
        ground_truth_df["date"] = pd.to_datetime(ground_truth_df["date"]).dt.date
        base_df = base_df.merge(ground_truth_df, on=[id_col, "date"], how="left")
    else:
        ground_truth_df = None
        logger.warning("Generating dataset without ground truth.")

    # Join admin bounds if any
    if admin_bounds_shp:
        logger.info(f"Generating dataset with admin bounds from {admin_bounds_shp}")
        admin_bounds_gdf = gpd.read_file(admin_bounds_shp)
        base_df = admin_bounds.join_admin_bounds(base_df, admin_bounds_gdf)
    else:
        admin_bounds_gdf = None
        logger.warning("No admin bounds provided.")

    # Save outputs
    run_timestamp = datetime.today().strftime("%Y-%m-%d_%H-%M-%S")

    out_filepath = f"generated_data_{run_timestamp}.csv"
    base_df.to_csv(settings.DATA_DIR / out_filepath, index=False)
    logger.info(
        f"Generated base table for ML modelling with {len(base_df)} rows. Saved to {out_filepath}"
    )

if __name__ == "__main__":
    main()


import numpy as np
from timeit import default_timer as timer
from os import path
from numba import jit, prange
import pyopencl as cl
import matplotlib.pyplot as plt
from os import environ
environ['PYOPENCL_COMPILER_OUTPUT'] = '1'

RADDEG = 180.0/np.pi
DEGRAD = np.pi/180.0

class Radon():
  def __init__(self, image=None, imageDim = None, nTheta = 180, nRho=90,rhoMax = None):
    self.nTheta = nTheta
    self.nRho = nRho
    self.rhoMax = rhoMax
    self.indexPlan = None
    if (image is None) and (imageDim is None):
      self.theta = None
      self.rho = None
      self.imDim = None
    else:
      if (image is not None):
        self.imDim = np.asarray(image.shape[-2:])
      else:
        self.imDim = np.asarray(imageDim[-2:])
      self.radon_plan_setup(imageDim=self.imDim, nTheta=self.nTheta, nRho=self.nRho, rhoMax=self.rhoMax)

  def radon_plan_setup(self, image=None, imageDim=None, nTheta=None, nRho=None, rhoMax=None):
    if (image is None) and (imageDim is not None):
      imDim = np.asarray(imageDim, dtype=np.int)
    elif (image is not None):
      imDim =  np.shape(image)[-2:] # this will catch if someone sends in a [1 x N x M] image
    else:
      return -1
    imDim = np.asarray(imDim)
    self.imDim = imDim
    if (nTheta is not None) : self.nTheta = nTheta
    if (nRho is not None): self.nRho = nRho
    self.rhoMax = rhoMax if (rhoMax is not None) else np.round(np.linalg.norm(imDim)*0.5)

    deltaRho = float(2 * self.rhoMax) / (self.nRho)
    self.theta = np.arange(self.nTheta, dtype = np.float32)*180.0/self.nTheta
    self.rho = np.arange(self.nRho, dtype = np.float32)*deltaRho - (self.rhoMax-deltaRho)

    #xmin = -1.0*(self.imDim[0]-1)*0.5
    #ymin = -1.0*(self.imDim[1]-1)*0.5
    xmin = -1.0*(self.imDim[0]-1)*0.5
    ymin = -1.0*(self.imDim[1]-1)*0.5

    #self.radon = np.zeros([self.nRho, self.nTheta])
    sTheta = np.sin(self.theta*DEGRAD)
    cTheta = np.cos(self.theta*DEGRAD)
    thetatest = np.abs(sTheta) >= (np.sqrt(2.) * 0.5)

    m = np.arange(self.imDim[0], dtype = np.uint32)
    n = np.arange(self.imDim[1], dtype = np.uint32)

    a = -1.0*np.where(thetatest == 1, cTheta, sTheta)
    a /= np.where(thetatest == 1, sTheta, cTheta)
    b = xmin*cTheta + ymin*sTheta

    self.indexPlan = np.zeros([self.nRho, self.nTheta, self.imDim.max()], dtype=np.uint64)
    outofbounds = self.imDim[0]*self.imDim[1]
    for i in np.arange(self.nTheta):
      b1 = self.rho - b[i]
      if thetatest[i]:
        b1 /= sTheta[i]
        b1 = b1.reshape(self.nRho, 1)
        indx_y = np.floor(a[i]*m+b1).astype(np.int64)
        indx_y = np.where(indx_y < 0, outofbounds, indx_y)
        indx_y = np.where(indx_y >= self.imDim[1], outofbounds, indx_y)
        #indx_y = np.clip(indx_y, 0, self.imDim[1])
        indx1D = np.clip(m+self.imDim[0]*indx_y, 0, outofbounds)
        self.indexPlan[:,i, :] = indx1D
      else:
        b1 /= cTheta[i]
        b1 = b1.reshape(self.nRho, 1)
        if cTheta[i] > 0:
          indx_x = np.floor(a[i]*n + b1).astype(np.int64)
        else:
          indx_x = np.ceil(a[i] * n + b1).astype(np.int64)
        indx_x = np.where(indx_x < 0, outofbounds, indx_x)
        indx_x = np.where(indx_x >= self.imDim[0], outofbounds, indx_x)
        indx1D = np.clip(indx_x+self.imDim[0]*n, 0, outofbounds)
        self.indexPlan[:, i, :] = indx1D
      self.indexPlan.sort(axis = -1)

  def radon_fast(self, imageIn, padding = np.array([0,0]), fixArtifacts = False, background = None):
    tic = timer()
    shapeIm = np.shape(imageIn)
    if imageIn.ndim == 2:
      nIm = 1
      image = imageIn[np.newaxis, : ,:]
      reform = True
    else:
      nIm = shapeIm[0]
      reform = False

    if background is None:
      image = imageIn.reshape(-1)
    else:
      image = imageIn - background
      image = image.reshape(-1)

    nPx = shapeIm[-1]*shapeIm[-2]
    im = np.zeros(nPx+1, dtype=np.float32)
    #radon = np.zeros([nIm, self.nRho, self.nTheta], dtype=np.float32)
    radon = np.zeros([nIm,self.nRho + 2 * padding[0],self.nTheta + 2 * padding[1]],dtype=np.float32)
    shpRdn = radon.shape
    norm = np.sum(self.indexPlan < nPx, axis = 2 ) + 1.0e-12
    for i in np.arange(nIm):
      im[:-1] = image[i,:,:].flatten()
      radon[i, padding[0]:shpRdn[1]-padding[0], padding[1]:shpRdn[2]-padding[1]] = np.sum(im.take(self.indexPlan.astype(np.int64)), axis=2) / norm

    if (fixArtifacts == True):
      radon[:,:,0] = radon[:,:,1]
      radon[:,:,-1] = radon[:,:,-2]

    radon = np.transpose(radon, [1,2,0]).copy()

    if reform==True:
      image = image.reshape(shapeIm)

    #print(timer()-tic)
    return radon

  def radon_faster(self,imageIn,padding = np.array([0,0]), fixArtifacts = False, background = None):
    tic = timer()
    shapeIm = np.shape(imageIn)
    if imageIn.ndim == 2:
      nIm = 1
      #image = image[np.newaxis, : ,:]
      #reform = True
    else:
      nIm = shapeIm[0]
    #  reform = False

    if background is None:
      image = imageIn.reshape(-1)
    else:
      image = imageIn - background
      image = image.reshape(-1)

    nPx = shapeIm[-1]*shapeIm[-2]
    indxDim = np.asarray(self.indexPlan.shape)
    #radon = np.zeros([nIm, self.nRho+2*padding[0], self.nTheta+2*padding[1]], dtype=np.float32)
    radon = np.zeros([self.nRho + 2 * padding[0],self.nTheta + 2 * padding[1], nIm],dtype=np.float32)
    shp = radon.shape

    self.rdn_loops(image,self.indexPlan,nIm,nPx,indxDim,radon, np.asarray(padding))

    if (fixArtifacts == True):
      radon[:,padding[1],:] = radon[:,padding[1]+1,:]
      radon[:,shp[1]-1-padding[1],:] = radon[:,shp[1]-padding[1]-2,:]

    image = image.reshape(shapeIm)

    #print(timer()-tic)
    return radon

  @staticmethod
  @jit(nopython=True, fastmath=True, cache=True, parallel=False)
  def rdn_loops(images,index,nIm,nPx,indxdim,radon, padding):
    nRho = indxdim[0]
    nTheta = indxdim[1]
    nIndex = indxdim[2]
    count = 0.0
    sum = 0.0
    for q in prange(nIm):
      imstart = q*nPx
      for i in range(nRho):
        ip = i+padding[0]
        for j in range(nTheta):
          jp = j+padding[1]
          count = 0.0
          sum = 0.0
          for k in range(nIndex):
            indx1 = index[i,j,k]
            if (indx1 >= nPx):
              break
            #radon[q, i, j] += images[imstart+indx1]
            sum += images[imstart + indx1]
            count += 1.0
          radon[ip,jp,q] = sum/(count + 1.0e-12)

  def radon_fasterCL(self,image,padding = np.array([0,0]),fixArtifacts = False, background = None, returnBuff = False, clparams=[None, None, None, None, None] ):

    tic = timer()
    if isinstance(clparams[1],cl.Context):
      gpu = clparams[0]
      ctx = clparams[1]
      prg = clparams[3]
      if isinstance(clparams[2], cl.CommandQueue):
        queue = clparams[2]
      else:
        queue = cl.CommandQueue(ctx)
      mf = clparams[4]
    else:
      try:
        gpu = cl.get_platforms()[0].get_devices(device_type=cl.device_type.GPU)
        ctx = cl.Context(devices={gpu[0]})
        queue = cl.CommandQueue(ctx)
        mf = cl.mem_flags
        kernel_location = path.dirname(__file__)
        prg = cl.Program(ctx,open(path.join(kernel_location,'clkernels.cl')).read()).build()
      except:
        return self.radon_faster(image,padding=padding,fixArtifacts = fixArtifacts), [None, None, None, None, None], None

    shapeIm = np.shape(image)
    if image.ndim == 2:
      nIm = 1
      image = image.reshape(1, shapeIm[0], shapeIm[1])
      shapeIm = np.shape(image)
    else:
      nIm = shapeIm[0]
    #  reform = False

    clvtypesize = 16 # this is the vector size to be used in the openCL implementation.
    nImCL = np.int32(clvtypesize * (np.int(np.ceil(nIm/clvtypesize))))
    # there is something very strange that happens if the number of images
    # is a exact multiple of the max group size (typically 256)
    mxGroupSz = gpu[0].get_info(cl.device_info.MAX_WORK_GROUP_SIZE)
    nImCL += np.int(16 * (1 - np.int(np.mod(nImCL, mxGroupSz ) > 0)))
    image_align = np.zeros((shapeIm[1], shapeIm[2], nImCL), dtype = np.float32)
    image_align[:,:,0:nIm] = np.transpose(image, [1,2,0]).copy()
    shpRdn = np.asarray( ((self.nRho+2*padding[0]), (self.nTheta+2*padding[1]), nImCL),dtype=np.uint64)
    radon_gpu = cl.Buffer(ctx,mf.READ_WRITE,size=int((self.nRho+2*padding[0])*(self.nTheta+2*padding[1])*nImCL*4))
    #radon_gpu = cl.Buffer(ctx,mf.READ_WRITE,size=radon.nbytes)
    #radon_gpu = cl.Buffer(ctx,mf.READ_WRITE | mf.COPY_HOST_PTR,hostbuf=radon)
    image_gpu = cl.Buffer(ctx,mf.READ_ONLY | mf.COPY_HOST_PTR,hostbuf=image_align)
    rdnIndx_gpu = cl.Buffer(ctx,mf.READ_ONLY | mf.COPY_HOST_PTR,hostbuf=self.indexPlan)

    imstep = np.uint64(np.product(shapeIm[-2:]))
    indxstep = np.uint64(self.indexPlan.shape[-1])
    rdnstep = np.uint64(self.nRho * self.nTheta)

    padRho = np.uint64(padding[0])
    padTheta = np.uint64(padding[1])
    tic = timer()

    nImChunk = np.uint64(nImCL/clvtypesize)

    if background is not None:
      back_gpu = cl.Buffer(ctx,mf.READ_ONLY | mf.COPY_HOST_PTR,hostbuf=background.astype(np.float32))
      prg.backSub(queue,(imstep, 1, 1),None,image_gpu,back_gpu,nImChunk)
      imBack = np.zeros((shapeIm[1], shapeIm[2], nImCL),dtype=np.float32)
      cl.enqueue_copy(queue,imBack,image_gpu,is_blocking=True)

    prg.radonSum(queue,(nImChunk,rdnstep),None,rdnIndx_gpu,image_gpu,radon_gpu,
                  imstep, indxstep,
                 shpRdn[0], shpRdn[1],
                 padRho, padTheta, np.uint64(self.nTheta))

    if (fixArtifacts == True):
       prg.radonFixArt(queue,(nImChunk,self.nRho),None,radon_gpu,
                       shpRdn[0],shpRdn[1],padTheta)

    rdnIndx_gpu.release()
    image_gpu.release()

    if returnBuff == False:
      radon = np.zeros([self.nRho + 2 * padding[0],self.nTheta + 2 * padding[1],nImCL],dtype=np.float32)
      cl.enqueue_copy(queue,radon,radon_gpu,is_blocking=True)
      radon_gpu.release()
      radon = radon[:,:, 0:nIm]
      radon_gpu = None
      clparams = [None, None, None, None, None]
    else:
      radon = None
      clparams = [gpu,ctx,queue,prg,mf]

    return radon, clparams, radon_gpu

    #if (fixArtifacts == True):
    #  radon[:,:,padding[1]] = radon[:,:,padding[1]+1]
    #  radon[:,:,-padding[1]-1] = radon[:,:,-2-padding[1]]

    #print(timer()-tic)

# if __name__ == "__main__":
#   import ebsd_pattern, ebsd_index
#   file = '~/Desktop/SLMtest/scan2v3nlparl09sw7.up1' ;f = ebsd_pattern.UPFile(file)
#
#   pat = f.read_data(patStartEnd=[0,1],convertToFloat=True,returnArrayOnly=True )
#   dat, indxer = ebsd_index.index_pats(filename = file, patStart = 0, patEnd = 1,return_indexer_obj = True)
#   dat = ebsd_index.index_pats_distributed(filename = file,patStart = 0, patEnd = -1, chunksize = 1000, ncpu = 34, ebsd_indexer_obj = indxer )
#


import matplotlib
# gosh. suppress tkinter usage; otherwise matplotlib.pyplot won't
# load.
matplotlib.use('agg')
import matplotlib.pyplot as plt

from contextlib import contextmanager
import datetime
import threading
import functools
import io

# matplotlib is entirely unsafe (this is bloody Matlab heritage - the
# most popular interface is "MATLAB style" which is inherently global)
_lock = threading.Lock()
def _locked(f):
    @functools.wraps(f)
    def wrap(*args, **kwargs):
        with _lock: return f(*args, **kwargs)
    return wrap

@_locked
def show_samples(samples):
    matplotlib.use('GTK3Cairo')
    plt.plot([datetime.datetime.fromtimestamp(ts) for ts,_ in samples], [temp for _,temp in samples])
    plt.show()
    plt.clf()

@contextmanager
def plot(title=None, xlabel=None, ylabel=None, legend=True,
         xlim=None, ylim=None, size_inches=None):
    try:
        _lock.acquire()

        # plt.xkcd()

        if title is not None:
            plt.title(title)
        if xlabel is not None:
            plt.xlabel(xlabel)
        if ylabel is not None:
            plt.ylabel(ylabel)
        if xlim is not None:
            plt.xlim(xlim)
        if ylim is not None:
            plt.ylim(ylim)
        if size_inches is not None:
            plt.gcf().set_size_inches(*size_inches)

        # disable xticks until someone needs them
        plt.xticks([])

        yield

        # wtf: clear global variables first. I used to test this in a
        # jupyter notebook and got confused. reason: IPython does a
        # plt.show() or something, and that *always* resets
        # matplotlib's global bullshit.
        plt.clf()
        plt.cla()
        plt.close()
    finally:
        _lock.release()

def plot_samples(samples, label=None):
    plt.plot(
        [ts for ts,_ in samples],
        [temp for _,temp in samples],
        label = label)

def as_svg_io(legend=True):
    'return io.BytesIO, suitable as input to flask.send_file()'

    if legend:
        plt.legend()

    data = io.BytesIO()
    plt.savefig(data, format='svg')
    data.seek(0)
    return data


from geometry import *;
from model import *;
from property import *;
from pyNastran.bdf.bdf import BDF, read_bdf;
import numpy;
import time;
import sys;

if __name__ == '__main__':
	numpy.set_printoptions(threshold = sys.maxsize);
	E = 200e3;
	rho = 7.9e-9;
	nu = 0.3;
	bdf = BDF(debug=False);
	bdf.read_bdf('A1.bdf');
	model = Model();
	m = Material();
	m.setProperty(MaterialProperty.rho, rho);
	m.setProperty(MaterialProperty.E, E);
	m.setProperty(MaterialProperty.nu, nu);
	p = Property3D(m);
	nodes = dict();
	for i, n in bdf.nodes.items():
		node = Node(n.nid, n.xyz[0], n.xyz[1], n.xyz[2]);
		nodes[n.nid] = node;

	for i, e in bdf.elements.items():
		list = [];
		for n in e.nodes:
			list.append(nodes[n]);
		element = Tet10Element(e.eid, list, p);
		model.addElement(element);

	for i, spc in bdf.spcs.items():
		for x in spc:
			if x.type == 'SPC1':
				for n in x.nodes:
					nodes[n].addConstraint(Constraint.X);
					nodes[n].addConstraint(Constraint.Y);
					nodes[n].addConstraint(Constraint.Z);

	for i, l in bdf.loads.items():
		for x in l:
			if x.type == 'FORCE':
				nodes[x.node].addLoad(Load.X, l[0].mag * x.xyz[0]);
				nodes[x.node].addLoad(Load.Y, l[0].mag * x.xyz[1]);
				nodes[x.node].addLoad(Load.Z, l[0].mag * x.xyz[2]);
	t1 = time.time();
	model.solve();
	t2 = time.time();
	print(t2 - t1);


import os
import logging
import numpy as np
from PIL import Image
from .util import dataset_home, download, checksum, archive_extract, checkpoint

log = logging.getLogger(__name__)

_ALIGNED_IMGS_URL = (
    'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=1',
    'b7e1990e1f046969bd4e49c6d804b93cd9be1646'
)

_PARTITIONS_URL = (
    'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AADxLE5t6HqyD8sQCmzWJRcHa/Eval/list_eval_partition.txt?dl=1',
    'fb3d89825c49a2d389601eacb10d73815fd3c52d'
)

_ATTRIBUTES_URL = (
    'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AAC7-uCaJkmPmvLX2_P5qy0ga/Anno/list_attr_celeba.txt?dl=1',
    'da6959c54754838f1a12cbb80ed9baba5618eddd'
)

class CelebA(object):
    '''
    Large-scale CelebFaces Attributes (CelebA) Dataset [1].
    http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html

    References:
    [1]: Ziwei Liu, Ping Luo, Xiaogang Wang and Xiaoou Tang.
         Deep Learning Face Attributes in the Wild. Proceedings of
         International Conference on Computer Vision (ICCV), December, 2015.
    '''

    def __init__(self):
        self.name = 'celeba'
        self.n_imgs = 202599
        self.data_dir = os.path.join(dataset_home, self.name)
        self._npz_path = os.path.join(self.data_dir, self.name+'.npz')
        self.img_dir = os.path.join(self.data_dir, 'img_align_celeba')
        self._install()
        (self.train_idxs, self.val_idxs, self.test_idxs, self.attribute_names,
         self.attributes) = self._load()

    def _download(self, url, sha1):
        log.info('Downloading %s', url)
        filepath = download(url, self.data_dir)
        if sha1 != checksum(filepath):
            raise RuntimeError('Checksum mismatch for %s.' % url)
        return filepath

    def img(self, idx):
        img_path = os.path.join(self.img_dir, '%.6d.jpg' % (idx+1))
        return np.array(Image.open(img_path))

    def imgs(self):
        for i in range(self.n_imgs):
            yield self.img(i)

    def _install(self):
        checkpoint_file = os.path.join(self.data_dir, '__install_check')
        with checkpoint(checkpoint_file) as exists:
            if exists:
                return
            url, md5 = _ALIGNED_IMGS_URL
            filepath = self._download(url, md5)
            log.info('Unpacking %s', filepath)
            archive_extract(filepath, self.data_dir)

            url, md5 = _PARTITIONS_URL
            filepath = self._download(url, md5)
            partitions = [[], [], []]
            with open(filepath, 'r') as f:
                for i, line in enumerate(f):
                    img_name, partition = line.strip().split(' ')
                    if int(img_name[:6]) != i + 1:
                        raise ValueError('Parse error.')
                    partition = int(partition)
                    partitions[partition].append(i)
            train_idxs, val_idxs, test_idxs = map(np.array, partitions)

            url, md5 = _ATTRIBUTES_URL
            filepath = self._download(url, md5)
            attributes = []
            with open(filepath, 'r') as f:
                f.readline()
                attribute_names = f.readline().strip().split(' ')
                for i, line in enumerate(f):
                    fields = line.strip().replace('  ', ' ').split(' ')
                    img_name = fields[0]
                    if int(img_name[:6]) != i + 1:
                        raise ValueError('Parse error.')
                    attr_vec = np.array(map(int, fields[1:]))
                    attributes.append(attr_vec)
            attributes = np.array(attributes)

            with open(self._npz_path, 'wb') as f:
                np.savez(f, train_idxs=train_idxs, val_idxs=val_idxs,
                         test_idxs=test_idxs, attribute_names=attribute_names,
                         attributes=attributes)

    def _load(self):
        with open(self._npz_path, 'rb') as f:
            dic = np.load(f)
            return (dic['train_idxs'], dic['val_idxs'], dic['test_idxs'],
                    dic['attribute_names'][()], dic['attributes'])


"""
File: anagram.py
Name: Diana Pei-Rung Yu
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19

If you correctly implement this program, you should see the
number of anagrams for each word listed below:
    * arm -> 3 anagrams
    * contains -> 5 anagrams
    * stop -> 6 anagrams
    * tesla -> 10 anagrams
    * spear -> 12 anagrams
"""

# Constants
FILE = 'dictionary.txt'       # This is the filename of an English dictionary
EXIT = '-1'                   # Controls when to stop the loop

# Global variable
dictionary = {}               # to save all the words in FILE

def main():
    """
    This program will find the anagrams of the word provide by user.
    user can leave the program by enter EXIT constant
    """
    print('Welcome to stanCode \"Anagram Generator\" (or -1 to quit)')
    read_dictionary()
    while True:
        # get word from user
        word = input('Find anagram for: ')
        # to be case insensitive
        word = word.lower()
        if word == EXIT:
            break
        else:
            find_anagrams(word)

def read_dictionary():
    """
    this function add all the words in FILE to global variable dictionary by use the alphabet letter as keys
    and words come with the alphabet as values
    """
    global dictionary
    with open(FILE, 'r') as f:
        for line in f:
            # clear the front and behind each line to have clean word
            line = line.strip()
            # add word to dictionary
            if line[0] not in dictionary:
                dictionary[line[0]] = [line]
            else:
                dictionary[line[0]].append(line)

def find_anagrams(s):
    """
    :param s: the word provide by user
    :return: the anagram in dictionary
    """
    # tell user the program is searching for anagram
    print('Searching...')
    # to store the anagrams that can be found in dictionary
    a_lst = []
    # turn the string given by user into lst
    s_lst = word_generator(s)
    # use s_lst to get character combinations and see if it's in dictionary
    find_anagrams_helper(s_lst, len(s_lst), [], a_lst)
    # show the number of anagrams we found and list of the anagrams
    print(len(a_lst), 'anagrams: ', a_lst)

def word_generator(s):
    """
    :param s: str, the the word get from user
    :return: lst, list contain all characters within s
    """
    s_lst = []
    for i in range(len(s)):
        ch = s[i]
        s_lst.append(ch)
    return s_lst

def find_anagrams_helper(lst, target, current, a_lst):
    """
    :param lst: lst, contain all the characters
    :param target: num, target length of current which is same as the length of the word provide by user
    :param current: lst, to store the characters by order
    :param a_lst: lst, to store the anagram of the word provided by user
    :return: lst, all anagram words
    """
    # check word if current length equals to lst
    if len(current) == target:
        # turn the current character order list into string
        candidate = word_processor(current)
        # avoid to have duplicate anagram
        if candidate in a_lst:
            return
        else:
            # check if candidate is in dictionary
            if candidate in dictionary[current[0]]:
                a_lst.append(candidate)
                print('Found: ' + candidate)
                # tell user the program is searching for anagram
                print('Searching...')
            # check next word combination
            else:
                return
    else:
        for i in range(len(lst)):
            ele = lst[i]
            # choose
            if len(current) == 0:
                current.append(ele)
            else:
                word = word_processor(current)
                # if there's a word come with current initial, will continue explore
                if has_prefix(word):
                    current.append(ele)
                else:
                    return
            # Explore
            find_anagrams_helper(lst[:i]+lst[i+1:], target, current, a_lst)
            # un-choose
            current.pop()

def word_processor(current):
    """
    :param current: lst, store the new order of the characters provide by user
    :return string: str, string version of current
    """
    string = ''
    for i in range(len(current)):
        ch = current[i]
        string += ch
    return string

def has_prefix(test_word):
    """
    :param test_word: str, the possible anagram word
    :return: bool, whether any word in dictionary begin with test_word
    """
    initial = test_word[0]
    if initial in dictionary:
        if len(test_word) == 1:
            return True
        else:
            for word in dictionary[initial]:
                if word.startswith(test_word):
                    return True
    return False

if __name__ == '__main__':
    main()


'''
Move Zeros to back of array in place
'''

array = [0, 9, 21, 44, 0, 12, 4, 62, 0, 1]

array2 = []

zero_count = 0

for position, value in enumerate(array):
    if value != 0:
        array2.append(value)
    else:
        zero_count += 1

for i in range(zero_count):
    array2.append(0)

print(array)
print(array2)


import random
import os

def print_mines_layout():

    global mine_values
    global n

    print()

    st = "   "
    for i in range(n):
        st = st + "     " + str(i + 1)
    print(st)

    for r in range(n):
        st = "     "
        if r == 0:
            for col in range(n):
                st = st + "______"
            print(st)

        st = "     "
        for col in range(n):
            st = st + "|     "
        print(st + "|")

        st = "  " + str(r + 1) + "  "
        for col in range(n):
            st = st + "|  " + str(mine_values[r][col]) + "  "
        print(st + "|")

        st = "     "
        for col in range(n):
            st = st + "|_____"
        print(st + '|')

    print()

def mine_placer():

    global no_of_mines
    global n
    global numbers
    """
    This function will track the number of mines already set up,
    take a random number from all of the grid positions while generating a row and column
    and place a mine if it doesn't already have one. this sould repeat until we have the required
    number of mines.
    """
    count = 0
    while count < no_of_mines:
        val = random.randint(0, n*n-1)
        r = val // n
        col = val % n

        if numbers[r][col] != -1:
            count = count + 1
            numbers[r][col]

def set_values():

    global n
    global numbers
    """
    below we will ad a for loop that will count each cell value and the if statements that will skip
    through each mine if one is present
    """
    for r in range(n):
        for col in range(n):
            if numbers[r][col] == -1:
                continue

            if r > 0 and numbers[r-1][col] == -1:
                numbers[r][col] = numbers[r][col] + 1
            if r < n-1 and numbers[r+1][col] == -1:
                numbers[r][col] = numbers[r][col] +1
            if col > 0 and numbers[r][col-1] == -1:
                numbers[r][col] = numbers[r][col] +1
            if col < n-1 and numbers[r][col+1] == -1:
                numbers[r][col] = numbers[r][col] +1
            if r >0 and col > 0 and numbers[r-1][col-1] == -1:
                numbers[r][col] = numbers[r][col] +1
            if r > 0 and col < n -1 and numbers[r-1][col-1] == -1:
                numbers[r][col] == numbers[r][col] +1
            if r < n-1 and col > 0 and numbers[r+1][col+1]== -1:
                numbers[r][col] = numbers[r][col] +1
            if r < n-1 and col < n-1 and numbers[r+1][col+1]== -1:
                numbers[r][col] = numbers[r][col] +1
        """
        The above statements go either + or - or both in the row and column to check in a full circle
        around each grid which should in return add 1 to every cell that is touching a mine.
        """
def zero_value_check(r, col):

    global mine_value
    global number
    global vis
    """
    This function will check for zeros surrounding the chosen cell using a recursive function.
    """

    if [r, col] not in vis:
        vis.append([r, col])

        if numbers[r][col] == 0:
            mine_value[r][col] = numbers[r][col]

            if r > 0:
                zero_value_check(r-1, col)
            if r < n-1:
                zero_value_check(r+1, col)
            if col > 0:
                zero_value_check(r, col-1)
            if col < n-1:
                zero_value_check(r, col+1)
            if r > 0 and col > 0:
                zero_value_check(r-1, col-1)
            if r > 0 and col < n-1:
                zero_value_check(r-1, col+1)
            if r < n-1 and col > 0:
                zero_value_check(r+1, col-1)
            if r < n-1 and col < n-1:
                zero_value_check(r+1, col+1)
        if numbers[r][col] != 0:
            mine_value[r][col] = numbers[r][col]

def clear():
    os.system("clear")
    """
    this function will check the progress of the game, count all of the numbered value and and for loop
    to check each cell in the grid.
    """
def check_game_progress():
    global mine_value
    global n
    global no_of_mines

    count = 0

    for r in range(n):
        for col in range(n):

            if mine_value[r][col] != ' ' and  mine_value[r][col]!= 'F':
                count = count + 1

    if count == n * n - no_of_mines:
        return True
    else:
        return False
    """
    this funtion will display all of the mine locations, mines have been given the
    value M for Mine.
    """
def mine_displayer():
    global mine_value
    global numbers
    global n

    for r in range(n):
        for col in range(n):
            if numbers[r][col] == -1:
                mine_value[r][col] = 'M'

if __name__ == "__main__":
    n = 8
    no_of_mines = 8

    numbers = [[0 for y in range(n)] for x in range(n)]
    mine_values = [[' ' for y in range(n)] for x in range(n)]
    flags = []
    mine_placer()
    set_values()
    over = False

    while not over:
        print_mines_layout()
        inp = input("Enter row number followed by space and column number = ").split()
        """
        Above: The input that enters your selections into the grid.
        Below: The try block that calls a ValueError if the input is invalid.
        """
        if len(inp) ==2:
            try:
                val = list(map(int, inp))
            except ValueError:
                clear()
                print("Invalid input, try again!")
                continue

        elif len(inp) == 3:
            if inp[2] != 'F' and inp[2] != 'f':
                clear()
                print("Invalid input, try again!")
                continue

            try:
                val = list(map(int, inp[:2]))
            except ValueError:
                clear()
                print("Invalid input, try again!")
                continue

            r = val[0]-1
            col = val


import json
import difflib

data = json.load(open("data.json"))

def translate(w):
  w = w.lower()
  if w in data:
    return data[w]
  elif w.upper() in data: # for capitalized words like USA and Nato
    return data[w.upper()]
  elif w.title() in data: # for words that start with a capital letter
    return data[w.title()]

  close_words = difflib.get_close_matches(w, data, cutoff=0.7) # A list of a word's close matches, if any

  if len(close_words) > 0:
    yn = input("Did you mean: {}? Y/N: ".format(close_words[0]))

    if yn.lower() == "y":
      return data[close_words[0]]

  return "Word not found. Please check your spelling and try again."

word = ""
while word.lower() != "q":
  word = input("Please enter a word (or q to quit): ")

  if word != "q":
    meanings = translate(word)
    if type(meanings) == str:
      print(meanings)
    else:
      for meaning in meanings:
        print("\n" + meaning)


import os

import torch.nn as nn
from utils import *

class dynamical_model(nn.Module):

    def __init__(self,
                input_length: int,
                in_channels: int,
                residual_channels: int,
                pred_var_dims: int=3,
                activation: str='relu',
                diagonal: bool=False,
                ):
        super(dynamical_model, self).__init__()
        self.in_channels = in_channels
        self.input_feat = 3*in_channels*input_length
        self.pred_var_dims = pred_var_dims
        self.diagonal = diagonal
        self.res_channels = residual_channels
        bias = True

        assert self.input_feat//8 > self.res_channels*3
        self.encoder = nn.Sequential(
            nn.Linear(in_features=self.input_feat, out_features=self.input_feat//2, bias=bias),
            activation_func(activation),
            #nn.Linear(in_features=self.input_feat, out_features=self.input_feat//2, bias=bias),
            #activation_func(activation),
            #nn.Linear(in_features=self.input_feat//2, out_features=self.input_feat//4, bias=bias),
            #activation_func(activation),
            #nn.Linear(in_features=self.input_feat//4, out_features=self.input_feat//8, bias=bias),
            #activation_func(activation),
            nn.Linear(in_features=self.input_feat//2, out_features=self.res_channels*3),
            #activation_func(activation),
            #nn.Linear(in_features=self.input_feat//2, out_features=self.input_feat//4),
            #activation_func(activation),
            #nn.Linear(in_features=self.input_feat//4, out_features=self.input_feat//8),
            #activation_func(activation),
        )
        self.dropout = nn.Dropout(0.5)

        self.enc_to_mean = nn.Linear(self.res_channels*3, self.pred_var_dims)
        if self.diagonal:
            self.enc_to_var = nn.Linear(self.res_channels*3, self.pred_var_dims)
        else:
            self.alpha = int(self.pred_var_dims*(1+ (self.pred_var_dims-1)/2)) # n*(n-1)/2
            self.enc_to_var = nn.Linear(self.res_channels*3, self.alpha)

    def forward(self, history_input, target_x, target_vel):
        #INPUT: batchsize x 1 x k history x nmodes x 3
        #TARGET: batchsize x 1 x nmodes x 3
        # encoding
        #self.history_input = history_input
        #self.history_input = history_input.squeeze(1).squeeze(2)
        self.rot_history = self.Rotate(history_input)
        out = self.encoder(self.rot_history.view( self.rot_history.size(0),-1))

        out_drop = self.dropout(out)
        rot_mean, logvar, encoded = self.encode(out_drop)

        #target_x = target_x.squeeze(1)
        #target_vel = target_vel.squeeze(1)
        rot_target_vel = torch.bmm(self.rotation_matrix.transpose(1,2),target_vel.swapaxes(1,2)).squeeze(-1) #target rotation to frame (t-1,t-2,t-3)
        rot_target_x = torch.bmm(self.rotation_matrix.transpose(1,2),target_x.swapaxes(1,2)).swapaxes(1,2)

        # Loss evaluation
        dyn_loss = self.NLL(rot_mean, logvar, rot_target_vel)
        loss = dyn_loss
        return loss, [rot_mean,logvar], encoded

    def encode(self, out):

        means = self.enc_to_mean(out)
        if self.diagonal:
           logvarsquared = self.enc_to_var(out)
           return means, logvarsquared
        else:
            elements = self.enc_to_var(out)
            lower = torch.zeros(elements.size(0), self.pred_var_dims, self.pred_var_dims).to(elements)
            batched_eye = torch.eye(self.pred_var_dims).unsqueeze(0).expand(elements.size(0),-1,-1).to(elements)
            lower = lower + batched_eye
            index = np.cumsum([n for n in range(0,self.pred_var_dims)])
            for row in range(1,self.pred_var_dims):
                lower[:,row,:row] = elements[:,index[row-1]:index[row]]

            diag = torch.exp(elements[:,self.alpha-self.pred_var_dims:]).unsqueeze(1)*batched_eye
            partial_prod1 = torch.bmm(lower, diag)
            self.sigma = torch.bmm(partial_prod1, lower.transpose(1,2))
            return means, [diag, lower], out

    def NLL(self, mean,logvar, target, diagonal=False):
        diag, lower = logvar
        partial_prod1 = torch.bmm(lower, diag)
        self.sigma = torch.bmm(partial_prod1, lower.transpose(1,2))
        sigma_inverse = torch.inverse(self.sigma)
        partial_prod2  = torch.bmm((mean-target).unsqueeze(1), sigma_inverse)
        logprob = -(1/2)*torch.diagonal(diag, dim1=1, dim2=2).sum(dim=1) - torch.bmm(partial_prod2, (mean-target).unsqueeze(-1)).squeeze(-1).squeeze(-1)/2
        return - logprob.mean()

    def get_parameters(self, history_input):
        #INPUT: batchsize x 1 x k history x nmodes x 3
        #TARGET: batchsize x 1 x nmodes x 3
        #self.history_input = history_input
        #self.history_input = history_input.squeeze(1).squeeze(2)
        self.rot_history = self.Rotate(history_input)
        out = self.encoder(self.rot_history.view( self.rot_history.size(0),-1))
        out_drop = self.dropout(out)
        rot_mean, logvar, _ = self.encode(out_drop)

        #rot_history = self.Rotate(history_input )
        #rot_mean, logvar, _ = self.encode(rot_history)
        return rot_mean, logvar

    def RotationMatrix(self):
        channels = self.history_input.size(2)
        rotation_matrix = torch.zeros(self.history_input.size(0), channels, channels).to(self.history_input)
        v_t1, norm_t1 = self.history_input[:,-1,:],  self.history_input[:,-1,:].norm(dim=1)
        v_t2 = self.history_input[:,-2,:]
        v_t3 = self.history_input[:,-3,:]
        orthonormal_b1 = v_t1/norm_t1.unsqueeze(-1).expand(-1,channels)
        aux_b2 = v_t2 - torch.bmm(v_t2.unsqueeze(1), orthonormal_b1.unsqueeze(-1)).squeeze(-1)*orthonormal_b1
        orthonormal_b2 = aux_b2/aux_b2.norm(dim=1).unsqueeze(-1).expand(-1,channels)
        rotation_matrix[:,:,0] = orthonormal_b1
        rotation_matrix[:,:,1] = orthonormal_b2
        orthonormal_b3 = torch.linalg.cross(orthonormal_b1, orthonormal_b2)
        sign_flip = torch.bmm(v_t3.unsqueeze(1), orthonormal_b3.unsqueeze(-1)) > 0
        mask = 2*sign_flip -1
        orthonormal_b3 = mask.squeeze(-1)*orthonormal_b3
        rotation_matrix[:,:,2] = orthonormal_b3
        return rotation_matrix

    def Rotate(self, history_input):
        self.history_input = history_input
         #INPUT: batchsize x k history x nmodes x 3dims
        self.rotation_matrix = self.RotationMatrix()
        #assert (torch.diagonal(torch.bmm(rotation_matrix, rotation_matrix.transpose(1,2)),dim1=1,dim2=2).sum() == float(self.history_input.size(0)*self.history_input.size(-1))).item()
        rot_traj = torch.zeros_like(self.history_input).to(self.history_input)
        for k in range(self.history_input.size(1)):
            rot_traj[:,k,:] = torch.bmm(self.rotation_matrix.transpose(1,2),self.history_input[:,k,:].unsqueeze(-1)).squeeze(-1)
        return rot_traj

    def __getitem__(self):
        return self.sigma

    def __getitem__(self):
        return self.rot_history


__author__ = 'twisted'
from PyQt4 import QtCore

class OutputReader(QtCore.QThread):
    def __init__(self, cmd_runner=None, _callback_object=None):
        QtCore.QThread.__init__(self)
        self.__cmdr = None
        self.__callback_object = None
        self.set_command_runner(cmd_runner)
        self.set_output_callback_object(_callback_object)
        self.__stop = False

    def set_command_runner(self, cmd_runner):
        self.__cmdr = cmd_runner

    # obsolete
    def set_output_callback_object(self, _callback_object):
        self.__callback_object = _callback_object

    def run(self):
        if self.__cmdr is not None:
            self.__stop = False
            while not self.__stop:
                line = (
                    self.__cmdr.get_process()
                        .stdout.readline().decode().replace('\n', ''))

                if str(line) != '':
                    self.emit(QtCore.SIGNAL('update(QString)'),
                              line)
            self.__cmdr.stop()

    def stop(self):
        self.__stop = True


import logging
from typing import Dict, List, Tuple
import struct as _struct
import platform as _platform
import re

from .archerror import ArchError
from . import RegisterOffset, RegisterName
from .tls import TLSArchInfo

import copy

l = logging.getLogger("archinfo.arch")
l.addHandler(logging.NullHandler())

try:
    import pyvex as _pyvex
except ImportError:
    _pyvex = None

try:
    import unicorn as _unicorn
except ImportError:
    _unicorn = None

try:
    import capstone as _capstone
except ImportError:
    _capstone = None

try:
    import keystone as _keystone
except ImportError:
    _keystone = None

class Endness: # pylint: disable=no-init
    """ Endness specifies the byte order for integer values

    :cvar LE:      little endian, least significant byte is stored at lowest address
    :cvar BE:      big endian, most significant byte is stored at lowest address
    :cvar ME:      Middle-endian. Yep.
    """
    LE = "Iend_LE"
    BE = "Iend_BE"
    ME = 'Iend_ME'

class Register:
    """
    A collection of information about a register. Each different architecture
    has its own list of registers, which is the base for all other
    register-related collections.

    It is, just like for Arch object, assumed that the information is compatible
    with PyVEX.

    :ivar str  name: The name of the register
    :ivar int  size: The size of the register (in bytes)
    :ivar int  vex_offset: The VEX offset used to identify this register
    :ivar str  vex_name: The name libVEX uses to identify the register
    :ivar list subregisters: The list of subregisters in the form (name, offset from vex_offset, size)
    :ivar tuple alias_names: The list of possible alias names
    :ivar bool general_purpose: Whether this is a general purpose register
    :ivar bool floating_point: Whether this is a floating-point register
    :ivar bool vector: Whether this is a vector register
    :ivar bool argument: Whether this is an argument register
    :ivar bool persistent: Whether this is a persistent register
    :ivar tuple default_value: The offset of the instruction pointer in the register file
    :ivar int, str linux_entry_value: The offset of the instruction pointer in the register file
    :ivar bool concretize_unique: Whether this register should be concretized, if unique, at the end of each block
    :ivar bool concrete: Whether this register should be considered during the synchronization of the concrete execution
                         of the process
    :ivar bool artificial: Whether this register is an artificial register added by VEX IR or other ILs.
    """
    def __init__(self, name, size, vex_offset=None, vex_name=None, subregisters=None,
                 alias_names=None, general_purpose=False, floating_point=False,
                 vector=False, argument=False, persistent=False, default_value=None,
                 linux_entry_value=None, concretize_unique=False, concrete=True,
                 artificial=False):
        self.name = name # type: RegisterName
        self.size = size # type: int
        self.vex_offset = vex_offset # type: RegisterOffset
        self.vex_name = vex_name
        self.subregisters = [] if subregisters is None else subregisters # type: List[Tuple[RegisterName, RegisterOffset, int]]
        self.alias_names = () if alias_names is None else alias_names
        self.general_purpose = general_purpose
        self.floating_point = floating_point
        self.vector = vector
        self.argument= argument
        self.persistent = persistent
        self.default_value = default_value
        self.linux_entry_value = linux_entry_value
        self.concretize_unique = concretize_unique
        self.concrete = concrete
        self.artificial = artificial

    def __repr__(self):
        return '<Register %s>' % (self.name,)

class Arch:
    """
    A collection of information about a given architecture. This class should be subclasses for each different
    architecture, and then that subclass should be registered with the ``register_arch`` method.

    A good number of assumptions are made that code is being processed under the VEX IR - for instance, it is expected
    the register file offsets are expected to match code generated by PyVEX.

    Arches may be compared with == and !=.

    :ivar str name: The name of the arch
    :ivar int bits: The number of bits in a word
    :ivar str vex_arch: The VEX enum name used to identify this arch
    :ivar str qemu_name: The name used by QEMU to identify this arch
    :ivar str ida_processor: The processor string used by IDA to identify this arch
    :ivar str triplet: The triplet used to identify a linux system on this arch
    :ivar int max_inst_bytes: The maximum number of bytes in a single instruction
    :ivar int ip_offset: The offset of the instruction pointer in the register file
    :ivar int sp_offset: The offset of the stack pointer in the register file
    :ivar int bp_offset: The offset of the base pointer in the register file
    :ivar int lr_offset: The offset of the link register (return address) in the register file
    :ivar int ret_offset: The offset of the return value register in the register file
    :ivar bool vex_conditional_helpers: Whether libVEX will generate code to process the conditional flags for this
            arch using ccalls
    :ivar int syscall_num_offset: The offset in the register file where the syscall number is stored
    :ivar bool call_pushes_ret: Whether this arch's call instruction causes a stack push
    :ivar int stack_change: The change to the stack pointer caused by a push instruction
    :ivar str memory_endness: The endness of memory, as a VEX enum
    :ivar str register_endness: The endness of registers, as a VEX enum. Should usually be same as above
    :ivar str instruction_endness: The endness of instructions stored in memory.
        In other words, this controls whether instructions are stored endian-flipped compared to their description
        in the ISA manual, and should be flipped when lifted. Iend_BE means "don't flip"
        NOTE: Only used for non-libVEX lifters.
    :ivar dict sizeof: A mapping from C type to variable size in bits
    :ivar cs_arch: The Capstone arch value for this arch
    :ivar cs_mode: The Capstone mode value for this arch
    :ivar ks_arch: The Keystone arch value for this arch
    :ivar ks_mode: The Keystone mode value for this arch
    :ivar uc_arch: The Unicorn engine arch value for this arch
    :ivar uc_mode: The Unicorn engine mode value for this arch
    :ivar uc_const: The Unicorn engine constants module for this arch
    :ivar uc_prefix: The prefix used for variables in the Unicorn engine constants module
    :ivar list function_prologs: A list of regular expressions matching the bytes for common function prologues
    :ivar list function_epilogs: A list of regular expressions matching the bytes for common function epilogues
    :ivar str ret_instruction: The bytes for a return instruction
    :ivar str nop_instruction: The bytes for a nop instruction
    :ivar int instruction_alignment: The instruction alignment requirement
    :ivar list default_register_values: A weird listing describing how registers should be initialized for purposes of
            sanity
    :ivar dict entry_register_values: A mapping from register name to a description of the value that should be in it
            at program entry on linux
    :ivar list default_symbolic_register: Honestly, who knows what this is supposed to do. Fill it with the names of
            the general purpose registers.
    :ivar dict register_names: A mapping from register file offset to register name
    :ivar dict registers: A mapping from register name to a tuple of (register file offset, size in bytes)
    :ivar list lib_paths: A listing of common locations where shared libraries for this architecture may be found
    :ivar str got_section_name: The name of the GOT section in ELFs
    :ivar str ld_linux_name: The name of the linux dynamic loader program
    :cvar int byte_width: the number of bits in a byte.
    :ivar TLSArchInfo elf_tls: A description of how thread-local storage works
    """
    byte_width = 8
    instruction_endness = "Iend_BE"
    elf_tls = None  # type: TLSArchInfo

    def __init__(self, endness, instruction_endness=None):

        self.bytes = self.bits // self.byte_width

        if endness not in (Endness.LE, Endness.BE, Endness.ME):
            raise ArchError('Must pass a valid endness: Endness.LE, Endness.BE, or Endness.ME')

        if instruction_endness is not None:
            self.instruction_endness = instruction_endness

        if self.vex_support and _pyvex:
            self.vex_archinfo = _pyvex.default_vex_archinfo()

        if endness == Endness.BE:
            if self.vex_archinfo:
                self.vex_archinfo['endness'] = _pyvex.vex_endness_from_string('VexEndnessBE')
            self.memory_endness = Endness.BE
            self.register_endness = Endness.BE
            if _capstone and self.cs_mode is not None:
                self.cs_mode -= _capstone.CS_MODE_LITTLE_ENDIAN
                self.cs_mode += _capstone.CS_MODE_BIG_ENDIAN
            if _keystone and self.ks_mode is not None:
                self.ks_mode -= _keystone.KS_MODE_LITTLE_ENDIAN
                self.ks_mode += _keystone.KS_MODE_BIG_ENDIAN
            self.ret_instruction = reverse_ends(self.ret_instruction)
            self.nop_instruction = reverse_ends(self.nop_instruction)

        if self.register_list and _pyvex is not None:
            (_, _), max_offset = max(_pyvex.vex_ffi.guest_offsets.items(), key=lambda x: x[1])
            max_offset += self.bits
            # Register collections
            if type(self.vex_arch) is str:
                va = self.vex_arch[7:].lower() # pylint: disable=unsubscriptable-object
                for r in self.register_list:
                    if r.vex_offset is None:
                        for name in (r.vex_name, r.name) + r.alias_names:
                            try:
                                r.vex_offset = _pyvex.vex_ffi.guest_offsets[(va, name)]
                            except KeyError:
                                r.vex_offset = max_offset
                                max_offset += r.size
                            else:
                                break

            self.default_register_values = [(r.name,) + r.default_value for r in self.register_list if r.default_value is not None]
            self.entry_register_values = {r.name: r.linux_entry_value for r in self.register_list if r.linux_entry_value is not None}
            self.default_symbolic_registers = [r.name for r in self.register_list if r.general_purpose]
            self.register_names = {r.vex_offset: r.name for r in self.register_list}
            self.registers = self._get_register_dict()
            self.argument_registers = set(r.vex_offset for r in self.register_list if r.argument)
            self.persistent_regs = [r.name for r in self.register_list if r.persistent]
            self.concretize_unique_registers = set(r.vex_offset for r in self.register_list if r.concretize_unique)
            self.artificial_registers = set(r.name for r in self.register_list if r.artificial)

            # Register offsets
            try:
                self.ip_offset = self.registers['ip'][0]
                self.sp_offset = self.registers['sp'][0]
                self.bp_offset = self.registers['bp'][0]
                self.lr_offset = self.registers.get('lr', (None, None))[0]
            except KeyError:
                pass

        # generate register mapping (offset, size): name
        self.register_size_names = {}
        for reg in self.register_list:
            if reg.vex_offset is None:
                continue
            self.register_size_names[(reg.vex_offset, reg.size)] = reg.name
            for name, off, sz in reg.subregisters:
                # special hacks for X86 and AMD64 - don't translate register names to bp, sp, etc.
                if self.name in {'X86', 'AMD64'} and name in {'bp', 'sp', 'ip'}:
                    continue
                self.register_size_names[(reg.vex_offset + off, sz)] = name

        # allow mapping a sub-register to its base register
        self.subregister_map = { }
        for reg in self.register_list:
            if reg.vex_offset is None:
                continue
            base_reg = reg.vex_offset, reg.size
            self.subregister_map[(reg.vex_offset, reg.size)] = base_reg
            self.subregister_map[reg.vex_offset] = base_reg
            for name, off, sz in reg.subregisters:
                if self.name in {'X86', 'AMD64'} and name in {'bp', 'sp', 'ip'}:
                    continue
                subreg_offset = reg.vex_offset + off
                self.subregister_map[(subreg_offset, sz)] = base_reg
                if subreg_offset not in self.subregister_map:
                    self.subregister_map[subreg_offset] = base_reg

        # Unicorn specific stuff
        if self.uc_mode is not None:
            if endness == Endness.BE:
                self.uc_mode -= _unicorn.UC_MODE_LITTLE_ENDIAN
                self.uc_mode += _unicorn.UC_MODE_BIG_ENDIAN
            self.uc_regs = { }
            # map register names to Unicorn const
            for r in self.register_names.values():
                reg_name = self.uc_prefix + 'REG_' + r.upper()
                if hasattr(self.uc_const, reg_name):
                    self.uc_regs[r] = getattr(self.uc_const, reg_name)

            # Register blacklist
            reg_blacklist = ('cs', 'ds', 'es', 'fs', 'gs', 'ss', 'mm0', 'mm1', 'mm2', 'mm3', 'mm4', 'mm5', 'mm6', 'mm7', 'gdt', 'ldt')
            self.reg_blacklist = []
            self.reg_blacklist_offsets = []
            for register in self.register_list:
                if register.name in reg_blacklist:
                    self.reg_blacklist.append(register.name)
                    self.reg_blacklist_offsets.append(register.vex_offset)

            # Artificial registers offsets
            self.artificial_registers_offsets = []
            self.vex_reg_to_size_map = {}
            for reg_name in self.artificial_registers:
                reg = self.get_register_by_name(reg_name)
                self.vex_reg_to_size_map[reg.vex_offset] = reg.size
                self.artificial_registers_offsets.extend(range(reg.vex_offset, reg.vex_offset + reg.size))

            # VEX register offset to unicorn register ID and to name maps
            self.vex_reg_offset_to_name = {}
            self.vex_to_unicorn_map = {}
            self.vex_sub_reg_to_reg_map = {}
            pc_reg_name = self.get_register_by_name("pc")
            for reg_name, unicorn_reg_id in self.uc_regs.items():
                if reg_name == pc_reg_name:
                    continue

                vex_reg = self.get_register_by_name(reg_name)
                self.vex_reg_offset_to_name[vex_reg.vex_offset] = (reg_name, vex_reg.size)
                self.vex_to_unicorn_map[vex_reg.vex_offset] = unicorn_reg_id
                self.vex_reg_to_size_map[vex_reg.vex_offset] = vex_reg.size
                for vex_sub_reg in vex_reg.subregisters:
                    vex_sub_reg_offset = self.get_register_offset(vex_sub_reg[0])
                    if vex_sub_reg_offset not in self.vex_reg_offset_to_name:
                        self.vex_reg_offset_to_name[vex_sub_reg_offset] = (reg_name, vex_reg.size)

                    self.vex_sub_reg_to_reg_map[vex_sub_reg_offset] = vex_reg.vex_offset

            # CPU flag registers
            cpu_flag_registers = {'d': 10, 'ac': 18, 'id': 21}
            self.cpu_flag_register_offsets_and_bitmasks_map = {}
            for flag_reg, bitmask in cpu_flag_registers.items():
                if flag_reg in self.registers:
                    flag_reg_offset = self.get_register_offset(flag_reg)
                    flag_bitmask = (1 << bitmask)
                    self.cpu_flag_register_offsets_and_bitmasks_map[flag_reg_offset] = flag_bitmask

    def copy(self):
        """
        Produce a copy of this instance of this arch.
        """
        res = copy.copy(self)
        res.vex_archinfo = copy.deepcopy(self.vex_archinfo)
        res._cs = None
        res._ks = None
        return res

    def __repr__(self):
        return '<Arch %s (%s)>' % (self.name, self.memory_endness[-2:])

    def __hash__(self):
        return hash((self.name, self.bits, self.memory_endness))

    def __eq__(self, other):
        if not isinstance(other, Arch):
            return False
        return  self.name == other.name and \
                self.bits == other.bits and \
                self.memory_endness == other.memory_endness

    def __ne__(self, other):
        return not self == other

    def __getstate__(self):
        self._cs = None
        self._ks = None
        return self.__dict__

    def __setstate__(self, data):
        self.__dict__.update(data)

    def get_register_by_name(self, reg_name):
        """
        Return the Register object associated with the given name.
        This includes subregisters.

        For example, if you are operating in a platform-independent
        setting, and wish to address "whatever the stack pointer is"
        you could pass 'sp' here, and get Register(...r13...) back
        on an ARM platform.
        """
        for r in self.register_list:
            if reg_name == r.name or reg_name in r.alias_names:
                return r
        return None

    def get_default_reg_value(self, register):
        if register == 'sp':
            # Convert it to the corresponding register name
            registers = [r for r, v in self.registers.items() if v[0] == self.sp_offset]
            if len(registers) > 0:
                register = registers[0]
            else:
                return None
        for reg, val, _, _ in self.default_register_values:
            if reg == register:
                return val
        return None

    def struct_fmt(self, size=None, signed=False, endness=None):
        """
        Produce a format string for use in python's ``struct`` module to decode a single word.

        :param int size:    The size in bytes to pack/unpack. Defaults to wordsize
        :param bool signed: Whether the data should be extracted signed/unsigned. Default unsigned
        :param str endness: The endian to use in packing/unpacking. Defaults to memory endness
        :return str:        A format string with an endness modifier and a single format character
        """
        if size is None:
            size = self.bytes
        if endness is None:
            endness = self.memory_endness

        if endness == Endness.BE:
            fmt_end = ">"
        elif endness == Endness.LE:
            fmt_end = "<"
        elif endness == Endness.ME:
            raise ValueError("Please don't middle-endian at me, I'm begging you")
        else:
            raise ValueError("Invalid endness value: %r" % endness)

        if size == 8:
            fmt_size = "Q"
        elif size == 4:
            fmt_size = "I"
        elif size == 2:
            fmt_size = "H"
        elif size == 1:
            fmt_size = "B"
        else:
            raise ValueError("Invalid size: Must be a integer power of 2 less than 16")

        if signed:
            fmt_size = fmt_size.lower()

        return fmt_end + fmt_size

    def _get_register_dict(self) ->  Dict[RegisterName, Tuple[RegisterOffset, int]]:
        res = {}
        for r in self.register_list:
            if r.vex_offset is None:
                continue
            res[r.name] = (r.vex_offset, r.size)
            for i in r.alias_names:
                res[i] = (r.vex_offset, r.size)
            for reg, offset, size in r.subregisters:
                res[reg] = (r.vex_offset + offset, size)
        return res

    # e.g. sizeof['int'] = 4
    sizeof = {}

    @property
    def capstone(self):
        """
        A Capstone instance for this arch
        """
        if _capstone is None:
            raise Exception("Capstone is not installed!")
        if self.cs_arch is None:
            raise ArchError("Arch %s does not support disassembly with Capstone" % self.name)
        if self._cs is None:
            self._cs = _capstone.Cs(self.cs_arch, self.cs_mode)
            self._configure_capstone()
            self._cs.detail = True
        return self._cs

    @property
    def keystone(self):
        """
        A Keystone instance for this arch
        """
        if self._ks is None:
            if _keystone is None:
                raise Exception("Keystone is not installed!")
            if self.ks_arch is None:
                raise ArchError("Arch %s does not support disassembly with Keystone" % self.name)
            self._ks = _keystone.Ks(self.ks_arch, self.ks_mode)
            self._configure_keystone()
        return self._ks

    def _configure_capstone(self):
        pass

    def _configure_keystone(self):
        pass

    @property
    def unicorn(self):
        """
        A Unicorn engine instance for this arch
        """
        if _unicorn is None or self.uc_arch is None:
            raise ArchError("Arch %s does not support with Unicorn" % self.name)
        # always create a new Unicorn instance
        return _unicorn.Uc(self.uc_arch, self.uc_mode)

    def asm(self, string, addr=0, as_bytes=True, thumb=False):
        """
        Compile the assembly instruction represented by string using Keystone

        :param string:      The textual assembly instructions, separated by semicolons
        :param addr:        The address at which the text should be assembled, to deal with PC-relative access. Default 0
        :param as_bytes:    Set to False to return a list of integers instead of a python byte string
        :param thumb:       If working with an ARM processor, set to True to assemble in thumb mode.
        :return:            The assembled bytecode
        """
        if thumb and not hasattr(self, 'keystone_thumb'):
            l.warning("Specified thumb=True on non-ARM architecture")
            thumb = False
        ks = self.keystone_thumb if thumb else self.keystone # pylint: disable=no-member

        try:
            encoding, _ = ks.asm(string, addr, as_bytes) # pylint: disable=too-many-function-args
        except TypeError:
            bytelist, _ = ks.asm(string, addr)
            if as_bytes:
                if bytes is str:
                    encoding = ''.join(chr(c) for c in bytelist)
                else:
                    encoding = bytes(bytelist)
            else:
                encoding = bytelist

        return encoding

    def disasm(self, bytestring, addr=0, thumb=False):
        if thumb and not hasattr(self, 'capstone_thumb'):
            l.warning("Specified thumb=True on non-ARM architecture")
            thumb = False
        cs = self.capstone_thumb if thumb else self.capstone # pylint: disable=no-member
        return '\n'.join('%#x:\t%s %s' % (insn.address, insn.mnemonic, insn.op_str) for insn in cs.disasm(bytestring, addr))

    def translate_dynamic_tag(self, tag):
        try:
            return self.dynamic_tag_translation[tag]
        except KeyError:
            if isinstance(tag, int):
                l.error("Please look up and add dynamic tag type %#x for %s", tag, self.name)
            return tag

    def translate_symbol_type(self, tag):
        try:
            return self.symbol_type_translation[tag]
        except KeyError:
            if isinstance(tag, int):
                l.error("Please look up and add symbol type %#x for %s", tag, self.name)
            return tag

    def translate_register_name(self, offset, size=None):
        if size is not None:
            try:
                return self.register_size_names[(offset, size)]
            except KeyError:
                pass

        try:
            return self.register_names[offset]
        except KeyError:
            return str(offset)

    def get_base_register(self, offset, size=None):
        """
        Convert a register or sub-register to its base register's offset.

        :param int offset:  The offset of the register to look up for.
        :param int size:    Size of the register.
        :return:            Offset and size of the base register, or None if no base register is found.
        """

        if size is None:
            key = offset
        else:
            key = (offset, size)

        return self.subregister_map.get(key, None)

    def get_register_offset(self, name):
        try:
            return self.registers[name][0]
        except:
            raise ValueError("Register %s does not exist!" % name)

    def is_artificial_register(self, offset, size):

        r = self.get_base_register(offset, size)
        if r is None:
            return False
        r_offset, _ = r

        try:
            r_name = self.register_names[r_offset]
        except KeyError:
            return False

        return r_name in self.artificial_registers

    # Determined by watching the output of strace ld-linux.so.2 --list --inhibit-cache
    def library_search_path(self, pedantic=False):
        """
        A list of paths in which to search for shared libraries.
        """
        subfunc = lambda x: x.replace('${TRIPLET}', self.triplet).replace('${ARCH}', self.linux_name)
        path = ['/lib/${TRIPLET}/', '/usr/lib/${TRIPLET}/', '/lib/', '/usr/lib', '/usr/${TRIPLET}/lib/']
        if self.bits == 64:
            path.append('/usr/${TRIPLET}/lib64/')
            path.append('/usr/lib64/')
            path.append('/lib64/')
        elif self.bits == 32:
            path.append('/usr/${TRIPLET}/lib32/')
            path.append('/usr/lib32/')
            path.append('/lib32/')

        if pedantic:
            path = sum([[x + 'tls/${ARCH}/', x + 'tls/', x + '${ARCH}/', x] for x in path], [])
        return list(map(subfunc, path))

    def m_addr(self, addr, *args, **kwargs):
        """
        Given the address of some code block, convert it to the address where this block
        is stored in memory. The memory address can also be referred to as the "real" address.

        :param addr:    The address to convert.
        :return:        The "real" address in memory.
        :rtype:         int
        """
        return addr

    def x_addr(self, addr, *args, **kwargs):
        """
        Given the address of some code block, convert it to the value that should be assigned
        to the instruction pointer register in order to execute the code in that block.

        :param addr:    The address to convert.
        :return:        The "execution" address.
        :rtype:         int
        """
        return addr

    def is_thumb(self, addr):  # pylint:disable=unused-argument
        """
        Return True, if the address is the THUMB address. False otherwise.

        For non-ARM architectures this method always returns False.

        :param addr:    The address to check.
        :return:        Whether the given address is the THUMB address.
        """
        return False

    @property
    def vex_support(self):
        """
        Whether the architecture is supported by VEX or not.

        :return: True if this Arch is supported by VEX, False otherwise.
        :rtype:  bool
        """

        return self.vex_arch is not None

    @property
    def unicorn_support(self):
        """
        Whether the architecture is supported by Unicorn engine or not,

        :return: True if this Arch is supported by the Unicorn engine, False otherwise.
        :rtype:  bool
        """

        return self.qemu_name is not None

    @property
    def capstone_support(self):
        """
        Whether the architecture is supported by the Capstone engine or not.

        :return: True if this Arch is supported by the Capstone engine, False otherwise.
        :rtype:  bool
        """

        return self.cs_arch is not None

    @property
    def keystone_support(self):
        """
        Whether the architecture is supported by the Keystone engine or not.

        :return: True if this Arch is supported by the Keystone engine, False otherwise.
        :rtype:  bool
        """

        return self.ks_arch is not None

    address_types = (int,)
    function_address_types = (int,)

    # various names
    name = None # type: str
    vex_arch = None
    qemu_name = None
    ida_processor = None
    linux_name = None
    triplet = None

    # instruction stuff
    max_inst_bytes = None
    ret_instruction = b''
    nop_instruction = b''
    instruction_alignment = None

    # register ofsets
    ip_offset = None # type: RegisterOffset
    sp_offset = None # type: RegisterOffset
    bp_offset = None # type: RegisterOffset
    ret_offset = None # type: RegisterOffset
    lr_offset = None # type: RegisterOffset

    # whether or not VEX has ccall handlers for conditionals for this arch
    vex_conditional_helpers = False

    # memory stuff
    bits = None
    memory_endness = Endness.LE
    register_endness = Endness.LE
    stack_change = None

    # is it safe to cache IRSBs?
    cache_irsb = True

    branch_delay_slot = False

    function_prologs = set()
    function_epilogs = set()

    # Capstone stuff
    cs_arch = None
    cs_mode = None
    _cs = None

    # Keystone stuff
    ks_arch = None
    ks_mode = None
    _ks = None

    # Unicorn stuff
    uc_arch = None
    uc_mode = None
    uc_const = None
    uc_prefix = None
    uc_regs = None
    artificial_registers_offsets = None
    artificial_registers = set()
    cpu_flag_register_offsets_and_bitmasks_map = None
    reg_blacklist = None
    reg_blacklist_offsets = None
    unicorn_flag_register = None
    vex_reg_offset_to_name = None
    vex_reg_to_size_map = None
    vex_sub_reg_to_reg_map = None
    vex_to_unicorn_map = None

    call_pushes_ret = False
    initial_sp = 0x7fff0000

    # Difference of the stack pointer after a call instruction (or its equivalent) is executed
    call_sp_fix = 0

    stack_size = 0x8000000

    # Register information
    register_list = [] # type: List[Register]
    default_register_values = []
    entry_register_values = {}
    default_symbolic_registers = []
    registers = {} # type:  Dict[RegisterName, Tuple[RegisterOffset, int]]
    register_names = {} # type: Dict[RegisterOffset, RegisterName]
    argument_registers = set()
    argument_register_positions = {}
    persistent_regs = []
    concretize_unique_registers = set() # this is a list of registers that should be concretized, if unique, at the end of each block

    lib_paths = []
    reloc_s_a = []
    reloc_b_a = []
    reloc_s = []
    reloc_copy = []
    reloc_tls_mod_id = []
    reloc_tls_doffset = []
    reloc_tls_offset = []
    dynamic_tag_translation = {}
    symbol_type_translation = {}
    got_section_name = ''

    vex_archinfo = None

arch_id_map = []

all_arches = []

def register_arch(regexes, bits, endness, my_arch):
    """
    Register a new architecture.
    Architectures are loaded by their string name using ``arch_from_id()``, and
    this defines the mapping it uses to figure it out.
    Takes a list of regular expressions, and an Arch class as input.

    :param regexes: List of regular expressions (str or SRE_Pattern)
    :type regexes: list
    :param bits: The canonical "bits" of this architecture, ex. 32 or 64
    :type bits: int
    :param endness: The "endness" of this architecture.  Use Endness.LE, Endness.BE, Endness.ME, "any", or None if the
                    architecture has no intrinsic endianness.
    :type endness: str or None
    :param class my_arch:
    :return: None
    """
    if not isinstance(regexes, list):
        raise TypeError("regexes must be a list")
    for rx in regexes:
        if not isinstance(rx, str) and not isinstance(rx,re._pattern_type):
            raise TypeError("Each regex must be a string or compiled regular expression")
        try:
            re.compile(rx)
        except:
            raise ValueError('Invalid Regular Expression %s' % rx)
    #if not isinstance(my_arch,Arch):
    #    raise TypeError("Arch must be a subclass of archinfo.Arch")
    if not isinstance(bits, int):
        raise TypeError("Bits must be an int")
    if endness is not None:
        if endness not in (Endness.BE, Endness.LE, Endness.ME, 'any'):
            raise TypeError("Endness must be Endness.BE, Endness.LE, or 'any'")
    arch_id_map.append((regexes, bits, endness, my_arch))
    if endness == 'any':
        all_arches.append(my_arch(Endness.BE))
        all_arches.append(my_arch(Endness.LE))
    else:
        all_arches.append(my_arch(endness))

class ArchNotFound(Exception):
    pass

def arch_from_id(ident, endness='any', bits='') -> Arch:
    """
    Take our best guess at the arch referred to by the given identifier, and return an instance of its class.

    You may optionally provide the ``endness`` and ``bits`` parameters (strings) to help this function out.
    """
    if bits == 64 or (isinstance(bits, str) and '64' in bits):
        bits = 64
    elif isinstance(bits,str) and '32' in bits:
        bits = 32
    elif not bits and '64' in ident:
        bits = 64
    elif not bits and '32' in ident:
        bits = 32

    endness = endness.lower()
    if 'lit' in endness:
        endness = Endness.LE
    elif 'big' in endness:
        endness = Endness.BE
    elif 'lsb' in endness:
        endness = Endness.LE
    elif 'msb' in endness:
        endness = Endness.BE
    elif 'le' in endness:
        endness = Endness.LE
    elif 'be' in endness:
        endness = Endness.BE
    elif 'l' in endness:
        endness = 'unsure'
    elif 'b' in endness:
        endness = 'unsure'
    else:
        endness = 'unsure'
    ident = ident.lower()
    cls = None
    aendness = ""
    for arxs, abits, aendness, acls in arch_id_map:
        found_it = False
        for rx in arxs:
            if re.search(rx, ident):
                found_it = True
                break
        if not found_it:
            continue
        if bits and bits != abits:
            continue
        if aendness == 'any' or endness == aendness or endness == 'unsure':
            cls = acls
            break
    if not cls:
        raise ArchNotFound("Can't find architecture info for architecture %s with %s bits and %s endness" % (ident, repr(bits), endness))
    if endness == 'unsure':
        if aendness == 'any':
            # We really don't care, use default
            return cls()
        else:
            # We're expecting the ident to pick the endness.
            # ex. 'armeb' means obviously this is Iend_BE
            return cls(aendness)
    else:
        return cls(endness)

def reverse_ends(string):
    count = (len(string) + 3) // 4
    ise = 'I' * count
    string += b'\x00' * (count * 4 - len(string))
    return _struct.pack('>' + ise, *_struct.unpack('<' + ise, string))

def get_host_arch():
    """
    Return the arch of the machine we are currently running on.
    """
    return arch_from_id(_platform.machine())


#christinajoice

n=int(input("Size of array"))
a=input().split()
b=[]
c=[]
for i in range(n):
  b.append(bin(int(a[i]))[2:])
  c.append(b[i].count('1'))
for i in range(0,n-1):
  for j in range(1,n):
    if i!=j:
      if c[i]<c[j]:
        a[i],a[j]=a[j],a[i]
      elif c[i]==c[j]:
        if a[i]<a[j]:
          a[i],a[j]=a[j],a[i]
print('\n'.join(a))