import copy

import inspect
from pprint import pprint
import numpy as np
import pandas as pd
from hatch_python_utils.earth.coordinates import geoclatR2geodlatheight
from hatch_python_utils import arrays as hArr
from datetime import timedelta
from hatch_python_utils.plot import colormaps as hCM
from apexpy import Apex

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from mpl_toolkits.basemap import Basemap, cm
from matplotlib.dates import DateFormatter, date2num, num2date

# def func():
#     global minutesplusminus, wantsite, wantbl
#     frame = inspect.currentframe()
#     previous_namespace = frame.f_back.f_locals
#     minutesplusminus, wantsite, wantbl = (previous_namespace[navn] for navn in [
#                                           'minutesplusminus', 'wantsite', 'wantbl'])
#     # pprint(previous_namespace)
#     # print(dir())
#     print(minutesplusminus, wantsite, wantbl)

def sort_chunk_decimate_Swarm_prod(prod, date0, date1,
                                   dtsec=600):

    # if isinstance(prod,list):
    if prod.size == 0:
        return prod

    prod.sort_index(inplace=True)

    prodChunks = []
    prodChunks.append(prod[date0:date1].copy())
    prod = pd.concat(prodChunks)
    prod.sort_index(inplace=True)

    # print("Add 'group#' column for df with columns {:s}".format(
    #     ",".join(prod.columns)))
    add_groupcolumn_basedon_timeindex(prod,
                                      dtsec=dtsec)

    return prod

def add_groupcolumn_basedon_timeindex(df, dtsec=100):
    df.loc[:, 'group'] = np.nan

    cnt = np.int64(0)

    diffs = np.insert(np.diff(df.index), 0, np.diff(
        df.index)[0]).astype(np.float64)/1e9
    indGroups = hArr.group_consecutives(np.where(diffs < dtsec)[0])

    # print("{:d} indgroups".format(len(indGroups)))

    for indgroup in indGroups:
        # print(cnt,indgroup.size)
        df.loc[df.iloc[indgroup].index, 'group'] = cnt
        cnt += 1

    # df.loc[:,'group'] = df['group']

def read_conjpickle_get_plusminus_slice(fil, conjTimes, minutesplusminus,
                                        debug=False):
    tdelt = timedelta(minutes=minutesplusminus)

    EISdf = pd.read_pickle(fil)
    print("Got {:d} rows, {:d} cols from {:s}".format(
        EISdf.shape[0], EISdf.shape[1], fil))

    gotIm = False
    for matchI, conjTime in enumerate(conjTimes):
        if debug:
            print(matchI, conjTime)
        if (EISdf.iloc[0].name <= conjTime) & (EISdf.iloc[-1].name >= conjTime):
            gotIm = True
            break

    if not gotIm:
        print("Never get a match!")

    if matchI == len(conjTimes):
        assert 2 < 0, "No match, I think, unless off-by-one indexing!"

    date0, date1 = conjTimes[matchI]-tdelt, conjTimes[matchI]+tdelt

    print(date0, date1, EISdf[date0:date1].shape)

    return conjTimes[matchI], EISdf[date0:date1].copy()

def find_conjpickle_get_plusminus_slice(fils, conjTime, minutesplusminus,
                                        debug=False,
                                        preferRadar='42m'):
    tdelt = timedelta(minutes=minutesplusminus)

    datoStr = conjTime.strftime("%Y-%m-%d")

    gotIm = False
    candidate_indices = []
    for iDate, fil in enumerate(fils):

        if datoStr in fil:

            EISdf = pd.read_pickle(fil)
            if debug:
                print("Trying {:s}, got {:d} rows, {:d} cols".format(
                    fil, EISdf.shape[0], EISdf.shape[1]))

            #     for matchI,conjTime in enumerate(conjTimes):
            # if debug:
            #     print(matchI,conjTime)
            if (EISdf.iloc[0].name <= conjTime) & (EISdf.iloc[-1].name >= conjTime):
                candidate_indices.append(iDate)
                gotIm = True
                # break

    if not gotIm:
        if debug:
            print("Never got a match!")
        return iDate, pd.DataFrame()

    elif gotIm:

        date0, date1 = conjTime-tdelt, conjTime+tdelt

        preferFiles = [(iDate, fils[iDate])
                       for iDate in candidate_indices if (preferRadar in fils[iDate])]
        nPrefers = len(preferFiles)

        if nPrefers > 0:
            for iDate, prefFil in preferFiles:
                useFil = prefFil
                # iDate = candidate_indices[iPref]
                print("YEAH")
                break
        else:
            iDate = candidate_indices[0]
            useFil = fils[iDate]
            print("Didn't get preferenceRadar, using {:s}".format(
                useFil))

        EISdf = pd.read_pickle(useFil)

        EISdf['utc'] = EISdf.index
        EISdf.sort_values(by=['utc', 'gdalt'], inplace=True)

        return iDate, EISdf[date0:date1].copy()

# def find_conjpickle_get_plusminus_slice(fils, conjTime, minutesplusminus,
#                                         debug=False):
#     tdelt = timedelta(minutes=minutesplusminus)

#     datoStr = conjTime.strftime("%Y-%m-%d")

#     gotIm = False
#     for iDate, fil in enumerate(fils):

#         if datoStr in fil:

#             EISdf = pd.read_pickle(fil)
#             if debug:
#                 print("Trying {:s}, got {:d} rows, {:d} cols".format(
#                     fil, EISdf.shape[0], EISdf.shape[1]))

#             #     for matchI,conjTime in enumerate(conjTimes):
#             # if debug:
#             #     print(matchI,conjTime)
#             if (EISdf.iloc[0].name <= conjTime) & (EISdf.iloc[-1].name >= conjTime):
#                 gotIm = True
#                 break

#     if not gotIm:
#         if debug:
#             print("Never got a match!")
#         return iDate, pd.DataFrame()

#     elif gotIm:

#         date0, date1 = conjTime-tdelt, conjTime+tdelt

#         EISdf['utc'] = EISdf.index
#         EISdf.sort_values(by=['utc', 'gdalt'], inplace=True)

#         return iDate, EISdf[date0:date1].copy()

def get_swarm_conjAlt_and_data(df, lab, conjTime,
                               latcol='Latitude',
                               loncol='Longitude',
                               radcol='Radius',
                               nearestNeighbor=True):

    swarmgdlat, swarmalt = geoclatR2geodlatheight(
        df[latcol].values, df[radcol].values/1000.)

    if nearestNeighbor:
        nearInds = np.argpartition(
            np.abs(df.index.drop_duplicates()-conjTime), 2)[:2]

        dts = np.abs(df.iloc[nearInds].index-conjTime).total_seconds()

        if np.where(dts == 0.)[0].size > 0:
            nearIndex = nearInds[np.where(dts == 0.)[0].item()]
            nearAlt = swarmalt[nearIndex]
            nearList = [nearAlt]+list(df.iloc[nearIndex][lab].values)

        else:

            totdt = np.abs(np.diff(df.iloc[nearInds].index)[
                0]/pd.Timedelta(seconds=1))
            w1, w0 = dts.values/totdt

            tmp0 = df.iloc[nearInds[0]]*w0
            tmp1 = df.iloc[nearInds[1]]*w1

            doze = pd.DataFrame(columns=lab)
            doze.loc['w0', lab] = tmp0
            doze.loc['w1', lab] = tmp1

            nearAlt = swarmalt[nearInds[0]]*w0+swarmalt[nearInds[1]]*w1

            nearList = [nearAlt] + list(doze.sum()[lab].values)

    else:

        nearIndex = df.index.drop_duplicates().get_loc(conjTime, method='nearest')
        nearAlt = swarmalt[nearIndex]
        nearList = [nearAlt]+list(df.iloc[nearIndex][lab].values)

    return nearList

def get_EISCAT_vals_at_time_and_alt(dfEISCAT, conjTime, wantAlt,
                                    gamlemaate=False,
                                    nyemaate=False,
                                    doWgtMean=True,
                                    convert_vo_to_voUp=False):

    assert gamlemaate or nyemaate or doWgtMean, "No maate valgt!"

    if gamlemaate:
        ECATnear = dfEISCAT.loc[dfEISCAT.index.drop_duplicates()[dfEISCAT.index.drop_duplicates().get_loc(conjTime,
                                                                                method='nearest')], :]
        if convert_vo_to_voUp:
            # ECATnear.loc[:, ['vo', 'dvo']] = ECATnear.loc[:, ['vo', 'dvo']
            #                                               ] * np.sin(np.deg2rad(ECATnear.loc[:, 'elm']))
            # ECATnear.loc[:, ['vo', 'dvo']] = ECATnear[['vo', 'dvo']
            #                                           ] * np.sin(np.deg2rad(ECATnear['elm'].values))
            ECATnear.loc[:, 'vo'] = ECATnear['vo'] * \
                np.sin(np.deg2rad(ECATnear['elm'].values))
            ECATnear.loc[:, 'dvo'] = ECATnear['dvo'] * \
                np.sin(np.deg2rad(ECATnear['elm'].values))

        neE, teE, voE, dneE, dteE, dvoE, altE = ECATnear.iloc[np.argmin(np.abs(
            ECATnear['gdalt'].values-wantAlt))][['ne', 'te', 'vo', 'dne', 'dte', 'dvo', 'gdalt']].values

        # if convert_vo_to_voUp:
        #     toUpFactor = np.sin(np.deg2rad(ECATnear.iloc[np.argmin(
        #         np.abs(ECATnear['gdalt'].values-wantAlt))]['elm']))

        #     assert np.isfinite(toUpFactor), "WHATT??!"
        #     voE = voE * toUpFactor
        #     dvoE = dvoE * toUpFactor

    elif nyemaate:

        print("HELT NYE MÅTE MED ALT AVERAGING")
        ECATnear = dfEISCAT.loc[dfEISCAT.index.drop_duplicates()[dfEISCAT.index.drop_duplicates().get_loc(conjTime,
                                                                                method='nearest')], :].copy()
        if convert_vo_to_voUp:
            # ECATnear.loc[:, ['vo', 'dvo']] = ECATnear.loc[:, ['vo', 'dvo']
            #                                               ] * np.sin(np.deg2rad(ECATnear.loc[:, 'elm']))
            # ECATnear.loc[:, ['vo', 'dvo']] = ECATnear[['vo', 'dvo']
            #                                           ] * np.sin(np.deg2rad(ECATnear['elm'].values))
            ECATnear.loc[:, 'vo'] = ECATnear['vo'] * \
                np.sin(np.deg2rad(ECATnear['elm'].values))
            ECATnear.loc[:, 'dvo'] = ECATnear['dvo'] * \
                np.sin(np.deg2rad(ECATnear['elm'].values))

        dAlts = ECATnear.iloc[1:]['gdalt'].values - \
            ECATnear.iloc[:-1]['gdalt'].values
        dAlts = np.insert(dAlts, dAlts.size, dAlts[-1])
        ECATnear['gdaltmid'] = ECATnear['gdalt'] + dAlts/2.

        altInd = np.argmin(np.abs(ECATnear['gdaltmid'].values-wantAlt))
        altInd2 = ((ECATnear.iloc[altInd]['gdaltmid']-wantAlt) < 0)*2-1+altInd

        if altInd2 == ECATnear.shape[0]:
            altInd2 -= 1
            neE, teE, voE, dneE, dteE, dvoE, altE = ECATnear.iloc[altInd][[
                'ne', 'te', 'vo', 'dne', 'dte', 'dvo', 'gdalt']].values

        else:

            if ECATnear.iloc[altInd2]['gdaltmid'] < ECATnear.iloc[altInd]['gdaltmid']:
                tmpaltind = copy.deepcopy(altInd2)
                altInd2 = altInd
                altInd = tmpaltind

            dAlt = ECATnear.iloc[altInd2]['gdaltmid'] - \
                ECATnear.iloc[altInd]['gdaltmid']
            w1 = np.abs(ECATnear.iloc[altInd]['gdaltmid']-wantAlt)/dAlt
            w0 = np.abs(ECATnear.iloc[altInd2]['gdaltmid']-wantAlt)/dAlt

            print(conjTime, wantAlt, " alt0, w0, vo0:",
                  ECATnear.iloc[altInd]['gdaltmid'], w0,
                  ECATnear.iloc[altInd]['vo'])
            print(conjTime, wantAlt, " alt1, w1, vo1:",
                  ECATnear.iloc[altInd2]['gdaltmid'], w1,
                  ECATnear.iloc[altInd2]['vo'])

            tmp0 = ECATnear.iloc[altInd]*w0
            tmp1 = ECATnear.iloc[altInd2]*w1
            # tmp0.name = 'w0'
            # tmp1.name = 'w1'

            doze = pd.DataFrame(columns=ECATnear.columns)
            doze.loc['w0', ECATnear.columns] = tmp0
            doze.loc['w1', ECATnear.columns] = tmp1

            neE, teE, voE, dneE, dteE, dvoE, altE = doze.sum(
            )[['ne', 'te', 'vo', 'dne', 'dte', 'dvo', 'gdalt']].values

    elif doWgtMean:

        print("HELT NYE MÅTE MED WGT AVERAGING")

        ECATnear = dfEISCAT.loc[dfEISCAT.index.drop_duplicates()[dfEISCAT.index.drop_duplicates().get_loc(
            conjTime,
            method='nearest')], :]

        if convert_vo_to_voUp:
            # ECATnear.loc[:, ['vo', 'dvo']] = ECATnear.loc[:, ['vo', 'dvo']
            #                                               ] * np.sin(np.deg2rad(ECATnear.loc[:, 'elm']))
            # ECATnear.loc[:, ['vo', 'dvo']] = ECATnear[['vo', 'dvo']
            #                                           ] * np.sin(np.deg2rad(ECATnear['elm'].values))
            ECATnear.loc[:, 'vo'] = ECATnear['vo'] * \
                np.sin(np.deg2rad(ECATnear['elm'].values))
            ECATnear.loc[:, 'dvo'] = ECATnear['dvo'] * \
                np.sin(np.deg2rad(ECATnear['elm'].values))

        dAlts = ECATnear.iloc[1:]['gdalt'].values - \
            ECATnear.iloc[:-1]['gdalt'].values
        dAlts = np.insert(dAlts, dAlts.size, dAlts[-1])
        ECATnear['gdaltmid'] = ECATnear['gdalt'] + dAlts/2.

        altInd = np.argmin(np.abs(ECATnear['gdaltmid'].values-wantAlt))
        altInd2 = ((ECATnear.iloc[altInd]['gdaltmid']-wantAlt) < 0)*2-1+altInd

        try:
            if altInd2 == ECATnear.shape[0]:
                print("Dude")
        except:
            breakpoint()

        if altInd2 == ECATnear.shape[0]:
            altInd2 -= 1
            neE, teE, voE, dneE, dteE, dvoE, altE = ECATnear.iloc[altInd][[
                'ne', 'te', 'vo', 'dne', 'dte', 'dvo', 'gdalt']].values

        else:

            if ECATnear.iloc[altInd2]['gdaltmid'] < ECATnear.iloc[altInd]['gdaltmid']:
                tmpaltind = copy.deepcopy(altInd2)
                altInd2 = altInd
                altInd = tmpaltind

            dAlt = ECATnear.iloc[altInd2]['gdaltmid'] - \
                ECATnear.iloc[altInd]['gdaltmid']
            w1 = np.abs(ECATnear.iloc[altInd]['gdaltmid']-wantAlt)/dAlt
            w0 = np.abs(ECATnear.iloc[altInd2]['gdaltmid']-wantAlt)/dAlt

            print(conjTime, wantAlt, " alt0, w0, vo0:",
                  ECATnear.iloc[altInd]['gdaltmid'], w0,
                  ECATnear.iloc[altInd]['vo'])
            print(conjTime, wantAlt, " alt1, w1, vo1:",
                  ECATnear.iloc[altInd2]['gdaltmid'], w1,
                  ECATnear.iloc[altInd2]['vo'])

            col = 'vo'
            uncCol = 'dvo'
            voE, dvoE = weightMeanFunc(ECATnear, altInd, altInd2,
                                       col, uncCol,
                                       w0, w1)

            col = 'te'
            uncCol = 'dte'
            teE, dteE = weightMeanFunc(ECATnear, altInd, altInd2,
                                       col, uncCol,
                                       w0, w1)

            col = 'ne'
            uncCol = 'dne'
            neE, dneE = weightMeanFunc(ECATnear, altInd, altInd2,
                                       col, uncCol,
                                       w0, w1)

            altE = (ECATnear.iloc[altInd]['gdaltmid']*w0 /
                    ECATnear.iloc[altInd2]['gdaltmid']*w1)/2.

    return neE, teE, voE, dneE, dteE, dvoE, altE

def layout3plot(lp, ctdf, mag, EISdf, latitude, longitude, conjTime,
                boundinglat=60,
                fig=None,
                axes0=None,
                EISCATaxes=None,
                mapAxes=None,
                maps=None,
                vizlimdict=None,
                conjInfoDict=None,
                plottdelt=timedelta(minutes=2),
                figtitle='',
                canvtitle='',
                Anjaway=True,
                ECATavg__gamlemaate=False,
                ECATavg__nyemaate=False,
                ECATavg__doWgtMean=False,
                convert_vo_to_voUp=False):

    ECATpunktcolor = 'black'

    apexRefHeight_km = 110

    use12MLTAslon_0 = True

    projection = 'cyl'
    projection = 'nsper'
    projection = 'npstere'

    resolution = 'i'

    if projection == 'npstere':
        resolution = 'l'

    doApexGridLines = True

    if conjInfoDict is None:
        conjInfoDict = get_conjugate_stuff(lp, ctdf, EISdf, conjTime,
                                           Anjaway=Anjaway,
                                           ECATavg__gamlemaate=ECATavg__gamlemaate,
                                           ECATavg__nyemaate=ECATavg__nyemaate,
                                           ECATavg__doWgtMean=ECATavg__doWgtMean,
                                           convert_vo_to_voUp=convert_vo_to_voUp)

    neE, teE, voE, dneE, dteE, dvoE, ECATT = (conjInfoDict[ting] for ting in [
        'ECATNe', 'ECATTe', 'ECATvo', 'ECATdNe', 'ECATdTe', 'ECATdvo', 'ECATT'])

    ########################################
    # Lek med layout3
    laptop = False
    swarmgdlat, swarmalt = geoclatR2geodlatheight(
        lp['Latitude'].values, lp['Radius'].values/1000.)

    if fig is None:
        if laptop:
            figsize = (14, 8)
        else:
            figsize = (17, 11)

        fig = plt.figure(figsize=figsize)

    if canvtitle != '':
        yunk = fig.canvas.set_window_title(canvtitle)

    if figtitle != '':
        yunk = fig.suptitle(figtitle)

    makeFigAndAxes = (axes0 is None) or (EISCATaxes is None)
    if makeFigAndAxes:

        gs1 = GridSpec(3, 1, left=0.07, right=0.47, bottom=0.05, top=0.49)
        ax00 = fig.add_subplot(gs1[0])
        ax10 = fig.add_subplot(gs1[1], sharex=ax00)
        ax20 = fig.add_subplot(gs1[2], sharex=ax00)
        # ax30 = fig.add_subplot(gs1[3],sharex=ax00)
        # ax40 = fig.add_subplot(gs1[4],sharex=ax00)

        gs2 = GridSpec(2, 1, left=0.07, right=0.44, bottom=0.54, top=0.98)
        ax30 = fig.add_subplot(gs2[0], sharex=ax00)
        ax40 = fig.add_subplot(gs2[1], sharex=ax00)

        axes0 = [ax00, ax10, ax20, ax30, ax40]

        for ax in axes0:
            ax.grid()

        gs2 = GridSpec(3, 1, left=0.53, right=0.98,
                       hspace=0.2, bottom=0.05, top=0.49)
        ax01 = fig.add_subplot(gs2[0], sharex=ax00)
        ax11 = fig.add_subplot(gs2[1], sharex=ax00)
        ax21 = fig.add_subplot(gs2[2], sharex=ax00)

        # The two maps
        gsmap1 = GridSpec(1, 1, left=0.66, right=1.04,
                          hspace=0.2, bottom=0.51, top=0.98)
        gsmap2 = GridSpec(1, 1, left=0.42, right=0.76,
                          hspace=0.2, bottom=0.51, top=0.98)

        axmap1 = fig.add_subplot(gsmap1[:])
        axmap2 = fig.add_subplot(gsmap2[:])

        mapAxes = [axmap1, axmap2]

        EISCATaxes = [ax01, ax11, ax21]

    else:
        axmap1 = mapAxes[0]
        axmap2 = mapAxes[1]

        ax00, ax10, ax20, ax30, ax40 = axes0

        ax01, ax11, ax21 = EISCATaxes

        # Wipe axes først?

    # Hide labels
    junk = plt.setp(ax00.get_xticklabels(), visible=False)
    junk = plt.setp(ax10.get_xticklabels(), visible=False)
    # junk = plt.setp(ax20.get_xticklabels(), visible=False)
    junk = plt.setp(ax30.get_xticklabels(), visible=False)
    # plt.setp(ax40.get_xticklabels(), visible=False)

    kunk = plt.setp(ax01.get_xticklabels(), visible=False)
    kunk = plt.setp(ax11.get_xticklabels(), visible=False)
    # plt.setp(ax21.get_xticklabels(), visible=False)

    lat_0 = latitude
    lon_0 = longitude

    if use12MLTAslon_0:
        a = Apex(conjTime, refh=apexRefHeight_km)

        # Use noon
        mlonFor12MLT = a.mlt2mlon(12.0, conjTime)
        glatFor12MLT, glonFor12MLT, errorFor12MLT = a.apex2geo(np.array([boundinglat]),
                                                               np.array(
            [mlonFor12MLT]),
            apexRefHeight_km)
        glonFor12MLT += 180

        # Use midnight
        # mlonFor12MLT = a.mlt2mlon(0.0,conjTime)
        # glatFor12MLT,glonFor12MLT, errorFor12MLT = a.apex2geo(np.array([80]),
        #                                                       np.array([mlonFor12MLT]),
        #                                                       apexRefHeight_km)

        lon_0 = glonFor12MLT

    if projection == 'nsper':
        satellite_height = 100*1000
        m = Basemap(projection='nsper',
                    lon_0=lon_0, lat_0=lat_0,
                    satellite_height=satellite_height,
                    resolution=resolution, ax=axmap1)
    elif projection == 'cyl':

        m = Basemap(projection=projection,
                    # lon_0=lon_0,lat_0=lat_0,
                    satellite_height=satellite_height,
                    resolution=resolution, ax=axmap1)

    elif projection == 'npstere':
        m = Basemap(projection='npstere', boundinglat=boundinglat,
                    lon_0=lon_0,
                    resolution=resolution,
                    ax=axmap1,
                    round=True)

        # yunk = m.drawparallels(np.arange(-80.,81.,10.))
        # yunk = m.drawmeridians(np.arange(-180.,181.,30.))

    junk = m.drawcoastlines()
    # junk = m.drawcountries()

    # map2
    m2 = Basemap(projection='npstere', boundinglat=boundinglat,
                 lon_0=0,            # Puts midnight at 6 0'clock
                 resolution=resolution,
                 ax=axmap2,
                 round=True)

    yunk = m2.drawparallels(np.arange(-80., 81., 10.))
    yunk = m2.drawmeridians(np.arange(-180., 181., 45.))

    if doApexGridLines:

        a = Apex(conjTime, refh=apexRefHeight_km)

        mlonsForGrid = np.arange(-180., 181., 10.)
        mlatsForGrid = np.arange(boundinglat, 86., 10.)

        mlatGridLines = []
        for mlfg in mlatsForGrid:
            glatgrid, glongrid, gerrorgrid = a.apex2geo(np.array([mlfg]*len(mlonsForGrid)),
                                                        mlonsForGrid,
                                                        apexRefHeight_km)
            gridline = m.plot(glongrid,
                              glatgrid,
                              latlon=True,
                              linestyle='-',
                              color='black')

            mlatGridLines.append(gridline)

        # Longitude lines
        # mlonsForGrid = np.arange(-180.,181.,30.)+lon_0
        mltsForGrid = np.arange(0, 24, 3)
        mlatsForGrid = np.arange(boundinglat-10, 81., 2.5)

        mlonsForGrid = []
        for mlt in mltsForGrid:
            mlonsForGrid.append(a.mlt2mlon(mlt, conjTime))

        mlonGridLines = []
        for mlfg in mlonsForGrid:
            glatgrid, glongrid, gerrorgrid = a.apex2geo(mlatsForGrid,
                                                        np.array(
                                                            [mlfg]*len(mlatsForGrid)),
                                                        apexRefHeight_km)
            gridline = m.plot(glongrid,
                              glatgrid,
                              latlon=True,
                              linestyle=':',
                              linewidth=2,
                              color='gray')

            mlonGridLines.append(gridline)
            # break

    EISplotcols = ['ne', 'te', 'vo']
    EISplot = EISdf.copy()
    if convert_vo_to_voUp:
        EISplotlabels = [r'$N_e$ (cm$^{-3}$)', r'T$_e$ (K)', r'vUp (m/s)']
        # EISplot.loc[:, ['vo', 'dvo']] = EISplot.loc[:, ['vo', 'dvo']
        #                                             ] * np.sin(np.deg2rad(EISplot.loc[:, 'elm']))

        # EISplot.loc[:, ['vo', 'dvo']] = EISplot[['vo', 'dvo']] * \
        #     np.sin(np.deg2rad(EISplot['elm'].values))
        EISplot.loc[:, 'vo'] = EISplot['vo'] * \
            np.sin(np.deg2rad(EISplot['elm'].values))
        EISplot.loc[:, 'dvo'] = EISplot['dvo'] * \
            np.sin(np.deg2rad(EISplot['elm'].values))

    else:
        EISplotlabels = [r'$N_e$ (cm$^{-3}$)', r'T$_e$ (K)', r'vo (m/s)']

    EISCATfings = EISCAT_plot_from_pickle(EISplot,
                                          dolog10=True,
                                          fig=fig,
                                          axes=EISCATaxes,
                                          plotcols=EISplotcols,
                                          plotlabels=EISplotlabels,
                                          plotzlims=[[1e10, 1e12], [
                                              0, 4000], [-400, 400]],
                                          plotcanlog=[True, False, False],
                                          ylims_centered_on_Swarm=True,
                                          swarmAlt=conjInfoDict['swarmAlt'],
                                          plottdelt=plottdelt,
                                          conjInfoDict=conjInfoDict)

    for ax in EISCATaxes:
        junk = ax.plot(lp.index.values,
                       swarmalt,
                       color='gray',
                       linewidth=3,
                       alpha=0.8)

    # Get groundlat,groundlon
    tmpgdlat, tmpalt = geoclatR2geodlatheight(
        ctdf['latitude'].values, ctdf['radius'].values/1000.)
    tmpalat, tmpalon = a.geo2apex(tmpgdlat, ctdf['longitude'].values, tmpalt)
    groundglat, groundglon, grounderror = a.apex2geo(
        tmpalat, tmpalon, np.array([apexRefHeight_km]*len(tmpalon)))

    # Get nærmeste lat,lon
    nearest = ctdf.index.get_loc(conjTime, method='Nearest')
    tNearest = ctdf.iloc[nearest].name
    nearlat, nearlon = ctdf.loc[tNearest, ['latitude', 'longitude']].values
    nearqdlat, nearqdmlt = ctdf.loc[tNearest, ['qdlat', 'mlt']].values
    nearqdmlt *= 15.

    # Get station MLT
    stationmlat, stationmlon = a.geo2apex(latitude, longitude, 0)
    stationmlt = a.mlon2mlt(stationmlon, conjTime)

    # swarmTrackPlot = m.plot(lp[lp['Latitude'] > boundinglat]['Longitude'].values,
    #                         lp[lp['Latitude'] > boundinglat]['Latitude'].values,
    swarmTrackPlot = m.plot(groundglon[groundglat > boundinglat],
                            groundglat[groundglat > boundinglat],
                            latlon=True,
                            linestyle='--',
                            color='gray')
    dotplot = m.plot(np.array([longitude-0.001, longitude+0.001]),
                     np.array([latitude-0.001, latitude+0.001]),
                     latlon=True,
                     linestyle='',
                     color='blue',
                     markersize=7,
                     marker='o')
    nearplot = m.plot(np.array([nearlon-0.001, nearlon+0.001]),
                      np.array([nearlat-0.001, nearlat+0.001]),
                      latlon=True,
                      linestyle='',
                      color='green',
                      marker='+',
                      markersize=9)

    swarmTrackPlot2 = m2.plot(ctdf[ctdf['qdlat'] >= boundinglat]['mlt'].values*15.,
                              ctdf[ctdf['qdlat'] >= boundinglat]['qdlat'].values,
                              latlon=True,
                              linestyle='--',
                              color='gray')

    dotplot2 = m2.plot(np.array([stationmlt*15.-0.001, stationmlt*15.+0.001]),
                       np.array([stationmlat-0.001, stationmlat+0.001]),
                       latlon=True,
                       linestyle='',
                       color='blue',
                       markersize=7,
                       marker='o')

    nearplot2 = m2.plot(np.array([nearqdmlt-0.001, nearqdmlt+0.001]),
                        np.array([nearqdlat-0.001, nearqdlat+0.001]),
                        latlon=True,
                        linestyle='',
                        color='green',
                        marker='+',
                        markersize=9)

    nelabs = ['Ne']  # ,'Ne_error']
    nenames = ['Ne']  # ,'Error']

    if conjInfoDict is not None:
        nenames[0] = nenames[0] + "={:.3g}".format(conjInfoDict['swarmNe'])
    for i, lab in enumerate(nelabs):
        # yonk = axes0[0].plot(np.log10(lp[lab]*1e6),label=nenames[i])
        yonk = axes0[0].plot(lp[lab]*1e6, label=nenames[i])
    yunk = axes0[0].set_ylabel('Ne')
    # yunk = axes0[0].set_ylim((10,12))
    yunk = axes0[0].set_ylim((1e9, 1e12))
    yunk = axes0[0].set_yscale('log')

    telabs = ['Te']  # ,'Te_error']
    tenames = ['Te']  # ,'Error']
    if conjInfoDict is not None:
        tenames[0] = tenames[0] + "={:.3g}".format(conjInfoDict['swarmTe'])
    for i, lab in enumerate(telabs):
        yonk = axes0[1].plot(lp[lab], label=tenames[i])
    yunk = axes0[1].set_ylabel('Te')
    yunk = axes0[1].set_ylim((0, 10000))

    # flowlabs = ['viy','viz']
    # flownames = ['viy','viz (flip!)']
    flowlabs = ['viz']
    flownames = ['viz (flip!)']
    if conjInfoDict is not None:
        flownames[0] = flownames[0] + \
            "={:.3g}".format(conjInfoDict['swarmviz'])
    for i, lab in enumerate(flowlabs):
        factor = 1 if (i == 0) else -1
        yonk = axes0[2].plot(ctdf[lab]*factor, label=flownames[i])
        bkupylim = (ctdf[(conjTime-plottdelt):(conjTime+plottdelt)]
                    [lab]*factor).dropna().describe()[['min', 'max']]
    try:
        if conjTime in vizlimdict.keys():
            yunk = axes0[2].set_ylim(vizlimdict[conjTime])
        else:
            yunk = axes0[2].set_ylim(*bkupylim)

    except:
        # print("DODATDATDAT")
        yunk = axes0[2].set_ylim(*bkupylim)
        print("")

    if mag.size > 0:
        maglabs = ['dBe1', 'dBe2']
        magnames = ['E-W', 'N-S']
        for i, lab in enumerate(maglabs):
            yonk = axes0[3].plot(mag[lab], label=magnames[i])
        leg00 = axes0[3].legend()

    ephemlabs = ['qdlat', 'mlt']
    ephemnames = ['qdlat', 'mlt']
    # for i,lab in enumerate(ephemlabs):
    yonk = axes0[4].plot(ctdf[ephemlabs[0]],
                         label=ephemnames[0],
                         color='C0')
    junk = axes0[4].set_ylabel(ephemlabs[0])

    ax40a = axes0[4].twinx()
    junk = ax40a.plot(ctdf[ephemlabs[1]],
                      label=ephemnames[1],
                      color='C1')

    junk = ax40a.set_ylabel(ephemlabs[1])
    # leg01 = axes0[2].legend()
    for ax in axes0+EISCATaxes:
        yunk = ax.axvline(conjTime, color='red', linewidth=3, alpha=0.5)
    plt.tight_layout()

    yonk0 = axes0[0].errorbar(ECATT, neE, yerr=dneE, marker='x',
                              color=ECATpunktcolor, label='N={:.3g} (EISCAT)'.format(neE))
    yonk1 = axes0[1].errorbar(ECATT, teE, yerr=dteE, marker='x',
                              color=ECATpunktcolor, label='T={:.3g} (EISCAT)'.format(teE))
    yonk2 = axes0[2].errorbar(ECATT, voE, yerr=dvoE, marker='x',
                              color=ECATpunktcolor, label='vo={:.3g} (EISCAT)'.format(voE))
    leg00 = axes0[0].legend()
    leg01 = axes0[1].legend()
    leg02 = axes0[2].legend()

    myFmt = DateFormatter("%H:%M:%S")
    axes0[0].xaxis.set_major_formatter(myFmt)
    plt.tight_layout()

    junk = axes0[0].set_xlim((conjTime-plottdelt, conjTime+plottdelt))

    for hideax in [ax20, ax40, ax21]:
        for label in hideax.xaxis.get_ticklabels()[::2]:
            label.set_visible(False)

    maps = [m, m2]

    return fig, axes0, EISCATaxes, mapAxes, maps

def EISCAT_plot_from_pickle(pickleFile,
                            dolog10=True,
                            fig=None,
                            axes=None,
                            plotcols=['ne', 'te', 'vo'],
                            plotlabels=[
                                r'Dens (cm$^{-3}$)', r'T$_e$ (K)', r'vo (m/s)'],
                            plotzlims=[[1e10, 1e12], [0, 4000], [-400, 400]],
                            plotz_scalewithdata=True,
                            plotz_swd__clips=[[1e9, 1e13],
                                              [0, 10000], [-2000, 2000]],
                            plotcanlog=[True, False, False],
                            cmap=hCM.parula,
                            ylims=[300, 800],
                            ylims_centered_on_Swarm=True,
                            swarmAlt=None,
                            plottdelt=timedelta(minutes=2),
                            conjInfoDict=None):

    if isinstance(pickleFile, str):
        df = pd.read_pickle(pickleFile)
    elif isinstance(pickleFile, pd.core.frame.DataFrame):
        df = pickleFile

    if ylims_centered_on_Swarm:
        if swarmAlt is None:
            ylims_centered_on_Swarm = False
        else:
            ylims_Swarmcentred = [swarmAlt-150, swarmAlt+150]

    odds = np.int64(np.arange(df.recno.max()/2)*2+1)
    df = df[~df.recno.isin(odds)]   # Drop all odd recnos
    grp = df.groupby('recno')

    # assert 2 < 0, "Need to figure out how to shift the EISCAT plots such that the provided timestamp is at the END of the interval"
    tdelts = np.diff(df.index.drop_duplicates(),
                     append=pd.DatetimeIndex([
                         df.index.drop_duplicates()[-1] +
                         (df.index.drop_duplicates()[-1] -
                             df.index.drop_duplicates()[-2])]))
    # dtSec = np.median(np.diff(df.index.drop_duplicates()) /
    #                   pd.Timedelta(seconds=1))
    tdelts = pd.TimedeltaIndex(tdelts, unit='s')
    # tdelts = pd.TimedeltaIndex([timedelta(seconds=dtSec) for dtSec in tdelts])

    if (fig is None) or (axes is None):
        fig, axes = plt.subplots(len(plotcols), 1,
                                 figsize=(15, 10),
                                 sharex=True,
                                 sharey=True)

    for iAx, ax in enumerate(axes):
        ax.grid()
        junk = ax.set_ylabel("Alt (km)")

    fig.subplots_adjust(left=0.06, bottom=0.06,
                        right=0.99, top=0.94, wspace=0.03)

    # Get plot lims
    plotzmins = np.zeros(len(plotcols))
    plotzmaxs = np.zeros(len(plotcols))
    plotz_swdc = plotz_swd__clips.copy()

    if conjInfoDict is not None:
        conjTime = num2date(conjInfoDict['ECATT']).replace(tzinfo=None)
        considerInds = (df.index >= (conjTime-plottdelt)) & \
            (df.index <= (conjTime+plottdelt*3/2)) & \
            (df['gdalt'] >= ylims_Swarmcentred[0]+50) & \
            (df['gdalt'] <= ylims_Swarmcentred[1]-50)

    else:
        considerInds = df.index > pd.Timestamp(1)  # corresponds to Jan 1, 1970

    for i in range(len(plotcols)):

        if plotz_scalewithdata:

            # If have conjugate info, base scaling on data in neighborhood
            # if conjInfoDict is not None:
            # else:
            freshprince = np.clip(df[considerInds][plotcols[i]].values,
                                  *plotz_swdc[i])

            freshprince = freshprince[np.isfinite(freshprince)]
            plotzmins[i], plotzmaxs[i] = np.min(
                freshprince), np.max(freshprince)
            # plotzmins[i] = plotz_swdc[i][0]
            # plotzmaxs[i] = plotz_swdc[i][1]
        else:
            plotzmins[i] = plotzlims[i][0]
            plotzmaxs[i] = plotzlims[i][1]

    if dolog10:
        for i in range(len(plotcols)):
            if plotcanlog[i]:
                print("Logging {:s} zlims ...".format(plotcols[i]))
                plotzlims[i][0] = np.log10(plotzlims[i][0])
                plotzlims[i][1] = np.log10(plotzlims[i][1])
                # plotz_swdc[i][0] = np.log10(plotz_swdc[i][0])
                # plotz_swdc[i][1] = np.log10(plotz_swdc[i][1])
                plotzmins[i] = np.log10(plotzmins[i])
                plotzmaxs[i] = np.log10(plotzmaxs[i])

    gotFirst = False
    cbList = []
    for tdelt, (name, grpie) in zip(tdelts, grp):

        ########################################
        # Make the bins, should have one dimension larger than data
        # we plot because that's what pcolormesh wants

        # Altitude bins: Original way, assumes EISCAT records give the BOTTOM
        # of the bin (which is false!)
        # tmphalfaltbins = grpie.gdalt.diff()/2.
        # tmphalfaltbins.iloc[0] = tmphalfaltbins.iloc[1]
        # tmphalfmin = tmphalfaltbins.iloc[0]*(-1.)

        # tmphalfaltbins += grpie.gdalt.values
        # tmphalfaltbins = np.insert(
        #     tmphalfaltbins.values, 0, tmphalfaltbins.values[0]+tmphalfmin)

        # Altitude bins: New way, assumes EISCAT records give the MIDDLE
        # of the bin (which is true!)
        tmpdalt = grpie.gdalt.diff()/2.
        tmpdalt.iloc[0] = tmpdalt.iloc[1]

        # For referanse
        # altbinbottoms = grpie.gdalt+tmpdalt
        # altbintops = grpie.gdalt-tmpdalt

        altbinedges = grpie.gdalt-tmpdalt
        altbinedges = np.append(
            altbinedges.values, altbinedges.values[-1]+tmpdalt[-1])

        # Time bins: ORIGINAL WAY, PRE-20191112
        # tmptids = grpie.index[0]-tdelt, grpie.index[0] + \
        #     tdelt, grpie.index[0]+tdelt*2

        # Time bins: NEW WAY, AS OF 20191112/DISCUSSION WITH ANJA STRØMME
        tmptids = grpie.index[0]-tdelt, grpie.index[0], grpie.index[0]+tdelt

        AA, TT = np.meshgrid(tmptids, altbinedges)

        # Now the axes
        for i, ax in enumerate(axes):

            yunk = np.array([grpie[plotcols[i]].values,
                             grpie[plotcols[i]].values]).T

            if dolog10:
                if plotcanlog[i]:
                    yunk = np.log10(yunk)

            yunk[:, 1] = np.nan

            junk = ax.pcolormesh(AA, TT, yunk,
                                 vmin=plotzmins[i],
                                 vmax=plotzmaxs[i],
                                 cmap=cmap)

            if not gotFirst:
                cbList.append(fig.colorbar(junk, ax=ax))
                yock = cbList[-1].ax.set_ylabel(plotlabels[i])

        if not gotFirst:        # Går her fordi du trenger "not gotFirst" for alle tre plott
            gotFirst = True

    if ylims is not None:
        if ylims_centered_on_Swarm:
            for ax in axes:
                junk = ax.set_ylim(ylims_Swarmcentred)
        else:
            for ax in axes:
                junk = ax.set_ylim(ylims)

    return fig, axes, cbList

def get_conjugate_stuff(lp, ctdf, EISdf, conjTime,
                        originalway=False,
                        Anjaway=True,
                        ECATavg__gamlemaate=False,
                        ECATavg__nyemaate=False,
                        ECATavg__doWgtMean=True,
                        convert_vo_to_voUp=False):

    # NEST
    lab = ['Ne', 'Te', 'Ne_error', 'Te_error']
    nearAlt, NeNear, TeNear, Ne_errornear, Te_errornear = get_swarm_conjAlt_and_data(lp, lab, conjTime,
                                                                                latcol='Latitude',
                                                                                loncol='Longitude',
                                                                                radcol='Radius')
    lab = ['viy', 'viz']
    nearAlt, viyNear, vizNear = get_swarm_conjAlt_and_data(ctdf, lab, conjTime,
                                                           latcol='latitude',
                                                           loncol='longitude',
                                                           radcol='radius')

    # Nærmeste ECAT datapunkter
    if originalway:

        print("Can fix up np.diff usage slik at you don't use np.insert; also, Anja sier at tidspunkter med EISCAT svarer faktisk til ENDEN av integrasjonstid!")
        breakpoint()
        tids = EISdf.index.drop_duplicates()
        tdiff = np.diff(tids)
        tdiff = np.insert(tdiff, 0, tdiff[0])

        tids2 = tids+tdiff/2

        nearInd = np.argmin(np.abs(tids-conjTime))

        ECATnear = EISdf.loc[pd.DatetimeIndex([tids[nearInd]]), :]

        if convert_vo_to_voUp:
            ECATnear.loc[:, 'vo'] = ECATnear['vo'] * \
                np.sin(np.deg2rad(ECATnear['elm'].values))
            ECATnear.loc[:, 'dvo'] = ECATnear['dvo'] * \
                np.sin(np.deg2rad(ECATnear['elm'].values))

        neE, teE, voE, dneE, dteE, dvoE = ECATnear.iloc[np.argmin(np.abs(
            ECATnear['gdalt'].values-nearAlt))][['ne', 'te', 'vo', 'dne', 'dte', 'dvo']].values
        ECATT = date2num(conjTime)

        # assert not convert_vo_to_voUp, "Not set up for this!"

        return dict(swarmAlt=nearAlt,
                    swarmNe=NeNear*1e6,
                    swarmTe=TeNear,
                    swarmNe_error=Ne_errornear*1e6,
                    swarmTe_error=Te_errornear,
                    swarmviy=viyNear,
                    swarmviz=vizNear,
                    ECATT=ECATT,
                    ECATNe=neE,
                    ECATTe=teE,
                    ECATvo=voE,
                    ECATdNe=dneE,
                    ECATdTe=dteE,
                    ECATdvo=dvoE,
                    ECATnear=ECATnear)

    elif Anjaway:

        print("The Anja way: EISCAT times are at end of integration window, altitude bins give altitude of CENTER of altitude/range bin ")
        # END OF THE INTEGRATION WINDOW, NOT BEGINNING LIKE I ORIGINALLY THOUGHT
        tids = EISdf.index.drop_duplicates()
        tidsMinusConjTime = (tids-conjTime)/pd.Timedelta('1s')

        pickind_ii = np.argmin(tidsMinusConjTime[tidsMinusConjTime > 0])
        nearInd = np.where(tidsMinusConjTime > 0)[0][pickind_ii]

        ECATnear = EISdf.loc[pd.DatetimeIndex([tids[nearInd]]), :]

        if convert_vo_to_voUp:
            ECATnear.loc[:, 'vo'] = ECATnear['vo'] * \
                np.sin(np.deg2rad(ECATnear['elm'].values))
            ECATnear.loc[:, 'dvo'] = ECATnear['dvo'] * \
                np.sin(np.deg2rad(ECATnear['elm'].values))

        neE, teE, voE, dneE, dteE, dvoE = ECATnear.iloc[np.argmin(np.abs(
            ECATnear['gdalt'].values-nearAlt))][['ne', 'te', 'vo', 'dne', 'dte', 'dvo']].values
        ECATT = date2num(conjTime)

        # assert not convert_vo_to_voUp, "Not set up for this!"

        return dict(swarmAlt=nearAlt,
                    swarmNe=NeNear*1e6,
                    swarmTe=TeNear,
                    swarmNe_error=Ne_errornear*1e6,
                    swarmTe_error=Te_errornear,
                    swarmviy=viyNear,
                    swarmviz=vizNear,
                    ECATT=ECATT,
                    ECATNe=neE,
                    ECATTe=teE,
                    ECATvo=voE,
                    ECATdNe=dneE,
                    ECATdTe=dteE,
                    ECATdvo=dvoE,
                    ECATnear=ECATnear)

    else:
        #
        matchInd = EISdf.index.drop_duplicates().get_loc(conjTime, method='nearest')
        if matchInd == 0:
            aftdt = EISdf.index.drop_duplicates(
            )[matchInd+1]-EISdf.index.drop_duplicates()[matchInd]
            befdt = EISdf.index.drop_duplicates(
            )[matchInd+1]-EISdf.index.drop_duplicates()[matchInd]
        elif matchInd == EISdf.index.drop_duplicates().size-1:
            aftdt = EISdf.index.drop_duplicates(
            )[matchInd]-EISdf.index.drop_duplicates()[matchInd-1]
            befdt = EISdf.index.drop_duplicates(
            )[matchInd]-EISdf.index.drop_duplicates()[matchInd-1]
        else:
            aftdt = EISdf.index.drop_duplicates(
            )[matchInd+1]-EISdf.index.drop_duplicates()[matchInd]
            befdt = EISdf.index.drop_duplicates(
            )[matchInd]-EISdf.index.drop_duplicates()[matchInd-1]
        candidateT = EISdf.index.drop_duplicates()[matchInd]

        print(matchInd)
        candidatos = np.array([candidateT-befdt/2, candidateT+aftdt/2])
        candidatoInd = np.argmin(
            np.abs([candidatos[0]-conjTime, candidatos[1]-conjTime]))
        candidateT = candidatos[candidatoInd]
        if candidatoInd == 0:
            matchInd -= 1

        print(matchInd)

        if (candidateT == conjTime) or (candidateT > conjTime):
            # candidateT represents a start time for integration, so if times match, grab the one before
            befInd = np.max([matchInd - 1, 0])
            aftInd = matchInd
        elif candidateT < conjTime:
            # candidateT represents a start time for integration, so if it's < conjTime, grab the one after
            befInd = matchInd
            aftInd = np.min(
                [matchInd + 1, EISdf.index.drop_duplicates().size-1])

        if befInd != aftInd:
            befTime = EISdf.index.drop_duplicates()[befInd]
            aftTime = EISdf.index.drop_duplicates()[aftInd]

            neE0, teE0, voE0, dneE0, dteE0, dvoE0, altE0 = get_EISCAT_vals_at_time_and_alt(
                EISdf, befTime, nearAlt,
                gamlemaate=ECATavg__gamlemaate,
                nyemaate=ECATavg__nyemaate,
                doWgtMean=ECATavg__doWgtMean,
                convert_vo_to_voUp=convert_vo_to_voUp)
            neE1, teE1, voE1, dneE1, dteE1, dvoE1, altE1 = get_EISCAT_vals_at_time_and_alt(
                EISdf, aftTime, nearAlt,
                gamlemaate=ECATavg__gamlemaate,
                nyemaate=ECATavg__nyemaate,
                doWgtMean=ECATavg__doWgtMean,
                convert_vo_to_voUp=convert_vo_to_voUp)

            ECATT = date2num(conjTime)

            print(befTime, aftTime)
            dTime = aftTime-befTime
            # NB: w0 svarer til aftTime, w1 til befTime pga at vi bruker nearest neighbors!
            w0 = ((aftTime+dTime/2)-conjTime).total_seconds() / \
                dTime.total_seconds()
            w1 = (conjTime-(befTime+dTime/2)).total_seconds() / \
                dTime.total_seconds()

            print("w0,w1:", w0, w1)
            if np.abs(1-np.abs(w0+w1)) > 0.01:
                print("landegoshen2!")
                assert 2 < 0, ""

            if (w0 < 0) or (w1 < 0):
                print("landegoshen!")
                assert 2 < 0, ""

            neE = finiteCombine(neE0, neE1, w0, w1)
            teE = finiteCombine(teE0, teE1, w0, w1)
            voE = finiteCombine(voE0, voE1, w0, w1)
            dneE = finiteCombine(dneE0, dneE1, w0, w1,
                                 isUncertainty=True)
            dteE = finiteCombine(dteE0, dteE1, w0, w1,
                                 isUncertainty=True)
            dvoE = finiteCombine(dvoE0, dvoE1, w0, w1,
                                 isUncertainty=True)

            # if np.isfinite(neE0) and np.isfinite(neE1):
            #     neE = neE0*w0+neE1*w1
            # elif np.isfinite(neE0):
            #     neE = neE0
            # elif np.isfinite(neE1):
            #     neE = neE1
            # else:
            #     neE = np.nan

            # teE = teE0*w0+teE1*w1
            # voE = voE0*w0+voE1*w1
            # dneE = dneE0*w0+dneE1*w1
            # dteE = dteE0*w0+dteE1*w1
            # dvoE = dvoE0*w0+dvoE1*w1

            # neE,teE,voE,dneE,dteE,dvoE
        else:
            befTime = EISdf.index.drop_duplicates()[befInd]
            neE, teE, voE, dneE, dteE, dvoE, altE = get_EISCAT_vals_at_time_and_alt(
                EISdf, befTime, nearAlt,
                gamlemaate=ECATavg__gamlemaate,
                nyemaate=ECATavg__nyemaate,
                doWgtMean=ECATavg__doWgtMean,
                convert_vo_to_voUp=convert_vo_to_voUp)
            ECATT = date2num(conjTime)

            print(befTime)

        # return dict(swarm=dict(nearAlt=nearAlt,
        #                        Ne=NeNear,
        #                        Te=TeNear,
        #                        Ne_error=Ne_errornear,
        #                        Te_error=Te_errornear),
        #             ECAT=dict(ECATT=ECATT,
        #                       Ne=neE,
        #                       Te=TeE,
        #                       vo=voE,
        #                       dNe=dneE,
        #                       dTe=dteE,
        #                       dvo=dvoE))

        return dict(swarmAlt=nearAlt,
                    swarmNe=NeNear*1e6,
                    swarmTe=TeNear,
                    swarmNe_error=Ne_errornear*1e6,
                    swarmTe_error=Te_errornear,
                    swarmviy=viyNear,
                    swarmviz=vizNear,
                    ECATT=ECATT,
                    ECATNe=neE,
                    ECATTe=teE,
                    ECATvo=voE,
                    ECATdNe=dneE,
                    ECATdTe=dteE,
                    ECATdvo=dvoE,
                    ECATnear="Gjelder bare originalway and Anjaway")

def finiteCombine(q0, q1, w0, w1,
                  isUncertainty=False):

    if isUncertainty:
        if np.isfinite(q0) and np.isfinite(q1):
            q = np.sqrt(q0**2.*w0+q1**2.*w1)
        elif np.isfinite(q0):
            q = q0
        elif np.isfinite(q1):
            q = q1
        else:
            q = np.nan
    else:
        if np.isfinite(q0) and np.isfinite(q1):
            q = q0*w0+q1*w1
        elif np.isfinite(q0):
            q = q0
        elif np.isfinite(q1):
            q = q1
        else:
            q = np.nan
    return q

def weightMeanFunc(ECATnear, altInd, altInd2, col, uncCol, w0, w1):

    if not np.isfinite(ECATnear.iloc[altInd][col]):
        return ECATnear.iloc[altInd2][[col, uncCol]]
    elif not np.isfinite(ECATnear.iloc[altInd2][col]):
        return ECATnear.iloc[altInd][[col, uncCol]]

    invweight = (1./ECATnear.iloc[[altInd, altInd2]][uncCol]**2.).sum()

    invweight2 = w0/ECATnear.iloc[altInd][uncCol]**2. +\
        w1/ECATnear.iloc[altInd2][uncCol]**2.

    wgtmean = []
    for aind, w in zip([altInd, altInd2], [w0, w1]):
        wgtmean.append(
            w*ECATnear.iloc[aind][col]/ECATnear.iloc[aind][uncCol]**2.)
    wgtmean = np.sum(np.array(wgtmean))/invweight
    wgtunc = np.sqrt(1./invweight)
    wgtunc2 = np.sqrt(1./invweight2)

    return wgtmean, wgtunc2


'''
  Insert Delete GetRandom O(1)
Design a data structure that supports all following operations in average O(1) time.
- insert(val): Inserts an item val to the set if not already present.
- remove(val): Removes an item val from the set if present.
- getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
'''

class RandomizedSet:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.data = []
        self.address = {}

    def insert(self, val: int) -> bool:
        """
        Inserts a value to the set. Returns true if the set did not already contain the specified element.
        """
        if val not in self.address.keys():
            self.data.append(val)
            self.address[val] = len(self.data)-1
            return True
        return False

    def remove(self, val: int) -> bool:
        """
        Removes a value from the set. Returns true if the set contained the specified element.
        """
        if val in self.address.keys():
            idx = self.address[val]
            self.data[idx] = self.data[-1]
            self.address[self.data[idx]] = idx
            self.data.pop()
            del self.address[val]
            return True
        return False

    def getRandom(self) -> int:
        """
        Get a random element from the set.
        """
        rand = randint(0, len(self.data)-1)
        return self.data[rand]

# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()


"""utility functions.
   The code is based on https://github.com/tensorflow/cleverhans/
   examples/nips17_adversarial_competition/sample_targeted_attacks/step_target_class
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import sys
import logging
import csv

import numpy as np
from scipy.misc import imread
from scipy.misc import imsave

import tensorflow as tf

def load_images(input_dir, batch_shape):
  """Read png images from input directory in batches.

  Args:
    input_dir: input directory
    batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]

  Yields:
    filenames: list file names without path of each image
      Lenght of this list could be less than batch_size, in this case only
      first few images of the result are elements of the minibatch.
    images: array with all images from this batch
  """
  images = np.zeros(batch_shape)
  filenames = []
  idx = 0
  batch_size = batch_shape[0]
  for filepath in tf.gfile.Glob(os.path.join(input_dir, '*.png')):
    with tf.gfile.Open(filepath, 'rb') as f:
      image = imread(f, mode='RGB').astype(np.float) / 255.0
    # Images for inception classifier are normalized to be in [-1, 1] interval.
    images[idx, :, :, :] = image * 2.0 - 1.0
    filenames.append(os.path.basename(filepath))
    idx += 1
    if idx == batch_size:
      yield filenames, images
      filenames = []
      images = np.zeros(batch_shape)
      idx = 0
  if idx > 0:
    yield filenames, images

def save_images(images, filenames, output_dir):
  """Saves images to the output directory.

  Args:
    images: array with minibatch of images
    filenames: list of filenames without path
      If number of file names in this list less than number of images in
      the minibatch then only first len(filenames) images will be saved.
    output_dir: directory where to save images
  """
  for i, filename in enumerate(filenames):
    # Images for inception classifier are normalized to be in [-1, 1] interval,
    # so rescale them back to [0, 1].
    # divide by images[i, :, :, :].max()?
    with tf.gfile.Open(os.path.join(output_dir, filename), 'w') as f:
      imsave(f, np.round((images[i, :, :, :] + 1.0) * 0.5 *
                         255.0).astype(np.uint8), format='png')

def load_target_class(input_dir):
  """Loads target classes."""
  with tf.gfile.Open(os.path.join(input_dir, 'target_class.csv')) as f:
    return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2}

def setup_logging():
  logger = logging.getLogger('jing')
  logger.setLevel(logging.INFO)

  formatter = logging.Formatter(
      "%(levelname)s:%(name)s:[%(module)s]: %(message)s")
  handler = logging.StreamHandler(sys.stderr)
  handler.setFormatter(formatter)

  logger.addHandler(handler)
  return logger


import unittest

class TestGenerator(unittest.TestCase):
    def test_generator_range(self):
        self.assertEqual(sum(range(1, 101)), 5050)

    def test_generator_my_range(self):
        actual = []
        for x in self.my_range(0, 5):
            actual.append(x)
        self.assertEqual(actual, [0, 1, 2, 3, 4])

    def my_range(self, first=0, last=10, step=1):
        number = first
        while number < last:
            yield number
            number += step

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


"""
Deep learning for efficient video surveillance segmentation, indexing and retrieval.

@author: Tom
"""

from nltk.corpus import wordnet as wn

def preds_to_hypernyms(preds):
    """Translate YOLO predictions to the corresponding wordnet hypernyms"""
    res = []
    for pred in preds:
        res.append(cat_to_hypernyms(pred))
    return res

def cat_to_hypernyms(cat):
    """Translate categories to the corresponding wordnet hypernyms"""
    res = []
    wo_syn = wn.synsets(cat)
    for elem in wo_syn:
        elem = elem.hypernyms()
        if elem:
            elem = elem[0].name().split(".")[0].replace('_', ' ')
            if elem not in res:
                res.append(elem)
    return res

def find_synset(noun):
    """Find synset of a word"""
    res = []
    wo_syn = wn.synsets(noun)
    for i in wo_syn:
        j = i.name().split(".")[0]
        type_i = i.name().split(".")[1]
        if type_i == 'n':
            res.append(j)
    return res

def similarities(cat1, cat2):
    """Return similarity between two words based on the wordnet graph"""
    node1 = wn.synset(str(cat1) + str('.n.01'))
    node2 = wn.synset(str(cat2) + str('.n.01'))
    return node1.path_similarity(node2)


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('ct_app', '0022_auto_20150313_2245'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='problem',
            name='email',
        ),
        migrations.AlterField(
            model_name='problem',
            name='category',
            field=models.CharField(max_length=20, choices=[(b'career', b'Career'), (b'love', b'Love & Dating'), (b'health', b'Health & Wellness'), (b'arts', b'The Arts'), (b'politics', b'Politics'), (b'sport', b'Sport'), (b'religion', b'Religion'), (b'miscellaneous', b'Miscellaneous')]),
            preserve_default=True,
        ),
    ]


from .booking import booking
from .discount import discountbooking
import pickle

class bookings:

	FILE_NAME = "st03/saved"

	def __init__(self):
		self.bookings = []

	def add(self):
		self.bookings.append(booking())

	def adddiscount(self):
		self.bookings.append(discountbooking())

	def print(self):
		if not self.bookings:
			print('List is clear!')
			return False
		i = 1
		for item in self.bookings:
			print('---' + str(i) + '---')
			item.print()
			i+=1
		print('---end---')
		return True

	def edit(self):
		if self.print():
			try:
				sw = input("Which one? ")
				self.bookings[int(sw) - 1].read()
			except:
				print('Incorrect input!')

	def delete(self):
		if self.print():
			try:
				sw = input("Which one? ")
				self.bookings.pop(int(sw) - 1)
			except:
				print('Incorrect input!')

	def savetofile(self):
		with open(self.FILE_NAME, "wb") as f:
			pickle.dump(self.bookings, f)

	def loadfromfile(self):
		try:
			with open(self.FILE_NAME, 'rb') as f:
				self.bookings = pickle.load(f)
		except FileNotFoundError:
			print("No saved data found")

	def clear(self):
		self.bookings.clear()


#!/usr/bin/python3

#import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler

# bootstrap uno component context
import uno
import unohelper

import uuid

# $  ooffice "-accept=socket,host=localhost,port=2002;urp;"

# a UNO struct later needed to create a document
from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
from com.sun.star.text.ControlCharacter import HARD_SPACE
from com.sun.star.text.ControlCharacter import SOFT_HYPHEN
from com.sun.star.text.TextContentAnchorType import AS_CHARACTER
from com.sun.star.awt import Size

from com.sun.star.style.ParagraphAdjust import LEFT
from com.sun.star.style.ParagraphAdjust import RIGHT
from com.sun.star.style.ParagraphAdjust import BLOCK

from com.sun.star.awt.FontWeight import BOLD
from com.sun.star.awt.FontWeight import NORMAL
# 095         0 : <member scope="com::sun::star::awt">FontWeight::DONTKNOW</member>
# 096         1 : <member scope="com::sun::star::awt">FontWeight::THIN</member>
# 097         2 : <member scope="com::sun::star::awt">FontWeight::ULTRALIGHT</member>
# 098         3 : <member scope="com::sun::star::awt">FontWeight::LIGHT</member>
# 099         4 : <member scope="com::sun::star::awt">FontWeight::SEMILIGHT</member>
# 100         5 : <member scope="com::sun::star::awt">FontWeight::NORMAL</member>
# 101         7 : <member scope="com::sun::star::awt">FontWeight::SEMIBOLD</member>
# 102         8 : <member scope="com::sun::star::awt">FontWeight::BOLD</member>
# 103         9 : <member scope="com::sun::star::awt">FontWeight::ULTRABOLD</member>
# 104         10 : <member scope="com::sun::star::awt">FontWeight::BLACK</member>

from com.sun.star.awt.FontSlant import ITALIC
from com.sun.star.awt.FontSlant import NONE
# http://api.openoffice.org/docs/common/ref/com/sun/star/awt/FontSlant.html

# http://api.openoffice.org/docs/common/ref/com/sun/star/style/CharacterProperties.html

# http://www.openoffice.org/api/docs/common/ref/com/sun/star/awt/FontUnderline.html
#from com.sun.star.awt.FontUnderline import NONE
from com.sun.star.awt.FontUnderline import SINGLE

from unohelper import systemPathToFileUrl, absolutize

from os import getcwd

#############################################################################################################

#**********************************************************************
#
#   Danny.OOo.OOoLib.py
#
#   A module to easily work with OpenOffice.org.
#
#**********************************************************************
#   Copyright (c) 2003-2004 Danny Brewer
#   d29583@groovegarden.com
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   See:  http://www.gnu.org/licenses/lgpl.html
#
#**********************************************************************
#   If you make changes, please append to the change log below.
#
#   Change Log
#   Danny Brewer         Revised 2004-06-07-01
#
#**********************************************************************

import string

# OOo's libraries
import uno

#------------------------------------------------------------
#   Uno ServiceManager access
#   A different version of this routine and global variable
#    is needed for code running inside a component.
#------------------------------------------------------------

# The ServiceManager of the running OOo.
# It is cached in a global variable.
goServiceManager = False
def getServiceManager( cHost="localhost", cPort="2003" ):
    """Get the ServiceManager from the running OpenOffice.org.
        Then retain it in the global variable goServiceManager for future use.
        This is similar to the GetProcessServiceManager() in OOo Basic.
    """
    global goServiceManager
    if not goServiceManager:
        # Get the uno component context from the PyUNO runtime
        oLocalContext = uno.getComponentContext()
        # Create the UnoUrlResolver on the Python side.
        oLocalResolver = oLocalContext.ServiceManager.createInstanceWithContext(
                                    "com.sun.star.bridge.UnoUrlResolver", oLocalContext )
        # Connect to the running OpenOffice.org and get its context.
        oContext = oLocalResolver.resolve( "uno:socket,host=" + cHost + ",port=" + cPort + ";urp;StarOffice.ComponentContext" )
        # Get the ServiceManager object
        goServiceManager = oContext.ServiceManager
    return goServiceManager

#------------------------------------------------------------
#   Uno convenience functions
#   The stuff in this section is just to make
#    python progrmaming of OOo more like using OOo Basic.
#------------------------------------------------------------

# This is the same as ServiceManager.createInstance( ... )
def createUnoService( cClass ):
    """A handy way to create a global objects within the running OOo.
    Similar to the function of the same name in OOo Basic.
    """
    oServiceManager = getServiceManager()
    oObj = oServiceManager.createInstance( cClass )
    return oObj

# The StarDesktop object.  (global like in OOo Basic)
# It is cached in a global variable.
StarDesktop = None
def getDesktop():
    """An easy way to obtain the Desktop object from a running OOo.
    """
    global StarDesktop
    if StarDesktop == None:
        StarDesktop = createUnoService( "com.sun.star.frame.Desktop" )
    return StarDesktop
# preload the StarDesktop variable.
getDesktop()

# The CoreReflection object.
# It is cached in a global variable.
goCoreReflection = False
def getCoreReflection():
    global goCoreReflection
    if not goCoreReflection:
        goCoreReflection = createUnoService( "com.sun.star.reflection.CoreReflection" )
    return goCoreReflection

def createUnoStruct( cTypeName ):
    """Create a UNO struct and return it.
    Similar to the function of the same name in OOo Basic.
    """
    oCoreReflection = getCoreReflection()
    # Get the IDL class for the type name
    oXIdlClass = oCoreReflection.forName( cTypeName )
    # Create the struct.
    oReturnValue, oStruct = oXIdlClass.createObject( None )
    return oStruct

#def newConnectionToOOo( cHost="localhost", cPort="8100" ):
#    """Call this to establish, or re-establish a connection to OOo."""
#    global goServiceManager
#    global StarDesktop
#    global goCoreReflection
#    goServiceManager = False
#    StarDesktop = None
#    goCoreReflection = False
#    getServiceManager( cHost, cPort )
#    getDesktop()

#------------------------------------------------------------
#   API helpers
#------------------------------------------------------------

def hasUnoInterface( oObject, cInterfaceName ):
    """Similar to Basic's HasUnoInterfaces() function, but singular not plural."""

    # Get the Introspection service.
    oIntrospection = createUnoService( "com.sun.star.beans.Introspection" )

    # Now inspect the object to learn about it.
    oObjInfo = oIntrospection.inspect( oObject )

    # Obtain an array describing all methods of the object.
    oMethods = oObjInfo.getMethods( uno.getConstantByName( "com.sun.star.beans.MethodConcept.ALL" ) )
    # Now look at every method.
    for oMethod in oMethods:
        # Check the method's interface to see if
        #  these aren't the droids you're looking for.
        cMethodInterfaceName = oMethod.getDeclaringClass().getName()
        if cMethodInterfaceName == cInterfaceName:
            return True
    return False

def hasUnoInterfaces( oObject, *cInterfaces ):
    """Similar to the function of the same name in OOo Basic."""
    for cInterface in cInterfaces:
        if not hasUnoInterface( oObject, cInterface ):
            return False
    return True

#------------------------------------------------------------
#   High level general purpose functions
#------------------------------------------------------------

def makePropertyValue( cName=None, uValue=None, nHandle=None, nState=None ):
    """Create a com.sun.star.beans.PropertyValue struct and return it.
    """
    oPropertyValue = createUnoStruct( "com.sun.star.beans.PropertyValue" )

    if cName != None:
        oPropertyValue.Name = cName
    if uValue != None:
        oPropertyValue.Value = uValue
    if nHandle != None:
        oPropertyValue.Handle = nHandle
    if nState != None:
        oPropertyValue.State = nState

    return oPropertyValue

def makePoint( nX, nY ):
    """Create a com.sun.star.awt.Point struct."""
    oPoint = createUnoStruct( "com.sun.star.awt.Point" )
    oPoint.X = nX
    oPoint.Y = nY
    return oPoint

def makeSize( nWidth, nHeight ):
    """Create a com.sun.star.awt.Size struct."""
    oSize = createUnoStruct( "com.sun.star.awt.Size" )
    oSize.Width = nWidth
    oSize.Height = nHeight
    return oSize

def makeRectangle( nX, nY, nWidth, nHeight ):
    """Create a com.sun.star.awt.Rectangle struct."""
    oRect = createUnoStruct( "com.sun.star.awt.Rectangle" )
    oRect.X = nX
    oRect.Y = nY
    oRect.Width = nWidth
    oRect.Height = nHeight
    return oRect

def Array( *args ):
    """This is just sugar coating so that code from OOoBasic which
    contains the Array() function can work perfectly in python."""
    tArray = ()
    for arg in args:
        tArray += (arg,)
    return tArray

def loadComponentFromURL( cUrl, tProperties=() ):
    """Open or Create a document from it's URL.
    New documents are created from URL's such as:
        private:factory/sdraw
        private:factory/swriter
        private:factory/scalc
        private:factory/simpress
    """
    StarDesktop = getDesktop()
    oDocument = StarDesktop.loadComponentFromURL( cUrl, "_blank", 0, tProperties )
    return oDocument

#def makeWriterDocument():
#    """Create a new OOo Writer document."""
#    return loadComponentFromURL( "private:factory/swriter" )
#
#
#def makeCalcDocument():
#    """Create a new OOo Calc document."""
#    return loadComponentFromURL( "private:factory/scalc" )

#------------------------------------------------------------
#   Styles
#------------------------------------------------------------

def defineStyle( oDrawDoc, cStyleFamily, cStyleName, cParentStyleName=None ):
    """Add a new style to the style catalog if it is not already present.
    This returns the style object so that you can alter its properties.
    """

    oStyleFamily = oDrawDoc.getStyleFamilies().getByName( cStyleFamily )

    # Does the style already exist?
    if oStyleFamily.hasByName( cStyleName ):
        # then get it so we can return it.
        oStyle = oStyleFamily.getByName( cStyleName )
    else:
        # Create new style object.
        oStyle = oDrawDoc.createInstance( "com.sun.star.style.Style" )

        # Set its parent style
        if cParentStyleName != None:
            oStyle.setParentStyle( cParentStyleName )

        # Add the new style to the style family.
        oStyleFamily.insertByName( cStyleName, oStyle )

    return oStyle

def getStyle( oDrawDoc, cStyleFamily, cStyleName ):
    """Lookup and return a style from the document.
    """
    return oDrawDoc.getStyleFamilies().getByName( cStyleFamily ).getByName( cStyleName )

#------------------------------------------------------------
#   General Utility functions
#------------------------------------------------------------

def convertToURL( cPathname ):
    """Convert a Windows or Linux pathname into an OOo URL."""
    if len( cPathname ) > 1:
        if cPathname[1:2] == ":":
            cPathname = "/" + cPathname[0] + "|" + cPathname[2:]
    cPathname = string.replace( cPathname, "\\", "/" )
    cPathname = "file://" + cPathname
    return cPathname

#############################################################################################################

class OOProxy:
    def __init__(self):
        self.docs = {}

    def create_document(self):
        localContext = uno.getComponentContext()

        resolver = localContext.ServiceManager.createInstanceWithContext(
        				"com.sun.star.bridge.UnoUrlResolver", localContext )

        self.smgr = resolver.resolve( "uno:socket,host=localhost,port=2003;urp;StarOffice.ServiceManager" )
        remoteContext = self.smgr.getPropertyValue( "DefaultContext" )

        desktop = self.smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",remoteContext)

        # open a writer document
        self.doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )

        # shortcuts
        self.text = self.doc.Text
        self.cursor = self.text.createTextCursor()

        doc_id = uuid.uuid1().hex
        self.docs[doc_id] = {
            'text':   self.text,
            'cursor': self.cursor,
            'doc':    self.doc
        }

        return doc_id

    def setup_locals(self, doc_id):
        self.text   = self.docs[doc_id]['text']
        self.doc    = self.docs[doc_id]['doc']
        self.cursor = self.docs[doc_id]['cursor']

    def set_char_color(self, doc, color):
        self.setup_locals(doc)
        self.cursor.setPropertyValue( "CharColor", color )
        return 1

    def set_char_weight(self, doc, weight):
        self.setup_locals(doc)
        if weight == 'NORMAL':
            w = NORMAL
        if weight == 'BOLD':
            w = BOLD
        self.cursor.setPropertyValue ( "CharWeight", w )
        return 1

    def set_char_posture(self, doc, slant):
        self.setup_locals(doc)
        s = NONE
        if slant == 'ITALIC':
            s = ITALIC
        self.cursor.setPropertyValue ( "CharPosture", s )
        return 1

    def set_char_underline(self, doc, underline):
        self.setup_locals(doc)
        u = 0
        if underline == 'SINGLE':
            u = SINGLE
        self.cursor.setPropertyValue ( "CharUnderline", u )
        return 1

    def set_char_height(self, doc, height):
        self.setup_locals(doc)
        self.cursor.setPropertyValue( "CharHeight", height )
        return 1

    def set_char_font_name(self, doc, font_name):
        self.setup_locals(doc)
        self.cursor.setPropertyValue( "CharFontName", font_name )
        return 1

    def insert_control_character(self, doc, char):
        self.setup_locals(doc)
        if char == 'HARD_SPACE':
            c = HARD_SPACE
        if char == 'PARAGRAPH_BREAK':
            c = PARAGRAPH_BREAK
        if char == 'SOFT_HYPHEN':
            c = SOFT_HYPHEN
        self.text.insertControlCharacter( self.cursor, c, 0 )
        return 1

    def set_char_escapement(self, doc, size, offset):
        self.setup_locals(doc)
        self.cursor.setPropertyValue( "CharEscapement", size )
        self.cursor.setPropertyValue( "CharEscapementHeight", offset )
        return 1

    def put_text( self, doc, text ):
        self.setup_locals(doc)
        self.text.insertString( self.cursor, text, 0 );
        return 1

    def save_and_close(self, doc, outputfile):
        self.setup_locals(doc)
        cwd = systemPathToFileUrl( getcwd() )
        args = ( makePropertyValue("FilterName","MS Word 97"), )
        destFile = absolutize( cwd, systemPathToFileUrl(outputfile) )
        self.doc.storeAsURL(destFile, args)
        try:
            self.doc.dispose()
        except:
            print("error while saving doc")
        del self.docs[doc]
        return 1

    def set_para_style(self, doc, style):
        self.setup_locals(doc)
        if (style == 'Default' or style == 'Normal'):
          style = 'Standard'

        self.cursor.ParaStyleName = style

        # #print style
        # #print self.cursor.ParaStyleName
        # #print self.cursor.getPropertyValue( 'ParaStyleName' )

        # style2 = self.cursor.getPropertyValue( 'ParaStyleName' )
        # self.text.insertString( self.cursor, style2, 0 );

        # #print "OK"
        # #self.cursor.setPropertyValue( 'ParaStyleName', style2 )
        #self.cursor.setPropertyValue( 'ParaStyleName', style )

        # style2 = self.cursor.getPropertyValue( 'ParaStyleName' )
        # self.text.insertString( self.cursor, style2, 0 );
        # #self.cursor.setPropertyValue( 'CharStyleName', style )
        return 1

    def set_para_adjust(self, doc, style):
        self.setup_locals(doc)
        if style == 'LEFT':
            s = LEFT
        if style == 'RIGHT':
            s = RIGHT
        if style == 'BLOCK':
            s = BLOCK
        self.cursor.ParaAdjust = s
        print(self.cursor.ParaAdjust)
        return 1
# http://flylib.com/books/en/4.290.1.129/1/ -- jevi se, jakoby BLOCK nefungovalo a chovalo se spis jako STRETCH

def start_ooffice():
  # $  ooffice "-accept=socket,host=localhost,port=2002;urp;"
  return 1

def run_xmlrpc_server():
  port = 1210
  oo_proxy = OOProxy()
  #server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", port))
  server = SimpleXMLRPCServer(("localhost", port))
  server.register_instance(oo_proxy)
  #Go into the main listener loop
  server.serve_forever()

#print "starting ooffice..."
#start_ooffice()

print("running server...")
run_xmlrpc_server()

print("server exited")

# vim: tabstop=4


import json

def get_favorite_number(filename):
    """Get stored number if available."""
    try:
        with open(filename) as f_obj:
            number = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return number

def get_new_number(filename):
    """Prompts for a new favorite number."""
    number = input("What is your favorite number? ")

    with open(filename, 'w') as f_obj:
        json.dump(number, f_obj)

    return number

def tell_fav_number():
    """Share the user darkest secrets, their favorite number"""
    filename = 'number.json'
    number = get_favorite_number(filename)

    if number:
        print("I know your favorite number! It's " + str(number))
    else:
        number = get_new_number(filename)
        print("I'll remember you darkest secret, the number " + number +
        "! Ha!")

tell_fav_number()


# 02_角点检测_Tomasi
import cv2
import numpy as np

img = cv2.imread('../Datasets/air.jpg')
grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 输出最多50个角点,角点间最小距离为50
cornerPoints = cv2.goodFeaturesToTrack(grayImg, 50, 0.01, 50)
cornerPoints = np.int0(cornerPoints)

for i in cornerPoints:
	x, y = i.ravel()
	# 绘制角点
	cv2.circle(img, (x, y), 3, [0, 255, 0], -1)
cv2.imshow('Shi-Tomasi', img)
cv2.waitKey(0)
cv2.destroyAllWindows()


from django.conf import settings
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('users', '0004_standardize_description'),
    ]

    operations = [
        migrations.CreateModel(
            name='UserConfig',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False)),
                ('data', django.contrib.postgres.fields.jsonb.JSONField(default=dict)),
                ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='config', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ['user'],
                'verbose_name': 'User Preferences',
                'verbose_name_plural': 'User Preferences'
            },
        ),
    ]


import os
import random
import sys
import time

def check(res, expect, test_name, result_path=None, command=None):
    time.sleep(5)
    if isinstance(res, str):
        res = res.strip()
    elif result_path is not None and os.path.isfile(result_path):
        with open(result_path) as fin:
            res = fin.read().strip()
    try:
        assert res == expect
        print("TEST {0} PASSED:\n COMMAND: {1}\n".format(test_name, command))
    except:
        print("TEST {0} FAILED:\n COMMAND: {3}\n RESULT: {1}\n EXPECTED: {2}\n".format(test_name, res, expect, command))

if __name__ == '__main__':
    if len(sys.argv) != 2:
        raise IOError('Usage: test.py your_dir_path')
    student = sys.argv[1]

    name = 'badboy'
    if not os.path.isdir(name):
        os.mkdir(name)
        s_boy = "I was! a, bad (((((boy)))))1 "
        s_girl = "She <- is nice) "

        for fold_num in range(1):
            os.mkdir("./{}/{}".format(name, fold_num))
            for text_num in range(2):
                with open("./{2}/{0}/{1}.txt".format(fold_num, text_num, name), 'w') as fout:
                    fout.write((s_boy * random.randint(1, 10000) + '\n') * random.randint(5, 100))

        os.mkdir("{}/0/girl".format(name))
        for text_num in range(0, 1):
            with open("{1}/0/girl/{0}.txt".format(text_num, name), 'w') as fout:
                fout.write((s_girl * random.randint(1, 10000) + '\n') * random.randint(5, 100))

    model_path = '{0}/model'.format(student)
    result_path = '{0}/result'.format(student)

    tests = {
        'badboy': [{
            'seed': 'i',
            'length': 10,
            'output': 'i was a bad boy i was a bad boy'
        }, {
            'seed': 'is',
            'length': 5,
            'output': 'is nice she is nice',
        }, {
            'seed': 'I',
            'length': 10,
            'output': 'ERROR'
        }]
    }

    # test pep8
    check(os.popen('pep8 {0}/train.py'.format(student)).read(), '', 'pep8 train')
    check(os.popen('pep8 {0}/generate.py'.format(student)).read(), '', 'pep8 generate')

    for test_case in tests.keys():
        # test for code not failed
        command = 'python {0}/train.py --input-dir {2} --model {1} --lc'.format(
            student, model_path,
            test_case
        )
        check(
            os.system(command),
            0,
            'train {} works'.format(test_case),
            command=command
        )

        # test that model is created
        check(os.path.isfile(model_path), True, 'model {} created'.format(test_case))

        # test that model can generate words
        for test_seed in tests[test_case]:
            command = 'python {0}/generate.py --seed {3} --model {1} --length {4} --output {2}'.format(
                student, model_path, result_path,
                test_seed['seed'], test_seed['length']
            )
            if test_seed['output'] != 'ERROR':
                check(
                    os.popen(command),
                    test_seed['output'],
                    'generate {0} on seed "{1}"'.format(test_case, test_seed['seed']),
                    result_path=result_path,
                    command=command
                )
            else:
                check(
                    os.system(command),
                    256,
                    'generate {0} on seed "{1}"'.format(test_case, test_seed['seed']),
                    result_path=None,
                    command=command
                )

            if os.path.isfile(result_path):
                os.remove(result_path)

        if os.path.isfile(model_path):
            os.remove(model_path)

    print("END")


from django.db import models
from django.contrib.auth.models import User

class UserDetail(models.Model):
    user = models.ForeignKey(User, models.CASCADE, default=None)
    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length=40)
    patronymic = models.CharField(max_length=40)

    is_teacher = models.BooleanField(default=False)

    def __str__(self):
        detail = 'преподаватель' if is_teacher else student_code
        return f'{first_name} {last_name} {patronymic}, {detail}'

    class Meta:
        verbose_name = 'Детальная информация'
        verbose_name_plural = 'Детальная информация'

class Student(models.Model):
    user = models.ForeignKey(User, models.CASCADE, default=None)
    student_code = models.IntegerField(default=0)

class Teacher(models.Model):
    user = models.ForeignKey(User, models.CASCADE, default=None)

class Subject(models.Model):
    teacher = models.ForeignKey(Teacher, models.CASCADE, default=None)
    name = models.CharField(max_length=40)
    semester = models.IntegerField(default=-1)

class Mark(models.Model):
    student = models.ForeignKey(Student, models.CASCADE, default=None)
    subject = models.ForeignKey(Subject, models.CASCADE, default=None)
    mark = models.IntegerField(default=0)


# -*- coding: gbk -*-
###################################################################
#    农信银系统.汇兑来账接收交易.委托收款接收
#==================================================================
#    程序文件：  TRCC005_1102.py
#    修改时间：  2008-6-5
#    作    者：  刘雨龙
#==================================================================
#    修改时间：  20080730
#    修改者  ：  关彬捷
#    修改内容:   因屏蔽掉模板中TRCDAT时间,所有外发的委托日期从BJEDTE取
#==================================================================
#    功    能：  收到汇兑来账交易后，进行必要性检查、记录到数据库内
#		 ，向主机发起记账，调用afe发送通讯回执
###################################################################
import TradeContext,AfaLoggerFunc, AfaFlowControl,miya,AfaAfeFunc,HostContext
import TransBillFunc, AfaFunc, rccpsDBFunc,rccpsHostFunc,rccpsEntries
import rccpsMap1101CTradeContext2Dtrcbka_dict,rccpsMap0000Dout_context2CTradeContext
import rccpsDBTrcc_trcbka,AfaDBFunc,rccpsState,rccpsGetFunc,rccpsDBTrcc_subbra

from types import *
from rccpsConst import *

def SubModuleDoFst():
    AfaLoggerFunc.tradeInfo( "====开始汇兑来账接收处理====" )

    #=====判断是否重复交易====
    sel_dict = {'TRCNO':TradeContext.TRCNO,'TRCDAT':TradeContext.TRCDAT,'SNDBNKCO':TradeContext.SNDBNKCO}
    record = rccpsDBTrcc_trcbka.selectu(sel_dict)
    if record == None:
        return AfaFlowControl.ExitThisFlow('S999','判断是否重复报文，查询汇兑业务登记簿相同报文异常')
    elif len(record) > 0:
        AfaLoggerFunc.tradeInfo('汇兑业务登记簿中存在相同数据,重复报文,进入下一流程')
        #=====为通讯回执报文赋值====
        out_context_dict = {}
        out_context_dict['sysType']  = 'rccpst'
        out_context_dict['TRCCO']    = '9900503'
        out_context_dict['MSGTYPCO'] = 'SET008'
        out_context_dict['RCVMBRCO'] = TradeContext.SNDMBRCO
        out_context_dict['SNDMBRCO'] = TradeContext.RCVMBRCO
        out_context_dict['SNDBRHCO'] = TradeContext.BESBNO
        out_context_dict['SNDCLKNO'] = TradeContext.BETELR
        out_context_dict['SNDTRDAT'] = TradeContext.BJEDTE
        out_context_dict['SNDTRTIM'] = TradeContext.BJETIM
        out_context_dict['ORMFN']    = TradeContext.MSGFLGNO
        out_context_dict['MSGFLGNO'] = out_context_dict['SNDMBRCO'] + TradeContext.BJEDTE + TradeContext.SerialNo
        out_context_dict['NCCWKDAT'] = TradeContext.NCCworkDate
        out_context_dict['OPRTYPNO'] = '99'
        out_context_dict['ROPRTPNO'] = TradeContext.OPRTYPNO
        out_context_dict['TRANTYP']  = '0'
        out_context_dict['ORTRCCO']  = TradeContext.TRCCO
        out_context_dict['PRCCO']    = 'RCCI0000'
        out_context_dict['STRINFO']  = '重复报文'

        rccpsMap0000Dout_context2CTradeContext.map(out_context_dict)

        #=====发送afe====
        AfaAfeFunc.CommAfe()

        return AfaFlowControl.ExitThisFlow('S999','重复报文，退出处理流程')

    AfaLoggerFunc.tradeInfo(">>>结束判断是否重复报文")

    #=====币种转换====
    if TradeContext.CUR == 'CNY':
        TradeContext.CUR  = '01'

    #====开始向字典赋值====
    trcbka_dict = {}
    if not rccpsMap1101CTradeContext2Dtrcbka_dict.map(trcbka_dict):
        return AfaFlowControl.ExitThisFlow('M999', '字典赋值出错')

    trcbka_dict['DCFLG'] = PL_DCFLG_CRE                  #借贷标识
    trcbka_dict['OPRNO'] = '01'                          #业务属性

    #=====开始插入数据库====
    if not rccpsDBFunc.insTransTrc(trcbka_dict):
        #=====RollBack操作====
        AfaDBFunc.RollbackSql()
        return AfaFlowControl.ExitThisFlow('D002', '插入数据库出错,RollBack成功')
    else:
        #=====commit操作====
        AfaDBFunc.CommitSql()
        AfaLoggerFunc.tradeInfo('插入汇兑业务登记簿，COMMIT成功')

    #=====设置状态为收妥====
    sstlog   = {}
    sstlog['BSPSQN']   = TradeContext.BSPSQN
    sstlog['BJEDTE']   = TradeContext.BJEDTE
    sstlog['BCSTAT']   = PL_BCSTAT_BNKRCV
    sstlog['BDWFLG']   = PL_BDWFLG_SUCC

    #=====设置状态为 收妥-成功 ====
    if not rccpsState.setTransState(sstlog):
        #=====RollBack操作====
        AfaDBFunc.RollbackSql()
        return AfaFlowControl.ExitThisFlow(TradeContext.errorCode, TradeContext.errorMsg)
    else:
        #=====commit操作====
        AfaDBFunc.CommitSql()
        AfaLoggerFunc.tradeInfo('>>>commit成功')

    ##========================= START 张恒 增加于20091011 来帐落机构及入帐挂账处理  =====================##
    #初始化记挂账标识,记账.0,挂账.1,默认记账
    accflag = 0
    #接收机构暂存
    TradeContext.BESBNOFIRST = TradeContext.BESBNO

    if accflag == 0:
        AfaLoggerFunc.tradeInfo(">>>开始校验密押")
        #=====开始调用密押服务器进行核押====
        SNDBANKCO  = TradeContext.SNDBNKCO
        RCVBANKCO  = TradeContext.RCVBNKCO
        SNDBANKCO = SNDBANKCO.rjust(12,'0')
        RCVBANKCO = RCVBANKCO.rjust(12,'0')
        AMOUNT = TradeContext.OCCAMT.split('.')[0] + TradeContext.OCCAMT.split('.')[1]
        AMOUNT = AMOUNT.rjust(15,'0')

        AfaLoggerFunc.tradeDebug('AMOUNT=' + str(AMOUNT) )
        AfaLoggerFunc.tradeDebug('SNDBANKCO=' + str(SNDBANKCO) )
        AfaLoggerFunc.tradeDebug('RCVBANKCO=' + str(RCVBANKCO) )

        ret = miya.DraftEncrypt(PL_SEAL_DEC,PL_TYPE_DZHD,TradeContext.TRCDAT,TradeContext.TRCNO,AMOUNT,SNDBANKCO,RCVBANKCO,'',TradeContext.SEAL)

        if ret != 0:
            #密押错,挂账
            AfaLoggerFunc.tradeInfo("密押校验未通过,ret=[" + str(ret) + "]")
            accflag = 1
            TradeContext.NOTE3 = "密押错,挂账!"
        else:
            #密押校验通过
            AfaLoggerFunc.tradeInfo("密押校验通过")

        AfaLoggerFunc.tradeInfo(">>>结束校验密押")

    #校验账号是否非法
    if accflag == 0:
        AfaLoggerFunc.tradeInfo("开始校验账号是否非法")

        if (len(TradeContext.PYEACC) != 23) and (len(TradeContext.PYEACC) != 19) :
            accflag = 1
            TradeContext.NOTE3 = '此账号不是对公或对私账号,挂账!'

        AfaLoggerFunc.tradeInfo("结束校验账号是否非法")

    #调用主机接口查询账户信息
    if accflag == 0:
        #调用8810查询账户信息
        AfaLoggerFunc.tradeInfo("开始查询账户信息")

        TradeContext.ACCNO = TradeContext.PYEACC
        TradeContext.HostCode = '8810'
        rccpsHostFunc.CommHost( '8810' )

        if TradeContext.errorCode != '0000':
            accflag = 1
            TradeContext.NOTE3 = '查询收款人信息失败,挂账!'
        elif TradeContext.errorCode == '0000' and len(TradeContext.ACCSO) == 0 :
            accflag = 1
            TradeContext.NOTE3 = '查询收款人开户机构失败,挂账!'

        AfaLoggerFunc.tradeInfo("结束查询账户信息")

    #校验账户状态是否正常
    if accflag == 0:
        AfaLoggerFunc.tradeInfo("开始校验是否跨法人")

        if TradeContext.ACCSO[0:6] != TradeContext.BESBNO[0:6] :
            accflag = 1
            TradeContext.NOTE3 = '接收行与账户开户行跨法人,挂账!'

        AfaLoggerFunc.tradeInfo("结束校验是否跨法人")

    #校验开户机构是否建立代理关系
    if accflag == 0:
        AfaLoggerFunc.tradeInfo("开始校验接收行与开户机构是否为同一机构")

        if TradeContext.ACCSO != TradeContext.BESBNOFIRST:
            khjg = {}
            khjg['BESBNO'] = TradeContext.ACCSO
            khjg['BTOPSB'] = TradeContext.BESBNOFIRST
            khjg['SUBFLG'] = PL_SUBFLG_SUB
            rec = rccpsDBTrcc_subbra.selectu(khjg)
            if rec == None:
                accflag = 1
                TradeContext.NOTE3 = '查询账户代理关系失败,挂账!'
            elif len(rec) <= 0:
                accflag = 1
                TradeContext.NOTE3 = '账户未建立代理关系,挂账!'
            else:
                #接收机构与开户机构存在代理关系,设置机构号为开户机构号
                TradeContext.BESBNO  =  TradeContext.ACCSO

        AfaLoggerFunc.tradeInfo("结束校验接收行与开户机构是否为同一机构")

    #校验账号状态是否正常
    if accflag == 0:
        AfaLoggerFunc.tradeInfo("开始校验账号状态是否正常")

        if TradeContext.ACCST != '0' and  TradeContext.ACCST != '2':
           accflag = 1
           TradeContext.NOTE3 = '账户状态不正常,挂账!'

           #在建立代理关系的情况下,账户状态不正常,同样挂账
           TradeContext.BESBNO  = TradeContext.BESBNOFIRST

        AfaLoggerFunc.tradeInfo("结束校验账号状态是否正常")

    #校验收款人户名是否一致
    if accflag == 0:
        AfaLoggerFunc.tradeInfo("开始校验收款人户名是否一致")

        if TradeContext.ACCNM != TradeContext.PYENAM :
             accflag = 1
             TradeContext.NOTE3 = '收款人户名不符,挂账!'

             #在建立代理关系的情况下,账户状态不正常,同样挂账
             TradeContext.BESBNO  = TradeContext.BESBNOFIRST

        AfaLoggerFunc.tradeInfo("结束校验收款人户名是否一致")

    if (TradeContext.existVariable( "PYEACC" ) and len(TradeContext.PYEACC) != 0):       #收款人名称
        TradeContext.PYEACC      = TradeContext.PYEACC
    else:
        TradeContext.PYEACC      = ''

    if (TradeContext.existVariable( "PYENAM" ) and len(TradeContext.PYENAM) != 0):       #收款人名称
        TradeContext.OTNM      = TradeContext.PYENAM
    else:
        TradeContext.OTNM      = ''

    #汇兑往帐记帐字典赋值
    input_dict = {}

    if (TradeContext.existVariable( "PYRNAM" ) and len(TradeContext.PYRNAM) != 0):          #付款人户名
        TradeContext.SBACACNM      =      TradeContext.PYRNAM

    input_dict['accflag']     = str(accflag)                                #记挂标志
    input_dict['OCCAMT']      = TradeContext.OCCAMT                         #交易金额
    input_dict['PYEACC']      = TradeContext.PYEACC                         #收款人账号
    input_dict['OTNM']        = TradeContext.OTNM                           #收款人名称
    input_dict['BESBNO']      = TradeContext.BESBNO

    #调用汇兑记账接口
    rccpsEntries.HDLZJZ(input_dict)

    TradeContext.accflag    = accflag                                    #代理标志

    #=====开始调函数拼贷方账号第25位校验位====
    TradeContext.HostCode = '8813'                                   #调用8813主机接口
    TradeContext.RCCSMCD  = PL_RCCSMCD_HDLZ                          #主机摘要代码：汇兑来账
    TradeContext.ACUR = '1'
    ##========================= END 张恒 增加于20091011 来帐落机构及入帐挂账处理  =====================##

    #=====新增sstlog表状态记录====
    if not rccpsState.newTransState(TradeContext.BJEDTE,TradeContext.BSPSQN,TradeContext.BCSTAT,TradeContext.BDWFLG):
        #=====RollBack操作====
        AfaDBFunc.RollbackSql()
        return AfaFlowControl.ExitThisFlow('M999', '设置状态['+TradeContext.BCSTAT+']['+TradeContext.BDWFLG+']失败,系统自动回滚')
    else:
        #=====commit操作====
        AfaDBFunc.CommitSql()

    return True
def SubModuleDoSnd():
    AfaLoggerFunc.tradeInfo('>>>主机记账后处理')

    #=====开始向字典赋值====
    sst_dict = {}
    sst_dict['BSPSQN']  = TradeContext.BSPSQN            #报单序号
    sst_dict['BJEDTE']  = TradeContext.BJEDTE            #交易日期
    sst_dict['SBAC']    = TradeContext.SBAC              #借方账号
    sst_dict['BESBNO']  = TradeContext.BESBNO            #机构号
    if (TradeContext.existVariable( "NOTE3" ) and len(TradeContext.NOTE3) != 0):
        sst_dict['NOTE3']   = TradeContext.NOTE3         #备注3
        AfaLoggerFunc.tradeDebug('>>>test  NOTE3 =['+TradeContext.NOTE3 +']')
    sst_dict['BJETIM']  = TradeContext.BJETIM            #交易时间
    sst_dict['MGID']     = TradeContext.errorCode         #主机返回代码
    sst_dict['STRINFO']  = TradeContext.errorMsg          #主机返回信息
    sst_dict['BETELR']  = TradeContext.BETELR            #柜员号

    #=====开始判断主机返回结果====
    out_context_dict = {}

    if TradeContext.errorCode == '0000' :
        AfaLoggerFunc.tradeDebug('>>>主机通讯成功,更新表状态开始')
        trcbka_jgh = {}
        trcbka_where = {}
        trcbka_jgh['BESBNO'] = TradeContext.BESBNO
        trcbka_where['BSPSQN'] = TradeContext.BSPSQN
        trcbka_where['BJEDTE'] = TradeContext.BJEDTE

        if not rccpsDBTrcc_trcbka.updateCmt( trcbka_jgh,trcbka_where ):
            #=====RollBack操作====
            AfaDBFunc.RollbackSql()
            return AfaFlowControl.ExitThisFlow('D002', '更新数据库出错,RollBack成功')
        else:
            #=====commit操作====
            AfaDBFunc.CommitSql()
            AfaLoggerFunc.tradeInfo('更新登记簿，COMMIT成功')

        if (TradeContext.existVariable( "RBAC" ) and len(TradeContext.RBAC) != 0):
            sst_dict['RBAC']   = TradeContext.RBAC
            AfaLoggerFunc.tradeDebug('>>>test  RBAC =['+TradeContext.RBAC +']')
        if (TradeContext.existVariable( "REAC" ) and len(TradeContext.REAC) != 0):
            sst_dict['REAC']   = TradeContext.REAC
            AfaLoggerFunc.tradeDebug('>>>test  REAC =['+TradeContext.REAC +']')

        #自动挂账
        if TradeContext.accflag == 1 :
            sst_dict['BCSTAT']  = PL_BCSTAT_HANG                #自动挂账
            AfaLoggerFunc.tradeDebug('>>>test  BCSTAT=['+str(sst_dict['BCSTAT']) +']')
        #自动入账
        elif TradeContext.accflag == 0 :
            sst_dict['BCSTAT']  = PL_BCSTAT_AUTO                 #自动入账
            AfaLoggerFunc.tradeDebug('>>>test  BCSTAT=['+str(sst_dict['BCSTAT']) +']')
        if (TradeContext.existVariable( "DASQ" ) and len(TradeContext.DASQ) != 0):
           sst_dict['DASQ']    = TradeContext.DASQ              #销账序号
           AfaLoggerFunc.tradeDebug('>>>test  DASQ  =['+TradeContext.DASQ +']')
        sst_dict['BDWFLG']  = PL_BDWFLG_SUCC                 #成功
        AfaLoggerFunc.tradeDebug('>>>test  BDWFLG=['+str(sst_dict['BDWFLG']) +']')
        sst_dict['TRDT']    = TradeContext.TRDT              #主机日期
        AfaLoggerFunc.tradeDebug('>>>test  TRDT  =['+TradeContext.TRDT   +']')
        sst_dict['TLSQ']    = TradeContext.TLSQ              #主机流水
        AfaLoggerFunc.tradeDebug('>>>test  TLSQ  =['+TradeContext.TLSQ   +']')

        AfaLoggerFunc.tradeDebug('>>>主机通讯成功,更新表状态结束')

        out_context_dict['PRCCO']    = 'RCCI0000'
        out_context_dict['STRINFO']  = '成功'

    else :
        if TradeContext.accflag == 1 :
            sst_dict['BCSTAT']  = PL_BCSTAT_HANG                            #自动挂账
            sst_dict['BDWFLG']  = PL_BDWFLG_FAIL                            #处理失败

            out_context_dict['PRCCO']    = 'RCCI1056'
            out_context_dict['STRINFO']  = '挂账失败,交易失败'

        elif TradeContext.accflag == 0 :
            #记账失败,挂代理机构账
            TradeContext.BESBNO = TradeContext.BESBNOFIRST
            #汇兑来帐挂帐字典赋值
            input_dict = {}
            input_dict['accflag']     = str(TradeContext.accflag)                   #记挂标志
            input_dict['OCCAMT']      = TradeContext.OCCAMT                         #交易金额
            input_dict['BESBNO']      = TradeContext.BESBNOFIRST

            #调用汇兑记账接口
            rccpsEntries.HDLZGZ(input_dict)

            rccpsHostFunc.CommHost( '8813' )

            sst_dict = {}
            sst_dict['BSPSQN']  = TradeContext.BSPSQN            #报单序号
            AfaLoggerFunc.tradeDebug('>>>test  BSPSQN=['+TradeContext.BSPSQN+']')
            sst_dict['BJEDTE']  = TradeContext.BJEDTE            #交易日期
            AfaLoggerFunc.tradeDebug('>>>test  BJEDTE=['+TradeContext.BJEDTE+']')
            sst_dict['SBAC']    = TradeContext.SBAC              #借方账号
            AfaLoggerFunc.tradeDebug('>>>test  SBAC=['+TradeContext.SBAC+']')
            sst_dict['BESBNO']  = TradeContext.BESBNO            #机构号
            AfaLoggerFunc.tradeDebug('>>>test  BESBNO=['+TradeContext.BESBNO+']')
            if (TradeContext.existVariable( "NOTE3" ) and len(TradeContext.NOTE3) != 0):
                sst_dict['NOTE3']   = TradeContext.NOTE3         #备注3
                AfaLoggerFunc.tradeDebug('>>>test  NOTE3 =['+TradeContext.NOTE3 +']')
            sst_dict['BJETIM']  = TradeContext.BJETIM            #交易时间
            AfaLoggerFunc.tradeDebug('>>>test  BJETIM=['+TradeContext.BJETIM+']')
            sst_dict['MGID']     = TradeContext.errorCode        #主机返回代码
            sst_dict['STRINFO']  = TradeContext.errorMsg         #主机返回信息
            sst_dict['BETELR']  = TradeContext.BETELR            #柜员号

            if TradeContext.errorCode == '0000':
                AfaLoggerFunc.tradeDebug(">>>SubModuleDoSnd--挂帐成功")
                sst_dict['BCSTAT']  = PL_BCSTAT_HANG
                sst_dict['BDWFLG']  = PL_BDWFLG_SUCC

                out_context_dict['PRCCO']    = 'RCCI0000'
                out_context_dict['STRINFO']  = '成功'

            else:
                AfaLoggerFunc.tradeDebug(">>>SubModuleDoSnd--挂帐失败")
                sst_dict['BCSTAT']  = PL_BCSTAT_HANG
                sst_dict['BDWFLG']  = PL_BDWFLG_FAIL
                out_context_dict['PRCCO']    = 'RCCI1056'
                out_context_dict['STRINFO']  = '挂账失败,交易失败'

    AfaLoggerFunc.tradeDebug('>>>当前业务状态[' + str(sst_dict['BCSTAT']) + ']')
    AfaLoggerFunc.tradeDebug('>>>当前流转标志[' + str(sst_dict['BDWFLG']) + ']')

    #=====设置状态为 记账/挂账-成功 ====
    if not rccpsState.setTransState(sst_dict):
        #=====RollBack操作====
        AfaDBFunc.RollbackSql()
        return AfaFlowControl.ExitThisFlow(TradeContext.errorCode, TradeContext.errorMsg)
    else:
        #=====commit操作====
        AfaDBFunc.CommitSql()
        AfaLoggerFunc.tradeDebug('>>>commit成功')

    #=====开始设置通讯回执报文信息====
    AfaLoggerFunc.tradeInfo('>>>开始组织通讯回执报文')

    out_context_dict['sysType']  = 'rccpst'
    out_context_dict['TRCCO']    = '9900503'
    out_context_dict['MSGTYPCO'] = 'SET008'
    out_context_dict['RCVMBRCO'] = TradeContext.SNDMBRCO
    out_context_dict['SNDMBRCO'] = TradeContext.RCVMBRCO
    out_context_dict['SNDBRHCO'] = TradeContext.BESBNO
    out_context_dict['SNDCLKNO'] = TradeContext.BETELR
    out_context_dict['SNDTRDAT'] = TradeContext.BJEDTE
    out_context_dict['SNDTRTIM'] = TradeContext.BJETIM
    out_context_dict['MSGFLGNO'] = out_context_dict['SNDMBRCO'] + TradeContext.BJEDTE + TradeContext.SerialNo
    out_context_dict['ORMFN']    = TradeContext.MSGFLGNO
    out_context_dict['NCCWKDAT'] = TradeContext.NCCworkDate
    out_context_dict['OPRTYPNO'] = '99'
    out_context_dict['ROPRTPNO'] = TradeContext.OPRTYPNO
    out_context_dict['TRANTYP']  = '0'
    out_context_dict['ORTRCCO']  = TradeContext.TRCCO

    rccpsMap0000Dout_context2CTradeContext.map(out_context_dict)

    return True
def SubModuleDoTrd():
    #=====判断afe返回结果====
    if TradeContext.errorCode == '0000':
        AfaLoggerFunc.tradeInfo('>>>发送回执报文成功')
    else:
        AfaLoggerFunc.tradeInfo('>>>发送回执报文失败')

    return True