text:
# Julia wrapper for header: /usr/include/postgresql/libpq-fe.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function PQconnectStart(conninfo)
    ccall((:PQconnectStart,libpq),Ptr{PGconn},(Cstring,),conninfo)
end

function PQconnectStartParams(keywords,values,expand_dbname::Cint)
    ccall((:PQconnectStartParams,libpq),Ptr{PGconn},(Ptr{Cstring},Ptr{Cstring},Cint),keywords,values,expand_dbname)
end

function PQconnectPoll(conn)
    ccall((:PQconnectPoll,libpq),PostgresPollingStatusType,(Ptr{PGconn},),conn)
end

function PQconnectdb(conninfo)
    ccall((:PQconnectdb,libpq),Ptr{PGconn},(Cstring,),conninfo)
end

function PQconnectdbParams(keywords,values,expand_dbname::Cint)
    ccall((:PQconnectdbParams,libpq),Ptr{PGconn},(Ptr{Cstring},Ptr{Cstring},Cint),keywords,values,expand_dbname)
end

function PQsetdbLogin(pghost,pgport,pgoptions,pgtty,dbName,login,pwd)
    ccall((:PQsetdbLogin,libpq),Ptr{PGconn},(Cstring,Cstring,Cstring,Cstring,Cstring,Cstring,Cstring),pghost,pgport,pgoptions,pgtty,dbName,login,pwd)
end

function PQfinish(conn)
    ccall((:PQfinish,libpq),Void,(Ptr{PGconn},),conn)
end

function PQconndefaults()
    ccall((:PQconndefaults,libpq),Ptr{PQconninfoOption},())
end

function PQconninfoParse(conninfo,errmsg)
    ccall((:PQconninfoParse,libpq),Ptr{PQconninfoOption},(Cstring,Ptr{Cstring}),conninfo,errmsg)
end

function PQconninfo(conn)
    ccall((:PQconninfo,libpq),Ptr{PQconninfoOption},(Ptr{PGconn},),conn)
end

function PQconninfoFree(connOptions)
    ccall((:PQconninfoFree,libpq),Void,(Ptr{PQconninfoOption},),connOptions)
end

function PQresetStart(conn)
    ccall((:PQresetStart,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQresetPoll(conn)
    ccall((:PQresetPoll,libpq),PostgresPollingStatusType,(Ptr{PGconn},),conn)
end

function PQreset(conn)
    ccall((:PQreset,libpq),Void,(Ptr{PGconn},),conn)
end

function PQgetCancel(conn)
    ccall((:PQgetCancel,libpq),Ptr{PGcancel},(Ptr{PGconn},),conn)
end

function PQfreeCancel(cancel)
    ccall((:PQfreeCancel,libpq),Void,(Ptr{PGcancel},),cancel)
end

function PQcancel(cancel,errbuf,errbufsize::Cint)
    ccall((:PQcancel,libpq),Cint,(Ptr{PGcancel},Cstring,Cint),cancel,errbuf,errbufsize)
end

function PQrequestCancel(conn)
    ccall((:PQrequestCancel,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQdb(conn)
    ccall((:PQdb,libpq),Cstring,(Ptr{PGconn},),conn)
end

function PQuser(conn)
    ccall((:PQuser,libpq),Cstring,(Ptr{PGconn},),conn)
end

function PQpass(conn)
    ccall((:PQpass,libpq),Cstring,(Ptr{PGconn},),conn)
end

function PQhost(conn)
    ccall((:PQhost,libpq),Cstring,(Ptr{PGconn},),conn)
end

function PQport(conn)
    ccall((:PQport,libpq),Cstring,(Ptr{PGconn},),conn)
end

function PQtty(conn)
    ccall((:PQtty,libpq),Cstring,(Ptr{PGconn},),conn)
end

function PQoptions(conn)
    ccall((:PQoptions,libpq),Cstring,(Ptr{PGconn},),conn)
end

function PQstatus(conn)
    ccall((:PQstatus,libpq),ConnStatusType,(Ptr{PGconn},),conn)
end

function PQtransactionStatus(conn)
    ccall((:PQtransactionStatus,libpq),PGTransactionStatusType,(Ptr{PGconn},),conn)
end

function PQparameterStatus(conn,paramName)
    ccall((:PQparameterStatus,libpq),Cstring,(Ptr{PGconn},Cstring),conn,paramName)
end

function PQprotocolVersion(conn)
    ccall((:PQprotocolVersion,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQserverVersion(conn)
    ccall((:PQserverVersion,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQerrorMessage(conn)
    ccall((:PQerrorMessage,libpq),Cstring,(Ptr{PGconn},),conn)
end

function PQsocket(conn)
    ccall((:PQsocket,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQbackendPID(conn)
    ccall((:PQbackendPID,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQconnectionNeedsPassword(conn)
    ccall((:PQconnectionNeedsPassword,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQconnectionUsedPassword(conn)
    ccall((:PQconnectionUsedPassword,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQclientEncoding(conn)
    ccall((:PQclientEncoding,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQsetClientEncoding(conn,encoding)
    ccall((:PQsetClientEncoding,libpq),Cint,(Ptr{PGconn},Cstring),conn,encoding)
end

function PQsslInUse(conn)
    ccall((:PQsslInUse,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQsslStruct(conn,struct_name)
    ccall((:PQsslStruct,libpq),Ptr{Void},(Ptr{PGconn},Cstring),conn,struct_name)
end

function PQsslAttribute(conn,attribute_name)
    ccall((:PQsslAttribute,libpq),Cstring,(Ptr{PGconn},Cstring),conn,attribute_name)
end

function PQsslAttributeNames(conn)
    ccall((:PQsslAttributeNames,libpq),Ptr{Cstring},(Ptr{PGconn},),conn)
end

function PQgetssl(conn)
    ccall((:PQgetssl,libpq),Ptr{Void},(Ptr{PGconn},),conn)
end

function PQinitSSL(do_init::Cint)
    ccall((:PQinitSSL,libpq),Void,(Cint,),do_init)
end

function PQinitOpenSSL(do_ssl::Cint,do_crypto::Cint)
    ccall((:PQinitOpenSSL,libpq),Void,(Cint,Cint),do_ssl,do_crypto)
end

function PQsetErrorVerbosity(conn,verbosity::PGVerbosity)
    ccall((:PQsetErrorVerbosity,libpq),PGVerbosity,(Ptr{PGconn},PGVerbosity),conn,verbosity)
end

function PQtrace(conn,debug_port)
    ccall((:PQtrace,libpq),Void,(Ptr{PGconn},Ptr{FILE}),conn,debug_port)
end

function PQuntrace(conn)
    ccall((:PQuntrace,libpq),Void,(Ptr{PGconn},),conn)
end

function PQsetNoticeReceiver(conn,proc::PQnoticeReceiver,arg)
    ccall((:PQsetNoticeReceiver,libpq),PQnoticeReceiver,(Ptr{PGconn},PQnoticeReceiver,Ptr{Void}),conn,proc,arg)
end

function PQsetNoticeProcessor(conn,proc::PQnoticeProcessor,arg)
    ccall((:PQsetNoticeProcessor,libpq),PQnoticeProcessor,(Ptr{PGconn},PQnoticeProcessor,Ptr{Void}),conn,proc,arg)
end

function PQregisterThreadLock(newhandler::pgthreadlock_t)
    ccall((:PQregisterThreadLock,libpq),pgthreadlock_t,(pgthreadlock_t,),newhandler)
end

function PQexec(conn,query)
    ccall((:PQexec,libpq),Ptr{PGresult},(Ptr{PGconn},Cstring),conn,query)
end

function PQexecParams(conn,command,nParams::Cint,paramTypes,paramValues,paramLengths,paramFormats,resultFormat::Cint)
    ccall((:PQexecParams,libpq),Ptr{PGresult},(Ptr{PGconn},Cstring,Cint,Ptr{Oid},Ptr{Cstring},Ptr{Cint},Ptr{Cint},Cint),conn,command,nParams,paramTypes,paramValues,paramLengths,paramFormats,resultFormat)
end

function PQprepare(conn,stmtName,query,nParams::Cint,paramTypes)
    ccall((:PQprepare,libpq),Ptr{PGresult},(Ptr{PGconn},Cstring,Cstring,Cint,Ptr{Oid}),conn,stmtName,query,nParams,paramTypes)
end

function PQexecPrepared(conn,stmtName,nParams::Cint,paramValues,paramLengths,paramFormats,resultFormat::Cint)
    ccall((:PQexecPrepared,libpq),Ptr{PGresult},(Ptr{PGconn},Cstring,Cint,Ptr{Cstring},Ptr{Cint},Ptr{Cint},Cint),conn,stmtName,nParams,paramValues,paramLengths,paramFormats,resultFormat)
end

function PQsendQuery(conn,query)
    ccall((:PQsendQuery,libpq),Cint,(Ptr{PGconn},Cstring),conn,query)
end

function PQsendQueryParams(conn,command,nParams::Cint,paramTypes,paramValues,paramLengths,paramFormats,resultFormat::Cint)
    ccall((:PQsendQueryParams,libpq),Cint,(Ptr{PGconn},Cstring,Cint,Ptr{Oid},Ptr{Cstring},Ptr{Cint},Ptr{Cint},Cint),conn,command,nParams,paramTypes,paramValues,paramLengths,paramFormats,resultFormat)
end

function PQsendPrepare(conn,stmtName,query,nParams::Cint,paramTypes)
    ccall((:PQsendPrepare,libpq),Cint,(Ptr{PGconn},Cstring,Cstring,Cint,Ptr{Oid}),conn,stmtName,query,nParams,paramTypes)
end

function PQsendQueryPrepared(conn,stmtName,nParams::Cint,paramValues,paramLengths,paramFormats,resultFormat::Cint)
    ccall((:PQsendQueryPrepared,libpq),Cint,(Ptr{PGconn},Cstring,Cint,Ptr{Cstring},Ptr{Cint},Ptr{Cint},Cint),conn,stmtName,nParams,paramValues,paramLengths,paramFormats,resultFormat)
end

function PQsetSingleRowMode(conn)
    ccall((:PQsetSingleRowMode,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQgetResult(conn)
    ccall((:PQgetResult,libpq),Ptr{PGresult},(Ptr{PGconn},),conn)
end

function PQisBusy(conn)
    ccall((:PQisBusy,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQconsumeInput(conn)
    ccall((:PQconsumeInput,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQnotifies(conn)
    ccall((:PQnotifies,libpq),Ptr{PGnotify},(Ptr{PGconn},),conn)
end

function PQputCopyData(conn,buffer,nbytes::Cint)
    ccall((:PQputCopyData,libpq),Cint,(Ptr{PGconn},Cstring,Cint),conn,buffer,nbytes)
end

function PQputCopyEnd(conn,errormsg)
    ccall((:PQputCopyEnd,libpq),Cint,(Ptr{PGconn},Cstring),conn,errormsg)
end

function PQgetCopyData(conn,buffer,async::Cint)
    ccall((:PQgetCopyData,libpq),Cint,(Ptr{PGconn},Ptr{Cstring},Cint),conn,buffer,async)
end

function PQgetline(conn,string,length::Cint)
    ccall((:PQgetline,libpq),Cint,(Ptr{PGconn},Cstring,Cint),conn,string,length)
end

function PQputline(conn,string)
    ccall((:PQputline,libpq),Cint,(Ptr{PGconn},Cstring),conn,string)
end

function PQgetlineAsync(conn,buffer,bufsize::Cint)
    ccall((:PQgetlineAsync,libpq),Cint,(Ptr{PGconn},Cstring,Cint),conn,buffer,bufsize)
end

function PQputnbytes(conn,buffer,nbytes::Cint)
    ccall((:PQputnbytes,libpq),Cint,(Ptr{PGconn},Cstring,Cint),conn,buffer,nbytes)
end

function PQendcopy(conn)
    ccall((:PQendcopy,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQsetnonblocking(conn,arg::Cint)
    ccall((:PQsetnonblocking,libpq),Cint,(Ptr{PGconn},Cint),conn,arg)
end

function PQisnonblocking(conn)
    ccall((:PQisnonblocking,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQisthreadsafe()
    ccall((:PQisthreadsafe,libpq),Cint,())
end

function PQping(conninfo)
    ccall((:PQping,libpq),PGPing,(Cstring,),conninfo)
end

function PQpingParams(keywords,values,expand_dbname::Cint)
    ccall((:PQpingParams,libpq),PGPing,(Ptr{Cstring},Ptr{Cstring},Cint),keywords,values,expand_dbname)
end

function PQflush(conn)
    ccall((:PQflush,libpq),Cint,(Ptr{PGconn},),conn)
end

function PQfn(conn,fnid::Cint,result_buf,result_len,result_is_int::Cint,args,nargs::Cint)
    ccall((:PQfn,libpq),Ptr{PGresult},(Ptr{PGconn},Cint,Ptr{Cint},Ptr{Cint},Cint,Ptr{PQArgBlock},Cint),conn,fnid,result_buf,result_len,result_is_int,args,nargs)
end

function PQresultStatus(res)
    ccall((:PQresultStatus,libpq),ExecStatusType,(Ptr{PGresult},),res)
end

function PQresStatus(status::ExecStatusType)
    ccall((:PQresStatus,libpq),Cstring,(ExecStatusType,),status)
end

function PQresultErrorMessage(res)
    ccall((:PQresultErrorMessage,libpq),Cstring,(Ptr{PGresult},),res)
end

function PQresultErrorField(res,fieldcode::Cint)
    ccall((:PQresultErrorField,libpq),Cstring,(Ptr{PGresult},Cint),res,fieldcode)
end

function PQntuples(res)
    ccall((:PQntuples,libpq),Cint,(Ptr{PGresult},),res)
end

function PQnfields(res)
    ccall((:PQnfields,libpq),Cint,(Ptr{PGresult},),res)
end

function PQbinaryTuples(res)
    ccall((:PQbinaryTuples,libpq),Cint,(Ptr{PGresult},),res)
end

function PQfname(res,field_num::Cint)
    ccall((:PQfname,libpq),Cstring,(Ptr{PGresult},Cint),res,field_num)
end

function PQfnumber(res,field_name)
    ccall((:PQfnumber,libpq),Cint,(Ptr{PGresult},Cstring),res,field_name)
end

function PQftable(res,field_num::Cint)
    ccall((:PQftable,libpq),Oid,(Ptr{PGresult},Cint),res,field_num)
end

function PQftablecol(res,field_num::Cint)
    ccall((:PQftablecol,libpq),Cint,(Ptr{PGresult},Cint),res,field_num)
end

function PQfformat(res,field_num::Cint)
    ccall((:PQfformat,libpq),Cint,(Ptr{PGresult},Cint),res,field_num)
end

function PQftype(res,field_num::Cint)
    ccall((:PQftype,libpq),Oid,(Ptr{PGresult},Cint),res,field_num)
end

function PQfsize(res,field_num::Cint)
    ccall((:PQfsize,libpq),Cint,(Ptr{PGresult},Cint),res,field_num)
end

function PQfmod(res,field_num::Cint)
    ccall((:PQfmod,libpq),Cint,(Ptr{PGresult},Cint),res,field_num)
end

function PQcmdStatus(res)
    ccall((:PQcmdStatus,libpq),Cstring,(Ptr{PGresult},),res)
end

function PQoidStatus(res)
    ccall((:PQoidStatus,libpq),Cstring,(Ptr{PGresult},),res)
end

function PQoidValue(res)
    ccall((:PQoidValue,libpq),Oid,(Ptr{PGresult},),res)
end

function PQcmdTuples(res)
    ccall((:PQcmdTuples,libpq),Cstring,(Ptr{PGresult},),res)
end

function PQgetvalue(res,tup_num::Cint,field_num::Cint)
    ccall((:PQgetvalue,libpq),Cstring,(Ptr{PGresult},Cint,Cint),res,tup_num,field_num)
end

function PQgetlength(res,tup_num::Cint,field_num::Cint)
    ccall((:PQgetlength,libpq),Cint,(Ptr{PGresult},Cint,Cint),res,tup_num,field_num)
end

function PQgetisnull(res,tup_num::Cint,field_num::Cint)
    ccall((:PQgetisnull,libpq),Cint,(Ptr{PGresult},Cint,Cint),res,tup_num,field_num)
end

function PQnparams(res)
    ccall((:PQnparams,libpq),Cint,(Ptr{PGresult},),res)
end

function PQparamtype(res,param_num::Cint)
    ccall((:PQparamtype,libpq),Oid,(Ptr{PGresult},Cint),res,param_num)
end

function PQdescribePrepared(conn,stmt)
    ccall((:PQdescribePrepared,libpq),Ptr{PGresult},(Ptr{PGconn},Cstring),conn,stmt)
end

function PQdescribePortal(conn,portal)
    ccall((:PQdescribePortal,libpq),Ptr{PGresult},(Ptr{PGconn},Cstring),conn,portal)
end

function PQsendDescribePrepared(conn,stmt)
    ccall((:PQsendDescribePrepared,libpq),Cint,(Ptr{PGconn},Cstring),conn,stmt)
end

function PQsendDescribePortal(conn,portal)
    ccall((:PQsendDescribePortal,libpq),Cint,(Ptr{PGconn},Cstring),conn,portal)
end

function PQclear(res)
    ccall((:PQclear,libpq),Void,(Ptr{PGresult},),res)
end

function PQfreemem(ptr)
    ccall((:PQfreemem,libpq),Void,(Ptr{Void},),ptr)
end

function PQmakeEmptyPGresult(conn,status::ExecStatusType)
    ccall((:PQmakeEmptyPGresult,libpq),Ptr{PGresult},(Ptr{PGconn},ExecStatusType),conn,status)
end

function PQcopyResult(src,flags::Cint)
    ccall((:PQcopyResult,libpq),Ptr{PGresult},(Ptr{PGresult},Cint),src,flags)
end

function PQsetResultAttrs(res,numAttributes::Cint,attDescs)
    ccall((:PQsetResultAttrs,libpq),Cint,(Ptr{PGresult},Cint,Ptr{PGresAttDesc}),res,numAttributes,attDescs)
end

function PQresultAlloc(res,nBytes::Cint)
    ccall((:PQresultAlloc,libpq),Ptr{Void},(Ptr{PGresult},Cint),res,nBytes)
end

function PQsetvalue(res,tup_num::Cint,field_num::Cint,value,len::Cint)
    ccall((:PQsetvalue,libpq),Cint,(Ptr{PGresult},Cint,Cint,Cstring,Cint),res,tup_num,field_num,value,len)
end

function PQescapeStringConn()
    ccall((:PQescapeStringConn,libpq),Cint,())
end

function PQescapeLiteral(conn,str,len::Cint)
    ccall((:PQescapeLiteral,libpq),Cstring,(Ptr{PGconn},Cstring,Cint),conn,str,len)
end

function PQescapeIdentifier(conn,str,len::Cint)
    ccall((:PQescapeIdentifier,libpq),Cstring,(Ptr{PGconn},Cstring,Cint),conn,str,len)
end

function PQescapeByteaConn(conn,from,from_length::Cint,to_length)
    ccall((:PQescapeByteaConn,libpq),Ptr{Cuchar},(Ptr{PGconn},Ptr{Cuchar},Cint,Ptr{Cint}),conn,from,from_length,to_length)
end

function PQunescapeBytea(strtext,retbuflen)
    ccall((:PQunescapeBytea,libpq),Ptr{Cuchar},(Ptr{Cuchar},Ptr{Cint}),strtext,retbuflen)
end

function PQescapeString()
    ccall((:PQescapeString,libpq),Cint,())
end

function PQescapeBytea(from,from_length::Cint,to_length)
    ccall((:PQescapeBytea,libpq),Ptr{Cuchar},(Ptr{Cuchar},Cint,Ptr{Cint}),from,from_length,to_length)
end

function PQprint(fout,res,ps)
    ccall((:PQprint,libpq),Void,(Ptr{FILE},Ptr{PGresult},Ptr{PQprintOpt}),fout,res,ps)
end

function PQdisplayTuples(res,fp,fillAlign::Cint,fieldSep,printHeader::Cint,quiet::Cint)
    ccall((:PQdisplayTuples,libpq),Void,(Ptr{PGresult},Ptr{FILE},Cint,Cstring,Cint,Cint),res,fp,fillAlign,fieldSep,printHeader,quiet)
end

function PQprintTuples(res,fout,printAttName::Cint,terseOutput::Cint,width::Cint)
    ccall((:PQprintTuples,libpq),Void,(Ptr{PGresult},Ptr{FILE},Cint,Cint,Cint),res,fout,printAttName,terseOutput,width)
end

function lo_open(conn,lobjId::Oid,mode::Cint)
    ccall((:lo_open,libpq),Cint,(Ptr{PGconn},Oid,Cint),conn,lobjId,mode)
end

function lo_close(conn,fd::Cint)
    ccall((:lo_close,libpq),Cint,(Ptr{PGconn},Cint),conn,fd)
end

function lo_read(conn,fd::Cint,buf,len::Cint)
    ccall((:lo_read,libpq),Cint,(Ptr{PGconn},Cint,Cstring,Cint),conn,fd,buf,len)
end

function lo_write(conn,fd::Cint,buf,len::Cint)
    ccall((:lo_write,libpq),Cint,(Ptr{PGconn},Cint,Cstring,Cint),conn,fd,buf,len)
end

function lo_lseek(conn,fd::Cint,offset::Cint,whence::Cint)
    ccall((:lo_lseek,libpq),Cint,(Ptr{PGconn},Cint,Cint,Cint),conn,fd,offset,whence)
end

function lo_lseek64(conn,fd::Cint,offset::pg_int64,whence::Cint)
    ccall((:lo_lseek64,libpq),pg_int64,(Ptr{PGconn},Cint,pg_int64,Cint),conn,fd,offset,whence)
end

function lo_creat(conn,mode::Cint)
    ccall((:lo_creat,libpq),Oid,(Ptr{PGconn},Cint),conn,mode)
end

function lo_create(conn,lobjId::Oid)
    ccall((:lo_create,libpq),Oid,(Ptr{PGconn},Oid),conn,lobjId)
end

function lo_tell(conn,fd::Cint)
    ccall((:lo_tell,libpq),Cint,(Ptr{PGconn},Cint),conn,fd)
end

function lo_tell64(conn,fd::Cint)
    ccall((:lo_tell64,libpq),pg_int64,(Ptr{PGconn},Cint),conn,fd)
end

function lo_truncate(conn,fd::Cint,len::Cint)
    ccall((:lo_truncate,libpq),Cint,(Ptr{PGconn},Cint,Cint),conn,fd,len)
end

function lo_truncate64(conn,fd::Cint,len::pg_int64)
    ccall((:lo_truncate64,libpq),Cint,(Ptr{PGconn},Cint,pg_int64),conn,fd,len)
end

function lo_unlink(conn,lobjId::Oid)
    ccall((:lo_unlink,libpq),Cint,(Ptr{PGconn},Oid),conn,lobjId)
end

function lo_import(conn,filename)
    ccall((:lo_import,libpq),Oid,(Ptr{PGconn},Cstring),conn,filename)
end

function lo_import_with_oid(conn,filename,lobjId::Oid)
    ccall((:lo_import_with_oid,libpq),Oid,(Ptr{PGconn},Cstring,Oid),conn,filename,lobjId)
end

function lo_export(conn,lobjId::Oid,filename)
    ccall((:lo_export,libpq),Cint,(Ptr{PGconn},Oid,Cstring),conn,lobjId,filename)
end

function PQlibVersion()
    ccall((:PQlibVersion,libpq),Cint,())
end

function PQmblen(s,encoding::Cint)
    ccall((:PQmblen,libpq),Cint,(Cstring,Cint),s,encoding)
end

function PQdsplen(s,encoding::Cint)
    ccall((:PQdsplen,libpq),Cint,(Cstring,Cint),s,encoding)
end

function PQenv2encoding()
    ccall((:PQenv2encoding,libpq),Cint,())
end

function PQencryptPassword(passwd,user)
    ccall((:PQencryptPassword,libpq),Cstring,(Cstring,Cstring),passwd,user)
end

function pg_char_to_encoding(name)
    ccall((:pg_char_to_encoding,libpq),Cint,(Cstring,),name)
end

function pg_encoding_to_char(encoding::Cint)
    ccall((:pg_encoding_to_char,libpq),Cstring,(Cint,),encoding)
end

function pg_valid_server_encoding_id(encoding::Cint)
    ccall((:pg_valid_server_encoding_id,libpq),Cint,(Cint,),encoding)
end

max_stars_repo_name: rbt-lang/rbt-proto

max_issues_repo_name: rbt-lang/rbt-proto

max_forks_repo_name: rbt-lang/rbt-proto


text:
using SparseArrays
using LinearAlgebra

#----------------- Get the A matrix
function getDivGrad(n1, n2, n3)

        # the Divergence
        D1 = kron(sparse(1.0I, n3, n3), kron(sparse(1.0I, n2, n2), ddx(n1)))
        D2 = kron(sparse(1.0I, n3, n3), kron(ddx(n2),sparse(1.0I, n1, n1)))
        D3 = kron(ddx(n3), kron(sparse(1.0I, n2, n2), sparse(1.0I, n1, n1)))

        # DIV from faces to cell-centers
        Div = [D1 D2 D3]

        return Div*Div'
end

#----------------- 1D finite difference on staggered grid
function ddx(n)
# generate 1D derivatives
    return d = spdiagm(0 => -ones(n), 1 => ones(n))[1:end-1, :]
end

ext: jl


text:
using Documenter
using ToyFHE

makedocs(sitename="ToyFHE.jl", modules=[ToyFHE],
pages = [
    "index.md",
    "Manual" => [
        "Background" => [
            "man/background.md",
            "man/background/rlwe.md",
            "man/background/fhe.md",
        ],
        "man/encoding.md",
        "man/ckks.md"
    ]
])

deploydocs(
    repo = "github.com/JuliaComputing/ToyFHE.jl.git",
)


text:
# dtft
SUITE["dtft"] = BenchmarkGroup()
let T=ComplexF32, N=2^10, M=2^11, n_shift=7
    rng = MersenneTwister(0)
    x = randn(rng, T, N)
    w = randn(rng, M)
    SUITE["dtft"]["fft"] = @benchmarkable fft($x)
    SUITE["dtft"]["loop_n"] = @benchmarkable MIRT.dtft_loop_n($w, $x)
    SUITE["dtft"]["loop_m"] = @benchmarkable MIRT.dtft_loop_m($w, $x)
    SUITE["dtft"]["dist_m"] = @benchmarkable MIRT.dtft_dist_m($w, $x)
    SUITE["dtft"]["pmap_m"] = @benchmarkable MIRT.dtft_pmap_m($w, $x)
    SUITE["dtft"]["matvec"] = @benchmarkable MIRT.dtft_matvec($w, $x)
end


text:
module MPBUtils
# ---------------------------------------------------------------------------------------- #

using Crystalline
using Crystalline: TEST_αβγ, DEFAULT_ATOL
using Crystalline: AbstractFourierLattice,
                   matching_littlegroups, constant, formatirreplabel
using StaticArrays
using Statistics: quantile # for `filling2isoval`
using DocStringExtensions
using Requires
using DelimitedFiles

# ---------------------------------------------------------------------------------------- #

export prepare_mpbcalc,
       prepare_mpbcalc!,
       mpb_calcname,
       write_lgs_to_mpb!,
       lattice_from_mpbparams,
       kvecs_from_mpbparams,
       filling2isoval,
       isoval2filling

# ---------------------------------------------------------------------------------------- #

include("utils.jl")
include("filling2isoval.jl")
include("export2mpb.jl")
include("read_utils.jl")
export parse_dim, parse_sgnum, load_symdata, symdata2representation, singlebandirreps

# ---------------------------------------------------------------------------------------- #

function __init__()
    # plotting utitilities when PyPlot is loaded
    @require PyPlot="d330b81b-6aea-500a-939a-2ce795aea3ee" begin
        include("compat/pyplot.jl")
        export plot_lattice_from_mpbparams
    end
end

# ---------------------------------------------------------------------------------------- #
end


text:
import MacroTools

const DSL_STATIC_ANNOTATION = :static
const DSL_ARG_GRAD_ANNOTATION = :grad
const DSL_RET_GRAD_ANNOTATION = :grad
const DSL_TRACK_DIFFS_ANNOTATION = :diffs
const DSL_NO_JULIA_CACHE_ANNOTATION = :nojuliacache

struct Argument
    name::Symbol
    typ::Union{Symbol,Expr}
    annotations::Set{Symbol}
    default::Union{Some{Any}, Nothing}
end

Argument(name, typ) = Argument(name, typ, Set{Symbol}(), nothing)
Argument(name, typ, annotations) = Argument(name, typ, annotations, nothing)

function parse_annotations(annotations_expr)
    annotations = Set{Symbol}()
    if isa(annotations_expr, Symbol)
        push!(annotations, annotations_expr)
    elseif isa(annotations_expr, Expr) && annotations_expr.head == :tuple
        for annotation in annotations_expr.args
            if !isa(annotation, Symbol)
                error("syntax error in annotations_expr at $annotation")
            else
                push!(annotations, annotation)
            end
        end
    else
        error("syntax error in annotations at $annotations")
    end
    annotations
end

function parse_arg(expr)
    if isa(expr, Symbol)
        # x
        arg = Argument(expr, :Any)
    elseif isa(expr, Expr) && expr.head == :(::)
        # x::Int
        arg = Argument(expr.args[1], expr.args[2])
    elseif isa(expr, Expr) && expr.head == :kw
        # x::Int=1
        sub_arg = parse_arg(expr.args[1])
        default = Some(expr.args[2])
        arg = Argument(sub_arg.name, sub_arg.typ, Set{Symbol}(), default)
    elseif isa(expr, Expr) && expr.head == :call
        # (grad,foo)(x::Int)
        annotations_expr = expr.args[1]
        sub_arg = parse_arg(expr.args[2])
        annotations = parse_annotations(annotations_expr)
        arg = Argument(sub_arg.name, sub_arg.typ, annotations, sub_arg.default)
    else
        dump(expr)
        error("syntax error in gen function argument at $expr")
    end
    arg
end

include("dynamic.jl")
include("static.jl")

function address_from_expression(lhs)
    if lhs isa Symbol
        QuoteNode(lhs)
    else
        error("Syntax error: Only a variable or an address expression can appear on the lefthand side of a ~. Invalid left-hand side: $(lhs).")
    end
end

function desugar_tildes(expr)
    MacroTools.postwalk(expr) do e
        if MacroTools.@capture(e, {*} ~ rhs_)
            :(@trace($rhs))
        elseif MacroTools.@capture(e, {addr_} ~ rhs_)
            :(@trace($rhs, $(addr)))
        elseif MacroTools.@capture(e, lhs_ ~ rhs_)
            addr_expr = address_from_expression(lhs)
            :($lhs = @trace($rhs, $(addr_expr)))
        else
            e
        end
    end
end

function parse_gen_function(ast, annotations)
    ast = MacroTools.longdef(ast)
    if ast.head != :function
        error("syntax error at $ast in $(ast.head)")
    end
    if length(ast.args) != 2
        error("syntax error at $ast in $(ast.args)")
    end
    signature = ast.args[1]
    body = desugar_tildes(ast.args[2])
    if signature.head == :(::)
        (call_signature, return_type) = signature.args
    elseif signature.head == :call
        (call_signature, return_type) = (signature, :Any)
    else
        error("syntax error at $(signature)")
    end
    name = call_signature.args[1]
    args = map(parse_arg, call_signature.args[2:end])
    static = DSL_STATIC_ANNOTATION in annotations
    if static
        make_static_gen_function(name, args, body, return_type, annotations)
    else
        make_dynamic_gen_function(name, args, body, return_type, annotations)
    end
end

macro gen(annotations_expr, ast)

    # parse the annotations
    annotations = parse_annotations(annotations_expr)

    # parse the function definition
    parse_gen_function(ast, annotations)
end

macro gen(ast)
    parse_gen_function(ast, Set{Symbol}())
end

max_stars_repo_name: ali-ramadhan/Gen

max_issues_repo_name: ali-ramadhan/Gen

max_forks_repo_name: ali-ramadhan/Gen


text:
using SoleViz
using Test

@testset "SoleViz.jl" begin
    # Write your tests here.
end

max_stars_repo_name: aclai-lab/SoleVisualizations

max_issues_repo_name: aclai-lab/SoleVisualizations

max_forks_repo_name: aclai-lab/SoleVisualizations


text:
# This file constains the Buffer for data buffering.

##### Buffer modes
"""
    $TYPEDEF

Abstract type for buffer mode. Subtypes of `BufferMode` is `CyclicMode` and `LinearMode`.
"""
abstract type BufferMode end

"""
    $TYPEDEF

Abstract type of cyclic buffer modes. See [`Cyclic`](@ref)
"""
abstract type CyclicMode <: BufferMode end

"""
    $TYPEDEF

Abstract type of linear buffer modes. See [`Normal`](@ref), [`Lifo`](@ref), [`Fifo`](@ref)
"""
abstract type LinearMode <: BufferMode end

"""
    $TYPEDEF

Cyclic buffer mode. The data is written to buffer until the buffer is full. When the buffer is full, new data is written by
overwriting the data available in the buffer starting from the beginning of the buffer. When the buffer is read, the element
written last is returned and the returned element is not deleted from the buffer.
"""
struct Cyclic <: CyclicMode end

"""
    $TYPEDEF

LinearMode buffer mode. The data is written to buffer until the buffer is full. When it is full, no more data is written to
the buffer. When read, the data written last is returned and the returned data is not deleted from the internal container of
the buffer.
"""
struct Normal <: LinearMode end

"""
    $TYPEDEF

Lifo (Last-in-first-out) buffer mode. This type of buffer is a *last-in-first-out* buffer. Data is written to the buffer
until the buffer is full. When the buffer is full, no more element can be written into the buffer. When read, the last
element written into buffer is returned. The returned element is deleted from the buffer.
"""
struct Lifo <: LinearMode end

"""
    $TYPEDEF

Fifo (First-in-last-out) buffer mode. This type of buffer is a *first-in-first-out* buffer. The data is written to the buffer
until the buffer is full. When the buffer is full, no more element can be written into the buffer. When read, the first
element written into the buffer is returned. The returned element is deleted from the buffer.
"""
struct Fifo <: LinearMode end

##### Buffer
"""
    $TYPEDEF

Constructs a `Buffer` of size `sz` with element type of `T`. `M` is the mode of the `Buffer` that determines how data is to
read from and written into the `Buffer`.  There exists for different buffer modes:

* `Normal`: See [`Normal`](@ref)

* `Cyclic`: See [`Cyclic`](@ref)

* `Lifo`: See [`Lifo`](@ref)

* `Fifo`: See [`Fifo`](@ref)

The default mode for `Buffer` is `Cyclic` and default element type is `Float64`.

    Buffer{M}(sz::Int...) where {M, T}

Constructs a `Buffer` of size `sz` and with element type of `T` and mode `M`.

    Buffer(dtype::Type{T}, sz::Int...) where T

Constructs a `Buffer` of size `sz` and element type `T`. The mode of buffer is `Cyclic`.

    Buffer(sz::Int...)

Constructs a `Buffer` of size `sz` with mode `Cyclic` and element type of `Float64`.

    Buffer{M}(data::AbstractVecOrMat{T}) where {M, T<:Real}

Constructs a `Buffer` with `data`.

# Fields

    $TYPEDFIELDS

# Example
```jldoctest
julia> buf = Buffer(5)
5-element Buffer{Cyclic,Float64,1}

julia> buf = Buffer{Fifo}(2, 5)
2×5 Buffer{Fifo,Float64,2}

julia> buf = Buffer{Lifo}(collect(reshape(1:8, 2, 4)))
2×4 Buffer{Lifo,Int64,2}
```
"""
mutable struct Buffer{M<:BufferMode, T, N} <: AbstractArray{T, N}
    "Internal data containers"
    internals::Vector{Array{T, N}}
    "Input containter"
    src::Int
    "Output container"
    dst::Int
    "Buffer index"
    index::Int
    "Current state of buffer. May be :full, :empty, :nonempty"
    state::Symbol
    "Unique identifier"
    id::UUID
    Buffer{M}(data::AbstractVecOrMat{T}) where {M, T<:Real} =
        new{M, T, ndims(data)}([copy(data), data], 1, 2, 1, :empty, uuid4())
end
Buffer{M}(dtype::Type{T}, sz::Int...) where {M, T} = Buffer{M}(zeros(T, sz...))
Buffer{M}(sz::Int...) where {M, T} = Buffer{M}(zeros(Float64, sz...))
Buffer(dtype::Type{T}, sz::Int...) where T  = Buffer{Cyclic}(dtype, sz...)
Buffer(sz::Int...) = Buffer(Float64, sz...)

show(io::IO, buf::Buffer)= print(io,
    "Buffer(mode:$(mode(buf)), eltype:$(eltype(buf)), size:$(size(buf)), index:$(buf.index), state:$(buf.state))")

function swapinternals(buf::Buffer)
    temp = buf.src
    buf.src = buf.dst
    buf.dst = temp
end

"""
    $SIGNATURES

Returns the element of `internals` of `buf` that is used to input data to `buf`. See also [`outbuf`][@ref)
"""
inbuf(buf::Buffer) = buf.internals[buf.src]

"""
    $SIGNATURES

Returns the element of `intervals` of `buf` that is used to take data out of `buf`. See also: [`inbuf`](@ref)
"""
outbuf(buf::Buffer) = buf.internals[buf.dst]

##### Buffer info.
"""
    $SIGNATURES

Returns buffer mode of `buf`. See also: [`Normal`](@ref), [`Cyclic`](@ref), [`Lifo`](@ref), [`Fifo`](@ref) for buffer modes.
"""
mode(buf::Buffer{M, T, N}) where {M, T, N} = M

##### AbstractArray interface.
"""
    $SIGNATURES

Returns the maximum number of data that can be hold in `buf`.

# Example
```jldoctest
julia> buf = Buffer(5);

julia> datalength(buf)
5

julia> buf2 = Buffer(2, 10);

julia> datalength(buf2)
10
```
"""
datalength(buf::Buffer{M, T, N}) where {M, T, N} = N == 1 ? size(buf, 1) : size(buf, 2)

"""
    $SIGNATURES

Returns the size of `buf`.
"""
size(buf::Buffer) = size(outbuf(buf))

"""
    $SIGNATURES

Returns an element from `buf` at index `idx`. Same as `buf[idx]`

# Example
```jldoctest
julia> buf = Buffer(2, 5);  # Construct a buffer.

julia> write!(buf, reshape(2 : 2 : 20, 2, 5))  # Write data into buffer.

julia> buf[1]
18.0

julia> buf[1, 2]
14.0

julia> buf[1, end]
2.0

julia> buf[:, 2]
2-element Array{Float64,1}:
 14.0
 16.0
```
"""
getindex(buf::Buffer, idx::Vararg{Int, N}) where N = getindex(outbuf(buf), idx...)

"""
    $SIGNATURES

Sets `val` to `buf` at index `idx`. Same as `buf[idx] = val`.

# Example
```jldoctest
julia> buf = Buffer(2, 5);

julia> buf[1] = 1
1

julia> buf[:, 2] = [1, 1]
2-element Array{Int64,1}:
 1
 1

julia> buf[end] = 10
10

julia> buf.internals
2-element Array{Array{Float64,2},1}:
 [1.0 1.0 … 0.0 0.0; 0.0 1.0 … 0.0 10.0]
 [0.0 0.0 … 0.0 0.0; 0.0 0.0 … 0.0 0.0]
```
"""
setindex!(buf::Buffer, item, idx::Vararg{Int, N}) where N = setindex!(inbuf(buf), item, idx...)

##### Buffer state control and check.
"""
    $SIGNATURES

Returns `true` if the index of `buf` is 1.
"""
isempty(buf::Buffer) = buf.state == :empty

"""
    $SIGNATURES

Returns `true` if the index of `buf` is equal to the length of `buf`.
"""
isfull(buf::Buffer) = buf.state == :full

"""
    $SIGNATURES

Returns true when `buf` index is an integer multiple of datalength of `buf`.

# Example
```jldoctest
julia> buf = Buffer(3);

julia> for val in 1 : 7
       write!(buf, val)
       @show ishit(buf)
       end
ishit(buf) = false
ishit(buf) = false
ishit(buf) = true
ishit(buf) = false
ishit(buf) = false
ishit(buf) = true
ishit(buf) = false
```
"""
ishit(buf::Buffer) = buf.state == :full

#
# `setproperty!` function is used to keep track of buffer status. The tracking is done through the updates of `index` of
# buffer.
#
function setproperty!(buf::Buffer, name::Symbol, val::Int)
    if name == :index
        buflen = datalength(buf)
        val < 1 && error("Buffer index cannot be less than 1.")
        setfield!(buf, name, val)
        if val == 1
            buf.state = :empty
        elseif val > buflen
            buf.state = :full
            if mode(buf) == Cyclic
                newidx = buflen == 1 ? 1 : (buf.index % buflen)
                setfield!(buf, :index, newidx)
            end
        else
            buf.state = :nonempty
        end
    else
        setfield!(buf, name, val)
    end
end

##### Writing into buffers
"""
    $SIGNATURES

Writes each column of `vals` into `buf`.

!!! warning Buffer mode determines how data is written into buffers. See also: [`Normal`](@ref), [`Cyclic`](@ref),
    [`Lifo`](@ref), [`Fifo`](@ref) for buffer modes.

# Example
```jldoctest
julia> buf = Buffer(5)
5-element Buffer{Cyclic,Float64,1}

julia> write!(buf, 1.)
1.0

julia> write!(buf, [2, 3])

julia> buf.internals
2-element Array{Array{Float64,1},1}:
 [3.0, 2.0, 1.0, 0.0, 0.0]
 [2.0, 1.0, 0.0, 0.0, 0.0]

julia> buf = Buffer(2,5)
2×5 Buffer{Cyclic,Float64,2}

julia> write!(buf, [1, 1])
2-element Array{Int64,1}:
 1
 1

julia> write!(buf, [2 3; 2 3])

julia> buf.internals
2-element Array{Array{Float64,2},1}:
 [3.0 2.0 … 0.0 0.0; 3.0 2.0 … 0.0 0.0]
 [2.0 1.0 … 0.0 0.0; 2.0 1.0 … 0.0 0.0]
```
"""
function write!(buf::Buffer, val) end
write!(buf::Buffer{M, <:Real, 1}, val::Real) where {M} = _write!(buf, val)
write!(buf::Buffer{M, <:Real, 2}, val::AbstractVector{<:Real}) where {M} = _write!(buf, val)
write!(buf::Buffer{M, <:Real, 1}, vals::AbstractVector{<:Real}) where {M} = foreach(val -> _write!(buf, val), vals)
write!(buf::Buffer{M, <:Real, 2}, vals::AbstractMatrix{<:Real}) where {M} = foreach(val -> _write!(buf, val), eachcol(vals))
function _write!(buf::Buffer, val)
    checkstate(buf)
    ibuf = inbuf(buf)
    obuf = outbuf(buf)
    rotate(ibuf, obuf, 1)
    writeitem(ibuf, val)
    buf.index += 1
    swapinternals(buf)
    val
end
# writeitem(buf::Buffer{M, T, 1}, val) where {M, T} = (buf[buf.index] = val; buf.index += 1)
writeitem(buf::AbstractArray{T, 1}, val) where {T} = buf[1] = val
writeitem(buf::AbstractArray{T, 2}, val) where {T} = buf[:, 1] = val
checkstate(buf::Buffer) = mode(buf) != Cyclic && isfull(buf) && error("Buffer is full")

##### Reading from buffers
"""
    $SIGNATURES

Reads an element from `buf`. Reading is performed according to the mode of `buf`. See also: [`Normal`](@ref),
[`Cyclic`](@ref), [`Lifo`](@ref), [`Fifo`](@ref) for buffer modes.

# Example
```jldoctest
julia> buf = Buffer(3)
3-element Buffer{Cyclic,Float64,1}

julia> write!(buf, [2, 4, 6])

julia> for i = 1 : 3
       @show (read(buf), buf.internals)
       end
(read(buf), buf.internals) = (6.0, [[6.0, 4.0, 2.0], [4.0, 2.0, 0.0]])
(read(buf), buf.internals) = (6.0, [[6.0, 4.0, 2.0], [4.0, 2.0, 0.0]])
(read(buf), buf.internals) = (6.0, [[6.0, 4.0, 2.0], [4.0, 2.0, 0.0]])

julia> buf = Buffer{Fifo}(5)
5-element Buffer{Fifo,Float64,1}

julia> write!(buf, [2, 4, 6])

julia> for i = 1 : 3
       @show (read(buf), buf.internals)
       end
(read(buf), buf.internals) = (2.0, [[6.0, 4.0, 0.0, 0.0, 0.0], [4.0, 2.0, 0.0, 0.0, 0.0]])
(read(buf), buf.internals) = (4.0, [[6.0, 0.0, 0.0, 0.0, 0.0], [4.0, 2.0, 0.0, 0.0, 0.0]])
(read(buf), buf.internals) = (6.0, [[0.0, 0.0, 0.0, 0.0, 0.0], [4.0, 2.0, 0.0, 0.0, 0.0]])
```
"""
function read(buf::Buffer)
    isempty(buf) && error("Buffer is empty.")
    val = _read(buf)
    val
end
function _read(buf::Buffer{Fifo, T, N}) where {T, N}
    obuf = outbuf(buf)
    val = readitem(obuf, buf.index - 1)
    buf.index -= 1
    insertzero(obuf, buf.index)
    val
end
function _read(buf::Buffer{Lifo, T, N}) where {T, N}
    obuf = outbuf(buf)
    ibuf = inbuf(buf)
    val = readitem(obuf, 1)
    rotate(ibuf, obuf, -1)
    buf.index -= 1
    swapinternals(buf)
    val
end
function _read(buf::Buffer{M, T, N}) where {M<:Union{Normal, Cyclic}, T, N}
    readitem(outbuf(buf), 1)
end
readitem(buf::AbstractArray{T, 1}, idx::Int) where {T} = buf[idx]
readitem(buf::AbstractArray{T, 2}, idx::Int) where {T} = buf[:, idx]
insertzero(buf::AbstractArray{T, 1}, idx::Int) where {T} = buf[idx] = zero(T)
insertzero(buf::AbstractArray{T, 2}, idx::Int) where {T} = buf[:, idx] = zeros(T, size(buf, 1))
rotate(ibuf::AbstractArray{T, 1}, obuf::AbstractArray{T, 1}, idx::Int) where {T} = circshift!(ibuf, obuf, idx)
rotate(ibuf::AbstractArray{T, 2}, obuf::AbstractArray{T, 2}, idx::Int) where {T} = circshift!(ibuf, obuf, (0, idx))

##### Accessing buffer internals
"""
    $SIGNATURES

Returns the current data of `buf`. If `flip` is `true`, the data to be returned is flipped. See also [`snapshot`](@ref)

# Example
```jldoctest
julia> buf = Buffer(5);

julia> write!(buf, 1:3)

julia> content(buf, flip=false)
3-element Array{Float64,1}:
 3.0
 2.0
 1.0

julia> buf = Buffer(2, 5);

julia> write!(buf, reshape(1:10, 2, 5))

julia> content(buf)
2×5 Array{Float64,2}:
 1.0  3.0  5.0  7.0   9.0
 2.0  4.0  6.0  8.0  10.0
```
"""
function content(buf::Buffer; flip::Bool=true)
    bufdim = ndims(buf)
    if isfull(buf)
        val = outbuf(buf)
    else
        val = bufdim == 1 ? buf[1 : buf.index - 1] : buf[:, 1 : buf.index - 1]
    end
    if flip
        return bufdim == 1 ? reverse(val, dims=1) : reverse(val, dims=2)
    else
        return val
    end
end

"""
    $SIGNATURES

Returns all elements in `buf`. See also: [`content`](@ref)
"""
snapshot(buf::Buffer) = outbuf(buf)

"""
    $(SIGNATURES)

Cleans the contents of `buf`.
"""
function clean!(buf::Buffer)
    buf.internals[1] .= 0.
    buf.internals[2] .= 0.
    buf.index = 1
    buf
end


text:
using HDF5
using PyCall

type IRData
    X
    y
    test
    train_index
    val_index
    next_index
    n_epochs

    function IRData()
        s = new()
        s.X = map(Float32, h5read("data/ir_training_data.h5", "/features"))
        s.y = map(Float32, h5read("data/ir_training_data.h5", "/labels"))
        s.test = h5read("data/ir_testing_data.h5", "/features")

        s.train_index = randperm(length(s.y))
        s.n_epochs = 1
        s.next_index = 1
        s
    end
end

next_epoch!(data::IRData) = begin
    index = randperm(length(data.train_index))
    data.train_index = data.train_index[index]
    data.next_index = 1
    data.n_epochs += 1
    data
end

Base.getindex(data::IRData, i) = data.X[:, :, i], data.y[i]

next_batch(data::IRData, n) = begin
    i = data.next_index
    j = i + n -1 > length(data.train_index) ? length(data.train_index) : i + n -1
    index = data.train_index[i:j]
    data.next_index += n

    if j==length(data.train_index)
        next_epoch!(data)
    end
    data[index]
end


text:
######################################################################
# montgomery.jl: Montgomery models
######################################################################

export Montgomery

######################################################################
# Basic methods
######################################################################

"""
Concrete type for (twisted) Montgomery curves.
"""
struct Montgomery{T<:Nemo.RingElem} <: EllipticCurve{T}
    A::T
    B::T
end

function base_ring(E::Montgomery)
	return Nemo.parent(E.A)
end

"""
Get a description of a Montgomery curve.
"""
function show(io::IO, E::Montgomery{T}) where T
    print(io, "Elliptic Curve  $(E.B) y² = x³ + $(E.A) x² + x  over ")
    show(io, base_ring(E))
end

"""
Get the j-invariant of a Montgomery Curve.
"""

function j_invariant(E::Montgomery{T}) where T<:Nemo.FieldElem
	K = base_ring(E)
	zero = Nemo.zero(K)
	return j_invariant(Weierstrass(zero, E.A, zero, Nemo.one(K), zero))
end

function projective_equation(E::Montgomery)
	K = base_ring(E)
	A, (X, Y, Z) = PolynomialRing(K, ["X", "Y", "Z"])
	return E.B * Z * Y^2 - X^3 - E.A * X^2 * Z - X * Z^2
end

function equation(E::Montgomery)
	K = base_ring(E)
	A, (X, Y) = PolynomialRing(K, ["X", "Y"])
	return E.B * Y^2 - X^3 - E.A * X^2 - X
end

function equation(E::Montgomery, X, Y)
	K = base_ring(E)
	return E.B * Y^2 - X^3 - E.A * X^2 - X
end

function isvalid(E::Montgomery)
	return (E.B != 0) & (E.A != 0) & (E.A != 2) & (E.A != -2)
end


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct AzureReachabilityReport <: SwaggerModel
    aggregationLevel::Any # spec type: Union{ Nothing, String } # spec name: aggregationLevel
    providerLocation::Any # spec type: Union{ Nothing, AzureReachabilityReportLocation } # spec name: providerLocation
    reachabilityReport::Any # spec type: Union{ Nothing, Vector{AzureReachabilityReportItem} } # spec name: reachabilityReport

    function AzureReachabilityReport(;aggregationLevel=nothing, providerLocation=nothing, reachabilityReport=nothing)
        o = new()
        validate_property(AzureReachabilityReport, Symbol("aggregationLevel"), aggregationLevel)
        setfield!(o, Symbol("aggregationLevel"), aggregationLevel)
        validate_property(AzureReachabilityReport, Symbol("providerLocation"), providerLocation)
        setfield!(o, Symbol("providerLocation"), providerLocation)
        validate_property(AzureReachabilityReport, Symbol("reachabilityReport"), reachabilityReport)
        setfield!(o, Symbol("reachabilityReport"), reachabilityReport)
        o
    end
end # type AzureReachabilityReport

const _property_map_AzureReachabilityReport = Dict{Symbol,Symbol}(Symbol("aggregationLevel")=>Symbol("aggregationLevel"), Symbol("providerLocation")=>Symbol("providerLocation"), Symbol("reachabilityReport")=>Symbol("reachabilityReport"))
const _property_types_AzureReachabilityReport = Dict{Symbol,String}(Symbol("aggregationLevel")=>"String", Symbol("providerLocation")=>"AzureReachabilityReportLocation", Symbol("reachabilityReport")=>"Vector{AzureReachabilityReportItem}")
Base.propertynames(::Type{ AzureReachabilityReport }) = collect(keys(_property_map_AzureReachabilityReport))
Swagger.property_type(::Type{ AzureReachabilityReport }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_AzureReachabilityReport[name]))}
Swagger.field_name(::Type{ AzureReachabilityReport }, property_name::Symbol) =  _property_map_AzureReachabilityReport[property_name]

function check_required(o::AzureReachabilityReport)
    (getproperty(o, Symbol("aggregationLevel")) === nothing) && (return false)
    (getproperty(o, Symbol("providerLocation")) === nothing) && (return false)
    (getproperty(o, Symbol("reachabilityReport")) === nothing) && (return false)
    true
end

function validate_property(::Type{ AzureReachabilityReport }, name::Symbol, val)
end


text:
using Test, OpenStreetMapPBF

@testset "Read file" begin
    # read the Chapel Hill, North Carolina, USA OSM file that is checked into the repository.
    # retrieved from https://protomaps.com/downloads/osm/08bb2494-c06e-4270-ad1f-243f050284cd

    file = joinpath(Base.source_dir(), "chapel_hill_nc_usa.osm.pbf")

    # Check node loading code
    node_ids = Set{Int64}()
    found_med_deli = false

    scan_nodes(file) do n
        # no duplicated nodes
        @test n.id ∉ node_ids
        push!(node_ids, n.id)

        if n.id == 3921279444
            found_med_deli = true
            # Check that tags were stored properly, for the best restaurant in Chapel Hill, node version 5
            @test n.tags["name"] == "Mediterranean Deli, Bakery and Catering"
            @test n.tags["addr:city"] == "Chapel Hill"
            @test n.tags["addr:country"] == "US"
            @test n.tags["addr:housenumber"] == "410"
            @test n.tags["addr:postcode"] == "27516"
            @test n.tags["addr:state"] == "NC"
            @test n.tags["addr:street"] == "West Franklin Street"
            @test n.tags["amenity"] == "restaurant"
            @test n.tags["capacity"] == "150"
            @test n.tags["contact:website"] == "http://www.mediterraneandeli.com"
            @test n.tags["cuisine"] == "kebab"
            @test n.tags["cuisine_1"] == "mediterranean"
            @test n.tags["cuisine_2"] == "shawerma"
            @test n.tags["delivery"] == "yes"
            @test n.tags["opening_hours"] == "Mo-Su 11:00-22:00"
            @test n.tags["payment:bitcoin"] == "yes"
            @test n.tags["smoking"] == "outside"
            @test n.tags["takeaway"] == "yes"

            @test length(n.tags) == 18  # make sure no extra tags

            # check location
            @test n.lat ≈ 35.9113153
            @test n.lon ≈ -79.0609806
        end
    end

    @test found_med_deli

    @test length(node_ids) == 632572

    # check ways
    way_ids = Set{Int64}()
    found_tanyard = false

    scan_ways(file) do way
        @test way.id ∉ way_ids
        push!(way_ids, way.id)

        @test all(way.nodes .∈ Ref(node_ids))

        if way.id == 651257375
            found_tanyard = true

            @test way.nodes == [5076304249, 7052878634, 5076304252, 5076304253, 5076304254, 7052878635, 5076304255, 5076304256, 7052878636, 5076304257, 5076304258, 5210917959, 4972477818]

            @test way.tags["bicycle"] == "designated"
            @test way.tags["foot"] == "designated"
            @test way.tags["highway"] == "cycleway"
            @test way.tags["lit"] == "no"
            @test way.tags["name"] == "Tanyard Branch Trail"
            @test way.tags["segregated"] == "no"
            @test way.tags["start_date"] == "2018-06-02"
            @test way.tags["surface"] == "concrete"
            @test way.tags["website"] == "https://www.townofchapelhill.org/town-hall/departments-services/parks-recreation/facilities-greenways-parks/greenways/tanyard-branch-trail"
            @test way.tags["width"] == "3"

            @test length(way.tags) == 10
        end
    end

    @test found_tanyard
    @test length(way_ids) == 50260

    rel_ids = Set{Int64}()
    found_u_turn = false

    scan_relations(file) do r
        @test r.id ∉ rel_ids
        push!(rel_ids, r.id)

        if r.id == 9360865
            # No U turn at Columbia/Franklin
            @test r.tags["type"] == "restriction"
            @test r.tags["restriction"] == "no_u_turn"
            @test length(r.tags) == 2

            @test map(x -> x.id, r.members) == [16711116, 172698088, 16711116]
            @test map(x -> x.type, r.members) == [way, node, way]
            @test map(x -> x.role, r.members) == ["from", "via", "to"]

            @test 16711116 ∈ way_ids
            @test 172698088 ∈ node_ids

            found_u_turn = true
        end
    end

    @test length(rel_ids) == 836
    @test found_u_turn

    # not checking that members are in file, as many may not be,
    # for instance most members of https://www.openstreetmap.org/relation/224045 won't be
end


text:
# see if point is in circle, store 1.0
function mapper(x)
    (sqrt(sum(x.^2)) < 1.0, 1.0)
end

# count the number of points in the circle, total points
function reducer(x, y)
    x .+ y
end


text:
@testset "Weighting" begin
  @testset "BlockWeighter" begin
    sdomain = RegularGrid(100,100)
    sdata = georef(DataFrame(z=rand(10000)), RegularGrid(100,100))
    for d in [sdomain, sdata]
      w = weight(d, BlockWeighter(10,10))
      @test length(unique(w)) == 1
      @test w[1] == 1 / 100
    end
  end

  @testset "DensityRatioWeighter" begin
    n = 1000; Random.seed!(123)

    r1 = Normal(0, 2)
    r2 = MixtureModel([Normal(-2,1), Normal(2,2)], [0.2, 0.8])

    z1 = sort(rand(r1, n))
    z2 = sort(rand(r2, n))

    d1 = georef(DataFrame(z=z1), PointSet(reshape(1:n,1,:)))
    d2 = georef(DataFrame(z=z2), PointSet(reshape(1:n,1,:)))

    w = weight(d1, DensityRatioWeighter(d2))

    if visualtests
      @plottest begin
        plot( z1, pdf.(r1, z1), size=(800,400), label="source")
        plot!(z1, pdf.(r2, z1), label="target")
        plot!(z1, w .* pdf.(r1, z1), label="approx")
      end joinpath(datadir,"density-ratio.png") !istravis
    end
  end
end


text:
"""
    fit(template::objective_function_template,
        data::Any,
        theta::Vector{Float64};
        estimation_method::String = "M",
        br_method::String = "implicit_trace",
        regularizer::Function = function regularizer(theta::Vector{Float64}, data::Any) Vector{Float64}() end,
        lower::Vector{Float64} = Vector{Float64}(),
        upper::Vector{Float64} = Vector{Float64}(),
        optim_method = LBFGS(),
        optim_options = Optim.Options(),
        optim_arguments...)

Fit an [`objective_function_template`](@ref) on `data` using M-estimation (`estimation_method = "M"`; default) or RBM-estimation (reduced-bias M estimation; [Kosmidis & Lunardon, 2020](http://arxiv.org/abs/2001.03786); `estimation_method = "RBM"`)

Arguments
===

+ `template`: an [`objective_function_template`](@ref) object.
+ `data`: typically an object of [composite type](https://docs.julialang.org/en/v1/manual/types/#Composite-Types-1) with all the data required to compute the `objective_function`.
+ `theta`: a `Vector{Float64}` of parameter values to use as starting values in `Optim.optimize`.

[Keyword arguments](https://docs.julialang.org/en/v1/manual/functions/#Keyword-Arguments-1)
===

+ `estimation_method`: either "M" (default) or "RBM"; see Details.
+ `br_method`: either "implicit_trace" (default) or "explicit_trace"; see Details.
+ `regularizer`: a function of `theta` and `data` returning a `Float64`, which is added to the (bias-reducing penalized) objective; the default value will result in no regularization.
+ `lower`: a `Vector{Float64}` of dimension equal to `theta` for setting box constraints for the optimization. The default will result in unconstrained optimization. See Details.
+ `upper`: a `Vector{Float64}` of dimension equal to `theta` for setting box constraints for the optimization. The default will result in unconstrained optimization. See Details.
+ `optim_method`: the optimization method to be used; deafult is `Optim.LBFGS()`. See Details.
+ `optim_options`: the result of a call to `Optim.Options` to be passed to `Optim.optimize`. Default is `Optim.Options()`. See details.
+ `optim_arugments...`: extra keyword arguments to be passed to `Optim.optimize`. See Details.

Details
===

Bias reduction is either through the maximization of the bias-reducing penalized objective in Kosmidis & Lunardon (2020) (`br_method = "implicit_trace"`; default) or by subtracting an estimate of the bias from the M-estimates (`br_method = "explicit_trace"`). The bias-reducing penalty is constructed internally using automatic differentiation (using the [**ForwardDiff**](https://github.com/JuliaDiff/ForwardDiff.jl) package), and the bias estimate using a combination of automatic differentiation and numerical differentiation (using the [**FiniteDiff**](https://github.com/JuliaDiff/FiniteDiff.jl) package).

The maximization of the objective or the penalized objective is done using the [**Optim**](https://github.com/JuliaNLSolvers/Optim.jl) package. Optimization methods and options can be supplied directly through the `optim_method` and `optim_options`, respectively. `optim_options` expects an object constructed through `Optim.Options`. Keyword arguments (e.g. `autodiff = :forward`) can be passed directly to `Optim.optimize` through extra keyword arguments. See the [Optim documentation](https://julianlsolvers.github.io/Optim.jl/stable/#user/config/#general-options) for more details on the available options.

An extra additive regularizer to either the objective or the bias-reducing penalized objective can be suplied via the keyword argument `regularizer`, which must be a scalar-valued function of the parameters and the data; the default value will result in no regularization.

`lower` and `upper` can be used to provide box contraints. If valid `lower` and `upper` vectors are supplier, then the internal call to `Optim.optimize` will use `Fminbox(optim_method)` as a method; see the [**Optim** documentation on box minimization](https://julianlsolvers.github.io/Optim.jl/stable/#examples/generated/ipnewton_basics/#box-minimzation) for more details.
"""
function fit(template::objective_function_template,
             data::Any,
             theta::Vector{Float64};
             estimation_method::String = "M",
             br_method::String = "implicit_trace",
             regularizer::Function = function regularizer(theta::Vector{Float64}, data::Any) Vector{Float64}() end,
             lower::Vector{Float64} = Vector{Float64}(),
             upper::Vector{Float64} = Vector{Float64}(),
             optim_method = LBFGS(),
             optim_options = Optim.Options(),
             optim_arguments...)
    if (estimation_method == "M")
        br = false
    elseif (estimation_method == "RBM")
        if (br_method == "implicit_trace")
            br = true
        elseif (br_method == "explicit_trace")
            br = false
        else
            error(br_method, " is not a recognized bias-reduction method")
        end
    else
        error(estimation_method, " is not a recognized estimation method")
    end

    ## Well we only need scalar-valued penalties here but let's leave
    ## it like this
    has_regularizer = length(regularizer(theta, data)) > 0

    ## down the line when/if det is implemented we need to be passing the
    ## bias reduction method to objetive_function
    if has_regularizer
        obj = beta -> - objective_function(beta, data, template, br) - regularizer(beta, data)
    else
        obj = beta -> - objective_function(beta, data, template, br)
    end

    if (length(lower) > 0) & (length(upper) > 0)
        out = optimize(obj, lower, upper, theta, Fminbox(optim_method), optim_options; optim_arguments...)
    else
        out = optimize(obj, theta, optim_method, optim_options; optim_arguments...)
    end
    if (estimation_method == "M")
        theta = out.minimizer
    elseif (estimation_method == "RBM")
        ## FIXME, 12/03/2020: Add stop if br_method is not implicit_trace
        if (br_method == "implicit_trace")
            theta = out.minimizer
        elseif (br_method == "explicit_trace")
            quants = obj_quantities(out.minimizer, data, template, true)
            jmat_inv = quants[2]
            ## We use finite differences to get the adjustment
            adjustment = FiniteDiff.finite_difference_gradient(beta -> obj_quantities(beta, data, template, true)[1], out.minimizer)
            theta = out.minimizer + jmat_inv * adjustment
            ## Reset br
            br = true
        end
    end
    MEstimation_results(out, theta, data, template, regularizer, br, true, has_regularizer, br_method)
end

"""
    fit(template::estimating_function_template,
        data::Any,
        theta::Vector{Float64};
        estimation_method::String = "M",
        br_method::String = "implicit_trace",
        concentrate::Vector{Int64} = Vector{Int64}(),
        regularizer::Function = function regularizer(theta::Vector{Float64}, data::Any) Vector{Float64}() end,
        nlsolve_arguments...)

Fit an [`estimating_function_template`](@ref) on `data` using M-estimation (`estimation_method = "M"`; default) or RBM-estimation (reduced-bias M estimation; [Kosmidis & Lunardon, 2020](http://arxiv.org/abs/2001.03786); `estimation_method = "RBM"`)

Arguments
===
+ `template`: an [`estimating_function_template`](@ref) object.
+ `data`: typically an object of [composite type](https://docs.julialang.org/en/v1/manual/types/#Composite-Types-1) with all the data required to compute the `objective_function`.
+ `theta`: a `Vector{Float64}` of parameter values to use as starting values in `Optim.optimize`.

[Keyword arguments](https://docs.julialang.org/en/v1/manual/functions/#Keyword-Arguments-1)
===
+ `estimation_method`: either "M" (default) or "RBM"; see Details.
+ `br_method`: either "implicit_trace" (default) or "explicit_trace"; see Details.
+ `concentrate`: a `Vector{Int64}`; if specified, empirical bias-reducing adjustments are added only to the subset of estimating functions indexed by `concentrate`. The default is to add empirical bias-reducing adjustments to all estimating functions.
+ `regularizer`: a function of `theta` and `data` returning a `Vector{Float64}` of dimension equal to the number of the estimating functions, which is added to the (bias-reducing) estimating function; the default value will result in no regularization.
+ `nlsolve_arguments...`: extra keyword arguments to be passed to `NLsolve.nlsolve`. See Details.

Details
===

Bias reduction is either through the solution of the empirically adjusted estimating functions in Kosmidis & Lunardon (2020) (`br_method = "implicit_trace"`; default) or by subtracting an estimate of the bias from the M-estimates (`br_method = "explicit_trace"`). The bias-reducing adjustments and the bias estimate are constructed internally using automatic differentiation (using the [**ForwardDiff**](https://github.com/JuliaDiff/ForwardDiff.jl) package).

Bias reduction for only a subset of parameters can be performed by setting `concentrate` to the vector of the indices for those parameters.

The solution of the estimating equations or the adjusted estimating equations is done using the [**NLsolve**](https://github.com/JuliaNLSolvers/NLsolve.jl) package. Keyword arguments can be passed directly to `NLsolve.nlsolve` through extra keyword arguments. See the [NLsolve README](https://github.com/JuliaNLSolvers/NLsolve.jl) for more information on available options.

An extra additive regularizer to either the estimating functions or the bias-reducing adjusted estimating functions can be suplied via the keyword argument `regularizer`, which must be a `length(theta)`-valued function of the parameters and the data; the default value will result in no regularization.
"""
function fit(template::estimating_function_template,
             data::Any,
             theta::Vector{Float64};
             estimation_method::String = "M",
             br_method::String = "implicit_trace",
             concentrate::Vector{Int64} = Vector{Int64}(),
             regularizer::Function = function regularizer(theta::Vector{Float64}, data::Any) Vector{Float64}() end,
             nlsolve_arguments...)
    if (estimation_method == "M")
        br = false
    elseif (estimation_method == "RBM")
        if (br_method == "implicit_trace")
            br = true
        elseif (br_method == "explicit_trace")
            br = false
        else
            error(br_method, " is not a recognized bias-reduction method")
        end
    else
        error(estimation_method, " is not a recognized estimation method")
    end

    ## Well we only need length(theta)-valued penalties here but let's leave
    ## it like this
    has_regularizer = length(regularizer(theta, data)) > 0

    ## down the line when/if det is implemented we need to be passing the
    ## bias reduction method to objetive_function
    if has_regularizer
        ef = get_estimating_function(data, template, br, concentrate, regularizer)
    else
        function non_regularizer(theta::Vector{Float64}, data::Any) fill(0, length(theta)) end
        ef = get_estimating_function(data, template, br, concentrate, non_regularizer)
    end

    out = nlsolve(ef, theta; nlsolve_arguments...)
    if (estimation_method == "M")
        theta = out.zero
    elseif (estimation_method == "RBM")
        if (br_method == "implicit_trace")
            theta = out.zero
        elseif (br_method == "explicit_trace")
            quants = ef_quantities(out.zero, data, template, true, concentrate)
            adjustment = quants[1]
            jmat_inv = quants[2]
            theta = out.zero + jmat_inv * adjustment
            ## Reset br
            br = true
        end
    end
    MEstimation_results(out, theta, data, template, regularizer, br, false, has_regularizer, br_method)
end


text:
#######################################################################
# Spectrum
#######################################################################
struct Spectrum{E,T,A<:AbstractMatrix{T}}
    energies::E
    states::A
end

"""
    spectrum(h; method = defaultmethod(h))

Compute the spectrum of a 0D Hamiltonian `h` (or alternatively of the bounded unit cell of a
finite dimensional `h`) using one of the following `method`s

    method                    diagonalization function
    --------------------------------------------------------------
    LinearAlgebraPackage()     LinearAlgebra.eigen!
    ArpackPackage()            Arpack.eigs (must be `using Arpack`)

The energies and eigenstates in the resulting `s::Spectrum` object can be accessed with
`energies(s)` and `states(s)`

# See also
    `energies`, `states`, `bandstructure`

"""
function spectrum(h; method = defaultmethod(h))
    matrix = similarmatrix(h, method)
    bloch!(matrix, h)
    (ϵk, ψk) = diagonalize(matrix, method)
    return Spectrum(ϵk, ψk)
end

"""
    energies(s::Spectrum)

Return the energies of `s` as a `Vector`

# See also
    `spectrum`, `states`
"""
energies(s::Spectrum) = s.energies

"""
    states(s::Spectrum)

Return the states of `s` as the columns of a `Matrix`

# See also
    `spectrum`, `energies`
"""
states(s::Spectrum) = s.states

#######################################################################
# Bandstructure
#######################################################################
struct Band{M,A<:AbstractVector{M},MD<:Mesh,S<:AbstractArray}
    mesh::MD        # Mesh with missing vertices removed
    simplices::S    # Tuples of indices of mesh vertices that define mesh simplices
    states::A       # Must be resizeable container to build & refine band
    dimstates::Int  # Needed to extract the state at a given vertex from vector `states`
end

function Band(mesh::Mesh{D}, states::AbstractVector{M}, dimstates::Int) where {M,D}
    simps = simplices(mesh, Val(D))
    return Band(mesh, simps, states, dimstates)
end

struct Bandstructure{D,M,B<:Band{M},MD<:Mesh{D}}   # D is dimension of parameter space
    bands::Vector{B}
    kmesh::MD
end

function Base.show(io::IO, b::Bandstructure{D,M}) where {D,M}
    ioindent = IOContext(io, :indent => string("  "))
    print(io,
"Bandstructure: bands for a $(D)D hamiltonian
  Bands        : $(length(b.bands))
  Element type : $(displayelements(M))")
    print(ioindent, "\n", b.kmesh)
end

# API #
"""
    bands(bs::Bandstructure)

Return a vector of all the `Band`s in `bs`.
"""
bands(bs::Bandstructure) = bs.bands

"""
    vertices(bs::Bandstructure, i)

Return the vertices `(k..., ϵ)` of the i-th band in `bs`, in the form of a
`Vector{SVector{L+1}}`, where `L` is the lattice dimension.
"""
vertices(bs::Bandstructure, i) = vertices(bands(bs)[i])

vertices(b::Band) = vertices(b.mesh)

"""
    states(bs::Bandstructure, i)

Return the states of each vertex of the i-th band in `bs`, in the form of a `Matrix` of size
`(nψ, nk)`, where `nψ` is the length of each state vector, and `nk` the number of vertices.
"""
states(bs::Bandstructure, i) = states(bands(bs)[i])

states(b::Band) = reshape(b.states, b.dimstates)

#######################################################################
# bandstructure
#######################################################################
"""
    bandstructure(h::Hamiltonian, mesh::Mesh; minprojection = 0.5, method = defaultmethod(h))

Compute the bandstructure of Bloch Hamiltonian `bloch(h, ϕs...)` with `ϕs` evaluated on the
vertices of `mesh`. It is assumed that `h` is hermitian.

The option `minprojection` determines the minimum projection between eigenstates to connect
them into a common subband. The option `method` is chosen automatically if unspecified, and
can be one of the following

    method                    diagonalization function
    --------------------------------------------------------------
    LinearAlgebraPackage()     LinearAlgebra.eigen!
    ArpackPackage()            Arpack.eigs (must be `using Arpack`)

Options passed to the `method` will be forwarded to the diagonalization function. For example,
`method = ArpackPackage(nev = 8, sigma = 1im)` will use `Arpack.eigs(matrix; nev = 8,
sigma = 1im)` to compute the bandstructure.

    bandstructure(h::Hamiltonian; resolution = 13, shift = missing, kw...)

Same as above with a  uniform `mesh = marchingmesh(h; npoints = resolution, shift = shift)`
of marching tetrahedra (generalized to the lattice dimensions of the Hamiltonian). Note that
`resolution` denotes the number of points along each Bloch axis, including endpoints (can be
a tuple for axis-dependent points).

# Example
```
julia> h = LatticePresets.honeycomb() |> unitcell(3) |> hamiltonian(hopping(-1, range = 1/√3));

julia> bandstructure(h; resolution = 25, method = LinearAlgebraPackage())
Bandstructure: bands for a 2D hamiltonian
  Bands        : 8
  Element type : scalar (Complex{Float64})
  Mesh{2}: mesh of a 2-dimensional manifold
    Vertices   : 625
    Edges      : 3552
```

# See also
    marchingmesh
"""
function bandstructure(h::Hamiltonian{<:Any,L,M}; resolution = 13, shift = missing, kw...) where {L,M}
    checkfinitedim(h)
    mesh = marchingmesh(h; npoints = resolution, shift = shift)
    return bandstructure(h,  mesh; kw...)
end

function bandstructure(h::Hamiltonian, mesh::Mesh; method = defaultmethod(h), minprojection = 0.5)
    checkfinitedim(h)
    ishermitian(h) || throw(ArgumentError("Hamiltonian must be hermitian"))
    d = diagonalizer(h, mesh, method, minprojection)
    matrix = similarmatrix(h, method)
    return bandstructure!(matrix, h, mesh, d)
end

function bandstructure!(matrix::AbstractMatrix, h::Hamiltonian{<:Lattice,<:Any,M}, mesh::MD, d::Diagonalizer) where {M,D,T,MD<:Mesh{D,T}}
    nϵ = 0                           # Temporary, to be reassigned
    ϵks = Matrix{T}(undef, 0, 0)     # Temporary, to be reassigned
    ψks = Array{M,3}(undef, 0, 0, 0) # Temporary, to be reassigned

    dimh = size(h, 1)
    nk = nvertices(mesh)
    # function to apply to eigenvalues when building bands (depends on momenta type)
    by = _maybereal(T)

    p = Progress(nk, "Step 1/2 - Diagonalising: ")
    for (n, ϕs) in enumerate(vertices(mesh))
        bloch!(matrix, h, ϕs)
        # (ϵk, ψk) = diagonalize(Hermitian(matrix), d)  ## This is faster (!)
        (ϵk, ψk) = diagonalize(matrix, d.method)
        resolve_degeneracies!(ϵk, ψk, ϕs, matrix, d.codiag)
        if n == 1  # With first vertex can now know the number of eigenvalues... Reassign
            nϵ = size(ϵk, 1)
            ϵks = Matrix{T}(undef, nϵ, nk)
            ψks = Array{M,3}(undef, dimh, nϵ, nk)
        end
        copyslice!(ϵks, CartesianIndices((1:nϵ, n:n)),
                   ϵk,  CartesianIndices((1:nϵ,)), by)
        copyslice!(ψks, CartesianIndices((1:dimh, 1:nϵ, n:n)),
                   ψk,  CartesianIndices((1:dimh, 1:nϵ)), identity)
        ProgressMeter.next!(p; showvalues = ())
    end

    p = Progress(nϵ * nk, "Step 2/2 - Connecting bands: ")
    pcounter = 0
    bands = Band{M,Vector{M},Mesh{D+1,T,Vector{SVector{D+1,T}}},Vector{NTuple{D+1,Int}}}[]
    vertindices = zeros(Int, nϵ, nk) # 0 == unclassified, -1 == different band, > 0 vertex index
    pending = CartesianIndex{2}[]
    sizehint!(pending, nk)
    while true
        src = findfirst(iszero, vertindices)
        src === nothing && break
        resize!(pending, 1)
        pending[1] = src # source CartesianIndex for band search
        band = extractband(mesh, pending, ϵks, ψks, vertindices, d.minprojection)
        nverts = nvertices(band.mesh)
        nverts > D && push!(bands, band) # avoid bands with no simplices
        pcounter += nverts
        ProgressMeter.update!(p, pcounter; showvalues = ())
    end
    return Bandstructure(bands, mesh)
end

_maybereal(::Type{<:Complex}) = identity
_maybereal(::Type{<:Real}) = real

function extractband(kmesh::Mesh{D,T}, pending, ϵks::AbstractArray{T}, ψks::AbstractArray{M}, vertindices, minprojection) where {D,T,M}
    dimh, nϵ, nk = size(ψks)
    kverts = vertices(kmesh)
    states = eltype(ψks)[]
    sizehint!(states, nk * dimh)
    verts = SVector{D+1,T}[]
    sizehint!(verts, nk)
    adjmat = SparseMatrixBuilder{Bool}()
    vertindices[first(pending)] = 1 # pending starts with a single vertex
    for c in pending
        ϵ, k = Tuple(c) # c == CartesianIndex(ϵ::Int, k::Int)
        vertex = vcat(kverts[k], SVector(ϵks[c]))
        push!(verts, vertex)
        appendslice!(states, ψks, CartesianIndices((1:dimh, ϵ:ϵ, k:k)))
        for edgek in edges(kmesh, k)
            k´ = edgedest(kmesh, edgek)
            proj, ϵ´ = findmostparallel(ψks, k´, ϵ, k)
            if proj >= minprojection
                if iszero(vertindices[ϵ´, k´]) # unclassified
                    push!(pending, CartesianIndex(ϵ´, k´))
                    vertindices[ϵ´, k´] = length(pending) # this is clever!
                end
                indexk´ = vertindices[ϵ´, k´]
                indexk´ > 0 && pushtocolumn!(adjmat, indexk´, true)
            end
        end
        finalizecolumn!(adjmat)
    end
    for (i, vi) in enumerate(vertindices)
        @inbounds vi > 0 && (vertindices[i] = -1) # mark as classified in a different band
    end
    mesh = Mesh(verts, sparse(adjmat))
    return Band(mesh, states, dimh)
end

function findmostparallel(ψks::Array{M,3}, destk, srcb, srck) where {M}
    T = real(eltype(M))
    dimh, nϵ, nk = size(ψks)
    maxproj = zero(T)
    destb = 0
    @inbounds for nb in 1:nϵ
        proj = zero(M)
        for i in 1:dimh
            proj += ψks[i, nb, destk]' * ψks[i, srcb, srck]
        end
        absproj = T(abs(tr(proj)))
        if maxproj <= absproj  # must happen at least once
            destb = nb
            maxproj = absproj
        end
    end
    return maxproj, destb
end

max_issues_repo_name: pablosanjose/QBox

max_forks_repo_name: pablosanjose/QBox


text:
"""
Julia package for creating new packages and updating existing ones, following common
practices and workflow recommendations.

**This package may overwrite existing files.** While care has been taken to ensure no data
loss, it may nevertheless happen. Keep backups, commit to a non-local git repository, and
**use at your own risk**.

[`PkgSkeleton.generate`](@ref) is the only exposed functionality.
"""
module PkgSkeleton

using ArgCheck: @argcheck
import Dates
using DocStringExtensions: SIGNATURES
import LibGit2
using UUIDs: uuid4, UUID
import Pkg
import TOML
using UnPack: @unpack

####
#### utilities
####

"""
$(SIGNATURES)

Print `xs...` as a message of the given `:kind` (see the source for docs).

!!! NOTE
    The only function used to communicate with the user, everything (except errors) should
    go through this so that it can be modified at a single point if necessary.
"""
function msg(kind, xs...; header::Bool = false)
    color = getproperty((general = :white, # general/progress
                         dirty = :magenta, # (writing to) uncommitted files in repository
                         clean = :green,   # (writing to) committed files
                         same = :blue),    # files with same content
                        kind)
    printstyled(stderr, xs..., '\n'; color = color, bold = header)
    nothing
end

####
#### template values
####

"""
$(SIGNATURES)

Extract a package name using the last component of a path.

The following all result in `"Foo"`:

```julia
pkg_name_from_path("/tmp/Foo")
pkg_name_from_path("/tmp/Foo/")
pkg_name_from_path("/tmp/Foo.jl")
pkg_name_from_path("/tmp/Foo.jl/")
```
"""
function pkg_name_from_path(path::AbstractString)
    base, ext = splitext(basename(isdirpath(path) ? dirname(path) : path))
    @argcheck(isempty(ext) || ext == ".jl",
              "Invalid extension $(ext), specify package as a replacement value.")
    base
end

"Docstring for replacement values."
const REPLACEMENTS_DOCSTRING = """
- `UUID`: the package UUID; default: random
- `PKGNAME`: the package name; default: taken from the destination directory
- `GHUSER`: the github user; default: taken from Git options
- `USERNAME`: the user name; default: taken from Git options
- `USEREMAIL`: the user e-mail; default: taken from Git options
- `YEAR`: the calendar year; default: from system time
"""

"""
Error type for git options not found in the global environment. Reporting with helpful error
message to the user.
"""
struct GitOptionNotFound <: Exception
    "The name for the option."
    option::String
    "What the option is used for (for the error message)."
    used_for::String
end

function Base.showerror(io::IO, e::GitOptionNotFound)
    print(io, """
    Could not find option “$(e.option)” in your global git configuration.

    It is necessary to set this for $(e.used_for).

    You can set this in the command line with

    git config --global $(e.option) "…"
    """)
end

"""
$(SIGNATURES)

Lookup UUIDs matching `pkg_name` in the local copy of registries in `DEPOT_PATH`.

Return a vector of strings.
"""
function lookup_UUIDs_in_registries(pkg_name)
    # Look up Registry.toml files in depots
    uuids = UUID[]
    for d in DEPOT_PATH
        regs = joinpath(d, "registries")
        if isdir(regs)
            for r in readdir(regs)
                toml_path = joinpath(regs, r, "Registry.toml")
                if isfile(toml_path)
                    toml = TOML.parsefile(toml_path)
                    if haskey(toml, "packages")
                        for (k, v) in toml["packages"]
                            if v["name"] == pkg_name
                                push!(uuids, UUID(k))
                            end
                        end
                    end
                end
            end
        end
    end
    uuids
end

"""
$(SIGNATURES)

Look up the UUID in the project file of `target_dir` and return it, or `nothing` if it is
not found or there is no project file.

When `pkg_name` is provided, an error is thrown if the project file has a different
name.
"""
function lookup_UUID_in_project(target_dir, pkg_name = nothing)
    toml_path = joinpath(target_dir, "Project.toml")
    if !isfile(toml_path)
        toml_path = joinpath(target_dir, "JuliaProject.toml")
        isfile(toml_path) || return nothing
    end
    toml = TOML.parsefile(toml_path)
    if pkg_name ≢ nothing && haskey(toml, "name")
        name = toml["name"]
        if name ≠ pkg_name
            error("name = $(name) in project file does not match $(pkg_name)")
        end
    end
    if haskey(toml, "uuid")
        UUID(toml["uuid"])
    else
        nothing
    end
end

"""
$(SIGNATURES)

Heuristic to find an existing UUID or generate a new one.

*If* there is a target directory, try to find a project file there with an UUID.

If this fails, check the registry, if matches are found, inform the user (printing the
UUIDs) and abort.

Otherwise, generate a random UUID.
"""
function existing_or_random_UUID(target_dir, pkg_name = nothing)
    if isdir(target_dir)
        uuid_project = lookup_UUID_in_project(target_dir, pkg_name)
        if uuid_project ≢ nothing
            msg(:general, "Found UUID from existing project file.")
            return uuid_project
        end
        uuids_registry = lookup_UUIDs_in_registries(pkg_name ≡ nothing ?
                                                    pkg_name_from_path(target_dir) : pkg_name)
        if length(uuids_registry) ≥ 1
            msg(:general, "Found the following UUIDs matching $(pkg_name) in the local registries:")
            for uuid in uuids_registry
                msg(:general, "  ", uuid)
            end
            error("Provide an UUID with Pkg.generate(target_dir, (UUID = Base.UUID(\"...\"), )).")
        end
    end
    uuid4()
end

"""
$(SIGNATURES)

Populate a NamedTuple replacements, either from arguments or by querying global settings and
state. When a value is available in `user_replacements`, it is used directly.

The following replacement values are used:

$(REPLACEMENTS_DOCSTRING)

`target_dir` is used as a path, and does not have to exist as a directory for this function
to work.
"""
function fill_replacements(user_replacements; target_dir)
    c = LibGit2.GitConfig()     # global configuration
    function _getgitopt(opt, used_for)
        try
            LibGit2.get(AbstractString, c, opt)
        catch e
            if e isa LibGit2.GitError # assume it is not found
                throw(GitOptionNotFound(opt, used_for))
            else
                rethrow(e)
            end
        end
    end
    _provided_values = propertynames(user_replacements)
    function _ensure_value(key, f)
        if key ∈ _provided_values
            # VERSION ≥ 1.2 could use hasproperty, but we support earlier versions too
            getproperty(user_replacements, key)
        else
            # we are lazy here so that the user can user an override when obtaining the
            # value from the environment would error
            f()
        end
    end
    defaults = (UUID = () -> existing_or_random_UUID(target_dir,
                                                     get(defaults, :PKG_NAME, nothing)),
                PKGNAME = () -> pkg_name_from_path(target_dir),
                GHUSER = () -> _getgitopt("github.user", "your Github username"),
                USERNAME = () -> _getgitopt("user.name",
                                            "your name (as the package author)"),
                USEREMAIL = () -> _getgitopt("user.email",
                                             "your e-mail (as the package author)"),
                YEAR = () -> Dates.year(Dates.now()))
    NamedTuple{keys(defaults)}(map(_ensure_value, keys(defaults), values(defaults)))
end

####
#### Template application
####

"""
$(SIGNATURES)

Return the template directory for `name`. Symbols refer to built-in templates, while strings
are considered paths. Directories are always verified to exist.
"""
function resolve_template_directory(name::Symbol)
    dir = abspath(joinpath(@__DIR__, "..", "templates", String(name)))
    @argcheck isdir(dir) "Could not find built-in template $(name)."
    dir
end

function resolve_template_directory(dir::AbstractString)
    @argcheck isdir(dir) "Could not find directory $(dir)."
    dir
end

"""
$(SIGNATURES)

Read a template directory, and return as a vector of `relative_path => content` pairs,
sorted on the relative path for consistency.
"""
function read_template_directory(template_dir)
    template = Vector{Pair{String,String}}()
    for (root, dirs, files) in walkdir(template_dir)
        for file in files
            absolute_path = joinpath(root, file)
            relative_path = relpath(absolute_path, template_dir)
            push!(template, relative_path => read(absolute_path, String))
        end
    end
    sort!(template, by = first)
end

"""
$(SIGNATURES)

Wrap replacements in `{}`s for use in the templates.

!!! NOTE
    This function is the sole place where the template logic is encoded. If templates syntax
    changes, nothing else needs to be rewritten.
"""
function delimited_replacements(replacements)
    ["{$(string(key))}" => string(value) for (key, value) in pairs(replacements)]
end

"""
$(SIGNATURES)

Replace multiple pairs in `str`, using `replace` iteratively.

`delimited_replacements` should be an iterable, it is applied in the given order.
"""
function replace_multiple(str, delimited_replacements)
    foldl(replace, delimited_replacements; init = str)
end

"""
$(SIGNATURES)

Apply the replacements in `template`, returning a vector of `relpath => content` pairs, in
the same order.
"""
function apply_replacements(template, delimited_replacements)
    _replace(x) = replace_multiple(x, delimited_replacements)
    [_replace(relpath) => _replace(content) for (relpath, content) in template]
end

"""
$(SIGNATURES)

Compare files in the applied template with the target directory.

Three vectors of `relpath => content` pairs are returned in a `NamedTuple`:

- `same_files`: files with identical content in the applied template.
- `dirty_files`: files with different content, which are not committed in the repository.
- `clean_files`: empty files or files which would change but are committed.
"""
function compare_with_target(target_dir, applied_template)
    repository = LibGit2.GitRepo(target_dir)
    same_files = Vector{Pair{String,String}}()
    dirty_files = Vector{Pair{String,String}}()
    clean_files = Vector{Pair{String,String}}()
    for relpath_content in applied_template
        relpath, content = relpath_content
        abspath = joinpath(target_dir, relpath)
        already_exists = ispath(abspath)
        already_exists && (@argcheck isfile(abspath) "$(abspath) is not a file, aborting.")
        if already_exists && read(abspath, String) == content
            push!(same_files, relpath_content)
        elseif already_exists && LibGit2.status(repository, relpath) ≠ 0
            push!(dirty_files, relpath_content)
        else
            push!(clean_files, relpath_content)
        end
    end
    # FIXME replace with compact (; ...) syntax once we only support VERSION ≥ 1.5
    (same_files = same_files, dirty_files = dirty_files, clean_files = clean_files)
end

"""
$(SIGNATURES)

"""
function msg_and_write(kind, header, target_dir, relpath_content_pairs)
    isempty(relpath_content_pairs) && return nothing
    msg(kind, header; header = true)
    for (relpath, content) in relpath_content_pairs
        msg(kind, "  $(relpath)")
        if target_dir ≢ nothing
            abspath = joinpath(target_dir, relpath)
            mkpath(dirname(abspath))
            write(abspath, content)
        end
    end
    nothing
end

####
#### exposed API
####

"""
$(SIGNATURES)

Generate the skeleton for a Julia package in `target_dir`. The directory is transformed with
`expanduser`, replacing `~` in paths. Print a summary of what changed.

!!! NOTE
    If a package already exists at `target_dir`, it is strongly recommended that the
    repository is in a clean state (no untracked files or uncommitted changes).

# Example

```julia
import PkgSkeleton
PkgSkeleton.generate("/tmp/Foo")
```

# Keyword arguments and defaults

- `template = :default`: specifies the template to use. Symbols refer to *built-in*
  templates delivered with this package. Strings are used as paths.

- `user_replacements = (;)`: a `NamedTuple` that can be used to manually specify the
  replacements (see below).

- `overwrite_uncommitted = false`: Existing files which are not committed in the repository
  are not overwritten unless this is `true`, generation is aborted with an error. **It is
  strongly advised that you just commit or delete exising files instead of using this
  flag.**

# Replacements

$(REPLACEMENTS_DOCSTRING)

Specifically, `PKGNAME` can be used to specify a package name, derived from `target_dir` by
default: the package name is `"Foo"` for all of

1. `"/tmp/Foo"`,
2. `"/tmp/Foo/"`,
3. `"/tmp/Foo.jl"`,
4. `"/tmp/Foo.jl/"`.

Use a different name only when you know what you are doing.
"""
function generate(target_dir; template = :default,
                  user_replacements::NamedTuple = NamedTuple(),
                  overwrite_uncommitted::Bool = false)
    target_dir = expanduser(target_dir)
    msg(:general, "getting template replacement values")
    replacements = fill_replacements(user_replacements; target_dir = target_dir)

    template_dir = resolve_template_directory(template)
    msg(:general, "reading template $(template) from $(template_dir)")
    template = read_template_directory(template_dir)
    applied_template = apply_replacements(template, delimited_replacements(replacements))

    if ispath(target_dir)
        @argcheck isdir(target_dir) "destination $(target_dir) is not a directory."
    end
    if isdir(target_dir)
        try
            LibGit2.GitRepo(target_dir)
        catch
            error("target $(target_dir) exists, but is not a valid git repository")
        end
    else
        msg(:general, "target $(target_dir) does not exist, creating with a git repository")
        mkpath(target_dir)
        LibGit2.init(target_dir)
    end

    @unpack same_files, dirty_files, clean_files =
        compare_with_target(target_dir, applied_template)

    if overwrite_uncommitted
        msg_and_write(:dirty,
                      "OVERWRITING the following uncommitted files as requested:",
                      target_dir, dirty_files)
    else
        msg_and_write(:dirty, "SKIPPING uncommitted changes in the following files:",
                      nothing, dirty_files)
    end

    msg_and_write(:clean,
                  "(OVER)WRITING the following files (missing or committed in the repository):",
                  target_dir, clean_files)

    msg_and_write(:same, "SKIPPING the following files as they would not change:",
                  nothing, same_files)

    # done
    msg(:general, "successfully generated $(replacements.PKGNAME)")

    nothing
end

end # module


text:
using MacroTools

function Base.convert(::Type{Expression}, ex::Expr)
    ex.head === :call || throw(ArgumentError("internal representation does not support non-call Expr"))

    op = eval(ex.args[1])  # HACK
    args = convert.(Expression, ex.args[2:end])

    return Operation(op, args)
end
Base.convert(::Type{Expression}, x::Expression) = x
Base.convert(::Type{Expression}, x::Number) = Constant(x)

function build_expr(head::Symbol, args)
    ex = Expr(head)
    append!(ex.args, args)
    ex
end
expr_arr_to_block(exprs) = build_expr(:block, exprs)

# used in parsing
isblock(x) = length(x) == 1 && x[1] isa Expr && x[1].head == :block
function flatten_expr!(x)
    isb = isblock(x)
    if isb
        x = MacroTools.striplines(x[1])
        filter!(z->z isa Symbol || z.head != :line, x.args)
        x = (x.args...,)
    end
    x
end

toexpr(ex) = MacroTools.postwalk(x -> isa(x, Expression) ? convert(Expr, x) : x, ex)

function partition(f, xs)
    idxs = map(f, xs)
    not_idxs = eachindex(xs) .∉ (idxs,)
    return (xs[idxs], xs[not_idxs])
end

is_constant(::Constant) = true
is_constant(::Any) = false

is_operation(::Operation) = true
is_operation(::Any) = false

has_dependent(t::Variable) = Base.Fix2(has_dependent, t)
has_dependent(x::Variable, t::Variable) =
    t ∈ x.dependents || any(has_dependent(t), x.dependents)


text:
function ten_to_two(n)
    b = zeros(Int8,15)
    temp_b = zeros(Int8,15)

    ite=1
    while n > 0
        b[ite] = n % 2
        n = Int((n-b[ite])/2)
        ite = ite +1
    end

    #=
    for i in 1:6
        temp_b[i] = b[6+1-i]
    end
    =#

    return b
end

function two_to_ten(b)
    n = Int8(0)

    for i in 1:length(b)
        n = n + 2^(i-1)*b[i]
    end
    return n
end

# ----------------------
# -- Inverse matrix   --
# ----------------------
function inverse_matrix(eu,ev)
# ----------------------
# -- A = ( eu[1]  ev[1])  --
# --     ( eu[2]  ev[2])  --
# ----------------------
    invA = zeros(2,2)
    detA = eu[1]*ev[2] - eu[2]*ev[1]

    invA[1,1] = (ev[2])/detA
    invA[1,2] = (-ev[1])/detA
    invA[2,1] = (-eu[2])/detA
    invA[2,2] = (eu[1])/detA
    return invA
end

function cal_morton(ulx,uly,ulz,lrx,lry,lrz,n_div) # 0<=s,tでreturn
    # 左上奥と右下前の座標を整数で
    morton_belong = 0
    morton_num = 0

    upl_morton = zeros(Int8,15)
    lowr_morton = zeros(Int8,15)
    temp_morton = zeros(Int8,15)

    # 左上の点のモートン空間番号
    x_two = ten_to_two(ulx)
    y_two = ten_to_two(uly)
    z_two = ten_to_two(ulz)

    for k in 1:5
        upl_morton[k*3-2] = x_two[k]
        upl_morton[k*3-1] = y_two[k]
        upl_morton[k*3]   = z_two[k]
    end

    # 右下の点のモートン空間番号
    x_two = ten_to_two(lrx)
    y_two = ten_to_two(lry)
    z_two = ten_to_two(lrz)

    for k in 1:5
        lowr_morton[k*3-2] = x_two[k]
        lowr_morton[k*3-1] = y_two[k]
        lowr_morton[k*3]   = z_two[k]
    end

    # 排他的論理和 xor
    for i in 1:15
        if upl_morton[i]+lowr_morton[i] == 2
            temp_morton[i] = 0
        else
            temp_morton[i] = upl_morton[i]+lowr_morton[i]
        end
    end

    # 所属空間のチェック

    ite = Int64(0)
    for i in 1:n_div
        s30 = 3*(n_div-(i-1))
        s31 = 3*(n_div-(i-1)) - 1
        s32 = 3*(n_div-(i-1)) - 2

        if temp_morton[s30] == 1 || temp_morton[s31] == 1 || temp_morton[s32] == 1
            morton_belong = ite                             # ルート空間
            break
        end
        #=
        if temp_morton[s_even] == 1 || temp_morton[s_odd] == 1
            morton_belong = 0                             # ルート空間
        elseif temp_morton[4] == 1 || temp_morton[3] == 1
            morton_belong = 1                             # 親空間
        elseif temp_morton[2] == 1 || temp_morton[1] == 1
            morton_belong = 2                             # 子空間
        else
            morton_belong = 3                             # 孫空間
        end
        =#
        ite += 1
    end

    # 所属空間番号
    temp_morton = zeros(Int8,15)

    s30 = 3*(n_div)
    s31 = 3*(n_div) - 1
    s32 = 3*(n_div) - 2
    if morton_belong == 0                             # ルート空間
        morton_num = 0
    elseif morton_belong == 1                         # 親空間
        # 4右シフト
        temp_morton[1] = lowr_morton[s32]
        temp_morton[2] = lowr_morton[s31]
        temp_morton[3] = lowr_morton[s30]

        morton_num = two_to_ten(temp_morton)

    elseif morton_belong == 2                         # 子空間
        # 2右シフト
        temp_morton[1] = lowr_morton[s32-3]
        temp_morton[2] = lowr_morton[s31-3]
        temp_morton[3] = lowr_morton[s30-3]
        temp_morton[4] = lowr_morton[s32]
        temp_morton[5] = lowr_morton[s31]
        temp_morton[6] = lowr_morton[s30]

        morton_num = two_to_ten(temp_morton)
    elseif morton_belong == 3                         # 孫空間

        # 0右シフト
        temp_morton[1] = lowr_morton[s32-6]
        temp_morton[2] = lowr_morton[s31-6]
        temp_morton[3] = lowr_morton[s30-6]
        temp_morton[4] = lowr_morton[s32-3]
        temp_morton[5] = lowr_morton[s31-3]
        temp_morton[6] = lowr_morton[s30-3]
        temp_morton[7] = lowr_morton[s32]
        temp_morton[8] = lowr_morton[s31]
        temp_morton[9] = lowr_morton[s30]

        morton_num = two_to_ten(temp_morton)

    elseif morton_belong == 4                         # 孫空間
        temp_morton = copy(lowr_morton)
        morton_num = two_to_ten(temp_morton)
    end

    return morton_belong,morton_num
end

function liner_morton(n_div)
    # 両方の探査を行うため，煩雑
    s = zeros(Int64,5)

    for j in 1:5
        for i in 1:(n_div+1)
            s[j] += floor(8.0^(i-j))
        end
        s[j] += (j-1)
    end

    search0 = zeros(Int64,8^0,s[1])
    search1 = zeros(Int64,8^1,s[2])
    search2 = zeros(Int64,8^2,s[3])
    search3 = zeros(Int64,8^3,s[4])
    search4 = zeros(Int64,8^4,s[5])

    # ルート空間：s0
    for i in 1:1
        for j in 1:s[1]
            search0[i,j] = j
        end
    end

    # 親空間：s1
    for i in 1:8
        search1[i,1] = 1　　　　　　　　　　　　　　　　# ルート空間
        search1[i,2] = i+1                           # 親空間
        for j in 1:8
            search1[i,j+2] = 10 + 8*(i-1) + (j-1)     # 子空間
        end
        for j in 1:64
            search1[i,j+10] = 73 + 8^2*(i-1) + (j-1)   # 孫空間
        end

        if n_div ==4
            for j in 1:512
                search1[i,j+74] = 1+8+64+512+1 + 8^3*(i-1) + (j-1)   # ひ孫空間
            end
        end
    end

    # 子空間：s2
    for i in 1:64
        search2[i,1] = 1                             # ルート空間
        search2[i,2] = div(i-1,8) + 2                # 親空間
        search2[i,3] = i+9                           # 子空間
        for j in 1:8
            search2[i,j+3] = 10 + 8*(i-1) + (j-1)    # 孫空間
        end
        if n_div ==4
            for j in 1:64
                search2[i,j+11] = 73 + 8^2*(i-1) + (j-1)    # 孫空間
            end
        end
    end

    # 孫空間
    for i in 1:512
        search3[i,1] = 1                             # ルート空間
        search3[i,2] = div(i-1,64) + 2               # 親空間
        search3[i,3] = div(i-1,8) + 10                # 子空間
        search3[i,4] = 73 + (i-1)                    # 孫空間
        if n_div >=4
            for j in 1:8
                search3[i,j+4] = 10 + 8*(i-1) + (j-1)    # 孫空間
            end
        end
    end

    # ひ孫空間
    if n_div >=4
        for i in 1:4096
            search4[i,1] = 1                             # ルート空間
            search4[i,2] = div(i-1,512) + 2               # 親空間
            search4[i,3] = div(i-1,64) + 10                # 子空間
            search4[i,4] = div(i-1,8) + 73               # 孫空間
            search4[i,5] = 585 + (i-1)                    # 孫空間
        end
    end

    return s,search0,search1,search2,search3,search4
end