code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
import geocat.viz.util as gvutil
path = r'H:\Python project 2021\climate_data_analysis_with_python\data\sst.mnmean.nc'
ds= xr.open_dataset(path)
# time slicing
sst = ds.sst.sel(time=slice('1920-01-01','2020-12-01'))
# anomaly with respect to 1971-2000 period
clm = ds.sst.sel(time=slice('1971-01-01','2000-12-01')).groupby('time.month').mean(dim='time')
anm = (sst.groupby('time.month') - clm)
time = anm.time
itime=np.arange(time.size)
def wgt_areaave(indat, latS, latN, lonW, lonE):
lat=indat.lat
lon=indat.lon
if ( ((lonW < 0) or (lonE < 0 )) and (lon.values.min() > -1) ):
anm=indat.assign_coords(lon=( (lon + 180) % 360 - 180) )
lon=( (lon + 180) % 360 - 180)
else:
anm=indat
iplat = lat.where( (lat >= latS ) & (lat <= latN), drop=True)
iplon = lon.where( (lon >= lonW ) & (lon <= lonE), drop=True)
# print(iplat)
# print(iplon)
wgt = np.cos(np.deg2rad(lat))
odat=anm.sel(lat=iplat,lon=iplon).weighted(wgt).mean(("lon", "lat"), skipna=True)
return(odat)
# bob sst
bob_anm = wgt_areaave(anm,5,25,80,100)
bob_ranm = bob_anm.rolling(time=7, center=True).mean('time')
##
# Create a list of colors based on the color bar values
colors = ['C1' if (value > 0) else 'C0' for value in bob_anm]
fig = plt.figure(figsize=[8,5])
ax1 = fig.add_subplot(111)
# Plot bar chart
ax1.bar(itime, bob_anm, align='edge', edgecolor="none", color=colors, width=1.0)
ax1.plot(itime, bob_ranm, color="black", linewidth=1.5)
ax1.legend(['7-month running mean'],fontsize=12)
# Use geocat.viz.util convenience function to add minor and major tick lines
gvutil.add_major_minor_ticks(ax1,
x_minor_per_major=4,
y_minor_per_major=5,
labelsize=12)
# Use geocat.viz.util convenience function to set axes parameters
ystr = 1920
yend = 2020
dyr = 20
ist, = np.where(time == pd.Timestamp(year=ystr, month=1, day=1) )
iet, = np.where(time == pd.Timestamp(year=yend, month=1, day=1) )
gvutil.set_axes_limits_and_ticks(ax1,
ylim=(-1.5, 1),
yticks=np.linspace(-1.5, 1, 6),
yticklabels=np.linspace(-1.5, 1, 6),
xlim=(itime[0], itime[-1]),
xticks=itime[ist[0]:iet[0]+1:12*dyr],
xticklabels=np.arange(ystr, yend+1, dyr))
# Use geocat.viz.util convenience function to set titles and labels
gvutil.set_titles_and_labels(ax1,
maintitle="SSTA in BoB (ERSST)",
ylabel='Anomalies',
xlabel= 'Year',
maintitlefontsize=18,
labelfontsize=15)
plt.tight_layout()
plt.savefig("bob_anomalies.png",dpi = 300)
########## BoB SST with respect to ENSO and IOD (ERSST)
#nino 3.4 and dipole mode index plot together
nino = wgt_areaave(anm,-5,5,-170,-120)
nino = nino.rolling(time=7, center=True).mean('time')
#IOD west: 50 ° E to 70 ° E and 10 ° S to 10 ° N.
iod_west = wgt_areaave(anm,-10,10,50,70)
# IOD east: 90 ° E to 110 ° E and 10 ° S to 0 ° S.
iod_east = wgt_areaave(anm,-10,0,90,110)
dmi = iod_west - iod_east
dmi = dmi.rolling(time=7, center=True).mean('time')
### Figure Plot
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8))
ax1.set_title('BoB anomaly with repect to ENSO')
ax1.plot(time, bob_ranm, '-', linewidth=1)
ax1.plot(time, nino, '-', linewidth=1)
ax1.tick_params(length = 7,right=True,labelsize=12)
ax1.legend(['BoB anomaly','Nino3.4 Index'],fontsize=12,frameon=False)
ax1.set_ylabel('SSTA (°C)',fontsize=12)
ax2.set_title('BoB anomaly with respect to IOD')
ax2.plot(time, bob_ranm, '-', linewidth=1)
ax2.plot(time, dmi, '-', linewidth=1)
ax2.tick_params(length = 7,right=True,labelsize=12)
ax2.legend(['BoB anomaly','Dipole Mode Index'],fontsize=12,frameon=False)
ax2.set_ylabel('SSTA (°C)',fontsize=12)
# Show the plot
plt.draw()
plt.tight_layout()
plt.savefig("nino-bob-dmi.png",dpi = 300)
####################### (Ploting Nino 3.4 Index)
nino = wgt_areaave(anm,-5,5,-170,-120)
rnino = nino.rolling(time=7, center=True).mean('time')
#nino standard
ninoSD=nino/nino.std(dim='time')
rninoSD=ninoSD.rolling(time=7, center=True).mean('time')
# -- -- -- -- -- -- -- -- - -- - -- --- -- - -- - -- - - -- - -
# -- figure plot
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8))
# Create a list of colors based on the color bar values
colors = ['C1' if (value > 0) else 'C0' for value in ninoSD]
# Plot bar chart
ax1.bar(itime, nino, align='edge', edgecolor="none", color=colors, width=1.0)
ax1.plot(itime, rnino, color="black", linewidth=1.5)
ax1.legend(['7-month running mean'],fontsize=12,frameon=False)
ax2.bar(itime, ninoSD, align='edge', edgecolor="none", color=colors, width=1.0)
ax2.plot(itime, rninoSD, color="black", linewidth=1.5)
# Use geocat.viz.util convenience function to set axes parameters
ystr = 1920
yend = 2020
dyr = 20
ist, = np.where(time == pd.Timestamp(year=ystr, month=1, day=1) )
iet, = np.where(time == pd.Timestamp(year=yend, month=1, day=1) )
gvutil.set_axes_limits_and_ticks(ax1,
ylim=(-3, 3.5),
yticks=np.linspace(-3, 3, 7),
yticklabels=np.linspace(-3, 3, 7),
xlim=(itime[0], itime[-1]),
xticks=itime[ist[0]:iet[0]+1:12*dyr],
xticklabels=np.arange(ystr, yend+1, dyr) )
gvutil.set_axes_limits_and_ticks(ax2,
ylim=(-3, 3.5),
yticks=np.linspace(-3, 3, 7),
yticklabels=np.linspace(-3, 3, 7),
xlim=(itime[0], itime[-1]),
xticks=itime[ist[0]:iet[0]+1:12*dyr],
xticklabels=np.arange(ystr, yend+1, dyr) )
# Use geocat.viz.util convenience function to add minor and major tick lines
gvutil.add_major_minor_ticks(ax1,
x_minor_per_major=4,
y_minor_per_major=5,
labelsize=12)
gvutil.add_major_minor_ticks(ax2,
x_minor_per_major=4,
y_minor_per_major=5,
labelsize=12)
# Use geocat.viz.util convenience function to set titles and labels
gvutil.set_titles_and_labels(ax1,
maintitle="SSTA in Nino3.4 region",
ylabel='Anomalies',
maintitlefontsize=18,
labelfontsize=15)
gvutil.set_titles_and_labels(ax2,
maintitle="Nino3.4 Index",
ylabel='Standardized',
xlabel='Year',
maintitlefontsize=18,
labelfontsize=15)
plt.draw()
plt.tight_layout()
plt.savefig("nino3.4_ERSST.png",dpi=300)
############### (Ploting DMI Index)
iod_west = wgt_areaave(anm,-10,10,50,70)
# IOD east: 90 ° E to 110 ° E and 10 ° S to 0 ° S.
iod_east = wgt_areaave(anm,-10,0,90,110)
dmi = iod_west - iod_east
rdmi = dmi.rolling(time=7, center=True).mean('time')
colors = ['C1' if (value > 0) else 'C0' for value in dmi]
fig = plt.figure(figsize=[8,5])
ax1 = fig.add_subplot(111)
# Plot bar chart
ax1.bar(itime, dmi, align='edge', edgecolor="none", color=colors, width=1.0)
ax1.plot(itime, rdmi, color="black", linewidth=1.5)
ax1.legend(['7-month running mean'],fontsize=12,frameon=False)
# Use geocat.viz.util convenience function to add minor and major tick lines
gvutil.add_major_minor_ticks(ax1,
x_minor_per_major=4,
y_minor_per_major=5,
labelsize=12)
# Use geocat.viz.util convenience function to set axes parameters
ystr = 1920
yend = 2020
dyr = 20
ist, = np.where(time == pd.Timestamp(year=ystr, month=1, day=1) )
iet, = np.where(time == pd.Timestamp(year=yend, month=1, day=1) )
gvutil.set_axes_limits_and_ticks(ax1,
ylim=(-1.5, 1.90),
yticks=np.linspace(-1, 1.5, 6),
yticklabels=np.linspace(-1, 1.5, 6),
xlim=(itime[0], itime[-1]),
xticks=itime[ist[0]:iet[0]+1:12*dyr],
xticklabels=np.arange(ystr, yend+1, dyr))
# Use geocat.viz.util convenience function to set titles and labels
gvutil.set_titles_and_labels(ax1,
maintitle=" Dipole Mode Index",
ylabel='Anomalies',
xlabel= 'Year',
maintitlefontsize=18,
labelfontsize=15)
plt.tight_layout()
plt.savefig("dmi_ersst.png",dpi = 300)
### (Global vs BoB time Series -ERSST v5)
# global vs bob sst anomaly
glob_anom = anm.mean(('lon','lat'),skipna = True)
glob_anom_ra = glob_anom.rolling(time=12, center=True).mean('time')
bob_anm = wgt_areaave(anm,5,25,80,100)
bob_anm_ra = bob_anm.rolling(time=12, center=True).mean('time')
xr.corr(glob_anom_ra,bob_anm_ra)
# plot
fig = plt.figure(figsize=[8,5])
ax1 = fig.add_subplot(111)
ax1.set_title('Global SSTA & BOB SSTA with 1 year moving average (ERSST v5)')
ax1.plot(time, glob_anom_ra, '-', linewidth=1)
ax1.plot(time, bob_anm_ra, '-', linewidth=1)
ax1.tick_params(length = 7,right=True,labelsize=12)
ax1.legend(['Globally averaged','BoB averaged'],fontsize=12,frameon=False)
ax1.set_ylabel('SSTA (°C)',fontsize=12)
ax1.set_xlabel('Year',fontsize=12)
ax1.text(pd.to_datetime('1975-01-01'),-0.8,'Correlation Coefficient = 0.89',fontsize=12)
#ax1.axis(xmin=pd.Timestamp("1982-01"), xmax=pd.Timestamp("2020-12"))
# Show the plot
plt.draw()
plt.tight_layout()
plt.savefig("bobvsgloobalanom_ersst.png",dpi = 300)
| [
"matplotlib.pyplot.savefig",
"geocat.viz.util.add_major_minor_ticks",
"pandas.Timestamp",
"pandas.to_datetime",
"matplotlib.pyplot.figure",
"xarray.corr",
"numpy.deg2rad",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.tight_layout",
"numpy.linspace",
"matplotlib.pyplot.draw",
"xarray.open_d... | [((215, 236), 'xarray.open_dataset', 'xr.open_dataset', (['path'], {}), '(path)\n', (230, 236), True, 'import xarray as xr\n'), ((509, 529), 'numpy.arange', 'np.arange', (['time.size'], {}), '(time.size)\n', (518, 529), True, 'import numpy as np\n'), ((1330, 1356), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[8, 5]'}), '(figsize=[8, 5])\n', (1340, 1356), True, 'import matplotlib.pyplot as plt\n'), ((1665, 1758), 'geocat.viz.util.add_major_minor_ticks', 'gvutil.add_major_minor_ticks', (['ax1'], {'x_minor_per_major': '(4)', 'y_minor_per_major': '(5)', 'labelsize': '(12)'}), '(ax1, x_minor_per_major=4, y_minor_per_major=5,\n labelsize=12)\n', (1693, 1758), True, 'import geocat.viz.util as gvutil\n'), ((2571, 2717), 'geocat.viz.util.set_titles_and_labels', 'gvutil.set_titles_and_labels', (['ax1'], {'maintitle': '"""SSTA in BoB (ERSST)"""', 'ylabel': '"""Anomalies"""', 'xlabel': '"""Year"""', 'maintitlefontsize': '(18)', 'labelfontsize': '(15)'}), "(ax1, maintitle='SSTA in BoB (ERSST)', ylabel=\n 'Anomalies', xlabel='Year', maintitlefontsize=18, labelfontsize=15)\n", (2599, 2717), True, 'import geocat.viz.util as gvutil\n'), ((2859, 2877), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2875, 2877), True, 'import matplotlib.pyplot as plt\n'), ((2878, 2919), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""bob_anomalies.png"""'], {'dpi': '(300)'}), "('bob_anomalies.png', dpi=300)\n", (2889, 2919), True, 'import matplotlib.pyplot as plt\n'), ((3428, 3462), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(8, 8)'}), '(2, 1, figsize=(8, 8))\n', (3440, 3462), True, 'import matplotlib.pyplot as plt\n'), ((4076, 4086), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (4084, 4086), True, 'import matplotlib.pyplot as plt\n'), ((4087, 4105), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4103, 4105), True, 'import matplotlib.pyplot as plt\n'), ((4106, 4146), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""nino-bob-dmi.png"""'], {'dpi': '(300)'}), "('nino-bob-dmi.png', dpi=300)\n", (4117, 4146), True, 'import matplotlib.pyplot as plt\n'), ((4590, 4624), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(8, 8)'}), '(2, 1, figsize=(8, 8))\n', (4602, 4624), True, 'import matplotlib.pyplot as plt\n'), ((6253, 6346), 'geocat.viz.util.add_major_minor_ticks', 'gvutil.add_major_minor_ticks', (['ax1'], {'x_minor_per_major': '(4)', 'y_minor_per_major': '(5)', 'labelsize': '(12)'}), '(ax1, x_minor_per_major=4, y_minor_per_major=5,\n labelsize=12)\n', (6281, 6346), True, 'import geocat.viz.util as gvutil\n'), ((6431, 6524), 'geocat.viz.util.add_major_minor_ticks', 'gvutil.add_major_minor_ticks', (['ax2'], {'x_minor_per_major': '(4)', 'y_minor_per_major': '(5)', 'labelsize': '(12)'}), '(ax2, x_minor_per_major=4, y_minor_per_major=5,\n labelsize=12)\n', (6459, 6524), True, 'import geocat.viz.util as gvutil\n'), ((6676, 6809), 'geocat.viz.util.set_titles_and_labels', 'gvutil.set_titles_and_labels', (['ax1'], {'maintitle': '"""SSTA in Nino3.4 region"""', 'ylabel': '"""Anomalies"""', 'maintitlefontsize': '(18)', 'labelfontsize': '(15)'}), "(ax1, maintitle='SSTA in Nino3.4 region',\n ylabel='Anomalies', maintitlefontsize=18, labelfontsize=15)\n", (6704, 6809), True, 'import geocat.viz.util as gvutil\n'), ((6923, 7066), 'geocat.viz.util.set_titles_and_labels', 'gvutil.set_titles_and_labels', (['ax2'], {'maintitle': '"""Nino3.4 Index"""', 'ylabel': '"""Standardized"""', 'xlabel': '"""Year"""', 'maintitlefontsize': '(18)', 'labelfontsize': '(15)'}), "(ax2, maintitle='Nino3.4 Index', ylabel=\n 'Standardized', xlabel='Year', maintitlefontsize=18, labelfontsize=15)\n", (6951, 7066), True, 'import geocat.viz.util as gvutil\n'), ((7208, 7218), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (7216, 7218), True, 'import matplotlib.pyplot as plt\n'), ((7219, 7237), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (7235, 7237), True, 'import matplotlib.pyplot as plt\n'), ((7238, 7279), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""nino3.4_ERSST.png"""'], {'dpi': '(300)'}), "('nino3.4_ERSST.png', dpi=300)\n", (7249, 7279), True, 'import matplotlib.pyplot as plt\n'), ((7614, 7640), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[8, 5]'}), '(figsize=[8, 5])\n', (7624, 7640), True, 'import matplotlib.pyplot as plt\n'), ((7955, 8048), 'geocat.viz.util.add_major_minor_ticks', 'gvutil.add_major_minor_ticks', (['ax1'], {'x_minor_per_major': '(4)', 'y_minor_per_major': '(5)', 'labelsize': '(12)'}), '(ax1, x_minor_per_major=4, y_minor_per_major=5,\n labelsize=12)\n', (7983, 8048), True, 'import geocat.viz.util as gvutil\n'), ((8864, 9009), 'geocat.viz.util.set_titles_and_labels', 'gvutil.set_titles_and_labels', (['ax1'], {'maintitle': '""" Dipole Mode Index"""', 'ylabel': '"""Anomalies"""', 'xlabel': '"""Year"""', 'maintitlefontsize': '(18)', 'labelfontsize': '(15)'}), "(ax1, maintitle=' Dipole Mode Index', ylabel=\n 'Anomalies', xlabel='Year', maintitlefontsize=18, labelfontsize=15)\n", (8892, 9009), True, 'import geocat.viz.util as gvutil\n'), ((9151, 9169), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (9167, 9169), True, 'import matplotlib.pyplot as plt\n'), ((9170, 9207), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""dmi_ersst.png"""'], {'dpi': '(300)'}), "('dmi_ersst.png', dpi=300)\n", (9181, 9207), True, 'import matplotlib.pyplot as plt\n'), ((9523, 9556), 'xarray.corr', 'xr.corr', (['glob_anom_ra', 'bob_anm_ra'], {}), '(glob_anom_ra, bob_anm_ra)\n', (9530, 9556), True, 'import xarray as xr\n'), ((9572, 9598), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[8, 5]'}), '(figsize=[8, 5])\n', (9582, 9598), True, 'import matplotlib.pyplot as plt\n'), ((10178, 10188), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (10186, 10188), True, 'import matplotlib.pyplot as plt\n'), ((10189, 10207), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (10205, 10207), True, 'import matplotlib.pyplot as plt\n'), ((10208, 10258), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""bobvsgloobalanom_ersst.png"""'], {'dpi': '(300)'}), "('bobvsgloobalanom_ersst.png', dpi=300)\n", (10219, 10258), True, 'import matplotlib.pyplot as plt\n'), ((10009, 10037), 'pandas.to_datetime', 'pd.to_datetime', (['"""1975-01-01"""'], {}), "('1975-01-01')\n", (10023, 10037), True, 'import pandas as pd\n'), ((975, 990), 'numpy.deg2rad', 'np.deg2rad', (['lat'], {}), '(lat)\n', (985, 990), True, 'import numpy as np\n'), ((1965, 2004), 'pandas.Timestamp', 'pd.Timestamp', ([], {'year': 'ystr', 'month': '(1)', 'day': '(1)'}), '(year=ystr, month=1, day=1)\n', (1977, 2004), True, 'import pandas as pd\n'), ((2031, 2070), 'pandas.Timestamp', 'pd.Timestamp', ([], {'year': 'yend', 'month': '(1)', 'day': '(1)'}), '(year=yend, month=1, day=1)\n', (2043, 2070), True, 'import pandas as pd\n'), ((2200, 2223), 'numpy.linspace', 'np.linspace', (['(-1.5)', '(1)', '(6)'], {}), '(-1.5, 1, 6)\n', (2211, 2223), True, 'import numpy as np\n'), ((2270, 2293), 'numpy.linspace', 'np.linspace', (['(-1.5)', '(1)', '(6)'], {}), '(-1.5, 1, 6)\n', (2281, 2293), True, 'import numpy as np\n'), ((2472, 2502), 'numpy.arange', 'np.arange', (['ystr', '(yend + 1)', 'dyr'], {}), '(ystr, yend + 1, dyr)\n', (2481, 2502), True, 'import numpy as np\n'), ((5214, 5253), 'pandas.Timestamp', 'pd.Timestamp', ([], {'year': 'ystr', 'month': '(1)', 'day': '(1)'}), '(year=ystr, month=1, day=1)\n', (5226, 5253), True, 'import pandas as pd\n'), ((5280, 5319), 'pandas.Timestamp', 'pd.Timestamp', ([], {'year': 'yend', 'month': '(1)', 'day': '(1)'}), '(year=yend, month=1, day=1)\n', (5292, 5319), True, 'import pandas as pd\n'), ((5449, 5470), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(7)'], {}), '(-3, 3, 7)\n', (5460, 5470), True, 'import numpy as np\n'), ((5517, 5538), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(7)'], {}), '(-3, 3, 7)\n', (5528, 5538), True, 'import numpy as np\n'), ((5717, 5747), 'numpy.arange', 'np.arange', (['ystr', '(yend + 1)', 'dyr'], {}), '(ystr, yend + 1, dyr)\n', (5726, 5747), True, 'import numpy as np\n'), ((5876, 5897), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(7)'], {}), '(-3, 3, 7)\n', (5887, 5897), True, 'import numpy as np\n'), ((5944, 5965), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(7)'], {}), '(-3, 3, 7)\n', (5955, 5965), True, 'import numpy as np\n'), ((6144, 6174), 'numpy.arange', 'np.arange', (['ystr', '(yend + 1)', 'dyr'], {}), '(ystr, yend + 1, dyr)\n', (6153, 6174), True, 'import numpy as np\n'), ((8255, 8294), 'pandas.Timestamp', 'pd.Timestamp', ([], {'year': 'ystr', 'month': '(1)', 'day': '(1)'}), '(year=ystr, month=1, day=1)\n', (8267, 8294), True, 'import pandas as pd\n'), ((8321, 8360), 'pandas.Timestamp', 'pd.Timestamp', ([], {'year': 'yend', 'month': '(1)', 'day': '(1)'}), '(year=yend, month=1, day=1)\n', (8333, 8360), True, 'import pandas as pd\n'), ((8493, 8516), 'numpy.linspace', 'np.linspace', (['(-1)', '(1.5)', '(6)'], {}), '(-1, 1.5, 6)\n', (8504, 8516), True, 'import numpy as np\n'), ((8563, 8586), 'numpy.linspace', 'np.linspace', (['(-1)', '(1.5)', '(6)'], {}), '(-1, 1.5, 6)\n', (8574, 8586), True, 'import numpy as np\n'), ((8765, 8795), 'numpy.arange', 'np.arange', (['ystr', '(yend + 1)', 'dyr'], {}), '(ystr, yend + 1, dyr)\n', (8774, 8795), True, 'import numpy as np\n')] |
# SpheralConservation
import mpi
from SpheralCompiledPackages import *
#-------------------------------------------------------------------------------
# Conservation
#-------------------------------------------------------------------------------
class SpheralConservation:
#---------------------------------------------------------------------------
# Constructor
#---------------------------------------------------------------------------
def __init__(self, dataBase,
packages = []):
self.restart = RestartableObject(self)
self.dataBase = dataBase
self.packages = packages
self.cycleHistory = []
self.timeHistory = []
self.massHistory = []
self.pmomHistory = []
self.amomHistory = []
self.KEHistory = []
self.TEHistory = []
self.EEHistory = []
self.EHistory = []
self.Vector = eval("Vector%id" % dataBase.nDim)
self.origin = self.Vector()
# Start the conservation history
self.updateHistory()
return
#---------------------------------------------------------------------------
# Add the current state to the history variables.
#---------------------------------------------------------------------------
def updateHistory(self, cycle=0, time=0.0):
self.cycleHistory.append(cycle)
self.timeHistory.append(time)
self.massHistory.append(self.findTotalMass())
self.pmomHistory.append(self.findTotalPmom())
self.amomHistory.append(self.findTotalAmom())
self.KEHistory.append(self.findTotalKE())
self.TEHistory.append(self.findTotalTE())
self.EEHistory.append(self.findTotalPackageEnergy())
self.EHistory.append(self.KEHistory[-1] +
self.TEHistory[-1] +
self.EEHistory[-1])
return
#---------------------------------------------------------------------------
# Determine the current total mass.
#---------------------------------------------------------------------------
def findTotalMass(self):
total = 0.0
massFL = self.dataBase.globalMass
for mass in massFL:
massValues = mass.internalValues()
total += sum(list(massValues) + [0.0])
return mpi.allreduce(total, mpi.SUM)
#---------------------------------------------------------------------------
# Determine the current total linear momentum.
#---------------------------------------------------------------------------
def findTotalPmom(self):
total = self.Vector()
massFL = self.dataBase.globalMass
velocityFL = self.dataBase.globalVelocity
for (mass, velocity) in zip(massFL, velocityFL):
massValues = mass.internalValues()
velocityValues = velocity.internalValues()
for mi, vi in zip(massValues, velocityValues):
total += mi*vi
# Tally momentum from packages.
for package in self.packages:
packageValue = package.extraMomentum()
total += packageValue
return mpi.allreduce(total, mpi.SUM)
#---------------------------------------------------------------------------
# Determine the current total angular momentum, with reference to the
# stored origin.
#---------------------------------------------------------------------------
def findTotalAmom(self):
total = Vector3d()
massFL = self.dataBase.globalMass
positionFL = self.dataBase.globalPosition
velocityFL = self.dataBase.globalVelocity
for (mass, position, velocity) in zip(massFL, positionFL, velocityFL):
massValues = mass.internalValues()
positionValues = position.internalValues()
velocityValues = velocity.internalValues()
for (mi, ri, vi) in zip(massValues, positionValues, velocityValues):
# Find the displacement of this node from the origin.
dr = ri - self.origin
# Now add this node angular momentum.
if self.dataBase.nDim == 2:
total.z += mi*(dr.x*vi.y - dr.y*vi.x)
elif self.dataBase.nDim == 3:
total += mi * dr.cross(vi)
return mpi.allreduce(total, mpi.SUM)
#---------------------------------------------------------------------------
# Determine the current total kinetic energy.
#---------------------------------------------------------------------------
def findTotalKE(self):
total = 0.0
massFL = self.dataBase.globalMass
velocityFL = self.dataBase.globalVelocity
for (mass, velocity) in zip(massFL, velocityFL):
massValues = mass.internalValues()
velocityValues = velocity.internalValues()
total += sum([mi*vi.magnitude2() for (mi, vi) in zip(massValues, velocityValues)] + [0.0])
return 0.5*mpi.allreduce(total, mpi.SUM)
#---------------------------------------------------------------------------
# Determine the current total thermal energy.
#---------------------------------------------------------------------------
def findTotalTE(self):
total = 0.0
massFL = self.dataBase.fluidMass
epsFL = self.dataBase.fluidSpecificThermalEnergy
for (mass, eps) in zip(massFL, epsFL):
massValues = mass.internalValues()
epsValues = eps.internalValues()
total += sum([mi*epsi for (mi, epsi) in zip(list(mass.internalValues()),
list(eps.internalValues()))] + [0.0])
return mpi.allreduce(total, mpi.SUM)
#---------------------------------------------------------------------------
# Determine the current total package (or "external") energy.
#---------------------------------------------------------------------------
def findTotalPackageEnergy(self):
total = 0.0
for package in self.packages:
total += package.extraEnergy()
return total # Note we assume this has already been parallel summed.
#---------------------------------------------------------------------------
# Write the history to the given file.
#---------------------------------------------------------------------------
def writeHistory(self, filename):
f = open(filename, 'w')
labels = ['"cycle"', '"time"',
'"Mass"',
'"Lin Mom Mag"', '"Lin Mom X"', '"Lin Mom Y"', '"Lin Mom Z"',
'"Ang Mom Mag"', '"Ang Mom X"', '"Ang Mom Y"', '"Ang Mom Z"',
'"Total E"', '"Kin E"', '"Therm E"', '"Pkg E"']
f.write('#')
for lab in labels:
f.write('%14s ' % lab)
f.write('\n')
for i in xrange(len(self.cycleHistory)):
for var in [self.cycleHistory[i], self.timeHistory[i],
self.massHistory[i],
self.pmomHistory[i].magnitude(),
self.pmomHistory[i].x,
self.pmomHistory[i].y,
self.pmomHistory[i].z,
self.amomHistory[i].magnitude(),
self.amomHistory[i].x,
self.amomHistory[i].y,
self.amomHistory[i].z,
self.EHistory[i],
self.KEHistory[i],
self.TEHistory[i],
self.EEHistory[i]]:
f.write('%14.8g ' % var)
f.write('\n')
f.close()
return
#---------------------------------------------------------------------------
# label
#---------------------------------------------------------------------------
def label(self):
return "SpheralConservation"
#---------------------------------------------------------------------------
# dumpState
#---------------------------------------------------------------------------
def dumpState(self, file, path):
file.writeObject(self.cycleHistory, path + "/cycleHistory")
file.writeObject(self.timeHistory, path + "/timeHistory")
file.writeObject(self.massHistory, path + "/massHistory")
file.writeObject(self.pmomHistory, path + "/pmomHistory")
file.writeObject(self.amomHistory, path + "/amomHistory")
file.writeObject(self.KEHistory, path + "/KEHistory")
file.writeObject(self.TEHistory, path + "/TEHistory")
file.writeObject(self.EEHistory, path + "/EEHistory")
file.writeObject(self.EHistory, path + "/EHistory")
file.writeObject(self.origin, path + "/origin")
#---------------------------------------------------------------------------
# restoreState
#---------------------------------------------------------------------------
def restoreState(self, file, path):
self.cycleHistory = file.readObject(path + "/cycleHistory")
self.timeHistory = file.readObject(path + "/timeHistory")
self.massHistory = file.readObject(path + "/massHistory")
self.pmomHistory = file.readObject(path + "/pmomHistory")
self.amomHistory = file.readObject(path + "/amomHistory")
self.KEHistory = file.readObject(path + "/KEHistory")
self.TEHistory = file.readObject(path + "/TEHistory")
self.EEHistory = file.readObject(path + "/EEHistory")
self.EHistory = file.readObject(path + "/EHistory")
self.origin = file.readObject(path + "/origin")
| [
"mpi.allreduce"
] | [((2341, 2370), 'mpi.allreduce', 'mpi.allreduce', (['total', 'mpi.SUM'], {}), '(total, mpi.SUM)\n', (2354, 2370), False, 'import mpi\n'), ((3165, 3194), 'mpi.allreduce', 'mpi.allreduce', (['total', 'mpi.SUM'], {}), '(total, mpi.SUM)\n', (3178, 3194), False, 'import mpi\n'), ((4344, 4373), 'mpi.allreduce', 'mpi.allreduce', (['total', 'mpi.SUM'], {}), '(total, mpi.SUM)\n', (4357, 4373), False, 'import mpi\n'), ((5732, 5761), 'mpi.allreduce', 'mpi.allreduce', (['total', 'mpi.SUM'], {}), '(total, mpi.SUM)\n', (5745, 5761), False, 'import mpi\n'), ((5009, 5038), 'mpi.allreduce', 'mpi.allreduce', (['total', 'mpi.SUM'], {}), '(total, mpi.SUM)\n', (5022, 5038), False, 'import mpi\n')] |
from django import forms
from django.contrib.auth.models import User
from models import Question, Answer
class AskForm(forms.ModelForm):
class Meta:
model = Question
fields = ['title', 'text']
def save(self, commit=True):
question = super(AskForm, self).save(commit=False)
question.author = self.user
if commit:
question.save()
return question
class AnswerForm(forms.Form):
text = forms.CharField()
question = forms.IntegerField()
def clean(self):
data = self.cleaned_data
try:
question = Question.objects.get(pk=data['question'])
except (Question.DoesNotExist, KeyError):
raise forms.ValidationError("Question doesn't exists.")
else:
data['question'] = question
return data
def save(self):
data = self.cleaned_data
answer = Answer.objects.create(text=data['text'],
question=data['question'],
author=self.user)
return answer
class UserCreationFormWithEmail(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'password', 'email',)
widgets = {
'password': forms.PasswordInput(),
}
def save(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
email = self.cleaned_data.get('email')
user = User.objects.create_user(username, email, password)
return user | [
"models.Answer.objects.create",
"django.forms.CharField",
"models.Question.objects.get",
"django.forms.PasswordInput",
"django.forms.ValidationError",
"django.forms.IntegerField",
"django.contrib.auth.models.User.objects.create_user"
] | [((458, 475), 'django.forms.CharField', 'forms.CharField', ([], {}), '()\n', (473, 475), False, 'from django import forms\n'), ((491, 511), 'django.forms.IntegerField', 'forms.IntegerField', ([], {}), '()\n', (509, 511), False, 'from django import forms\n'), ((926, 1016), 'models.Answer.objects.create', 'Answer.objects.create', ([], {'text': "data['text']", 'question': "data['question']", 'author': 'self.user'}), "(text=data['text'], question=data['question'], author=\n self.user)\n", (947, 1016), False, 'from models import Question, Answer\n'), ((1489, 1540), 'django.contrib.auth.models.User.objects.create_user', 'User.objects.create_user', (['username', 'email', 'password'], {}), '(username, email, password)\n', (1513, 1540), False, 'from django.contrib.auth.models import User\n'), ((612, 653), 'models.Question.objects.get', 'Question.objects.get', ([], {'pk': "data['question']"}), "(pk=data['question'])\n", (632, 653), False, 'from models import Question, Answer\n'), ((1278, 1299), 'django.forms.PasswordInput', 'forms.PasswordInput', ([], {}), '()\n', (1297, 1299), False, 'from django import forms\n'), ((722, 771), 'django.forms.ValidationError', 'forms.ValidationError', (['"""Question doesn\'t exists."""'], {}), '("Question doesn\'t exists.")\n', (743, 771), False, 'from django import forms\n')] |
#
# Pow Default Tests
#
#
# runtest script.
# runs test with respect to some paramters
# currently only os
import sys
import pytest
# possible sys.platform results:
# http://stackoverflow.com/questions/446209/possible-values-from-sys-platform
MODELNAME = "pow_test_model"
class TestClass:
@pytest.mark.notonosx
@pytest.mark.run(order=1)
@pytest.mark.minimal
def test_server(self):
""" test if server starts
calls baseurl:port/test/12
must return 12.
This test the server, routing and method dispatching
"""
print(" .. Test if server works" )
from multiprocessing import Process
import coronadash.server
import requests
import coronadash.conf.config as cfg
import time
p = Process(target=coronadash.server.main)
p.start()
testurl=cfg.server_settings["protocol"] + cfg.server_settings["host"] + ":" + str(cfg.server_settings["port"]) + "/test/12"
r = requests.get(testurl)
p.terminate()
assert int(r.text)==12
@pytest.mark.run(order=2)
@pytest.mark.minimal
def test_sql_generate_model(self):
""" test if sql model is generated"""
print(" .. Test generate_model")
import coronadash.generate_model as gm
import uuid
import os.path
ret = gm.generate_model(MODELNAME, "sql", appname="coronadash")
# generate model returns true in case of success
assert ret is True
assert os.path.exists(os.path.normpath("../models/sql/" + MODELNAME + ".py"))
@pytest.mark.run(order=3)
@pytest.mark.minimal
def test_sql_model_type(self):
""" based on test_generate_model. Tests if a model can insert values
DB sqlite by default.
"""
print(" .. Test model is correct type")
from coronadash.models.sql.pow_test_model import PowTestModel
m = PowTestModel()
assert isinstance(m, PowTestModel)
@pytest.mark.run(order=4)
def test_sql_dbsetup(self):
""" test the setup of the alembic environment """
print(" .. Test SQL: db_setup")
import coronadash.init_sqldb_environment
import os
os.chdir("..")
r = coronadash.init_sqldb_environment.init_migrations()
assert r == True
os.chdir(os.path.abspath(os.path.dirname(__file__)))
@pytest.mark.run(order=5)
def test_sql_migration(self):
""" test the setup of the alembic environment
generate a migration
"""
print(" .. Test SQL: generate_migration")
import coronadash.generate_migration
import os
os.chdir("..")
script = coronadash.generate_migration.generate_migration(message="pow_test")
assert os.path.exists(os.path.normpath(script.path))
os.chdir(os.path.abspath(os.path.dirname(__file__)))
@pytest.mark.run(order=6)
def test_sql_dbupdate(self):
""" test the setup of the alembic environment
actually migrate the DB schema up
"""
print(" .. Test SQL: update_db -d up")
import coronadash.update_db
import os, time
ret = None
os.chdir("..")
time.sleep(1)
try:
ret = coronadash.update_db.migrate("up")
except Exception as e:
print(e)
ret = True
time.sleep(5)
os.chdir(os.path.abspath(os.path.dirname(__file__)))
@pytest.mark.run(order=7)
def test_if_sql_model_validation_works(self):
"""
check if validation works
"""
print(" .. Test SQL: model.upsert() and model.find()")
from coronadash.models.sql.pow_test_model import PowTestModel
m = PowTestModel()
assert m.validate() == True
@pytest.mark.run(order=8)
def test_if_sql_model_validation_fails_successfully(self):
"""
check if validation fails if type is wrong
"""
print(" .. Test SQL: model.upsert() and model.find()")
from coronadash.models.sql.pow_test_model import PowTestModel
m = PowTestModel()
m.title="123456789123456789123456789123456789"
assert m.validate() == False
@pytest.mark.run(order=9)
def test_sql_insert_and_find(self):
""" based on test_generate_model.
Tests if a model can insert values in the DB
and can be found by title attribute.
"""
print(" .. Test SQL: model.upsert() and model.find()")
from coronadash.models.sql.pow_test_model import PowTestModel
import os
m = PowTestModel()
m.title = "TestnamePowTestRunner"
m.upsert()
res=m.find(PowTestModel.title=="TestnamePowTestRunner")
assert res.count()==1
m.session.close()
os.chdir(os.path.abspath(os.path.dirname(__file__)))
#
# tinyDB tests
#
@pytest.mark.run(order=10)
@pytest.mark.minimal
def test_tinydb_generate_model(self):
""" test if sql model is generated"""
print(" .. Test tinyDB generate_model")
import coronadash.generate_model as gm
import uuid
import os.path
ret = gm.generate_model(MODELNAME, "tinydb", appname="coronadash")
# generate model returns true in case of success
assert ret is True
assert os.path.exists(os.path.normpath("../models/tinydb/" + MODELNAME + ".py"))
@pytest.mark.run(order=11)
@pytest.mark.minimal
def test_if_tinydb_model_validation_works(self):
"""
check if validation works
"""
print(" .. Test SQL: model.upsert() and model.find()")
from coronadash.models.tinydb.pow_test_model import PowTestModel
m = PowTestModel()
assert m.validate() == True
@pytest.mark.run(order=12)
@pytest.mark.minimal
def test_if_tinydb_model_validation_fails_successfully(self):
"""
check if validation fails if type is wrong
"""
print(" .. Test SQL: model.upsert() and model.find()")
from coronadash.models.tinydb.pow_test_model import PowTestModel
m = PowTestModel()
m.title="123456789123456789123456789123456789"
assert m.validate() == False
@pytest.mark.run(order=13)
@pytest.mark.minimal
def test_tinydb_model_type(self):
""" based on test_generate_model. Tests if a model can insert values
DB sqlite by default.
"""
print(" .. Test model tinyDB is correct type")
from coronadash.models.tinydb.pow_test_model import PowTestModel
m = PowTestModel()
assert isinstance(m, PowTestModel)
@pytest.mark.run(order=14)
def test_tinydb_insert_and_find(self):
""" based on test_generate_model. Tests if a model can insert values
and can be found back.
"""
print(" .. Test tinyDB: model.upsert() and model.find()")
from coronadash.models.tinydb.pow_test_model import PowTestModel
import os
m = PowTestModel()
m.title = "TestnamePowTestRunner"
m.upsert()
res=m.find(m.Query.title=="TestnamePowTestRunner")
assert res
m.db.close()
os.chdir(os.path.abspath(os.path.dirname(__file__)))
if __name__ == "__main__":
print(55*"-")
print(" running pow Tests on: " + sys.platform)
print(" ... ")
if sys.platform.startswith("darwin"):
# osx
ret = pytest.main(["-k-notonosx", "pow_tests.py"])
else:
ret = pytest.main(["pow_tests.py"])
print(" Failures: " +str(ret))
print(55*"-")
| [
"coronadash.models.tinydb.pow_test_model.PowTestModel",
"coronadash.generate_model.generate_model",
"pytest.mark.run",
"multiprocessing.Process",
"sys.platform.startswith",
"requests.get",
"time.sleep",
"os.chdir",
"pytest.main",
"os.path.normpath",
"os.path.dirname"
] | [((325, 349), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(1)'}), '(order=1)\n', (340, 349), False, 'import pytest\n'), ((1099, 1123), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(2)'}), '(order=2)\n', (1114, 1123), False, 'import pytest\n'), ((1613, 1637), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(3)'}), '(order=3)\n', (1628, 1637), False, 'import pytest\n'), ((2021, 2045), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(4)'}), '(order=4)\n', (2036, 2045), False, 'import pytest\n'), ((2426, 2450), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(5)'}), '(order=5)\n', (2441, 2450), False, 'import pytest\n'), ((2939, 2963), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(6)'}), '(order=6)\n', (2954, 2963), False, 'import pytest\n'), ((3515, 3539), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(7)'}), '(order=7)\n', (3530, 3539), False, 'import pytest\n'), ((3860, 3884), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(8)'}), '(order=8)\n', (3875, 3884), False, 'import pytest\n'), ((4287, 4311), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(9)'}), '(order=9)\n', (4302, 4311), False, 'import pytest\n'), ((4972, 4997), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(10)'}), '(order=10)\n', (4987, 4997), False, 'import pytest\n'), ((5503, 5528), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(11)'}), '(order=11)\n', (5518, 5528), False, 'import pytest\n'), ((5880, 5905), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(12)'}), '(order=12)\n', (5895, 5905), False, 'import pytest\n'), ((6343, 6368), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(13)'}), '(order=13)\n', (6358, 6368), False, 'import pytest\n'), ((6765, 6790), 'pytest.mark.run', 'pytest.mark.run', ([], {'order': '(14)'}), '(order=14)\n', (6780, 6790), False, 'import pytest\n'), ((7494, 7527), 'sys.platform.startswith', 'sys.platform.startswith', (['"""darwin"""'], {}), "('darwin')\n", (7517, 7527), False, 'import sys\n'), ((810, 848), 'multiprocessing.Process', 'Process', ([], {'target': 'coronadash.server.main'}), '(target=coronadash.server.main)\n', (817, 848), False, 'from multiprocessing import Process\n'), ((1014, 1035), 'requests.get', 'requests.get', (['testurl'], {}), '(testurl)\n', (1026, 1035), False, 'import requests\n'), ((1379, 1436), 'coronadash.generate_model.generate_model', 'gm.generate_model', (['MODELNAME', '"""sql"""'], {'appname': '"""coronadash"""'}), "(MODELNAME, 'sql', appname='coronadash')\n", (1396, 1436), True, 'import coronadash.generate_model as gm\n'), ((1953, 1967), 'coronadash.models.tinydb.pow_test_model.PowTestModel', 'PowTestModel', ([], {}), '()\n', (1965, 1967), False, 'from coronadash.models.tinydb.pow_test_model import PowTestModel\n'), ((2251, 2265), 'os.chdir', 'os.chdir', (['""".."""'], {}), "('..')\n", (2259, 2265), False, 'import os\n'), ((2706, 2720), 'os.chdir', 'os.chdir', (['""".."""'], {}), "('..')\n", (2714, 2720), False, 'import os\n'), ((3244, 3258), 'os.chdir', 'os.chdir', (['""".."""'], {}), "('..')\n", (3252, 3258), False, 'import os\n'), ((3267, 3280), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (3277, 3280), False, 'import os, time\n'), ((3430, 3443), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (3440, 3443), False, 'import os, time\n'), ((3799, 3813), 'coronadash.models.tinydb.pow_test_model.PowTestModel', 'PowTestModel', ([], {}), '()\n', (3811, 3813), False, 'from coronadash.models.tinydb.pow_test_model import PowTestModel\n'), ((4174, 4188), 'coronadash.models.tinydb.pow_test_model.PowTestModel', 'PowTestModel', ([], {}), '()\n', (4186, 4188), False, 'from coronadash.models.tinydb.pow_test_model import PowTestModel\n'), ((4678, 4692), 'coronadash.models.tinydb.pow_test_model.PowTestModel', 'PowTestModel', ([], {}), '()\n', (4690, 4692), False, 'from coronadash.models.tinydb.pow_test_model import PowTestModel\n'), ((5263, 5323), 'coronadash.generate_model.generate_model', 'gm.generate_model', (['MODELNAME', '"""tinydb"""'], {'appname': '"""coronadash"""'}), "(MODELNAME, 'tinydb', appname='coronadash')\n", (5280, 5323), True, 'import coronadash.generate_model as gm\n'), ((5819, 5833), 'coronadash.models.tinydb.pow_test_model.PowTestModel', 'PowTestModel', ([], {}), '()\n', (5831, 5833), False, 'from coronadash.models.tinydb.pow_test_model import PowTestModel\n'), ((6226, 6240), 'coronadash.models.tinydb.pow_test_model.PowTestModel', 'PowTestModel', ([], {}), '()\n', (6238, 6240), False, 'from coronadash.models.tinydb.pow_test_model import PowTestModel\n'), ((6697, 6711), 'coronadash.models.tinydb.pow_test_model.PowTestModel', 'PowTestModel', ([], {}), '()\n', (6709, 6711), False, 'from coronadash.models.tinydb.pow_test_model import PowTestModel\n'), ((7129, 7143), 'coronadash.models.tinydb.pow_test_model.PowTestModel', 'PowTestModel', ([], {}), '()\n', (7141, 7143), False, 'from coronadash.models.tinydb.pow_test_model import PowTestModel\n'), ((7557, 7601), 'pytest.main', 'pytest.main', (["['-k-notonosx', 'pow_tests.py']"], {}), "(['-k-notonosx', 'pow_tests.py'])\n", (7568, 7601), False, 'import pytest\n'), ((7626, 7655), 'pytest.main', 'pytest.main', (["['pow_tests.py']"], {}), "(['pow_tests.py'])\n", (7637, 7655), False, 'import pytest\n'), ((1551, 1605), 'os.path.normpath', 'os.path.normpath', (["('../models/sql/' + MODELNAME + '.py')"], {}), "('../models/sql/' + MODELNAME + '.py')\n", (1567, 1605), False, 'import os\n'), ((2837, 2866), 'os.path.normpath', 'os.path.normpath', (['script.path'], {}), '(script.path)\n', (2853, 2866), False, 'import os\n'), ((5438, 5495), 'os.path.normpath', 'os.path.normpath', (["('../models/tinydb/' + MODELNAME + '.py')"], {}), "('../models/tinydb/' + MODELNAME + '.py')\n", (5454, 5495), False, 'import os\n'), ((2388, 2413), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2403, 2413), False, 'import os\n'), ((2901, 2926), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2916, 2926), False, 'import os\n'), ((3477, 3502), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (3492, 3502), False, 'import os\n'), ((4907, 4932), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (4922, 4932), False, 'import os\n'), ((7337, 7362), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (7352, 7362), False, 'import os\n')] |
import os
from datatable import dt, as_type
# -- Enable logging
from loguru import logger
import sys
logger_config = {
"handlers": [
{"sink": sys.stdout, "colorize": True, "format":
"<green>{time}</green> <level>{message}</level>"},
{"sink": f"logs/write_pset_tables.log",
"serialize": True, # Write logs as JSONs
"enqueue": True}, # Makes logging queue based and thread safe
]
}
logger.configure(**logger_config)
@logger.catch
def write_pset_table(pset_df, df_name, pset_name, df_dir):
"""
Write a PSet table to a .jay file.
@param pset_df: [`DataFrame`] A PSet DataFrame
@param pset_name: [`string`] The name of the PSet
@param df_dir: [`string`] The name of the directory to hold all the PSet tables
@return [`None`]
"""
pset_path = os.path.join(df_dir, pset_name)
# Make sure directory for this PSet exists
if not os.path.exists(pset_path):
os.mkdir(pset_path)
# Convert to datatable Frame for fast write to disk
pset_df = dt.Frame(pset_df)
print(f'Writing {df_name} table to {pset_path}...')
# Use datatable to convert df to csv
pset_df.to_jay(os.path.join(pset_path, f'{pset_name}_{df_name}.jay'))
| [
"os.path.exists",
"os.path.join",
"os.mkdir",
"loguru.logger.configure",
"datatable.dt.Frame"
] | [((442, 475), 'loguru.logger.configure', 'logger.configure', ([], {}), '(**logger_config)\n', (458, 475), False, 'from loguru import logger\n'), ((832, 863), 'os.path.join', 'os.path.join', (['df_dir', 'pset_name'], {}), '(df_dir, pset_name)\n', (844, 863), False, 'import os\n'), ((1048, 1065), 'datatable.dt.Frame', 'dt.Frame', (['pset_df'], {}), '(pset_df)\n', (1056, 1065), False, 'from datatable import dt, as_type\n'), ((922, 947), 'os.path.exists', 'os.path.exists', (['pset_path'], {}), '(pset_path)\n', (936, 947), False, 'import os\n'), ((957, 976), 'os.mkdir', 'os.mkdir', (['pset_path'], {}), '(pset_path)\n', (965, 976), False, 'import os\n'), ((1183, 1236), 'os.path.join', 'os.path.join', (['pset_path', 'f"""{pset_name}_{df_name}.jay"""'], {}), "(pset_path, f'{pset_name}_{df_name}.jay')\n", (1195, 1236), False, 'import os\n')] |
from timemachines.skaters.orbt.orbitinclusion import using_orbit
if using_orbit:
from timemachines.skaters.orbt.orbitwrappers import orbit_lgt_iskater
from timemachines.skatertools.utilities.conventions import Y_TYPE, A_TYPE, R_TYPE, E_TYPE, T_TYPE
from timemachines.skatertools.batch.batchskater import batch_skater_factory
def orbit_lgt_skater_factory(y: Y_TYPE, s, k: int, a: A_TYPE = None, t: T_TYPE = None, e: E_TYPE = None, r: R_TYPE = None,
emp_mass=0.0,
seasonality=None):
return batch_skater_factory(y=y, s=s, k=k, a=a, t=t, e=e, r=r, emp_mass=emp_mass,
iskater=orbit_lgt_iskater,
iskater_kwargs={'seasonality': seasonality},
min_e=0, n_warm=20)
def orbit_lgt_12(y,s,k,a=None, t=None,e=None):
return orbit_lgt_skater_factory(y=y, s=s, k=k, a=a,t=t,e=e, seasonality=12)
def orbit_lgt_24(y,s,k,a=None, t=None,e=None):
return orbit_lgt_skater_factory(y, s, k, a=a,t=t,e=e, seasonality=24)
| [
"timemachines.skatertools.batch.batchskater.batch_skater_factory"
] | [((549, 723), 'timemachines.skatertools.batch.batchskater.batch_skater_factory', 'batch_skater_factory', ([], {'y': 'y', 's': 's', 'k': 'k', 'a': 'a', 't': 't', 'e': 'e', 'r': 'r', 'emp_mass': 'emp_mass', 'iskater': 'orbit_lgt_iskater', 'iskater_kwargs': "{'seasonality': seasonality}", 'min_e': '(0)', 'n_warm': '(20)'}), "(y=y, s=s, k=k, a=a, t=t, e=e, r=r, emp_mass=emp_mass,\n iskater=orbit_lgt_iskater, iskater_kwargs={'seasonality': seasonality},\n min_e=0, n_warm=20)\n", (569, 723), False, 'from timemachines.skatertools.batch.batchskater import batch_skater_factory\n')] |
"""Support for Luxtronik heatpump binary states."""
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
from homeassistant.const import CONF_FRIENDLY_NAME, CONF_ICON, CONF_ID, CONF_SENSORS
import homeassistant.helpers.config_validation as cv
from homeassistant.util import slugify
from . import DOMAIN, ENTITY_ID_FORMAT
from .const import (
CONF_CALCULATIONS,
CONF_GROUP,
CONF_INVERT_STATE,
CONF_PARAMETERS,
CONF_VISIBILITIES,
)
ICON_ON = "mdi:check-circle-outline"
ICON_OFF = "mdi:circle-outline"
_LOGGER = logging.getLogger(__name__)
DEFAULT_DEVICE_CLASS = None
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_SENSORS): vol.All(
cv.ensure_list,
[
{
vol.Required(CONF_GROUP): vol.All(
cv.string,
vol.In([CONF_PARAMETERS, CONF_CALCULATIONS, CONF_VISIBILITIES]),
),
vol.Required(CONF_ID): cv.string,
vol.Optional(CONF_FRIENDLY_NAME): cv.string,
vol.Optional(CONF_ICON): cv.string,
vol.Optional(CONF_INVERT_STATE, default=False): cv.boolean,
}
],
)
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Luxtronik binary sensor."""
luxtronik = hass.data.get(DOMAIN)
if not luxtronik:
return False
sensors = config.get(CONF_SENSORS)
entities = []
for sensor_cfg in sensors:
sensor = luxtronik.get_sensor(sensor_cfg[CONF_GROUP], sensor_cfg[CONF_ID])
if sensor:
entities.append(
LuxtronikBinarySensor(
luxtronik,
sensor,
sensor_cfg.get(CONF_FRIENDLY_NAME),
sensor_cfg.get(CONF_ICON),
sensor_cfg.get(CONF_INVERT_STATE),
)
)
else:
_LOGGER.warning(
"Invalid Luxtronik ID %s in group %s",
sensor_cfg[CONF_ID],
sensor_cfg[CONF_GROUP],
)
add_entities(entities, True)
class LuxtronikBinarySensor(BinarySensorEntity):
"""Representation of a Luxtronik binary sensor."""
def __init__(self, luxtronik, sensor, friendly_name, icon, invert_state):
"""Initialize a new Luxtronik binary sensor."""
self._luxtronik = luxtronik
self._sensor = sensor
self._name = friendly_name
self._icon = icon
self._invert = invert_state
@property
def entity_id(self):
"""Return the entity_id of the sensor."""
if not self._name:
return ENTITY_ID_FORMAT.format(slugify(self._sensor.name))
return ENTITY_ID_FORMAT.format(slugify(self._name))
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon
@property
def name(self):
"""Return the name of the sensor."""
if not self._name:
return self._sensor.name
return self._name
@property
def is_on(self):
"""Return true if binary sensor is on."""
if self._invert:
return not self._sensor.value
return self._sensor.value
@property
def device_class(self):
"""Return the dvice class."""
return DEFAULT_DEVICE_CLASS
def update(self):
"""Get the latest status and use it to update our sensor state."""
self._luxtronik.update()
| [
"logging.getLogger",
"voluptuous.Required",
"homeassistant.util.slugify",
"voluptuous.Optional",
"voluptuous.In"
] | [((608, 635), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (625, 635), False, 'import logging\n'), ((722, 748), 'voluptuous.Required', 'vol.Required', (['CONF_SENSORS'], {}), '(CONF_SENSORS)\n', (734, 748), True, 'import voluptuous as vol\n'), ((2888, 2907), 'homeassistant.util.slugify', 'slugify', (['self._name'], {}), '(self._name)\n', (2895, 2907), False, 'from homeassistant.util import slugify\n'), ((2821, 2847), 'homeassistant.util.slugify', 'slugify', (['self._sensor.name'], {}), '(self._sensor.name)\n', (2828, 2847), False, 'from homeassistant.util import slugify\n'), ((839, 863), 'voluptuous.Required', 'vol.Required', (['CONF_GROUP'], {}), '(CONF_GROUP)\n', (851, 863), True, 'import voluptuous as vol\n'), ((1041, 1062), 'voluptuous.Required', 'vol.Required', (['CONF_ID'], {}), '(CONF_ID)\n', (1053, 1062), True, 'import voluptuous as vol\n'), ((1095, 1127), 'voluptuous.Optional', 'vol.Optional', (['CONF_FRIENDLY_NAME'], {}), '(CONF_FRIENDLY_NAME)\n', (1107, 1127), True, 'import voluptuous as vol\n'), ((1160, 1183), 'voluptuous.Optional', 'vol.Optional', (['CONF_ICON'], {}), '(CONF_ICON)\n', (1172, 1183), True, 'import voluptuous as vol\n'), ((1216, 1262), 'voluptuous.Optional', 'vol.Optional', (['CONF_INVERT_STATE'], {'default': '(False)'}), '(CONF_INVERT_STATE, default=False)\n', (1228, 1262), True, 'import voluptuous as vol\n'), ((933, 996), 'voluptuous.In', 'vol.In', (['[CONF_PARAMETERS, CONF_CALCULATIONS, CONF_VISIBILITIES]'], {}), '([CONF_PARAMETERS, CONF_CALCULATIONS, CONF_VISIBILITIES])\n', (939, 996), True, 'import voluptuous as vol\n')] |
from setuptools import setup, find_packages
# Building and Distributing Packages with Setuptools
# Documentation here: https://setuptools.pypa.io/en/latest/setuptools.html
setup(name='app', version='1.0', packages=find_packages())
| [
"setuptools.find_packages"
] | [((216, 231), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (229, 231), False, 'from setuptools import setup, find_packages\n')] |
# Generated by Django 2.0.13 on 2021-08-27 12:23
from django.db import migrations
def populate_sponsorship_package_fk(apps, schema_editor):
Sponsorship = apps.get_model('sponsors.Sponsorship')
SponsorshipPackage = apps.get_model('sponsors.SponsorshipPackage')
for sponsorship in Sponsorship.objects.all().iterator():
try:
package = SponsorshipPackage.objects.get(name=sponsorship.level_name)
sponsorship.package = package
sponsorship.save()
except SponsorshipPackage.DoesNotExist:
continue
class Migration(migrations.Migration):
dependencies = [
('sponsors', '0037_sponsorship_package'),
]
operations = [
migrations.RunPython(populate_sponsorship_package_fk, migrations.RunPython.noop)
]
| [
"django.db.migrations.RunPython"
] | [((717, 802), 'django.db.migrations.RunPython', 'migrations.RunPython', (['populate_sponsorship_package_fk', 'migrations.RunPython.noop'], {}), '(populate_sponsorship_package_fk, migrations.RunPython.noop\n )\n', (737, 802), False, 'from django.db import migrations\n')] |
from builtins import isinstance
from typing import Any, Dict, Tuple
from fugue import (
DataFrame,
FugueWorkflow,
WorkflowDataFrame,
WorkflowDataFrames,
Yielded,
)
from fugue.constants import FUGUE_CONF_SQL_IGNORE_CASE
from fugue.workflow import is_acceptable_raw_df
from fugue_sql._parse import FugueSQL
from fugue_sql._utils import LazyWorkflowDataFrame, fill_sql_template
from fugue_sql._visitors import FugueSQLHooks, _Extensions
from fugue_sql.exceptions import FugueSQLSyntaxError
from triad.utils.assertion import assert_or_throw
from triad.utils.convert import get_caller_global_local_vars
class FugueSQLWorkflow(FugueWorkflow):
"""Fugue workflow that supports Fugue SQL. Please read |FugueSQLTutorial|."""
def __init__(self, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
self._sql_vars: Dict[str, WorkflowDataFrame] = {}
@property
def sql_vars(self) -> Dict[str, WorkflowDataFrame]:
return self._sql_vars
def __call__(self, code: str, *args: Any, **kwargs: Any) -> None:
global_vars, local_vars = get_caller_global_local_vars()
variables = self._sql(
code, self._sql_vars, global_vars, local_vars, *args, **kwargs
)
for k, v in variables.items():
if isinstance(v, WorkflowDataFrame) and v.workflow is self:
self._sql_vars[k] = v
def _sql(
self, code: str, *args: Any, **kwargs: Any
) -> Dict[str, Tuple[WorkflowDataFrame, WorkflowDataFrames, LazyWorkflowDataFrame]]:
# TODO: move dict construction to triad
params: Dict[str, Any] = {}
for a in args:
assert_or_throw(
isinstance(a, Dict), lambda: f"args can only have dict: {a}"
)
params.update(a)
params.update(kwargs)
params, dfs = self._split_params(params)
code = fill_sql_template(code, params)
sql = FugueSQL(
code,
"fugueLanguage",
ignore_case=self.conf.get_or_throw(FUGUE_CONF_SQL_IGNORE_CASE, bool),
simple_assign=True,
)
v = _Extensions(
sql, FugueSQLHooks(), self, dfs, local_vars=params # type: ignore
)
v.visit(sql.tree)
return v.variables
def _split_params(
self, params: Dict[str, Any]
) -> Tuple[Dict[str, Any], Dict[str, LazyWorkflowDataFrame]]:
p: Dict[str, Any] = {}
dfs: Dict[str, LazyWorkflowDataFrame] = {}
for k, v in params.items():
if isinstance(v, (int, str, float, bool)):
p[k] = v
elif isinstance(v, (DataFrame, Yielded)) or is_acceptable_raw_df(v):
dfs[k] = LazyWorkflowDataFrame(k, v, self)
else:
p[k] = v
return p, dfs
def fsql(
sql: str, *args: Any, fsql_ignore_case: bool = False, **kwargs: Any
) -> FugueSQLWorkflow:
"""Fugue SQL functional interface
:param sql: the Fugue SQL string (can be a jinja template)
:param args: variables related to the SQL string
:param fsql_ignore_case: whether to ignore case when parsing the SQL string
defaults to False.
:param kwargs: variables related to the SQL string
:return: the translated Fugue workflow
.. code-block:: python
# Basic case
fsql('''
CREATE [[0]] SCHEMA a:int
PRINT
''').run()
# With external data sources
df = pd.DataFrame([[0],[1]], columns=["a"])
fsql('''
SELECT * FROM df WHERE a=0
PRINT
''').run()
# With external variables
df = pd.DataFrame([[0],[1]], columns=["a"])
t = 1
fsql('''
SELECT * FROM df WHERE a={{t}}
PRINT
''').run()
# The following is the explicit way to specify variables and datafrems
# (recommended)
df = pd.DataFrame([[0],[1]], columns=["a"])
t = 1
fsql('''
SELECT * FROM df WHERE a={{t}}
PRINT
''', df=df, t=t).run()
# Using extensions
def dummy(df:pd.DataFrame) -> pd.DataFrame:
return df
fsql('''
CREATE [[0]] SCHEMA a:int
TRANSFORM USING dummy SCHEMA *
PRINT
''').run()
# It's recommended to provide full path of the extension inside
# Fugue SQL, so the SQL definition and exeuction can be more
# independent from the extension definition.
# Run with different execution engines
sql = '''
CREATE [[0]] SCHEMA a:int
TRANSFORM USING dummy SCHEMA *
PRINT
'''
fsql(sql).run(user_defined_spark_session())
fsql(sql).run(SparkExecutionEngine, {"spark.executor.instances":10})
fsql(sql).run(DaskExecutionEngine)
# Passing dataframes between fsql calls
result = fsql('''
CREATE [[0]] SCHEMA a:int
YIELD DATAFRAME AS x
CREATE [[1]] SCHEMA a:int
YIELD DATAFRAME AS y
''').run(DaskExecutionEngine)
fsql('''
SELECT * FROM x
UNION
SELECT * FROM y
UNION
SELECT * FROM z
PRINT
''', result, z=pd.DataFrame([[2]], columns=["z"])).run()
# Get framework native dataframes
result["x"].native # Dask dataframe
result["y"].native # Dask dataframe
result["x"].as_pandas() # Pandas dataframe
# Use lower case fugue sql
df = pd.DataFrame([[0],[1]], columns=["a"])
t = 1
fsql('''
select * from df where a={{t}}
print
''', df=df, t=t, fsql_ignore_case=True).run()
"""
global_vars, local_vars = get_caller_global_local_vars()
dag = FugueSQLWorkflow(None, {FUGUE_CONF_SQL_IGNORE_CASE: fsql_ignore_case})
try:
dag._sql(sql, global_vars, local_vars, *args, **kwargs)
except FugueSQLSyntaxError as ex:
raise FugueSQLSyntaxError(str(ex)).with_traceback(None) from None
return dag
| [
"fugue_sql._utils.LazyWorkflowDataFrame",
"builtins.isinstance",
"triad.utils.convert.get_caller_global_local_vars",
"fugue.workflow.is_acceptable_raw_df",
"fugue_sql._visitors.FugueSQLHooks",
"fugue_sql._utils.fill_sql_template"
] | [((5708, 5738), 'triad.utils.convert.get_caller_global_local_vars', 'get_caller_global_local_vars', ([], {}), '()\n', (5736, 5738), False, 'from triad.utils.convert import get_caller_global_local_vars\n'), ((1100, 1130), 'triad.utils.convert.get_caller_global_local_vars', 'get_caller_global_local_vars', ([], {}), '()\n', (1128, 1130), False, 'from triad.utils.convert import get_caller_global_local_vars\n'), ((1901, 1932), 'fugue_sql._utils.fill_sql_template', 'fill_sql_template', (['code', 'params'], {}), '(code, params)\n', (1918, 1932), False, 'from fugue_sql._utils import LazyWorkflowDataFrame, fill_sql_template\n'), ((2170, 2185), 'fugue_sql._visitors.FugueSQLHooks', 'FugueSQLHooks', ([], {}), '()\n', (2183, 2185), False, 'from fugue_sql._visitors import FugueSQLHooks, _Extensions\n'), ((2555, 2593), 'builtins.isinstance', 'isinstance', (['v', '(int, str, float, bool)'], {}), '(v, (int, str, float, bool))\n', (2565, 2593), False, 'from builtins import isinstance\n'), ((1301, 1333), 'builtins.isinstance', 'isinstance', (['v', 'WorkflowDataFrame'], {}), '(v, WorkflowDataFrame)\n', (1311, 1333), False, 'from builtins import isinstance\n'), ((1703, 1722), 'builtins.isinstance', 'isinstance', (['a', 'Dict'], {}), '(a, Dict)\n', (1713, 1722), False, 'from builtins import isinstance\n'), ((2637, 2672), 'builtins.isinstance', 'isinstance', (['v', '(DataFrame, Yielded)'], {}), '(v, (DataFrame, Yielded))\n', (2647, 2672), False, 'from builtins import isinstance\n'), ((2676, 2699), 'fugue.workflow.is_acceptable_raw_df', 'is_acceptable_raw_df', (['v'], {}), '(v)\n', (2696, 2699), False, 'from fugue.workflow import is_acceptable_raw_df\n'), ((2726, 2759), 'fugue_sql._utils.LazyWorkflowDataFrame', 'LazyWorkflowDataFrame', (['k', 'v', 'self'], {}), '(k, v, self)\n', (2747, 2759), False, 'from fugue_sql._utils import LazyWorkflowDataFrame, fill_sql_template\n')] |
#!/usr/bin/python
# -*- coding:utf-8 -*-
from Spider import Spider
# 入口
spider = Spider()
fans = spider.get_my_fans()
for fan in fans:
spider.user_crawl(fan.user_id)
spider.status_crawl(fan.user_id)
followers = spider.get_my_follower()
for follower in followers:
spider.user_crawl(fan.user_id)
spider.status_crawl(fan.user_id)
| [
"Spider.Spider"
] | [((82, 90), 'Spider.Spider', 'Spider', ([], {}), '()\n', (88, 90), False, 'from Spider import Spider\n')] |
import pygame
import random
import yaml
import os
import Objects
OBJECT_TEXTURE = os.path.join("texture", "objects")
ENEMY_TEXTURE = os.path.join("texture", "enemies")
ALLY_TEXTURE = os.path.join("texture", "ally")
def create_sprite(img, sprite_size, mmp_tile):
icon = pygame.image.load(img).convert_alpha()
icon_mmp = pygame.transform.scale(icon, (mmp_tile, mmp_tile))
icon = pygame.transform.scale(icon, (sprite_size, sprite_size))
sprite = pygame.Surface((sprite_size, sprite_size), pygame.HWSURFACE)
sprite_mmp = pygame.Surface((mmp_tile, mmp_tile), pygame.HWSURFACE)
sprite.blit(icon, (0, 0))
sprite_mmp.blit(icon_mmp, (0, 0))
return sprite, sprite_mmp
def reload_game(engine, hero):
global level_list
level_list_max = len(level_list) - 1
engine.level += 1
hero.position = [1, 1]
engine.objects = []
generator = level_list[min(engine.level, level_list_max)]
_map = generator['map'].get_map()
engine.load_map(_map)
engine.add_objects(generator['obj'].get_objects(_map))
engine.add_hero(hero)
def restore_hp(engine, hero):
if random.randint(1, 10) == 1:
engine.score -= 0.05
engine.hero = Objects.EvilEye(hero)
engine.notify("You were cursed: unlucky")
else:
engine.score += 0.1
hero.hp = hero.max_hp
engine.notify("HP restored")
def apply_blessing(engine, hero):
if hero.gold >= int(20 * 1.5 ** engine.level) - 2 * hero.stats["intelligence"]:
engine.score += 0.2
hero.gold -= int(20 * 1.5 ** engine.level) - \
2 * hero.stats["intelligence"]
if random.randint(0, 1) == 0:
engine.hero = Objects.Blessing(hero)
engine.notify("Blessing applied")
else:
engine.hero = Objects.Berserk(hero)
engine.notify("Berserk applied")
else:
engine.score -= 0.1
engine.notify("Nothing happened")
def remove_effect(engine, hero):
if hero.gold >= int(10 * 1.5 ** engine.level) - 2 * hero.stats["intelligence"] and "base" in dir(hero):
hero.gold -= int(10 * 1.5 ** engine.level) - \
2 * hero.stats["intelligence"]
engine.hero = hero.base
engine.hero.calc_max_HP()
engine.notify("Effect removed")
else:
engine.notify("Nothing happened")
def add_gold(engine, hero):
if random.randint(1, 10) == 1:
engine.score -= 0.05
engine.hero = Objects.Weakness(hero)
engine.notify("You were cursed: weak")
else:
engine.score += 0.1
gold = int(random.randint(10, 1000) * (1.1 ** (engine.hero.level - 1)))
hero.gold += gold
engine.notify(f"{gold} gold added")
def fight(engine, enemy, hero):
enemy_value = enemy.stats['strength'] + enemy.stats['endurance'] + \
enemy.stats['intelligence'] + enemy.stats['luck']
hero_value = sum(hero.stats.values())
while random.randint(1, enemy_value + hero_value) > hero_value and hero.hp > 0:
hero.hp -= 1
if hero.hp > 0:
engine.score += 1
hero.exp += enemy.xp
engine.notify("Defeated enemy!")
hero.level_up()
else:
engine.game_process = False
engine.notify("Lost!")
engine.notify("GAME OVER!!!")
def enhance(engine, hero):
engine.score += 0.2
engine.hero = Objects.Enhance(hero)
hero.hp = max(hero.max_hp, hero.hp)
engine.notify("You was enhanced!")
class MapFactory(yaml.YAMLObject):
@classmethod
def from_yaml(cls, loader, node):
def get_end(loader, node):
return {'map': EndMap.Map(), 'obj': EndMap.Objects()}
def get_random(loader, node):
return {'map': RandomMap.Map(), 'obj': RandomMap.Objects()}
def get_special(loader, node):
data = loader.construct_mapping(node)
try:
rat = data["rat"]
except KeyError:
rat = 0
try:
knight = data["knight"]
except KeyError:
knight = 0
ret = {}
_map = SpecialMap.Map()
_obj = SpecialMap.Objects()
_obj.config = {'rat': rat, 'knight': knight}
ret["map"] = _map
ret["obj"] = _obj
return ret
def get_empty(loader, node):
return {'map': EmptyMap.Map(), 'obj': EmptyMap.Objects()}
data = loader.construct_mapping(node)
try:
rat = data["rat"]
except KeyError:
rat = 0
try:
knight = data["knight"]
except KeyError:
knight = 0
_obj = cls.create_objects()
_obj.config = {'rat': rat, 'knight': knight}
return {'map': cls.create_map(), 'obj': _obj}
@classmethod
def create_map(cls):
return cls.Map()
@classmethod
def create_objects(cls):
return cls.Objects()
class EndMap(MapFactory):
yaml_tag = "!end_map"
class Map:
def __init__(self):
self.Map = ['000000000000000000000000000000000000000',
'0 0',
'0 0',
'0 0 0 000 0 0 00000 0 0 0',
'0 0 0 0 0 0 0 0 0 0 0',
'0 000 0 0 00000 0000 0 0 0',
'0 0 0 0 0 0 0 0 0 0 0',
'0 0 0 000 0 0 00000 00000 0',
'0 0 0',
'0 0',
'000000000000000000000000000000000000000'
]
self.Map = list(map(list, self.Map))
for i in self.Map:
for j in range(len(i)):
i[j] = wall if i[j] == '0' else floor1
def get_map(self):
return self.Map
class Objects:
def __init__(self):
self.objects = []
def get_objects(self, _map):
return self.objects
class RandomMap(MapFactory):
yaml_tag = "!random_map"
class Map:
w, h = 39, 25
def __init__(self):
w = self.w
h = self.h
self.Map = [[0 for _ in range(w)] for _ in range(h)]
for i in range(w):
for j in range(h):
if i == 0 or j == 0 or i == w - 1 or j == h - 1:
self.Map[j][i] = wall
else:
self.Map[j][i] = [wall, floor1, floor2, floor3, floor1,
floor2, floor3, floor1, floor2][random.randint(0, 8)]
def get_map(self):
return self.Map
class Objects:
def __init__(self):
self.objects = []
def get_objects(self, _map):
w, h = 38, 24
for obj_name in object_list_prob['objects']:
prop = object_list_prob['objects'][obj_name]
for i in range(random.randint(prop['min-count'], prop['max-count'])):
coord = (random.randint(1, w), random.randint(1, h))
intersect = True
while intersect:
intersect = False
if _map[coord[1]][coord[0]] == wall:
intersect = True
coord = (random.randint(1, w), random.randint(1, h))
continue
for obj in self.objects:
if coord == obj.position or coord == (1, 1):
intersect = True
coord = (random.randint(1, w), random.randint(1, h))
self.objects.append(Objects.Ally(
prop['sprite'], prop['action'], coord))
for obj_name in object_list_prob['ally']:
prop = object_list_prob['ally'][obj_name]
for i in range(random.randint(prop['min-count'], prop['max-count'])):
coord = (random.randint(1, w), random.randint(1, h))
intersect = True
while intersect:
intersect = False
if _map[coord[1]][coord[0]] == wall:
intersect = True
coord = (random.randint(1, w), random.randint(1, h))
continue
for obj in self.objects:
if coord == obj.position or coord == (1, 1):
intersect = True
coord = (random.randint(1, w), random.randint(1, h))
self.objects.append(Objects.Ally(
prop['sprite'], prop['action'], coord))
for obj_name in object_list_prob['enemies']:
prop = object_list_prob['enemies'][obj_name]
for i in range(random.randint(0, 5)):
coord = (random.randint(1, w), random.randint(1, h))
intersect = True
while intersect:
intersect = False
if _map[coord[1]][coord[0]] == wall:
intersect = True
coord = (random.randint(1, w), random.randint(1, h))
continue
for obj in self.objects:
if coord == obj.position or coord == (1, 1):
intersect = True
coord = (random.randint(1, w), random.randint(1, h))
self.objects.append(Objects.Enemy(
prop['sprite'], prop, prop['experience'], coord))
return self.objects
class SpecialMap(MapFactory):
yaml_tag = "!special_map"
class Map:
def __init__(self):
self.Map = ['000000000000000000000000000000000000000',
'0 0',
'0 0 0',
'0 0 0 0000 0 0 00 00 0 0',
'0 0 0 0 0 0 0 0 00 0 0 00',
'0 000 0000 0000 0 0 0 00',
'0 0 0 0 0 0 0 0 0 0 00',
'0 0 0 0 0000 0 0 0 0 0',
'0 0 0',
'0 0',
'000000000000000000000000000000000000000'
]
self.Map = list(map(list, self.Map))
for i in self.Map:
for j in range(len(i)):
i[j] = wall if i[j] == '0' else floor1
def get_map(self):
return self.Map
class Objects:
def __init__(self):
self.objects = []
self.config = {}
def get_objects(self, _map):
w, h = 10, 38
for obj_name in object_list_prob['objects']:
prop = object_list_prob['objects'][obj_name]
for i in range(random.randint(prop['min-count'], prop['max-count'])):
coord = (random.randint(1, h), random.randint(1, w))
intersect = True
while intersect:
intersect = False
if _map[coord[1]][coord[0]] == wall:
intersect = True
coord = (random.randint(1, h),
random.randint(1, w))
continue
for obj in self.objects:
if coord == obj.position or coord == (1, 1):
intersect = True
coord = (random.randint(1, h),
random.randint(1, w))
self.objects.append(Objects.Ally(
prop['sprite'], prop['action'], coord))
for obj_name in object_list_prob['ally']:
prop = object_list_prob['ally'][obj_name]
for i in range(random.randint(prop['min-count'], prop['max-count'])):
coord = (random.randint(1, h), random.randint(1, w))
intersect = True
while intersect:
intersect = False
if _map[coord[1]][coord[0]] == wall:
intersect = True
coord = (random.randint(1, h),
random.randint(1, w))
continue
for obj in self.objects:
if coord == obj.position or coord == (1, 1):
intersect = True
coord = (random.randint(1, h),
random.randint(1, w))
self.objects.append(Objects.Ally(
prop['sprite'], prop['action'], coord))
for enemy, count in self.config.items():
prop = object_list_prob['enemies'][enemy]
for i in range(random.randint(0, count)):
coord = (random.randint(1, h), random.randint(1, w))
intersect = True
while intersect:
intersect = False
if _map[coord[1]][coord[0]] == wall:
intersect = True
coord = (random.randint(1, h),
random.randint(1, w))
continue
for obj in self.objects:
if coord == obj.position or coord == (1, 1):
intersect = True
coord = (random.randint(1, h),
random.randint(1, w))
self.objects.append(Objects.Enemy(
prop['sprite'], prop, prop['experience'], coord))
return self.objects
class EmptyMap(MapFactory):
yaml_tag = "!empty_map"
@classmethod
def from_yaml(cls, loader, node):
return {'map': EmptyMap.Map(), 'obj': EmptyMap.Objects()}
class Map:
def __init__(self):
self.Map = [[]]
def get_map(self):
return self.Map
class Objects:
def __init__(self):
self.objects = []
def get_objects(self, _map):
return self.objects
wall = [0]
floor1 = [0]
floor2 = [0]
floor3 = [0]
def service_init(sprite_size, tile, full=True):
global object_list_prob, level_list
global wall
global floor1
global floor2
global floor3
wall[0] = create_sprite(os.path.join("texture", "wall.png"), sprite_size, tile)
floor1[0] = create_sprite(os.path.join("texture", "Ground_1.png"), sprite_size, tile)
floor2[0] = create_sprite(os.path.join("texture", "Ground_2.png"), sprite_size, tile)
floor3[0] = create_sprite(os.path.join("texture", "Ground_3.png"), sprite_size, tile)
file = open("objects.yml", "r")
object_list_tmp = yaml.load(file.read(), Loader=yaml.Loader)
if full:
object_list_prob = object_list_tmp
object_list_actions = {'reload_game': reload_game,
'add_gold': add_gold,
'apply_blessing': apply_blessing,
'remove_effect': remove_effect,
'restore_hp': restore_hp,
'fight': fight,
'enhance': enhance}
for obj in object_list_prob['objects']:
prop = object_list_prob['objects'][obj]
prop_tmp = object_list_tmp['objects'][obj]
prop['sprite'][0] = create_sprite(
os.path.join(OBJECT_TEXTURE, prop_tmp['sprite'][0]), sprite_size, tile)
prop['action'] = object_list_actions[prop_tmp['action']]
for ally in object_list_prob['ally']:
prop = object_list_prob['ally'][ally]
prop_tmp = object_list_tmp['ally'][ally]
prop['sprite'][0] = create_sprite(
os.path.join(ALLY_TEXTURE, prop_tmp['sprite'][0]), sprite_size, tile)
prop['action'] = object_list_actions[prop_tmp['action']]
for enemy in object_list_prob['enemies']:
prop = object_list_prob['enemies'][enemy]
prop_tmp = object_list_tmp['enemies'][enemy]
prop['sprite'][0] = create_sprite(
os.path.join(ENEMY_TEXTURE, prop_tmp['sprite'][0]), sprite_size, tile)
prop['action'] = object_list_actions['fight']
file.close()
if full:
file = open("levels.yml", "r")
level_list = yaml.load(file.read(), Loader=yaml.Loader)['levels']
level_list.append({'map': EndMap.Map(), 'obj': EndMap.Objects()})
file.close()
| [
"Objects.Ally",
"Objects.Weakness",
"pygame.Surface",
"Objects.Enemy",
"os.path.join",
"Objects.Berserk",
"Objects.Blessing",
"Objects.EvilEye",
"pygame.image.load",
"random.randint",
"Objects.Enhance",
"pygame.transform.scale"
] | [((89, 123), 'os.path.join', 'os.path.join', (['"""texture"""', '"""objects"""'], {}), "('texture', 'objects')\n", (101, 123), False, 'import os\n'), ((141, 175), 'os.path.join', 'os.path.join', (['"""texture"""', '"""enemies"""'], {}), "('texture', 'enemies')\n", (153, 175), False, 'import os\n'), ((192, 223), 'os.path.join', 'os.path.join', (['"""texture"""', '"""ally"""'], {}), "('texture', 'ally')\n", (204, 223), False, 'import os\n'), ((343, 393), 'pygame.transform.scale', 'pygame.transform.scale', (['icon', '(mmp_tile, mmp_tile)'], {}), '(icon, (mmp_tile, mmp_tile))\n', (365, 393), False, 'import pygame\n'), ((406, 462), 'pygame.transform.scale', 'pygame.transform.scale', (['icon', '(sprite_size, sprite_size)'], {}), '(icon, (sprite_size, sprite_size))\n', (428, 462), False, 'import pygame\n'), ((477, 537), 'pygame.Surface', 'pygame.Surface', (['(sprite_size, sprite_size)', 'pygame.HWSURFACE'], {}), '((sprite_size, sprite_size), pygame.HWSURFACE)\n', (491, 537), False, 'import pygame\n'), ((556, 610), 'pygame.Surface', 'pygame.Surface', (['(mmp_tile, mmp_tile)', 'pygame.HWSURFACE'], {}), '((mmp_tile, mmp_tile), pygame.HWSURFACE)\n', (570, 610), False, 'import pygame\n'), ((3477, 3498), 'Objects.Enhance', 'Objects.Enhance', (['hero'], {}), '(hero)\n', (3492, 3498), False, 'import Objects\n'), ((1148, 1169), 'random.randint', 'random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (1162, 1169), False, 'import random\n'), ((1229, 1250), 'Objects.EvilEye', 'Objects.EvilEye', (['hero'], {}), '(hero)\n', (1244, 1250), False, 'import Objects\n'), ((2462, 2483), 'random.randint', 'random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (2476, 2483), False, 'import random\n'), ((2543, 2565), 'Objects.Weakness', 'Objects.Weakness', (['hero'], {}), '(hero)\n', (2559, 2565), False, 'import Objects\n'), ((15603, 15638), 'os.path.join', 'os.path.join', (['"""texture"""', '"""wall.png"""'], {}), "('texture', 'wall.png')\n", (15615, 15638), False, 'import os\n'), ((15690, 15729), 'os.path.join', 'os.path.join', (['"""texture"""', '"""Ground_1.png"""'], {}), "('texture', 'Ground_1.png')\n", (15702, 15729), False, 'import os\n'), ((15781, 15820), 'os.path.join', 'os.path.join', (['"""texture"""', '"""Ground_2.png"""'], {}), "('texture', 'Ground_2.png')\n", (15793, 15820), False, 'import os\n'), ((15872, 15911), 'os.path.join', 'os.path.join', (['"""texture"""', '"""Ground_3.png"""'], {}), "('texture', 'Ground_3.png')\n", (15884, 15911), False, 'import os\n'), ((288, 310), 'pygame.image.load', 'pygame.image.load', (['img'], {}), '(img)\n', (305, 310), False, 'import pygame\n'), ((1685, 1705), 'random.randint', 'random.randint', (['(0)', '(1)'], {}), '(0, 1)\n', (1699, 1705), False, 'import random\n'), ((1739, 1761), 'Objects.Blessing', 'Objects.Blessing', (['hero'], {}), '(hero)\n', (1755, 1761), False, 'import Objects\n'), ((1851, 1872), 'Objects.Berserk', 'Objects.Berserk', (['hero'], {}), '(hero)\n', (1866, 1872), False, 'import Objects\n'), ((3041, 3084), 'random.randint', 'random.randint', (['(1)', '(enemy_value + hero_value)'], {}), '(1, enemy_value + hero_value)\n', (3055, 3084), False, 'import random\n'), ((16678, 16729), 'os.path.join', 'os.path.join', (['OBJECT_TEXTURE', "prop_tmp['sprite'][0]"], {}), "(OBJECT_TEXTURE, prop_tmp['sprite'][0])\n", (16690, 16729), False, 'import os\n'), ((17015, 17064), 'os.path.join', 'os.path.join', (['ALLY_TEXTURE', "prop_tmp['sprite'][0]"], {}), "(ALLY_TEXTURE, prop_tmp['sprite'][0])\n", (17027, 17064), False, 'import os\n'), ((17362, 17412), 'os.path.join', 'os.path.join', (['ENEMY_TEXTURE', "prop_tmp['sprite'][0]"], {}), "(ENEMY_TEXTURE, prop_tmp['sprite'][0])\n", (17374, 17412), False, 'import os\n'), ((2674, 2698), 'random.randint', 'random.randint', (['(10)', '(1000)'], {}), '(10, 1000)\n', (2688, 2698), False, 'import random\n'), ((7389, 7441), 'random.randint', 'random.randint', (["prop['min-count']", "prop['max-count']"], {}), "(prop['min-count'], prop['max-count'])\n", (7403, 7441), False, 'import random\n'), ((8395, 8447), 'random.randint', 'random.randint', (["prop['min-count']", "prop['max-count']"], {}), "(prop['min-count'], prop['max-count'])\n", (8409, 8447), False, 'import random\n'), ((9405, 9425), 'random.randint', 'random.randint', (['(0)', '(5)'], {}), '(0, 5)\n', (9419, 9425), False, 'import random\n'), ((11739, 11791), 'random.randint', 'random.randint', (["prop['min-count']", "prop['max-count']"], {}), "(prop['min-count'], prop['max-count'])\n", (11753, 11791), False, 'import random\n'), ((12825, 12877), 'random.randint', 'random.randint', (["prop['min-count']", "prop['max-count']"], {}), "(prop['min-count'], prop['max-count'])\n", (12839, 12877), False, 'import random\n'), ((13908, 13932), 'random.randint', 'random.randint', (['(0)', 'count'], {}), '(0, count)\n', (13922, 13932), False, 'import random\n'), ((7474, 7494), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (7488, 7494), False, 'import random\n'), ((7496, 7516), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (7510, 7516), False, 'import random\n'), ((8168, 8219), 'Objects.Ally', 'Objects.Ally', (["prop['sprite']", "prop['action']", 'coord'], {}), "(prop['sprite'], prop['action'], coord)\n", (8180, 8219), False, 'import Objects\n'), ((8480, 8500), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (8494, 8500), False, 'import random\n'), ((8502, 8522), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (8516, 8522), False, 'import random\n'), ((9172, 9223), 'Objects.Ally', 'Objects.Ally', (["prop['sprite']", "prop['action']", 'coord'], {}), "(prop['sprite'], prop['action'], coord)\n", (9184, 9223), False, 'import Objects\n'), ((9458, 9478), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (9472, 9478), False, 'import random\n'), ((9480, 9500), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (9494, 9500), False, 'import random\n'), ((10152, 10214), 'Objects.Enemy', 'Objects.Enemy', (["prop['sprite']", 'prop', "prop['experience']", 'coord'], {}), "(prop['sprite'], prop, prop['experience'], coord)\n", (10165, 10214), False, 'import Objects\n'), ((11824, 11844), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (11838, 11844), False, 'import random\n'), ((11846, 11866), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (11860, 11866), False, 'import random\n'), ((12598, 12649), 'Objects.Ally', 'Objects.Ally', (["prop['sprite']", "prop['action']", 'coord'], {}), "(prop['sprite'], prop['action'], coord)\n", (12610, 12649), False, 'import Objects\n'), ((12910, 12930), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (12924, 12930), False, 'import random\n'), ((12932, 12952), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (12946, 12952), False, 'import random\n'), ((13682, 13733), 'Objects.Ally', 'Objects.Ally', (["prop['sprite']", "prop['action']", 'coord'], {}), "(prop['sprite'], prop['action'], coord)\n", (13694, 13733), False, 'import Objects\n'), ((13965, 13985), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (13979, 13985), False, 'import random\n'), ((13987, 14007), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (14001, 14007), False, 'import random\n'), ((14739, 14801), 'Objects.Enemy', 'Objects.Enemy', (["prop['sprite']", 'prop', "prop['experience']", 'coord'], {}), "(prop['sprite'], prop, prop['experience'], coord)\n", (14752, 14801), False, 'import Objects\n'), ((7005, 7025), 'random.randint', 'random.randint', (['(0)', '(8)'], {}), '(0, 8)\n', (7019, 7025), False, 'import random\n'), ((7783, 7803), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (7797, 7803), False, 'import random\n'), ((7805, 7825), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (7819, 7825), False, 'import random\n'), ((8789, 8809), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (8803, 8809), False, 'import random\n'), ((8811, 8831), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (8825, 8831), False, 'import random\n'), ((9767, 9787), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (9781, 9787), False, 'import random\n'), ((9789, 9809), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (9803, 9809), False, 'import random\n'), ((12133, 12153), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (12147, 12153), False, 'import random\n'), ((12193, 12213), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (12207, 12213), False, 'import random\n'), ((13219, 13239), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (13233, 13239), False, 'import random\n'), ((13279, 13299), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (13293, 13299), False, 'import random\n'), ((14274, 14294), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (14288, 14294), False, 'import random\n'), ((14334, 14354), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (14348, 14354), False, 'import random\n'), ((8081, 8101), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (8095, 8101), False, 'import random\n'), ((8103, 8123), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (8117, 8123), False, 'import random\n'), ((9087, 9107), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (9101, 9107), False, 'import random\n'), ((9109, 9129), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (9123, 9129), False, 'import random\n'), ((10065, 10085), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (10079, 10085), False, 'import random\n'), ((10087, 10107), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (10101, 10107), False, 'import random\n'), ((12469, 12489), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (12483, 12489), False, 'import random\n'), ((12533, 12553), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (12547, 12553), False, 'import random\n'), ((13555, 13575), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (13569, 13575), False, 'import random\n'), ((13619, 13639), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (13633, 13639), False, 'import random\n'), ((14610, 14630), 'random.randint', 'random.randint', (['(1)', 'h'], {}), '(1, h)\n', (14624, 14630), False, 'import random\n'), ((14674, 14694), 'random.randint', 'random.randint', (['(1)', 'w'], {}), '(1, w)\n', (14688, 14694), False, 'import random\n')] |
import os
import glob
import json
import unittest
import satsearch.config as config
from satstac import Item
from satsearch.search import SatSearchError, Search
class Test(unittest.TestCase):
path = os.path.dirname(__file__)
results = []
@classmethod
def setUpClass(cls):
fnames = glob.glob(os.path.join(cls.path, '*-item*.json'))
for fname in fnames:
with open(fname) as f:
cls.results.append(json.load(f))
def get_searches(self):
""" Initialize and return search object """
return [Search(datetime=r['properties']['datetime']) for r in self.results]
def test_search_init(self):
""" Initialize a search object """
search = self.get_searches()[0]
dts = [r['properties']['datetime'] for r in self.results]
assert(len(search.kwargs) == 1)
assert('time' in search.kwargs)
for kw in search.kwargs:
self.assertTrue(search.kwargs[kw] in dts)
def test_search_for_items_by_date(self):
""" Search for specific item """
search = self.get_searches()[0]
sids = [r['id'] for r in self.results]
items = search.items()
assert(len(items) == 1)
for s in items:
self.assertTrue(s.id in sids)
def test_empty_search(self):
""" Perform search for 0 results """
search = Search(datetime='2001-01-01')
self.assertEqual(search.found(), 0)
def test_geo_search(self):
""" Perform simple query """
with open(os.path.join(self.path, 'aoi1.geojson')) as f:
aoi = json.dumps(json.load(f))
search = Search(datetime='2019-07-01', intersects=aoi)
assert(search.found() == 13)
items = search.items()
assert(len(items) == 13)
assert(isinstance(items[0], Item))
def test_search_sort(self):
""" Perform search with sort """
with open(os.path.join(self.path, 'aoi1.geojson')) as f:
aoi = json.dumps(json.load(f))
search = Search.search(datetime='2019-07-01/2019-07-07', intersects=aoi, sort=['<datetime'])
items = search.items()
assert(len(items) == 27)
def test_get_items_by_id(self):
""" Get Items by ID """
ids = ['LC81692212019263', 'LC81691102019263']
items = Search.items_by_id(ids, collection='landsat-8-l1')
assert(len(items) == 2)
def test_get_ids_search(self):
""" Get Items by ID through normal search """
ids = ['LC81692212019263', 'LC81691102019263']
search = Search.search(ids=ids, collection='landsat-8-l1')
items = search.items()
assert(search.found() == 2)
assert(len(items) == 2)
def test_get_ids_without_collection(self):
with self.assertRaises(SatSearchError):
search = Search.search(ids=['LC80340332018034LGN00'])
items = search.items()
def test_query_bad_url(self):
with self.assertRaises(SatSearchError):
Search.query(url=os.path.join(config.API_URL, 'collections/nosuchcollection'))
def test_search_property_operator(self):
expected = {'query': {'eo:cloud_cover': {'lte': '10'}, 'collection': {'eq': 'sentinel-2-l1c'}}}
instance = Search.search(collection='sentinel-2-l1c',
property=['eo:cloud_cover<=10'])
actual = instance.kwargs
assert actual == expected
| [
"satsearch.search.Search",
"os.path.join",
"os.path.dirname",
"json.load",
"satsearch.search.Search.items_by_id",
"satsearch.search.Search.search"
] | [((208, 233), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (223, 233), False, 'import os\n'), ((1396, 1425), 'satsearch.search.Search', 'Search', ([], {'datetime': '"""2001-01-01"""'}), "(datetime='2001-01-01')\n", (1402, 1425), False, 'from satsearch.search import SatSearchError, Search\n'), ((1664, 1709), 'satsearch.search.Search', 'Search', ([], {'datetime': '"""2019-07-01"""', 'intersects': 'aoi'}), "(datetime='2019-07-01', intersects=aoi)\n", (1670, 1709), False, 'from satsearch.search import SatSearchError, Search\n'), ((2053, 2141), 'satsearch.search.Search.search', 'Search.search', ([], {'datetime': '"""2019-07-01/2019-07-07"""', 'intersects': 'aoi', 'sort': "['<datetime']"}), "(datetime='2019-07-01/2019-07-07', intersects=aoi, sort=[\n '<datetime'])\n", (2066, 2141), False, 'from satsearch.search import SatSearchError, Search\n'), ((2341, 2391), 'satsearch.search.Search.items_by_id', 'Search.items_by_id', (['ids'], {'collection': '"""landsat-8-l1"""'}), "(ids, collection='landsat-8-l1')\n", (2359, 2391), False, 'from satsearch.search import SatSearchError, Search\n'), ((2586, 2635), 'satsearch.search.Search.search', 'Search.search', ([], {'ids': 'ids', 'collection': '"""landsat-8-l1"""'}), "(ids=ids, collection='landsat-8-l1')\n", (2599, 2635), False, 'from satsearch.search import SatSearchError, Search\n'), ((3275, 3350), 'satsearch.search.Search.search', 'Search.search', ([], {'collection': '"""sentinel-2-l1c"""', 'property': "['eo:cloud_cover<=10']"}), "(collection='sentinel-2-l1c', property=['eo:cloud_cover<=10'])\n", (3288, 3350), False, 'from satsearch.search import SatSearchError, Search\n'), ((321, 359), 'os.path.join', 'os.path.join', (['cls.path', '"""*-item*.json"""'], {}), "(cls.path, '*-item*.json')\n", (333, 359), False, 'import os\n'), ((571, 615), 'satsearch.search.Search', 'Search', ([], {'datetime': "r['properties']['datetime']"}), "(datetime=r['properties']['datetime'])\n", (577, 615), False, 'from satsearch.search import SatSearchError, Search\n'), ((2852, 2896), 'satsearch.search.Search.search', 'Search.search', ([], {'ids': "['LC80340332018034LGN00']"}), "(ids=['LC80340332018034LGN00'])\n", (2865, 2896), False, 'from satsearch.search import SatSearchError, Search\n'), ((1557, 1596), 'os.path.join', 'os.path.join', (['self.path', '"""aoi1.geojson"""'], {}), "(self.path, 'aoi1.geojson')\n", (1569, 1596), False, 'import os\n'), ((1633, 1645), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1642, 1645), False, 'import json\n'), ((1946, 1985), 'os.path.join', 'os.path.join', (['self.path', '"""aoi1.geojson"""'], {}), "(self.path, 'aoi1.geojson')\n", (1958, 1985), False, 'import os\n'), ((2022, 2034), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2031, 2034), False, 'import json\n'), ((460, 472), 'json.load', 'json.load', (['f'], {}), '(f)\n', (469, 472), False, 'import json\n'), ((3044, 3104), 'os.path.join', 'os.path.join', (['config.API_URL', '"""collections/nosuchcollection"""'], {}), "(config.API_URL, 'collections/nosuchcollection')\n", (3056, 3104), False, 'import os\n')] |
import tensorflow as tf
def extract_image_patches(image_batch, patch_size,patch_stride):
patches = tf.extract_image_patches(images =image_batch,ksizes=[1,patch_size,patch_size,1],rates=[1,1,1,1],strides=[1,patch_stride,patch_stride,1],padding='VALID')
patches_shape = patches.get_shape().as_list()
return tf.reshape(patches,[-1,patch_size,patch_size,3])#, patches_shape[1]*patches_shape[2] # NOTE: assuming 3 channels
def conv_init(name,input_channels, filter_height, filter_width, num_filters, groups=1):
weights = get_scope_variable(name, 'weights', shape=[filter_height, filter_width, input_channels/groups, num_filters], trainable=False)
biases = get_scope_variable(name, 'biases', shape = [num_filters],trainable=False)
def fc_init(name, num_in, num_out):
weights = get_scope_variable(name, 'weights', shape=[num_in, num_out], trainable=False)
biases = get_scope_variable(name, 'biases', shape=[num_out], trainable=False)
def conv(x, filter_height, filter_width, num_filters, stride_y, stride_x, name, padding='SAME', relu=True):
input_channels = int(x.get_shape().as_list()[3])
convolve = lambda i, k: tf.nn.conv2d(i, k, strides = [1, stride_y, stride_x, 1], padding = padding)
weights = get_scope_variable(name, 'weights', shape=[filter_height, filter_width, input_channels, num_filters])
biases = get_scope_variable(name, 'biases', shape = [num_filters])
conv = convolve(x, weights)
bias_val = tf.reshape(tf.nn.bias_add(conv, biases), tf.shape(conv))
if relu == True:
relu = tf.nn.relu(bias_val, name = name)
return relu
else:
return bias_val
def fc(x, num_in, num_out, name, relu = True):
weights = get_scope_variable(name, 'weights', shape=[num_in, num_out])
biases = get_scope_variable(name, 'biases', shape=[num_out])
act = tf.nn.xw_plus_b(x, weights, biases, name=name)
if relu == True:
relu = tf.nn.relu(act)
return relu
else:
return act
def max_pool(x, filter_height, filter_width, stride_y, stride_x, name, padding='SAME'):
return tf.nn.max_pool(x, ksize=[1, filter_height, filter_width, 1], strides = [1, stride_y, stride_x, 1], padding = padding, name = name)
def dropout(x, keep_prob):
return tf.nn.dropout(x, keep_prob)
def get_scope_variable(scope_name, var, shape=None, initialvals=None,trainable=False):
with tf.variable_scope(scope_name,reuse=tf.AUTO_REUSE) as scope:
v = tf.get_variable(var,shape,dtype=tf.float32, initializer=initialvals,trainable=trainable)
return v
| [
"tensorflow.nn.conv2d",
"tensorflow.nn.max_pool",
"tensorflow.shape",
"tensorflow.variable_scope",
"tensorflow.nn.relu",
"tensorflow.get_variable",
"tensorflow.nn.xw_plus_b",
"tensorflow.nn.dropout",
"tensorflow.reshape",
"tensorflow.extract_image_patches",
"tensorflow.nn.bias_add"
] | [((103, 275), 'tensorflow.extract_image_patches', 'tf.extract_image_patches', ([], {'images': 'image_batch', 'ksizes': '[1, patch_size, patch_size, 1]', 'rates': '[1, 1, 1, 1]', 'strides': '[1, patch_stride, patch_stride, 1]', 'padding': '"""VALID"""'}), "(images=image_batch, ksizes=[1, patch_size,\n patch_size, 1], rates=[1, 1, 1, 1], strides=[1, patch_stride,\n patch_stride, 1], padding='VALID')\n", (127, 275), True, 'import tensorflow as tf\n'), ((311, 363), 'tensorflow.reshape', 'tf.reshape', (['patches', '[-1, patch_size, patch_size, 3]'], {}), '(patches, [-1, patch_size, patch_size, 3])\n', (321, 363), True, 'import tensorflow as tf\n'), ((1812, 1858), 'tensorflow.nn.xw_plus_b', 'tf.nn.xw_plus_b', (['x', 'weights', 'biases'], {'name': 'name'}), '(x, weights, biases, name=name)\n', (1827, 1858), True, 'import tensorflow as tf\n'), ((2043, 2171), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['x'], {'ksize': '[1, filter_height, filter_width, 1]', 'strides': '[1, stride_y, stride_x, 1]', 'padding': 'padding', 'name': 'name'}), '(x, ksize=[1, filter_height, filter_width, 1], strides=[1,\n stride_y, stride_x, 1], padding=padding, name=name)\n', (2057, 2171), True, 'import tensorflow as tf\n'), ((2212, 2239), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['x', 'keep_prob'], {}), '(x, keep_prob)\n', (2225, 2239), True, 'import tensorflow as tf\n'), ((1134, 1205), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['i', 'k'], {'strides': '[1, stride_y, stride_x, 1]', 'padding': 'padding'}), '(i, k, strides=[1, stride_y, stride_x, 1], padding=padding)\n', (1146, 1205), True, 'import tensorflow as tf\n'), ((1457, 1485), 'tensorflow.nn.bias_add', 'tf.nn.bias_add', (['conv', 'biases'], {}), '(conv, biases)\n', (1471, 1485), True, 'import tensorflow as tf\n'), ((1487, 1501), 'tensorflow.shape', 'tf.shape', (['conv'], {}), '(conv)\n', (1495, 1501), True, 'import tensorflow as tf\n'), ((1533, 1564), 'tensorflow.nn.relu', 'tf.nn.relu', (['bias_val'], {'name': 'name'}), '(bias_val, name=name)\n', (1543, 1564), True, 'import tensorflow as tf\n'), ((1888, 1903), 'tensorflow.nn.relu', 'tf.nn.relu', (['act'], {}), '(act)\n', (1898, 1903), True, 'import tensorflow as tf\n'), ((2335, 2385), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope_name'], {'reuse': 'tf.AUTO_REUSE'}), '(scope_name, reuse=tf.AUTO_REUSE)\n', (2352, 2385), True, 'import tensorflow as tf\n'), ((2401, 2496), 'tensorflow.get_variable', 'tf.get_variable', (['var', 'shape'], {'dtype': 'tf.float32', 'initializer': 'initialvals', 'trainable': 'trainable'}), '(var, shape, dtype=tf.float32, initializer=initialvals,\n trainable=trainable)\n', (2416, 2496), True, 'import tensorflow as tf\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 5 06:34:04 2015
@author: tanay
"""
from lasagne.layers import InputLayer, DropoutLayer, DenseLayer
from lasagne.updates import nesterov_momentum
from lasagne.objectives import binary_crossentropy
from nolearn.lasagne import NeuralNet
import theano
from theano import tensor as T
from theano.tensor.nnet import sigmoid
from sklearn import metrics
from sklearn.utils import shuffle
import numpy as np
learning_rate = theano.shared(np.float32(0.1))
input_size=Xtrh.shape
class AdjustVariable(object):
def __init__(self, variable, target, half_life=20):
self.variable = variable
self.target = target
self.half_life = half_life
def __call__(self, nn, train_history):
delta = self.variable.get_value() - self.target
delta /= 2**(1.0/self.half_life)
self.variable.set_value(np.float32(self.target + delta))
net = NeuralNet(
layers=[
('input', InputLayer),
('hidden1', DenseLayer),
('dropout1', DropoutLayer),
('hidden2', DenseLayer),
('dropout2', DropoutLayer),
('output', DenseLayer),
],
# layer parameters:
input_shape=(None, input_size),
hidden1_num_units=400,
dropout1_p=0.4,
hidden2_num_units=200,
dropout2_p=0.4,
output_nonlinearity=sigmoid,
output_num_units=4,
# optimization method:
update=nesterov_momentum,
update_learning_rate=learning_rate,
update_momentum=0.899,
# Decay the learning rate
on_epoch_finished=[
AdjustVariable(learning_rate, target=0, half_life=4),
],
# This is silly, but we don't want a stratified K-Fold here
# To compensate we need to pass in the y_tensor_type and the loss.
regression=True,
y_tensor_type = T.imatrix,
objective_loss_function = binary_crossentropy,
max_epochs=75,
eval_size=0.1,
verbose=1,
)
X, y = shuffle(Xtrh, y, random_state=123)
net.fit(X, y)
_, X_valid, _, y_valid = net.train_test_split(X, y, net.eval_size)
probas = net.predict_proba(X_valid)[:,0]
print("ROC score", metrics.roc_auc_score(y_valid, probas))
| [
"sklearn.utils.shuffle",
"numpy.float32",
"sklearn.metrics.roc_auc_score"
] | [((1809, 1843), 'sklearn.utils.shuffle', 'shuffle', (['Xtrh', 'y'], {'random_state': '(123)'}), '(Xtrh, y, random_state=123)\n', (1816, 1843), False, 'from sklearn.utils import shuffle\n'), ((479, 494), 'numpy.float32', 'np.float32', (['(0.1)'], {}), '(0.1)\n', (489, 494), True, 'import numpy as np\n'), ((1986, 2024), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['y_valid', 'probas'], {}), '(y_valid, probas)\n', (2007, 2024), False, 'from sklearn import metrics\n'), ((875, 906), 'numpy.float32', 'np.float32', (['(self.target + delta)'], {}), '(self.target + delta)\n', (885, 906), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
""" Train the Boston house prices model on your local machine.
"""
import pandas as pd
from ml2p.core import LocalEnv
import model
def train(env):
""" Train and save the model locally. """
trainer = model.BostonModel().trainer(env)
trainer.train()
def predict(env):
""" Load a model and make predictions locally. """
predictor = model.BostonModel().predictor(env)
predictor.setup()
data = pd.read_csv("house-prices.csv")
house = dict(data.iloc[0])
del house["target"]
print("Making a prediction for:")
print(house)
result = predictor.invoke(house)
print("Prediction:")
print(result)
if __name__ == "__main__":
env = LocalEnv(".", "ml2p.yml")
train(env)
predict(env)
| [
"ml2p.core.LocalEnv",
"model.BostonModel",
"pandas.read_csv"
] | [((447, 478), 'pandas.read_csv', 'pd.read_csv', (['"""house-prices.csv"""'], {}), "('house-prices.csv')\n", (458, 478), True, 'import pandas as pd\n'), ((708, 733), 'ml2p.core.LocalEnv', 'LocalEnv', (['"""."""', '"""ml2p.yml"""'], {}), "('.', 'ml2p.yml')\n", (716, 733), False, 'from ml2p.core import LocalEnv\n'), ((235, 254), 'model.BostonModel', 'model.BostonModel', ([], {}), '()\n', (252, 254), False, 'import model\n'), ((379, 398), 'model.BostonModel', 'model.BostonModel', ([], {}), '()\n', (396, 398), False, 'import model\n')] |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/01a_datasets_download.ipynb (unless otherwise specified).
__all__ = ['get_cifar10', 'get_oxford_102_flowers', 'get_cub_200_2011']
# Internal Cell
import glob
import json
from pathlib import Path
import os
import subprocess
import tarfile
import urllib
import zlib
# Internal Cell
def _download_url(url, root, filename=None):
"""Download a file from a url and place it in root.
Args:
url (str): URL to download file from
root (str): Directory to place downloaded file in
filename (str, optional): Name to save the file under. If None, use the basename of the URL
"""
root = os.path.expanduser(root)
if not filename:
filename = os.path.basename(url)
fpath = os.path.join(root, filename)
os.makedirs(root, exist_ok=True)
if not os.path.isfile(fpath):
try:
print('Downloading ' + url + ' to ' + fpath)
urllib.request.urlretrieve(url, fpath)
except (urllib.error.URLError, IOError) as e:
if url[:5] == 'https':
url = url.replace('https:', 'http:')
print('Failed download. Trying https -> http instead.'
' Downloading ' + url + ' to ' + fpath)
urllib.request.urlretrieve(url, fpath)
else:
print(f'File {filename} already exists, skip download.')
# Internal Cell
def _extract_tar(tar_path, output_dir):
try:
print('Extracting...')
with tarfile.open(tar_path) as tar:
tar.extractall(output_dir)
except (tarfile.TarError, IOError, zlib.error) as e:
print('Failed to extract!', e)
# Cell
def get_cifar10(output_dir):
output_dir = Path(output_dir)
dataset_dir = output_dir / 'cifar10'
_download_url(url='https://s3.amazonaws.com/fast-ai-imageclas/cifar10.tgz', root=output_dir)
if not dataset_dir.is_dir():
_extract_tar(output_dir / 'cifar10.tgz', output_dir)
else:
print(f'Directory {dataset_dir} already exists, skip extraction.')
print('Generating train/test data..')
imdir_train = dataset_dir / 'train'
imdir_test = dataset_dir / 'test'
# split train/test
train = [Path(p) for p in glob.glob(f'{imdir_train}/*/*')]
test = [Path(p) for p in glob.glob(f'{imdir_test}/*/*')]
# generate data for annotations.json
# {'image-file.jpg': ['label1.jpg']}
annotations_train = dict((str(p), [f'{p.parts[-2]}.jpg']) for p in train)
annotations_test = dict((str(p), [f'{p.parts[-2]}.jpg']) for p in test)
train_path = dataset_dir / 'annotations_train.json'
test_path = dataset_dir / 'annotations_test.json'
with open(train_path, 'w') as f:
json.dump(annotations_train, f)
with open(test_path, 'w') as f:
json.dump(annotations_test, f)
print("Done")
return train_path, test_path
# Cell
def get_oxford_102_flowers(output_dir):
output_dir = Path(output_dir)
dataset_dir = output_dir / 'oxford-102-flowers'
_download_url(url='https://s3.amazonaws.com/fast-ai-imageclas/oxford-102-flowers.tgz', root=output_dir)
if not dataset_dir.is_dir():
_extract_tar(output_dir / 'oxford-102-flowers.tgz', output_dir)
else:
print(f'Directory {dataset_dir} already exists, skip extraction.')
print('Generating train/test data..')
with open(dataset_dir / 'train.txt', 'r') as f:
annotations_train = dict(tuple(line.split()) for line in f)
annotations_train = {str(dataset_dir / k): [v+'.jpg'] for k, v in annotations_train.items()}
with open(dataset_dir / 'test.txt', 'r') as f:
annotations_test = dict(tuple(line.split()) for line in f)
annotations_test = {str(dataset_dir / k): [v+'.jpg'] for k, v in annotations_test.items()}
train_path = dataset_dir / 'annotations_train.json'
test_path = dataset_dir / 'annotations_test.json'
with open(train_path, 'w') as f:
json.dump(annotations_train, f)
with open(test_path, 'w') as f:
json.dump(annotations_test, f)
print("Done")
return train_path, test_path
# Cell
def get_cub_200_2011(output_dir):
output_dir = Path(output_dir)
dataset_dir = output_dir / 'CUB_200_2011'
_download_url(url='https://s3.amazonaws.com/fast-ai-imageclas/CUB_200_2011.tgz', root=output_dir)
if not dataset_dir.is_dir():
_extract_tar(output_dir / 'CUB_200_2011.tgz', output_dir)
else:
print(f'Directory {dataset_dir} already exists, skip extraction.')
print('Generating train/test data..')
with open(dataset_dir / 'images.txt','r') as f:
image_id_map = dict(tuple(line.split()) for line in f)
with open(dataset_dir / 'classes.txt','r') as f:
class_id_map = dict(tuple(line.split()) for line in f)
with open(dataset_dir / 'train_test_split.txt','r') as f:
splitter = dict(tuple(line.split()) for line in f)
# image ids for test/train
train_k = [k for k, v in splitter.items() if v == '0']
test_k = [k for k, v in splitter.items() if v == '1']
with open(dataset_dir / 'image_class_labels.txt','r') as f:
anno_ = dict(tuple(line.split()) for line in f)
annotations_train = {str(dataset_dir / 'images' / image_id_map[k]): [class_id_map[v]+'.jpg'] for k, v in anno_.items() if k in train_k}
annotations_test = {str(dataset_dir / 'images' / image_id_map[k]): [class_id_map[v]+'.jpg'] for k, v in anno_.items() if k in test_k}
train_path = dataset_dir / 'annotations_train.json'
test_path = dataset_dir / 'annotations_test.json'
with open(train_path, 'w') as f:
json.dump(annotations_train, f)
with open(test_path, 'w') as f:
json.dump(annotations_test, f)
print("Done")
return train_path, test_path | [
"tarfile.open",
"os.makedirs",
"pathlib.Path",
"urllib.request.urlretrieve",
"json.dump",
"os.path.join",
"os.path.isfile",
"glob.glob",
"os.path.basename",
"os.path.expanduser"
] | [((666, 690), 'os.path.expanduser', 'os.path.expanduser', (['root'], {}), '(root)\n', (684, 690), False, 'import os\n'), ((765, 793), 'os.path.join', 'os.path.join', (['root', 'filename'], {}), '(root, filename)\n', (777, 793), False, 'import os\n'), ((798, 830), 'os.makedirs', 'os.makedirs', (['root'], {'exist_ok': '(True)'}), '(root, exist_ok=True)\n', (809, 830), False, 'import os\n'), ((1725, 1741), 'pathlib.Path', 'Path', (['output_dir'], {}), '(output_dir)\n', (1729, 1741), False, 'from pathlib import Path\n'), ((2948, 2964), 'pathlib.Path', 'Path', (['output_dir'], {}), '(output_dir)\n', (2952, 2964), False, 'from pathlib import Path\n'), ((4168, 4184), 'pathlib.Path', 'Path', (['output_dir'], {}), '(output_dir)\n', (4172, 4184), False, 'from pathlib import Path\n'), ((731, 752), 'os.path.basename', 'os.path.basename', (['url'], {}), '(url)\n', (747, 752), False, 'import os\n'), ((843, 864), 'os.path.isfile', 'os.path.isfile', (['fpath'], {}), '(fpath)\n', (857, 864), False, 'import os\n'), ((2219, 2226), 'pathlib.Path', 'Path', (['p'], {}), '(p)\n', (2223, 2226), False, 'from pathlib import Path\n'), ((2281, 2288), 'pathlib.Path', 'Path', (['p'], {}), '(p)\n', (2285, 2288), False, 'from pathlib import Path\n'), ((2724, 2755), 'json.dump', 'json.dump', (['annotations_train', 'f'], {}), '(annotations_train, f)\n', (2733, 2755), False, 'import json\n'), ((2801, 2831), 'json.dump', 'json.dump', (['annotations_test', 'f'], {}), '(annotations_test, f)\n', (2810, 2831), False, 'import json\n'), ((3950, 3981), 'json.dump', 'json.dump', (['annotations_train', 'f'], {}), '(annotations_train, f)\n', (3959, 3981), False, 'import json\n'), ((4027, 4057), 'json.dump', 'json.dump', (['annotations_test', 'f'], {}), '(annotations_test, f)\n', (4036, 4057), False, 'import json\n'), ((5624, 5655), 'json.dump', 'json.dump', (['annotations_train', 'f'], {}), '(annotations_train, f)\n', (5633, 5655), False, 'import json\n'), ((5701, 5731), 'json.dump', 'json.dump', (['annotations_test', 'f'], {}), '(annotations_test, f)\n', (5710, 5731), False, 'import json\n'), ((948, 986), 'urllib.request.urlretrieve', 'urllib.request.urlretrieve', (['url', 'fpath'], {}), '(url, fpath)\n', (974, 986), False, 'import urllib\n'), ((1505, 1527), 'tarfile.open', 'tarfile.open', (['tar_path'], {}), '(tar_path)\n', (1517, 1527), False, 'import tarfile\n'), ((2236, 2267), 'glob.glob', 'glob.glob', (['f"""{imdir_train}/*/*"""'], {}), "(f'{imdir_train}/*/*')\n", (2245, 2267), False, 'import glob\n'), ((2298, 2328), 'glob.glob', 'glob.glob', (['f"""{imdir_test}/*/*"""'], {}), "(f'{imdir_test}/*/*')\n", (2307, 2328), False, 'import glob\n'), ((1280, 1318), 'urllib.request.urlretrieve', 'urllib.request.urlretrieve', (['url', 'fpath'], {}), '(url, fpath)\n', (1306, 1318), False, 'import urllib\n')] |
#!/usr/bin/env python
# coding: utf-8
#Project name: Excel --> netCDF
#Description: It receives an excel file with a predefined format and returns the equivalent file in netCDF format.
#Programmers: <NAME>
#Date: 07-09-2020
import pandas as pd
import xarray
import scipy
print("Enter the exact name of the workbook. Please do include the file extension (e.g, .xlsx, .xls, etc):")
workbook_name = input()
print("\n")
print("Enter the exact name of the sheet within this workbook that should be converted:")
excel_sheet_name = input()
data_file = ("./data/input/"+workbook_name).strip()
# choose sheet
sheet_name= excel_sheet_name.strip()
# read excel file
df = pd.read_excel(data_file,
sheet_name=sheet_name,
index_col=[0],
na_values=['b.d.'])
# take description from top left cell
description = df.index.names[0]
# use "SAMPLE NAME" as index header
df.index = df.index.set_names(df.index[3])
# create mask to be able to distinguish difference in the column structure
mask = df.iloc[3,].isnull().values
# gather column names from two different rows
column_names = list(df.iloc[3,~mask].values) + list(df.iloc[0,mask].values)
column_names = [s.replace('/', ' ') for s in column_names]
df.columns = column_names
df.loc["flag"] = ["1.{}".format(i+1) if j == False else "2.{}".format(i+11) for i,j in enumerate(mask)]
# convert dataframe to xarray
xr = df.iloc[5:,].to_xarray()
# global attributes
xr.attrs = {'Conventions': 'CF-1.6', 'Title': sheet_name, 'Description': description}
# add variable attributes
units = df.iloc[2,mask]
method_codes = df.iloc[1,mask]
for i, col in enumerate(df.columns[mask]):
getattr(xr, col).attrs = {'units': units[i], 'comment': 'METHOD CODE: {}'.format(method_codes[i])}
comments = df.iloc[4,~mask]
for i, col in enumerate(df.columns[~mask]):
getattr(xr, col).attrs = {'comment': comments[i]}
# write xarray to netcdf file
xr.to_netcdf('./data/output/{}.nc'.format('-'.join((workbook_name.replace(".","")+" "+excel_sheet_name).split())))
| [
"pandas.read_excel"
] | [((672, 759), 'pandas.read_excel', 'pd.read_excel', (['data_file'], {'sheet_name': 'sheet_name', 'index_col': '[0]', 'na_values': "['b.d.']"}), "(data_file, sheet_name=sheet_name, index_col=[0], na_values=[\n 'b.d.'])\n", (685, 759), True, 'import pandas as pd\n')] |
"""Module defining DiagGGNPermute."""
from backpack.core.derivatives.permute import PermuteDerivatives
from backpack.extensions.secondorder.diag_ggn.diag_ggn_base import DiagGGNBaseModule
class DiagGGNPermute(DiagGGNBaseModule):
"""DiagGGN extension of Permute."""
def __init__(self):
"""Initialize."""
super().__init__(derivatives=PermuteDerivatives())
| [
"backpack.core.derivatives.permute.PermuteDerivatives"
] | [((359, 379), 'backpack.core.derivatives.permute.PermuteDerivatives', 'PermuteDerivatives', ([], {}), '()\n', (377, 379), False, 'from backpack.core.derivatives.permute import PermuteDerivatives\n')] |
import sys
import numpy as np
from sklearn.externals import joblib
sys.path.append("common")
from train_classifier import *
staring_verb_extractor = StartingVerbExtractor()
verb_count_extractor = VerbCountExtractor()
starting_modal_extractor = StartingModalExtractor()
noun_count_extractor = NounCountExtractor()
def test_load_data(file_name):
return load_data(file_name)
def test_stating_verb_extract(text):
print(staring_verb_extractor.starting_verb(text))
def test_transform(X):
print(staring_verb_extractor.transform(X))
def test_tokenize(text):
print(tokenize_text(text))
def test_total_verb_counts(text):
print(verb_count_extractor.count_verbs(text))
def test_stating_modals(text):
print(starting_modal_extractor.starting_modals(text))
def test_total_noun_counts(text):
print(noun_count_extractor.count_nouns(text))
def test_evaluate_model(X, Y, col_names, model_path='./models/classifier.pkl'):
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
model = joblib.load(model_path)
evaluate_model(model, X_test, Y_test, col_names)
if __name__ == "__main__":
debug_data = ['.', './data/DisasterResponse.db', './models/classifier.pkl']
X, Y, col_names = load_data(debug_data[1])
# for text in X[:100].values:
# test_tokenize(text)
# for text in texts:
# test_stating_verb_extract(text)
#
# test_transform(X)
# for text in X[:100].values:
# test_total_verb_counts(text)
#
# for text in X[:100].values:
# test_total_noun_counts(text)
#
# for text in X[:100].values:
# test_stating_modals(text)
test_evaluate_model(X, Y, col_names)
| [
"sklearn.externals.joblib.load",
"sys.path.append"
] | [((68, 93), 'sys.path.append', 'sys.path.append', (['"""common"""'], {}), "('common')\n", (83, 93), False, 'import sys\n'), ((1037, 1060), 'sklearn.externals.joblib.load', 'joblib.load', (['model_path'], {}), '(model_path)\n', (1048, 1060), False, 'from sklearn.externals import joblib\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 11 10:44:44 2020.
@author: powel
"""
import random
from random import randint
import numpy as np
from mazes import RandomMaze, PrimMaze, KruskalMaze, RecursiveDivisionMaze, MazeBase
from percolation import check_percolation
class Maze:
def __init__(self):
self.maze = None
def make_maze(self, n_x: int, n_y: int, maze_type: str = 'Prim') -> np.ndarray:
if maze_type == 'Random':
maze_class = RandomMaze
elif maze_type == 'Prim':
maze_class = PrimMaze
elif maze_type == 'Kruskal':
maze_class = KruskalMaze
elif maze_type == 'Recursive':
maze_class = RecursiveDivisionMaze
else:
raise ValueError("Invalid maze_type")
maze = self._make_check_maze(n_x, n_y, maze_class)
return maze
def _make_check_maze(self, n_x: int, n_y: int, maze_class: MazeBase) -> np.ndarray:
maze = maze_class().make_maze(n_x, n_y)
maze = self._set_entrance(maze)
maze = self._set_exit(maze)
while not check_percolation(maze):
maze = maze_class().make_maze(n_x, n_y)
maze = self._set_entrance(maze)
maze = self._set_exit(maze)
return maze
@staticmethod
def _set_entrance(maze: np.ndarray) -> np.ndarray:
while True:
x, y = randint(1, maze.shape[0] - 1), 0
if maze[x, y + 1] == 0:
break
maze[x, y] = 2
return maze
@staticmethod
def _set_exit(maze: np.ndarray) -> np.ndarray:
while True:
x, y = randint(1, maze.shape[0] - 1), maze.shape[1] - 1
if maze[x, y - 1] == 0:
break
maze[x, y] = 3
return maze
if __name__ == "__main__":
random.seed(1)
N = 10
maze = Maze().make_maze(N, N, maze_type='Recursive')
print(maze.__repr__())
| [
"random.randint",
"random.seed",
"percolation.check_percolation"
] | [((1839, 1853), 'random.seed', 'random.seed', (['(1)'], {}), '(1)\n', (1850, 1853), False, 'import random\n'), ((1119, 1142), 'percolation.check_percolation', 'check_percolation', (['maze'], {}), '(maze)\n', (1136, 1142), False, 'from percolation import check_percolation\n'), ((1413, 1442), 'random.randint', 'randint', (['(1)', '(maze.shape[0] - 1)'], {}), '(1, maze.shape[0] - 1)\n', (1420, 1442), False, 'from random import randint\n'), ((1656, 1685), 'random.randint', 'randint', (['(1)', '(maze.shape[0] - 1)'], {}), '(1, maze.shape[0] - 1)\n', (1663, 1685), False, 'from random import randint\n')] |
import json
import os
from pathlib import Path
from subprocess import run
import pytest
from examples import verify_and_test_examples
from git import Repo
import cruft
from cruft import exceptions
from cruft._commands.utils import get_cruft_file
def test_invalid_cookiecutter_repo(tmpdir):
with pytest.raises(exceptions.InvalidCookiecutterRepository):
cruft.create("DNE", Path(tmpdir))
def test_no_cookiecutter_dir(tmpdir):
with pytest.raises(exceptions.UnableToFindCookiecutterTemplate):
cruft.create("https://github.com/samj1912/cookiecutter-test", Path(tmpdir))
def test_create_examples(tmpdir):
tmpdir.chdir()
verify_and_test_examples(cruft.create)
def test_check_examples(tmpdir, project_dir):
tmpdir.chdir()
with pytest.raises(exceptions.NoCruftFound):
verify_and_test_examples(cruft.check)
os.chdir(project_dir)
verify_and_test_examples(cruft.check)
def test_update_and_check_real_repo(tmpdir):
tmpdir.chdir()
repo = Repo.clone_from("https://github.com/timothycrosley/cruft", str(tmpdir))
repo.head.reset(commit="86a6e6beda8095690414ff7652c15b7ae36e6128", working_tree=True)
with open(os.path.join(tmpdir, ".cruft.json")) as cruft_file:
cruft_state = json.load(cruft_file)
cruft_state["skip"] = ["cruft/__init__.py", "tests"]
with open(os.path.join(tmpdir, ".cruft.json"), "w") as cruft_file:
json.dump(cruft_state, cruft_file)
repo_dir = Path(tmpdir)
assert not cruft.check(repo_dir)
# Update should fail since we have an unclean git repo
assert not cruft.update(repo_dir)
# Commit the changes so that the repo is clean
run(
[
"git",
"-c",
"user.name='test'",
"-c",
"user.email='<EMAIL>'",
"commit",
"-am",
"test",
],
cwd=repo_dir,
)
assert cruft.update(repo_dir, skip_apply_ask=True)
def test_relative_repo_check(tmpdir):
tmpdir.chdir()
temp_dir = Path(tmpdir)
Repo.clone_from("https://github.com/samj1912/cookiecutter-test", str(temp_dir / "cc"))
project_dir = cruft.create("./cc", output_dir=str(temp_dir / "output"), directory="dir")
assert cruft.check(project_dir)
def test_update_examples(project_dir, tmpdir):
tmpdir.chdir()
with pytest.raises(exceptions.NoCruftFound):
verify_and_test_examples(cruft.update)
os.chdir(project_dir)
verify_and_test_examples(cruft.update)
def test_link_examples(project_dir, tmpdir):
os.chdir(project_dir)
with pytest.raises(exceptions.CruftAlreadyPresent):
verify_and_test_examples(cruft.link)
tmpdir.chdir()
Repo.clone_from("https://github.com/timothycrosley/cruft", str(tmpdir))
os.remove(os.path.join(tmpdir, ".cruft.json"))
verify_and_test_examples(cruft.link)
def test_directory_and_checkout(tmpdir):
output_path = cruft.create(
"https://github.com/samj1912/cookiecutter-test",
output_dir=Path(tmpdir),
directory="dir",
checkout="initial",
)
cruft_file = get_cruft_file(output_path)
assert cruft_file.exists()
assert cruft.check(output_path, checkout="initial")
assert not cruft.check(output_path, checkout="updated")
assert cruft.update(output_path, checkout="updated")
assert cruft.check(output_path, checkout="updated")
cruft_file.unlink()
assert not cruft_file.exists()
assert cruft.link(
"https://github.com/samj1912/cookiecutter-test",
project_dir=output_path,
directory="dir",
checkout="updated",
)
assert cruft.check(output_path, checkout="updated")
# Add checks for strictness where master is an older
# version than updated
assert not cruft.check(output_path, strict=True)
assert cruft.check(output_path, strict=False)
| [
"examples.verify_and_test_examples",
"pathlib.Path",
"subprocess.run",
"cruft._commands.utils.get_cruft_file",
"os.path.join",
"cruft.check",
"os.chdir",
"pytest.raises",
"json.load",
"cruft.link",
"cruft.update",
"json.dump"
] | [((654, 692), 'examples.verify_and_test_examples', 'verify_and_test_examples', (['cruft.create'], {}), '(cruft.create)\n', (678, 692), False, 'from examples import verify_and_test_examples\n'), ((860, 881), 'os.chdir', 'os.chdir', (['project_dir'], {}), '(project_dir)\n', (868, 881), False, 'import os\n'), ((886, 923), 'examples.verify_and_test_examples', 'verify_and_test_examples', (['cruft.check'], {}), '(cruft.check)\n', (910, 923), False, 'from examples import verify_and_test_examples\n'), ((1463, 1475), 'pathlib.Path', 'Path', (['tmpdir'], {}), '(tmpdir)\n', (1467, 1475), False, 'from pathlib import Path\n'), ((1665, 1776), 'subprocess.run', 'run', (['[\'git\', \'-c\', "user.name=\'test\'", \'-c\', "user.email=\'<EMAIL>\'", \'commit\',\n \'-am\', \'test\']'], {'cwd': 'repo_dir'}), '([\'git\', \'-c\', "user.name=\'test\'", \'-c\', "user.email=\'<EMAIL>\'",\n \'commit\', \'-am\', \'test\'], cwd=repo_dir)\n', (1668, 1776), False, 'from subprocess import run\n'), ((1914, 1957), 'cruft.update', 'cruft.update', (['repo_dir'], {'skip_apply_ask': '(True)'}), '(repo_dir, skip_apply_ask=True)\n', (1926, 1957), False, 'import cruft\n'), ((2032, 2044), 'pathlib.Path', 'Path', (['tmpdir'], {}), '(tmpdir)\n', (2036, 2044), False, 'from pathlib import Path\n'), ((2240, 2264), 'cruft.check', 'cruft.check', (['project_dir'], {}), '(project_dir)\n', (2251, 2264), False, 'import cruft\n'), ((2434, 2455), 'os.chdir', 'os.chdir', (['project_dir'], {}), '(project_dir)\n', (2442, 2455), False, 'import os\n'), ((2460, 2498), 'examples.verify_and_test_examples', 'verify_and_test_examples', (['cruft.update'], {}), '(cruft.update)\n', (2484, 2498), False, 'from examples import verify_and_test_examples\n'), ((2550, 2571), 'os.chdir', 'os.chdir', (['project_dir'], {}), '(project_dir)\n', (2558, 2571), False, 'import os\n'), ((2824, 2860), 'examples.verify_and_test_examples', 'verify_and_test_examples', (['cruft.link'], {}), '(cruft.link)\n', (2848, 2860), False, 'from examples import verify_and_test_examples\n'), ((3102, 3129), 'cruft._commands.utils.get_cruft_file', 'get_cruft_file', (['output_path'], {}), '(output_path)\n', (3116, 3129), False, 'from cruft._commands.utils import get_cruft_file\n'), ((3172, 3216), 'cruft.check', 'cruft.check', (['output_path'], {'checkout': '"""initial"""'}), "(output_path, checkout='initial')\n", (3183, 3216), False, 'import cruft\n'), ((3288, 3333), 'cruft.update', 'cruft.update', (['output_path'], {'checkout': '"""updated"""'}), "(output_path, checkout='updated')\n", (3300, 3333), False, 'import cruft\n'), ((3345, 3389), 'cruft.check', 'cruft.check', (['output_path'], {'checkout': '"""updated"""'}), "(output_path, checkout='updated')\n", (3356, 3389), False, 'import cruft\n'), ((3460, 3586), 'cruft.link', 'cruft.link', (['"""https://github.com/samj1912/cookiecutter-test"""'], {'project_dir': 'output_path', 'directory': '"""dir"""', 'checkout': '"""updated"""'}), "('https://github.com/samj1912/cookiecutter-test', project_dir=\n output_path, directory='dir', checkout='updated')\n", (3470, 3586), False, 'import cruft\n'), ((3632, 3676), 'cruft.check', 'cruft.check', (['output_path'], {'checkout': '"""updated"""'}), "(output_path, checkout='updated')\n", (3643, 3676), False, 'import cruft\n'), ((3825, 3863), 'cruft.check', 'cruft.check', (['output_path'], {'strict': '(False)'}), '(output_path, strict=False)\n', (3836, 3863), False, 'import cruft\n'), ((303, 358), 'pytest.raises', 'pytest.raises', (['exceptions.InvalidCookiecutterRepository'], {}), '(exceptions.InvalidCookiecutterRepository)\n', (316, 358), False, 'import pytest\n'), ((451, 509), 'pytest.raises', 'pytest.raises', (['exceptions.UnableToFindCookiecutterTemplate'], {}), '(exceptions.UnableToFindCookiecutterTemplate)\n', (464, 509), False, 'import pytest\n'), ((769, 807), 'pytest.raises', 'pytest.raises', (['exceptions.NoCruftFound'], {}), '(exceptions.NoCruftFound)\n', (782, 807), False, 'import pytest\n'), ((817, 854), 'examples.verify_and_test_examples', 'verify_and_test_examples', (['cruft.check'], {}), '(cruft.check)\n', (841, 854), False, 'from examples import verify_and_test_examples\n'), ((1251, 1272), 'json.load', 'json.load', (['cruft_file'], {}), '(cruft_file)\n', (1260, 1272), False, 'import json\n'), ((1413, 1447), 'json.dump', 'json.dump', (['cruft_state', 'cruft_file'], {}), '(cruft_state, cruft_file)\n', (1422, 1447), False, 'import json\n'), ((1491, 1512), 'cruft.check', 'cruft.check', (['repo_dir'], {}), '(repo_dir)\n', (1502, 1512), False, 'import cruft\n'), ((1587, 1609), 'cruft.update', 'cruft.update', (['repo_dir'], {}), '(repo_dir)\n', (1599, 1609), False, 'import cruft\n'), ((2342, 2380), 'pytest.raises', 'pytest.raises', (['exceptions.NoCruftFound'], {}), '(exceptions.NoCruftFound)\n', (2355, 2380), False, 'import pytest\n'), ((2390, 2428), 'examples.verify_and_test_examples', 'verify_and_test_examples', (['cruft.update'], {}), '(cruft.update)\n', (2414, 2428), False, 'from examples import verify_and_test_examples\n'), ((2581, 2626), 'pytest.raises', 'pytest.raises', (['exceptions.CruftAlreadyPresent'], {}), '(exceptions.CruftAlreadyPresent)\n', (2594, 2626), False, 'import pytest\n'), ((2636, 2672), 'examples.verify_and_test_examples', 'verify_and_test_examples', (['cruft.link'], {}), '(cruft.link)\n', (2660, 2672), False, 'from examples import verify_and_test_examples\n'), ((2783, 2818), 'os.path.join', 'os.path.join', (['tmpdir', '""".cruft.json"""'], {}), "(tmpdir, '.cruft.json')\n", (2795, 2818), False, 'import os\n'), ((3232, 3276), 'cruft.check', 'cruft.check', (['output_path'], {'checkout': '"""updated"""'}), "(output_path, checkout='updated')\n", (3243, 3276), False, 'import cruft\n'), ((3776, 3813), 'cruft.check', 'cruft.check', (['output_path'], {'strict': '(True)'}), '(output_path, strict=True)\n', (3787, 3813), False, 'import cruft\n'), ((388, 400), 'pathlib.Path', 'Path', (['tmpdir'], {}), '(tmpdir)\n', (392, 400), False, 'from pathlib import Path\n'), ((581, 593), 'pathlib.Path', 'Path', (['tmpdir'], {}), '(tmpdir)\n', (585, 593), False, 'from pathlib import Path\n'), ((1177, 1212), 'os.path.join', 'os.path.join', (['tmpdir', '""".cruft.json"""'], {}), "(tmpdir, '.cruft.json')\n", (1189, 1212), False, 'import os\n'), ((1348, 1383), 'os.path.join', 'os.path.join', (['tmpdir', '""".cruft.json"""'], {}), "(tmpdir, '.cruft.json')\n", (1360, 1383), False, 'import os\n'), ((3012, 3024), 'pathlib.Path', 'Path', (['tmpdir'], {}), '(tmpdir)\n', (3016, 3024), False, 'from pathlib import Path\n')] |
"""
Helper for loading a ``Trading History`` dataset
"""
import json
import zlib
import pandas as pd
import analysis_engine.consts as ae_consts
import spylunking.log.setup_logging as log_utils
log = log_utils.build_colorized_logger(name=__name__)
def prepare_history_dataset(
data,
compress=False,
encoding='utf-8',
convert_to_dict=False,
include_keys=None,
ignore_keys=None,
convert_to_dates=None,
verbose=False):
"""prepare_history_dataset
Load a ``Trading History`` dataset into a dictionary
with a ``pd.DataFrame`` for the trading history record
list
:param data: string holding contents of a ``Trading History``
from a file, s3 key or redis-key
:param compress: optional - boolean flag for decompressing
the contents of the ``data`` if necessary
(default is ``False`` and algorithms
use ``zlib`` for compression)
:param convert_to_dict: optional - bool for s3 use ``False``
and for files use ``True``
:param encoding: optional - string for data encoding
:param include_keys: optional - list of string keys
to include before from the dataset
.. note:: tickers are automatically included in the ``pd.DataFrame``
:param ignore_keys: optional - list of string keys
to remove before building the ``pd.DataFrame``
:param convert_to_dates: optional - list of string keys
to convert to datetime before building the ``pd.DataFrame``
:param verbose: optional - bool show the logs
(default is ``False``)
"""
if verbose:
log.debug('start')
use_data = None
parsed_data = None
data_as_dict = None
if compress:
if verbose:
log.debug('decompressing')
parsed_data = zlib.decompress(
data).decode(
encoding)
else:
parsed_data = data
if not parsed_data:
log.error('failed parsing')
return None
if verbose:
log.debug('loading as dict')
use_data = {}
if convert_to_dict:
try:
data_as_dict = json.loads(parsed_data)
except Exception as e:
if (
'the JSON object must be str, bytes or '
'bytearray, not') in str(e):
log.critical(
f'failed decoding json for string - double '
f'compression for history dataset found ex={e}')
data_as_dict = parsed_data
else:
data_as_dict = parsed_data
if len(data_as_dict) == 0:
log.error(
'empty trading history dictionary')
return use_data
convert_these_date_keys = [
'date',
'minute',
'exp_date'
]
use_include_keys = [
'tickers',
'version',
'last_trade_data',
'algo_config_dict',
'algo_name',
'created'
]
if include_keys:
use_include_keys = include_keys
use_ignore_keys = []
if ignore_keys:
use_ignore_keys = ignore_keys
for k in data_as_dict:
if k in use_include_keys:
use_data[k] = data_as_dict[k]
all_records = []
num_records = 0
for ticker in data_as_dict['tickers']:
if ticker not in use_data:
use_data[ticker] = []
for node in data_as_dict[ticker]:
for ignore in use_ignore_keys:
node.pop(ignore, None)
all_records.append(node)
# end for all datasets on this date to load
num_records = len(all_records)
if num_records:
if verbose:
log.info(f'found records={num_records}')
history_df = pd.DataFrame(all_records)
for dc in convert_these_date_keys:
if dc in history_df:
history_df[dc] = pd.to_datetime(
history_df[dc],
format=ae_consts.COMMON_TICK_DATE_FORMAT)
# end of converting all date columns
use_data[ticker] = history_df
else:
log.error(
f'did not find any records={num_records} in history dataset')
# end for all tickers in the dataset
return use_data
# end of prepare_history_dataset
| [
"json.loads",
"pandas.DataFrame",
"pandas.to_datetime",
"spylunking.log.setup_logging.build_colorized_logger",
"zlib.decompress"
] | [((201, 248), 'spylunking.log.setup_logging.build_colorized_logger', 'log_utils.build_colorized_logger', ([], {'name': '__name__'}), '(name=__name__)\n', (233, 248), True, 'import spylunking.log.setup_logging as log_utils\n'), ((2136, 2159), 'json.loads', 'json.loads', (['parsed_data'], {}), '(parsed_data)\n', (2146, 2159), False, 'import json\n'), ((3733, 3758), 'pandas.DataFrame', 'pd.DataFrame', (['all_records'], {}), '(all_records)\n', (3745, 3758), True, 'import pandas as pd\n'), ((1813, 1834), 'zlib.decompress', 'zlib.decompress', (['data'], {}), '(data)\n', (1828, 1834), False, 'import zlib\n'), ((3880, 3952), 'pandas.to_datetime', 'pd.to_datetime', (['history_df[dc]'], {'format': 'ae_consts.COMMON_TICK_DATE_FORMAT'}), '(history_df[dc], format=ae_consts.COMMON_TICK_DATE_FORMAT)\n', (3894, 3952), True, 'import pandas as pd\n')] |
"""
Holds the base classes for storage module.
These are special hashables whose state can be serialized on disk.
"""
import typing as t
import pathlib
import datetime
import dataclasses
import abc
from .. import util, logger, settings
from .. import marshalling as m
from .. import error as e
from . import state
# noinspection PyUnreachableCode
if False:
from . import store
_LOGGER = logger.get_logger()
_DOT_DOT_TYPE = t.Literal['..']
# noinspection PyUnresolvedReferences
_DOT_DOT = _DOT_DOT_TYPE.__args__[0]
@dataclasses.dataclass(frozen=True)
class StorageHashable(m.HashableClass, abc.ABC):
@property
@util.CacheResult
def config(self) -> state.Config:
return state.Config(
hashable=self,
path_prefix=self.path.as_posix(),
)
@property
@util.CacheResult
def info(self) -> state.Info:
return state.Info(
hashable=self,
path_prefix=self.path.as_posix(),
)
@property
@util.CacheResult
def internal(self) -> m.Internal:
return m.Internal(self)
@property
@util.CacheResult
def path(self) -> pathlib.Path:
"""
Never override this.
Always resolve folder structure from group_by and name.
Note that root_dir can still be overridden if you want different
result locations
"""
if isinstance(self.group_by, list):
_split_strs = self.group_by
elif isinstance(self.group_by, str):
_split_strs = [self.group_by]
elif self.group_by is None:
_split_strs = []
else:
e.code.ShouldNeverHappen(
msgs=[
f"unsupported group_by value {self.group_by}"
]
)
raise
_path = self.root_dir
for _ in _split_strs:
_path /= _
return _path / self.name
@property
@util.CacheResult
def root_dir(self) -> pathlib.Path:
# if not using parent_folder then this property should never be
# called as it will ideally overridden
if not self.uses_parent_folder:
e.code.ShouldNeverHappen(
msgs=[
f"You have configured class {self.__class__} to not to use "
f"parent_folder so we expect you to override `root_dir` "
f"property inside class {self.__class__}"
]
)
# get parent folder
try:
_parent_folder = getattr(self, 'parent_folder')
except AttributeError:
e.code.CodingError(
msgs=[
f"This is already checked .... ideally field "
f"parent_folder should be present in class {self.__class__}"
]
)
raise
# If parent_folder is provided this property will not be overridden,
# hence we will reach here.
# In order to avoid creating Folder instance for parent_folder we use
# `..` string while saving to disc. This makes sure that there is no
# recursive instances of Folder being created. These instances again
# tries to sync leading to recursion
# But that means the Folder which is creating this instance must set
# itself as parent_folder.
# Also check documentation for `Folder.sync()` and
# `StorageHashable.init_validate()`
# Note in init_validate if self.parent_folder is `..` we raise error
# stating that you are creating instance from yaml file directly and
# it is not allowed as parent_folder should do it while syncing
if _parent_folder == _DOT_DOT:
e.code.CodingError(
msgs=[
f"Yaml on disk can have `..` string so the Folder which "
f"is creating this instance must update it and then call "
f"__post_init__ over the StorageHashable",
f"{Folder.sync} is responsible to set parent_folder while "
f"syncing.",
f"While in case if you are creating instance "
f"directly from yaml file then "
f"{StorageHashable.init_validate} should ideally block "
f"you as it is not possible to create instance.",
f"Also note that we do all this because hex_hash will be "
f"corrupt if parent_folder is not set appropriately "
f"before `Hashable.init` runs"
]
)
raise
# Now if parent_folder is Folder simply return the path of
# parent_folder as it is the root plus the name for this StorageHashable
if isinstance(_parent_folder, Folder):
return _parent_folder.path
# if above thing does not return that means we have a problem so
# raise error
e.code.CodingError(
msgs=[
f"The field parent_folder is not None nor it is valid "
f"Folder",
f"The type is {type(_parent_folder)}"
]
)
raise
@property
def group_by(self) -> t.Optional[t.Union[str, t.List[str]]]:
"""
Default is use not grouping ... override this if you need grouping
"""
return None
@property
def uses_parent_folder(self) -> bool:
"""
Adds a parent_folder behavior i.e. this subclass of StorageHashable
can be managed by parent_folder
"""
return False
@property
def is_created(self) -> bool:
_info_there = self.info.is_available
_config_there = self.config.is_available
if _info_there ^ _config_there:
e.code.CodingError(
msgs=[
f"Both config and info should be present or none should "
f"be present ...",
dict(
_info_there=_info_there, _config_there=_config_there
)
]
)
return _info_there and _config_there
@classmethod
def hook_up_methods(cls):
# call super
super().hook_up_methods()
# hook up create
util.HookUp(
cls=cls,
silent=True,
method=cls.create,
pre_method=cls.create_pre_runner,
post_method=cls.create_post_runner,
)
# hook up delete
util.HookUp(
cls=cls,
silent=True,
method=cls.delete,
pre_method=cls.delete_pre_runner,
post_method=cls.delete_post_runner,
)
def init_validate(self):
# ----------------------------------------------------------- 01
# if uses_parent_folder
if self.uses_parent_folder:
# ------------------------------------------------------- 01.01
# check if necessary field added
if 'parent_folder' not in self.dataclass_field_names:
e.code.CodingError(
msgs=[
f"We expect you to define field `parent_folder` as you "
f"have configured property `uses_parent_folder` to "
f"True for class {self.__class__}"
]
)
# ------------------------------------------------------- 01.02
# the root_dir property must not be overrided
if self.__class__.root_dir != StorageHashable.root_dir:
e.code.CodingError(
msgs=[
f"Please do not override property `root_dir` in class "
f"{self.__class__} as it is configured to use "
f"parent_folder"
]
)
# ------------------------------------------------------- 01.03
# test if parent_folder is Folder
_parent_folder = getattr(self, 'parent_folder')
if not isinstance(_parent_folder, Folder):
if _parent_folder != _DOT_DOT:
e.code.CodingError(
msgs=[
f"We expect parent_folder to be set with instance "
f"of type {Folder}",
f"Instead found value of type "
f"{type(_parent_folder)}"
]
)
# ------------------------------------------------------- 01.04
# If parent_folder is provided this property will not be overridden,
# hence we will reach here.
# In order to avoid creating Folder instance for parent_folder
# we use `..` string while saving to disc. This makes sure that
# there is no recursive instances of Folder being created. These
# instances again tries to sync leading to recursion
# But that means the Folder which is creating this instance must set
# itself as parent_folder.
# Also check documentation for `Folder.sync()` and
# `StorageHashable.init_validate()`
# Note in init_validate if self.parent_folder is `..` we raise error
# stating that you are creating instance from yaml file directly and
# it is not allowed as parent_folder should do it while syncing
if _parent_folder == _DOT_DOT:
e.code.CodingError(
msgs=[
f"Problem with initializing {self.__class__}",
f"Yaml on disc can have `..` string so the Folder "
f"which is creating this instance must update it and "
f"then call __post_init__ over the StorageHashable",
f"{Folder.sync} is responsible to set parent_folder "
f"while syncing.",
f"While in case if you are creating instance "
f"directly from yaml file then we block "
f"you as it is not possible to create instance.",
f"Also note that we do all this because hex_hash "
f"will be corrupt if parent_folder is not set "
f"appropriately before `Hashable.init` runs"
]
)
raise
# ------------------------------------------------------- 01.05
# if parent_folder supplied check what it can contain
_contains = _parent_folder.contains
# if None
if _contains is not None:
# note we do not use isinstance() as all folder
# subclasses will be concrete and subclassing is not anything
# special as there is no hierarchy in folder types
if self.__class__ != _parent_folder.contains:
e.code.NotAllowed(
msgs=[
f"The parent_folder is configured to contain only "
f"instances of class "
f"{_parent_folder.contains} but you "
f"are trying to add instance of type "
f"{self.__class__}"
]
)
# ----------------------------------------------------------- 02
# check for path length
e.io.LongPath(path=self.path, msgs=[])
# if path exists check if it is a folder
if self.path.exists():
if not self.path.is_dir():
e.validation.NotAllowed(
msgs=[
f"We expect {self.path} to be a dir"
]
)
# ----------------------------------------------------------- 03
# call super
super().init_validate()
def init(self):
# ----------------------------------------------------------- 01
# call super
super().init()
# ----------------------------------------------------------- 02
# if root dir does not exist make it
if not self.path.exists():
self.path.mkdir(parents=True)
# ----------------------------------------------------------- 03
# if not created create
if not self.is_created:
self.create()
# ----------------------------------------------------------- 04
# if parent_folder can track then add self to items
# Note that when contains is None we might still have Folder and
# FileGroup inside it but we will not do tracking for it and it is
# job of user to handle in respective parent_folder class
if self.uses_parent_folder:
# noinspection PyUnresolvedReferences
_parent_folder = self.parent_folder # type: Folder
if _parent_folder.contains is not None:
# add item ...
# Note that item can already exist due to sync in that case
_parent_folder.add_item(hashable=self)
@classmethod
def from_dict(
cls,
yaml_state: t.Dict[str, "m.SUPPORTED_HASHABLE_OBJECTS_TYPE"],
**kwargs
) -> "StorageHashable":
if "parent_folder" in yaml_state.keys():
# update .. to parent_folder supplied from kwargs
if yaml_state["parent_folder"] == _DOT_DOT:
if "parent_folder" not in kwargs.keys():
e.code.CodingError(
msgs=[
f"The yaml_state dict loaded from file_or_text "
f"does has parent_folder set to `..`",
f"This means we do not have access to "
f"parent_folder instance so please supply it "
f"while Folder syncs files/folders inside it.",
f"Note that if you are using from_yaml then also "
f"you can supply the extra kwarg so that "
f"from_dict receives it."
]
)
else:
yaml_state["parent_folder"] = kwargs["parent_folder"]
# noinspection PyArgumentList
return cls(**yaml_state)
def as_dict(
self
) -> t.Dict[str, m.SUPPORTED_HASHABLE_OBJECTS_TYPE]:
# get dict from super
_dict = super().as_dict()
# if uses parent_folder
if self.uses_parent_folder:
# get parent folder
_parent_folder = getattr(self, 'parent_folder')
# if there is parent_folder update it to ..
if _parent_folder == _DOT_DOT:
e.code.CodingError(
msgs=[
f"If loading from yaml on disk make sure that a "
f"Folder is doing that un sync so that parent_folder "
f"is set appropriately before calling __post_init__ on "
f"StorageHashable"
]
)
# modify dict so that representation is change on disc
# note that this does not modify self.__dict__ ;)
# we do this only when parent_folder is available
_dict['parent_folder'] = _DOT_DOT
# return
return _dict
def create_pre_runner(self):
# check if already created
if self.is_created:
e.code.NotAllowed(
msgs=[
f"Things related to hashable class {self.__class__} "
f"with name `{self.name}` has already been created ...",
]
)
def create(self) -> t.Any:
e.code.CodingError(
msgs=[
f"There is nothing to create for class {self.__class__}",
F"You might need to override this method if you have "
F"something to create ...",
f"If you override this method make sure you override "
f"corresponding `delete()` too ..."
]
)
# noinspection PyUnusedLocal
def create_post_runner(
self, *, hooked_method_return_value: t.Any
):
# ----------------------------------------------------------- 01
# The below call will create state manager files on the disk
# check if .info and .config file exists i.e. state exists
if self.config.is_available:
e.code.CodingError(
msgs=[
f"Looks like you have updated config before this parent "
f"create_post_runner was called.",
f"Try to make updates to config after the config is "
f"created the parent create_post_runner by calling sync()"
]
)
if self.info.is_available:
e.code.CodingError(
msgs=[
f"looks like info file for this StorageHashable is "
f"already present",
f"As files were just created we expect that this state "
f"file should not be present ..."
]
)
# redundant
_ = self.is_created
# ----------------------------------------------------------- 02
# sync to disk ... note that from here on state files will be on the
# disc and the child methods that will call super can take over and
# modify state files like config
self.info.sync()
self.config.sync()
# ----------------------------------------------------------- 03
# also sync the created on ... note that config can auto sync on
# update to its fields
self.config.created_on = datetime.datetime.now()
# ----------------------------------------------------------- 04
# check if property updated
if not self.is_created:
e.code.NotAllowed(
msgs=[
f"Did you forget to update appropriately the things in "
f"`create()` method of {self.__class__}",
f"Property `self.is_created` should return `True` as "
f"things are now created."
]
)
# noinspection PyUnusedLocal
def delete_pre_runner(self, *, force: bool = False):
# check if already created
if not self.is_created:
e.code.NotAllowed(
msgs=[
f"Things related to hashable class {self.__class__} are "
f"not created ..."
]
)
def delete(self, *, force: bool = False) -> t.Any:
e.code.CodingError(
msgs=[
f"There is nothing to delete for class {self.__class__}",
F"You might need to override this method if you have "
F"something to delete ...",
f"You only `delete()` if you create something in `create()`"
]
)
# noinspection PyUnusedLocal
def delete_post_runner(
self, *, hooked_method_return_value: t.Any
):
# delete state files as they were created along with the
# files for this StorageHashable in create_post_runner
self.info.delete()
self.config.delete()
# also delete the empty path folder
if util.io_is_dir_empty(self.path):
self.path.rmdir()
else:
e.code.CodingError(
msgs=[
f"All the files inside folder should be deleted by now ...",
f"Expected path dir to be empty",
f"Check path {self.path}"
]
)
# check if property updated
if self.is_created:
e.code.NotAllowed(
msgs=[
f"Did you forget to update appropriately the things in "
f"`delete()` method of {self.__class__}",
f"Property `self.is_created` should return `False` as "
f"things are now deleted."
]
)
# if parent_folder is there try to remove item from the tracking dict
# items
if self.uses_parent_folder:
# get parent folder
_parent_folder = getattr(self, 'parent_folder')
# if parent folder can track then delete items that it has tracked
if _parent_folder.contains is not None:
# just do sanity check if we are having same item
if id(self) != id(_parent_folder.items[self.name]):
e.code.CodingError(
msgs=[
f"We expect these objects to be same ... "
f"make sure to add item using "
f"parent_folder.add_item() method for integrity"
]
)
# in init() we added self by calling
# self.parent_folder.add_item(self) ... now we just remove the
# item from tracking dict items so that parent folder is in sync
del _parent_folder.items[self.name]
# now we have removed strong reference to self in parent_folder.items
# dict ... let us make this instance useless as files are deleted
# hence we want to make sure any other references will fail to use
# this instance ...
# To achieve this we just clear out the internal __dict__
if not settings.FileHash.DEBUG_HASHABLE_STATE:
self.__dict__.clear()
@dataclasses.dataclass(frozen=True)
class Folder(StorageHashable):
"""
A folder for hashable instance like Dataset or Model.
Name of the folder:
The name of folder is the name of the hashable it represents. The
dataclass field `for_hashable` signifies the uniqueness of the folder
while the `paren_folder` field super class does not affect uniqueness
as the folder represented by this class is saved under it ;)
Deviation from `HashableClass.name` behaviour:
You might be thinking why not have have folder hex_hash as folder name.
That sounds fine. But the name of folder using hashables name can in
future let us use via external utilities to pick up folders only by
knowing hashable and the path must be provided only once.
Also parent_folder is required only to get parent folder info we can
get away just by knowing the path.
Note that for FileGroup the parent_folder is considered as they have
even more fields and here we ignore parent_folder so that for_hashable
decides the folder name
We do not allow to add fields in subclass:
In order that *.info files do not pollute with more info we do not
allow to add fields to Folder class while subclassing.
In case you want more info please use *.config file via Folder.config
property
The contains property:
Indicates what will stored in this Folder
When parent_folder is None override path
This behaviour is borrowed from super class and well suits the
requirement for Folder class
Made up of three things
+ <hash>.info
- when loaded gives out Folder object with hashable instance object
+ <hash>.config
- the access info
+ <hash> folder
- A folder inside which you can have folder's or file_group's
"""
for_hashable: t.Union[str, m.HashableClass]
@property
def name(self) -> str:
"""
Do not override.
NOTE this also happens to be name of the folder
Note that for Folder the uniqueness is completely decided by
self.for_hashable field.
If self.for_hashable is str then the user is not using hashable and
simply wants to create folder with some specific name
We use self.for_hashable.name as name of the folder. Remember that
name is to be unique across hashable. By default the name returns
hex_hash but when you override it to return string the user need to
take care that it is unique for each instance of that class.
Note that FileGroup considers parent_folder while creating name but
here we ignore as there are no extra fields we will define here. Also
we want fo_hashable to dictate things in Folder like the name of
folder created on disk.
"""
# the name is dictated by for_hashable as we will not allow any
# fields in Folder (check validation)
# This is unlike FileGroup where all fields decide name ... this si
# because in FileGroup we intend to have more fields
if isinstance(self.for_hashable, str):
return self.for_hashable
else:
# the name defaults to hex_hash but if you have overridden it then
# we assume you have taken care of creating unique name for all
# possible instance of hashable class
return self.for_hashable.name
@property
def is_created(self) -> bool:
"""
This does mean we need call to create_all
todo: maybe not that big of a overhead but try to check if call to
this property is minimal
"""
# ----------------------------------------------------------------01
_folder_present = self.path.is_dir()
# (The super method is responsible to do this as state manager is
# available)
_state_manager_files_available = super().is_created
# ----------------------------------------------------------------02
# if _state_manager_files_available then folder must be present... the
# vice versa is not necessary ... this is because when state manager
# files are deleted we might still retain Folders as they hold
# valuable files like download files, processed files, results etc.
# NOTE: we do delete state files in cases when config and info files
# are are modifies over new versions ... so we need to protect data
# deletion
if _state_manager_files_available:
if not _folder_present:
e.code.CodingError(
msgs=[
f"The state is available but respective folder is "
f"absent."
]
)
# ----------------------------------------------------------------03
# time to return
return _state_manager_files_available
@property
def contains(self) -> t.Union[
None, t.Type[StorageHashable]
]:
"""
todo: for contains and read_only we can have a class decorator for
Folder like StoreField ... although that means we need to avoid
subclassing the Folder decorator ... but can figure it out later
Indicates what this folder should contain ... it can be one of Folder
or FileGroup or None (i.e. Files that will not use auto hashing
mechanism)
Default is None that means we have files whose hash is not tested ...
in that case we also will not have state manager files like
*.info and *.hash
If you return t.Any then any arbitrary thing can be added including
Folder's and FileGroup's. It is upto user to take care of name
clashes and managing the state manager files that will be generated.
"""
return None
@property
@util.CacheResult
def items(self) -> util.SmartDict:
if self.contains is None:
e.code.CodingError(
msgs=[
f"You have set contains to None so we do not know what "
f"will be stored .... so ideally you will never track "
f"things in the folder so you should not be using this "
f"property .... check class {self.__class__}"
]
)
return util.SmartDict(
allow_nested_dict_or_list=False,
supplied_items=None,
use_specific_class=self.contains,
)
def init_validate(self):
# ----------------------------------------------------------- 01
# folder can have only two fields
for f in self.dataclass_field_names:
if f not in ['for_hashable', 'parent_folder']:
e.code.CodingError(
msgs=[
f"The subclasses of class {Folder} can have only two "
f"fields {['for_hashable', 'parent_folder']}",
f"Please remove field `{f}` from class {self.__class__}"
]
)
# ----------------------------------------------------------- 03
# call super
super().init_validate()
def init(self):
# call super
super().init()
# # Note due to sync that gets called when parent_folder instance
# # was created the items dict of parent_folder will get instance
# # of self if already present on disc ... in that case delete the
# # item in dict and replace with self ...
# if _hashable.name in self.items.keys():
# # Also we do sanity check for integrity to check if hash of
# # existing item matches hashable ... this ensure that this is
# # safe update of dict
# if _hashable.hex_hash != \
# self.items[_hashable.name].hex_hash:
# e.code.NotAllowed(
# msgs=[
# f"While syncing from disk the hashable had different "
# f"hex_hash than one assigned now",
# f"We expect that while creating objects of "
# f"StorageHashable it should match with hex_hash of "
# f"equivalent object that was instantiated from disk",
# {
# "yaml_on_dsk":
# self.items[_hashable.name].yaml(),
# "yaml_in_memory":
# _hashable.yaml(),
# }
# ]
# )
# # note we do not call delete() method of item as it will delete
# # actual files/folder on disc
# # here we just update dict
# del self.items[_hashable.name]
# this is like `get()` for Folder .... note that all
# FileGroups/Folders will be added here via add_item
if self.contains is not None:
self.sync()
def create(self) -> pathlib.Path:
"""
If there is no Folder we create an empty folder.
"""
if not self.path.is_dir():
self.path.mkdir()
# return
return self.path
def delete(self, *, force: bool = False):
"""
Deletes Folder.
Note: Do not do read_only check here as done in delete_item method as
it is not applicable here and completely depends on parent folder
permissions
Note we delete only empty folders, and the state ... we will not
support deleting non-empty folders
note: force kwarg does not matter for a folder but just kept alongside
FileGroup.delete for generic behaviour
todo: when `self.contains is None` handle delete differently as we
will not have items dict
"""
# todo: do u want to add permission check for
# Folder similar to FileGroup
# when contains is None we delete everything ... this is default
# behaviour if you want to do something special please override this
# method
# todo: fix later
if self.contains is None:
# note that this will also delete folder self.path
util.pathlib_rmtree(path=self.path, recursive=True, force=force)
# remember to make empty dir as per API ... this will be deleted
# by delete_post_runner while deleting state files
self.path.mkdir(exist_ok=True)
# else since the folder can track items delete them using items and
# calling the respective delete of items
else:
_items = self.items.keys()
for item in _items:
# first delete the item physically
self.items[item].delete(force=force)
# todo: remove redundant check
# by now we are confident that folder is empty so just check it
if not util.io_is_dir_empty(self.path):
e.code.CodingError(
msgs=[
f"The folder should be empty by now ...",
f"Check path {self.path}"
]
)
def warn_about_garbage(self):
"""
In sync() we skip anything that does not end with *.info this will also
skip files that are not StorageHashable .... but that is okay for
multiple reasons ...
+ performance
+ we might want something extra lying around in folders
+ we might have deleted state info but the folders might be
lying around and might be wise to not delete it
The max we can do in that case is warn users that some
thing else is lying around in folder check method
warn_about_garbage.
todo: implement this
"""
...
def sync(self):
"""
Sync is heavy weight call rarely we aim to do all validations here
and avoid any more validations later ON ...
todo: We can have special Config class for Folder which can do some
indexing operation
"""
# -----------------------------------------------------------------01
# Validations
if self.contains is None:
e.code.CodingError(
msgs=[
f"The caller code should take care to check if there is "
f"anything trackable inside this Folder",
f"Property contains is None so do not call sync"
]
)
# tracking dict should be empty
if len(self.items) != 0:
e.code.CodingError(
msgs=[
f"We expect that the tracker dict be empty",
f"Make sure that you are calling sync only once i.e. from "
f"__post_init__"
]
)
# -----------------------------------------------------------------02
# track for registered file groups
for f in self.path.iterdir():
# *** NOTE ***
# We skip anything that does not end with *.info this will also
# skip files that are not StorageHashable .... but that is okay
# for multiple reasons ...
# + performance
# + we might want something extra lying around in folders
# + we might have deleted state info but the folders might be
# lying around and might be wise to not delete it
# The max we can do in that case is warn users that some
# thing else is lying around in folder check method
# warn_about_garbage.
# registered items have metainfo file with them
# only consider if meta info file exists
if not f.name.endswith(state.Suffix.info):
continue
# construct hashable instance from meta file
# Note that when instance for hashable is created it will check
# things on its own periodically
# Note the __post_init__ call will also sync things if it is folder
# noinspection PyTypeChecker
_hashable = self.contains.from_yaml(
f, parent_folder=self,
) # type: StorageHashable
# add tuple for tracking
# todo: no longer needed to add here as when we create instance
# the instance adds itself to parent_folder instance ... delete
# this code later ... kept for now just for reference
# noinspection PyTypeChecker
# self.items[_hashable.name] = _hashable
# -----------------------------------------------------------------03
# sync is equivalent to accessing folder
# so update state manager files
self.config.append_last_accessed_on()
def add_item(self, hashable: StorageHashable):
# since we are adding hashable item that are persisted to disk their
# state should be present on disk
if not hashable.is_created:
# err msg
if isinstance(hashable, StorageHashable):
_err_msg = f"This should never happen for " \
f"{hashable.__class__} " \
f"sub-class, there might be some coding error." \
f"Did you forget to call create file/folder " \
f"before adding the item."
e.code.CodingError(
msgs=[
f"We cannot find the state for the following hashable "
f"item on disk",
hashable.yaml(), _err_msg,
]
)
else:
_err_msg = f"Don't know the type {type(hashable)}"
e.code.ShouldNeverHappen(msgs=[_err_msg])
# add item
self.items[hashable.name] = hashable
@dataclasses.dataclass(frozen=True)
class ResultsFolder(Folder):
"""
A special folder that store results for Hashable class with unique naming
convention and unique path checking.
It will also be used by StoreField decorator to store the pyarrow results.
"""
for_hashable: m.HashableClass
@property
@util.CacheResult
def root_dir(self) -> pathlib.Path:
"""
As the results generated by hashable can be deleted ...
"""
return settings.Dir.ROOT_DEL
@property
@util.CacheResult
def store(self) -> "store.StoreFieldsFolder":
"""
Should return location where you intend to save results of method
decorated by StoreField
todo: This restricts us to have only one possible store location for
decorated methods. We can easily have one more argument to
StoreField to indicate which property to use while saving the
results. But we can plan this later on need basis.
Alternative:
Every task is special so we can have multiple Hashable Class for
each task and then we can afford to have a single
path. An easy and effective solution.
"""
from . import store
return store.StoreFieldsFolder(
parent_folder=self, for_hashable="store"
)
@property
@util.CacheResult
def store_fields(self) -> t.List[str]:
"""
Gets you the Tables that will be stored under store
That is returns properties/methods decorated by StoreField where each
of them will have a sub-folder under Store
"""
from . import store
_ret = []
for _name in dir(self.for_hashable.__class__):
if _name.startswith("_"):
continue
if store.is_store_field(
getattr(self.for_hashable.__class__, _name)
):
_ret.append(_name)
return _ret
def init_validate(self):
# call super
super().init_validate()
# check if path has the unique name
# this is needed as the user need to take care of keeping
# path unique as then he can decide the possible
# sequence of folders under which he can store the storage results
if self.path.as_posix().find(
self.for_hashable.name
) == -1:
e.validation.NotAllowed(
msgs=[
f"You need to have unique path for `{self.__class__}` "
f"derived from hashable class"
f" {self.for_hashable.__class__}",
f"Please try to have `self.for_hashable.name` in the "
f"`{self.__class__}` property `path` to avoid this error"
]
)
def init_store_df_files(self):
for _sf in self.store_fields:
getattr(self.for_hashable, _sf)(mode='e')
| [
"datetime.datetime.now",
"dataclasses.dataclass"
] | [((526, 560), 'dataclasses.dataclass', 'dataclasses.dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (547, 560), False, 'import dataclasses\n'), ((21890, 21924), 'dataclasses.dataclass', 'dataclasses.dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (21911, 21924), False, 'import dataclasses\n'), ((37902, 37936), 'dataclasses.dataclass', 'dataclasses.dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (37923, 37936), False, 'import dataclasses\n'), ((18011, 18034), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (18032, 18034), False, 'import datetime\n')] |
import pulp as pl
def create_affine_expression(coeffs, var_names):
assert len(coeffs) == len(var_names)
n = len(coeffs)
X = [pl.LpVariable(var_names[i]) for i in range(n)]
affine = pl.LpAffineExpression([(X[i], coeffs[i]) for i in range(n)])
return affine
def create_constraint(coeffs, var_names, sense, rhs):
"""Creates a constraint based on the args
Args:
coeffs: coefficients of the constraints
vars: Names of the vars
sense: +1, 0, -1 based on >=, ==, <= respectively. Or we can use pl.LpConstraintLE
rhs: numerical value of the rhs
Returns:
"""
assert len(coeffs) == len(var_names)
lhs = create_affine_expression(coeffs, var_names)
constr = pl.LpConstraint(lhs, sense=sense, rhs=rhs)
return constr
def test_affine_expression(coeffs=[1, 2, 3], var_names=['x_0', 'x_1', 'x_2']):
print(f'coeffs: {coeffs} | var_names: {var_names}')
affine = create_affine_expression(coeffs, var_names)
print(affine)
def test_constraint(coeffs=[1, 2, 3], var_names=['x_0', 'x_1', 'x_2'], sense=pl.LpConstraintLE, rhs=1):
print(f'coeffs: {coeffs} | var_names: {var_names} | sense: {sense} | rhs: {rhs}')
constraint = create_constraint(coeffs, var_names, sense, rhs)
print(constraint)
def test_0(solver_type):
model = pl.LpProblem("Example", pl.LpMaximize)
print(solver_type)
solver = pl.getSolver(solver_type)
_var = pl.LpVariable('a', 0, 1)
_var2 = pl.LpVariable('a2', 0, 2)
model += _var + _var2 <= 3
model += _var + _var2
x = _var + _var2
status = model.solve(solver)
print(pl.value(_var), pl.value(_var2))
print(pl.value(x))
return status
if __name__ == "__main__":
# Get the available solvers
av = pl.listSolvers(onlyAvailable=True)
print(av)
# Take the first available solver
status = test_0(av[0])
print(status)
test_affine_expression()
test_constraint()
| [
"pulp.LpProblem",
"pulp.listSolvers",
"pulp.LpConstraint",
"pulp.getSolver",
"pulp.value",
"pulp.LpVariable"
] | [((733, 775), 'pulp.LpConstraint', 'pl.LpConstraint', (['lhs'], {'sense': 'sense', 'rhs': 'rhs'}), '(lhs, sense=sense, rhs=rhs)\n', (748, 775), True, 'import pulp as pl\n'), ((1325, 1363), 'pulp.LpProblem', 'pl.LpProblem', (['"""Example"""', 'pl.LpMaximize'], {}), "('Example', pl.LpMaximize)\n", (1337, 1363), True, 'import pulp as pl\n'), ((1400, 1425), 'pulp.getSolver', 'pl.getSolver', (['solver_type'], {}), '(solver_type)\n', (1412, 1425), True, 'import pulp as pl\n'), ((1437, 1461), 'pulp.LpVariable', 'pl.LpVariable', (['"""a"""', '(0)', '(1)'], {}), "('a', 0, 1)\n", (1450, 1461), True, 'import pulp as pl\n'), ((1474, 1499), 'pulp.LpVariable', 'pl.LpVariable', (['"""a2"""', '(0)', '(2)'], {}), "('a2', 0, 2)\n", (1487, 1499), True, 'import pulp as pl\n'), ((1765, 1799), 'pulp.listSolvers', 'pl.listSolvers', ([], {'onlyAvailable': '(True)'}), '(onlyAvailable=True)\n', (1779, 1799), True, 'import pulp as pl\n'), ((139, 166), 'pulp.LpVariable', 'pl.LpVariable', (['var_names[i]'], {}), '(var_names[i])\n', (152, 166), True, 'import pulp as pl\n'), ((1621, 1635), 'pulp.value', 'pl.value', (['_var'], {}), '(_var)\n', (1629, 1635), True, 'import pulp as pl\n'), ((1637, 1652), 'pulp.value', 'pl.value', (['_var2'], {}), '(_var2)\n', (1645, 1652), True, 'import pulp as pl\n'), ((1664, 1675), 'pulp.value', 'pl.value', (['x'], {}), '(x)\n', (1672, 1675), True, 'import pulp as pl\n')] |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.feature_selection import VarianceThreshold
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn import metrics
from sklearn.base import BaseEstimator
from sklearn.neighbors import KNeighborsRegressor
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
# Semilla fijada
np.random.seed(1)
# Constantes
FILENAME = 'datos/data_regression.csv'
TEST_SIZE = 0.2
N_JOBS = 6
VISUALIZE_TRAIN_SET = False
CROSS_VALIDATION = False
CROSS_VALIDATION_KNR = False
VARIANCE_THRESHOLD = 1e-3
POL_DEGREE = 2
PCA_EXPLAINED_VARIANCE = 0.99999
K_SPLITS = 5
REG_PARAM_VALUES1 = [0.1, 1, 5, 10, 20]
REG_PARAM_VALUES2 = [4, 4.5, 5, 5.5, 6]
REG_PARAM = 5
NUM_NEIGHBORS_VALUES = [5, 10, 15, 20]
NUM_NEIGHBORS = 5
def readData(filename):
X = []
y = []
with open(filename) as f:
for line in f:
attribs_label = line.split(",")
X.append(attribs_label[:-1])
y.append(attribs_label[-1])
X.pop(0)
y.pop(0)
X = np.array(X, np.float64)
y = np.array(y, np.float64)
return X, y
def tableCVResults(cv_results, precision=5):
row = list(cv_results["params"][0].keys())+["mean E_in","mean E_cv"]
format_row = "{:<20}" * len(row)
print(format_row.format(*row))
for i in range(len(cv_results["params"])):
row = list(cv_results["params"][i].values())
row.append(round(1-cv_results["mean_train_score"][i],precision))
row.append(round(1-cv_results["mean_test_score"][i],precision))
print(format_row.format(*row))
class PseudoinverseLinearRegression(BaseEstimator):
def __init__(self, reg_param=0.0):
self.reg_param = reg_param # regularization parameter (lambda)
# Ajuste del modelo
def fit(self, X, y):
inverse = np.linalg.inv(X.T @ X + self.reg_param*np.identity(X.shape[1]))
self.w = np.dot( inverse, np.dot(X.T,y) )
# Predicción de clases
def predict(self, X):
return np.dot(X,self.w)
# Error Cuadrático Medio
def mse(self, X, y):
return metrics.mean_squared_error(y,self.predict(X))
# Error Absoluto Medio
def mae(self, X, y):
return metrics.mean_absolute_error(y,self.predict(X))
# Coeficiente de determinación (R^2)
def R2(self, X, y):
return 1-self.mse(X,y)/np.var(y)
# Score: R^2
def score(self, X, y):
return self.R2(X,y)
class KNR(BaseEstimator):
def __init__(self, num_neighbors=5, weight_function='uniform'):
self.num_neighbors = num_neighbors # número de vecinos
# Ajuste del modelo
def fit(self, X, y):
self.model = KNeighborsRegressor(n_neighbors=self.num_neighbors,
weights='uniform',
n_jobs=N_JOBS)
self.model.fit(X,y)
# Predicción de clases
def predict(self, X):
return self.model.predict(X)
# Error Cuadrático Medio
def mse(self, X, y):
return metrics.mean_squared_error(y,self.predict(X))
# Error Absoluto Medio
def mae(self, X, y):
return metrics.mean_absolute_error(y,self.predict(X))
# Coeficiente de determinación (R^2)
def R2(self, X, y):
return self.model.score(X,y)
# Score: R^2
def score(self, X, y):
return self.R2(X,y)
if __name__ == "__main__":
X, y = readData(FILENAME)
# Separación train-test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=TEST_SIZE, random_state=42)
# Representación de datos en histogramas y en un espacio bidimensional mediante PCA y t-SNE
if VISUALIZE_TRAIN_SET:
print("#################################################################")
print("########## VISUALIZACIÓN DEL CONJUNTO DE ENTRENAMIENTO ##########")
print("#################################################################\n")
print("Histograma con las temperaturas críticas y sus frec. absolutas")
plt.hist(y_train, bins=37, density=False, cumulative=False)
plt.xlabel("Temperatura crítica")
plt.ylabel("Frecuencia absoluta")
plt.title("Histograma con las temperaturas críticas y sus frec. absolutas")
plt.grid(True)
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
print("Histograma con las temperaturas críticas y sus frec. relativas acum.")
plt.hist(y_train, bins=37, density=True, cumulative=True)
plt.xlabel("Temperatura crítica")
plt.ylabel("Frecuencia relativa acumulada")
plt.title("Histograma con las temperaturas críticas y sus frec. relativas acum.")
plt.grid(True)
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
cmap='plasma'
alpha=0.2
X_train_95 = X_train[np.where(y_train<95.0)]
y_train_95 = y_train[np.where(y_train<95.0)]
print("Representación de los datos con reducción de dimensionalidad usando PCA")
X_PCA = PCA(n_components=2, random_state=42).fit_transform(X_train_95)
plt.scatter(X_PCA[:,0], X_PCA[:,1], c=y_train_95, cmap=cmap, alpha=alpha)
plt.colorbar()
plt.title("Representación de los datos en 2D usando PCA")
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
print("Representación de los datos con reducción de dimensionalidad usando t-SNE")
X_TSNE = TSNE(n_components=2, init=X_PCA).fit_transform(X_train_95)
plt.scatter(X_TSNE[:,0], X_TSNE[:,1], c=y_train_95, cmap=cmap, alpha=alpha)
plt.colorbar()
plt.title("Representación de los datos en 2D usando t-SNE")
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
print("##################################")
print("########## PREPROCESADO ##########")
print("##################################\n")
# Matriz de coeficientes de correlación de Pearson con los datos iniciales
# (previamente, eliminamos características constantes)
correlation_matrix = np.corrcoef(np.transpose(VarianceThreshold().fit_transform(X_train)))
print("Matriz de coeficientes de correlación de Pearson (datos iniciales)")
plt.matshow(correlation_matrix, cmap='plasma')
plt.colorbar()
plt.title("Matriz de coef. de corr. de Pearson \n(datos iniciales)", pad=40.0)
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
print("Evolución del número de características:")
print("\tDatos iniciales:", X_train.shape[1])
# Eliminación de características con varianza muy baja
variance_threshold = VarianceThreshold(VARIANCE_THRESHOLD)
X_train = variance_threshold.fit_transform(X_train)
X_test = variance_threshold.transform(X_test)
print("\tVarianceThreshold:",X_train.shape[1])
# Ampliación con características no lineales (polinomios con grado acotado)
# También añade la característica asociada al término independiente
polynomial_features = PolynomialFeatures(POL_DEGREE)
X_train = polynomial_features.fit_transform(X_train)
X_test = polynomial_features.transform(X_test)
print("\tPolynomialFeatures:",X_train.shape[1])
# Estándarización (características con media 0 y varianza 1)
standard_scaler = StandardScaler()
X_train = standard_scaler.fit_transform(X_train)
X_test = standard_scaler.transform(X_test)
print("\tStandardScaler:",X_train.shape[1])
# Reducción de dimensionalidad mediante Análisis de Componentes Principales
pca = PCA(n_components=PCA_EXPLAINED_VARIANCE)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
print("\tPCA:",X_train.shape[1])
input("\n--- Pulsar tecla para continuar ---\n")
# Matriz de coeficientes de correlación de Pearson con los datos preprocesados
correlation_matrix = np.corrcoef(np.transpose(X_train))
print("Matriz de coeficientes de correlación de Pearson (datos preprocesados)")
plt.matshow(correlation_matrix, cmap='plasma')
plt.colorbar()
plt.title("Matriz de coef. de corr. de Pearson \n(datos preprocesados)", pad=40.0)
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
# Creación del modelo de Regresión Lineal que usa la Pseudoinversa
plr = PseudoinverseLinearRegression(reg_param=REG_PARAM)
# Añado el término independiente a los elementos del conjunto de entrenamiento y test
X_train = np.hstack(( np.ones((X_train.shape[0],1)), X_train ))
X_test = np.hstack(( np.ones((X_test.shape[0],1)), X_test ))
if CROSS_VALIDATION:
print("######################################")
print("########## CROSS-VALIDATION ##########")
print("######################################\n")
param_grid = {'reg_param':REG_PARAM_VALUES1}
cv_searcher = GridSearchCV(plr, param_grid, n_jobs=N_JOBS, verbose=1, return_train_score=True)
cv_searcher.fit(X_train, y_train)
print()
tableCVResults(cv_searcher.cv_results_)
print()
print("Mejores hiperparámetros:",cv_searcher.best_params_)
print("E_in medio:",round(1-cv_searcher.cv_results_["mean_train_score"][np.where(cv_searcher.cv_results_["rank_test_score"]==1)[0][0]],5))
print("E_cv medio:",round(1-cv_searcher.best_score_,5))
print()
param_grid = {'reg_param':REG_PARAM_VALUES2}
cv_searcher = GridSearchCV(plr, param_grid, n_jobs=N_JOBS, verbose=1, return_train_score=True)
cv_searcher.fit(X_train, y_train)
print()
tableCVResults(cv_searcher.cv_results_)
print()
print("Mejores hiperparámetros:",cv_searcher.best_params_)
print("E_in medio:",round(1-cv_searcher.cv_results_["mean_train_score"][np.where(cv_searcher.cv_results_["rank_test_score"]==1)[0][0]],5))
print("E_cv medio:",round(1-cv_searcher.best_score_,5))
print()
plr.set_params(**(cv_searcher.best_params_))
input("\n--- Pulsar tecla para continuar ---\n")
print("##########################################################")
print("########## EVALUACIÓN DE LA HIPÓTESIS FINAL ##############")
print("##########################################################\n")
plr.fit(X_train, y_train)
print("\nE_in =",round(1-plr.R2(X_train,y_train),5))
print("R²_in =",round(plr.R2(X_train,y_train),5))
print("MAE_in =",round(plr.mae(X_train,y_train),5))
print("\nE_test =",round(1-plr.R2(X_test,y_test),5))
print("R²_test =",round(plr.R2(X_test,y_test),5))
print("MAE_test:",round(plr.mae(X_test,y_test),5))
input("\n--- Pulsar tecla para continuar ---\n")
# Creación del modelo KNR
knr = KNR(num_neighbors=NUM_NEIGHBORS)
# Elimino el término independiente de los elementos del conjunto de entrenamiento y test
X_train = X_train[:,1:]
X_test = X_test[:,1:]
if CROSS_VALIDATION_KNR:
print("############################################")
print("########## CROSS-VALIDATION (KNR) ##########")
print("############################################\n")
param_grid = {'num_neighbors':NUM_NEIGHBORS_VALUES}
cv_searcher = GridSearchCV(knr, param_grid, n_jobs=N_JOBS, verbose=1, return_train_score=True)
cv_searcher.fit(X_train, y_train)
print()
tableCVResults(cv_searcher.cv_results_)
print()
print("Mejores hiperparámetros:",cv_searcher.best_params_)
print("E_in medio:",round(1-cv_searcher.cv_results_["mean_train_score"][np.where(cv_searcher.cv_results_["rank_test_score"]==1)[0][0]],5))
print("E_cv medio:",round(1-cv_searcher.best_score_,5))
print()
knr.set_params(**(cv_searcher.best_params_))
input("\n--- Pulsar tecla para continuar ---\n")
print("################################################################")
print("########## EVALUACIÓN DE LA HIPÓTESIS FINAL (KNR) ##############")
print("################################################################\n")
knr.fit(X_train,y_train)
print("\nE_in =",round(1-knr.R2(X_train,y_train),5))
print("R²_in =",round(knr.R2(X_train,y_train),5))
print("MAE_in =",round(knr.mae(X_train,y_train),5))
print("\nE_test =",round(1-knr.R2(X_test,y_test),5))
print("R²_test =",round(knr.R2(X_test,y_test),5))
print("MAE_test:",round(knr.mae(X_test,y_test),5)) | [
"sklearn.model_selection.GridSearchCV",
"sklearn.preprocessing.PolynomialFeatures",
"matplotlib.pyplot.hist",
"sklearn.feature_selection.VarianceThreshold",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.ylabel",
"numpy.array",
"sklearn.decomposition.PCA",
"numpy.where",
"matplotlib.pyplot.xlabel",
... | [((491, 508), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (505, 508), True, 'import numpy as np\n'), ((1217, 1240), 'numpy.array', 'np.array', (['X', 'np.float64'], {}), '(X, np.float64)\n', (1225, 1240), True, 'import numpy as np\n'), ((1250, 1273), 'numpy.array', 'np.array', (['y', 'np.float64'], {}), '(y, np.float64)\n', (1258, 1273), True, 'import numpy as np\n'), ((3826, 3886), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': 'TEST_SIZE', 'random_state': '(42)'}), '(X, y, test_size=TEST_SIZE, random_state=42)\n', (3842, 3886), False, 'from sklearn.model_selection import train_test_split, GridSearchCV\n'), ((6819, 6865), 'matplotlib.pyplot.matshow', 'plt.matshow', (['correlation_matrix'], {'cmap': '"""plasma"""'}), "(correlation_matrix, cmap='plasma')\n", (6830, 6865), True, 'import matplotlib.pyplot as plt\n'), ((6871, 6885), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (6883, 6885), True, 'import matplotlib.pyplot as plt\n'), ((6891, 6977), 'matplotlib.pyplot.title', 'plt.title', (['"""Matriz de coef. de corr. de Pearson \n(datos iniciales)"""'], {'pad': '(40.0)'}), '("""Matriz de coef. de corr. de Pearson \n(datos iniciales)""", pad\n =40.0)\n', (6900, 6977), True, 'import matplotlib.pyplot as plt\n'), ((6975, 6985), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6983, 6985), True, 'import matplotlib.pyplot as plt\n'), ((7256, 7293), 'sklearn.feature_selection.VarianceThreshold', 'VarianceThreshold', (['VARIANCE_THRESHOLD'], {}), '(VARIANCE_THRESHOLD)\n', (7273, 7293), False, 'from sklearn.feature_selection import VarianceThreshold\n'), ((7641, 7671), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', (['POL_DEGREE'], {}), '(POL_DEGREE)\n', (7659, 7671), False, 'from sklearn.preprocessing import PolynomialFeatures, StandardScaler\n'), ((7930, 7946), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (7944, 7946), False, 'from sklearn.preprocessing import PolynomialFeatures, StandardScaler\n'), ((8196, 8236), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'PCA_EXPLAINED_VARIANCE'}), '(n_components=PCA_EXPLAINED_VARIANCE)\n', (8199, 8236), False, 'from sklearn.decomposition import PCA\n'), ((8660, 8706), 'matplotlib.pyplot.matshow', 'plt.matshow', (['correlation_matrix'], {'cmap': '"""plasma"""'}), "(correlation_matrix, cmap='plasma')\n", (8671, 8706), True, 'import matplotlib.pyplot as plt\n'), ((8712, 8726), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (8724, 8726), True, 'import matplotlib.pyplot as plt\n'), ((8732, 8821), 'matplotlib.pyplot.title', 'plt.title', (['"""Matriz de coef. de corr. de Pearson \n(datos preprocesados)"""'], {'pad': '(40.0)'}), '("""Matriz de coef. de corr. de Pearson \n(datos preprocesados)""",\n pad=40.0)\n', (8741, 8821), True, 'import matplotlib.pyplot as plt\n'), ((8820, 8830), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8828, 8830), True, 'import matplotlib.pyplot as plt\n'), ((2228, 2245), 'numpy.dot', 'np.dot', (['X', 'self.w'], {}), '(X, self.w)\n', (2234, 2245), True, 'import numpy as np\n'), ((2935, 3024), 'sklearn.neighbors.KNeighborsRegressor', 'KNeighborsRegressor', ([], {'n_neighbors': 'self.num_neighbors', 'weights': '"""uniform"""', 'n_jobs': 'N_JOBS'}), "(n_neighbors=self.num_neighbors, weights='uniform',\n n_jobs=N_JOBS)\n", (2954, 3024), False, 'from sklearn.neighbors import KNeighborsRegressor\n'), ((4395, 4454), 'matplotlib.pyplot.hist', 'plt.hist', (['y_train'], {'bins': '(37)', 'density': '(False)', 'cumulative': '(False)'}), '(y_train, bins=37, density=False, cumulative=False)\n', (4403, 4454), True, 'import matplotlib.pyplot as plt\n'), ((4464, 4497), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Temperatura crítica"""'], {}), "('Temperatura crítica')\n", (4474, 4497), True, 'import matplotlib.pyplot as plt\n'), ((4507, 4540), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Frecuencia absoluta"""'], {}), "('Frecuencia absoluta')\n", (4517, 4540), True, 'import matplotlib.pyplot as plt\n'), ((4550, 4625), 'matplotlib.pyplot.title', 'plt.title', (['"""Histograma con las temperaturas críticas y sus frec. absolutas"""'], {}), "('Histograma con las temperaturas críticas y sus frec. absolutas')\n", (4559, 4625), True, 'import matplotlib.pyplot as plt\n'), ((4635, 4649), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (4643, 4649), True, 'import matplotlib.pyplot as plt\n'), ((4659, 4669), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4667, 4669), True, 'import matplotlib.pyplot as plt\n'), ((4864, 4921), 'matplotlib.pyplot.hist', 'plt.hist', (['y_train'], {'bins': '(37)', 'density': '(True)', 'cumulative': '(True)'}), '(y_train, bins=37, density=True, cumulative=True)\n', (4872, 4921), True, 'import matplotlib.pyplot as plt\n'), ((4931, 4964), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Temperatura crítica"""'], {}), "('Temperatura crítica')\n", (4941, 4964), True, 'import matplotlib.pyplot as plt\n'), ((4974, 5017), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Frecuencia relativa acumulada"""'], {}), "('Frecuencia relativa acumulada')\n", (4984, 5017), True, 'import matplotlib.pyplot as plt\n'), ((5027, 5113), 'matplotlib.pyplot.title', 'plt.title', (['"""Histograma con las temperaturas críticas y sus frec. relativas acum."""'], {}), "(\n 'Histograma con las temperaturas críticas y sus frec. relativas acum.')\n", (5036, 5113), True, 'import matplotlib.pyplot as plt\n'), ((5118, 5132), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (5126, 5132), True, 'import matplotlib.pyplot as plt\n'), ((5142, 5152), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5150, 5152), True, 'import matplotlib.pyplot as plt\n'), ((5600, 5675), 'matplotlib.pyplot.scatter', 'plt.scatter', (['X_PCA[:, 0]', 'X_PCA[:, 1]'], {'c': 'y_train_95', 'cmap': 'cmap', 'alpha': 'alpha'}), '(X_PCA[:, 0], X_PCA[:, 1], c=y_train_95, cmap=cmap, alpha=alpha)\n', (5611, 5675), True, 'import matplotlib.pyplot as plt\n'), ((5683, 5697), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (5695, 5697), True, 'import matplotlib.pyplot as plt\n'), ((5707, 5764), 'matplotlib.pyplot.title', 'plt.title', (['"""Representación de los datos en 2D usando PCA"""'], {}), "('Representación de los datos en 2D usando PCA')\n", (5716, 5764), True, 'import matplotlib.pyplot as plt\n'), ((5774, 5784), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5782, 5784), True, 'import matplotlib.pyplot as plt\n'), ((6061, 6138), 'matplotlib.pyplot.scatter', 'plt.scatter', (['X_TSNE[:, 0]', 'X_TSNE[:, 1]'], {'c': 'y_train_95', 'cmap': 'cmap', 'alpha': 'alpha'}), '(X_TSNE[:, 0], X_TSNE[:, 1], c=y_train_95, cmap=cmap, alpha=alpha)\n', (6072, 6138), True, 'import matplotlib.pyplot as plt\n'), ((6146, 6160), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (6158, 6160), True, 'import matplotlib.pyplot as plt\n'), ((6170, 6229), 'matplotlib.pyplot.title', 'plt.title', (['"""Representación de los datos en 2D usando t-SNE"""'], {}), "('Representación de los datos en 2D usando t-SNE')\n", (6179, 6229), True, 'import matplotlib.pyplot as plt\n'), ((6239, 6249), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6247, 6249), True, 'import matplotlib.pyplot as plt\n'), ((8547, 8568), 'numpy.transpose', 'np.transpose', (['X_train'], {}), '(X_train)\n', (8559, 8568), True, 'import numpy as np\n'), ((9579, 9664), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', (['plr', 'param_grid'], {'n_jobs': 'N_JOBS', 'verbose': '(1)', 'return_train_score': '(True)'}), '(plr, param_grid, n_jobs=N_JOBS, verbose=1, return_train_score=True\n )\n', (9591, 9664), False, 'from sklearn.model_selection import train_test_split, GridSearchCV\n'), ((10171, 10256), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', (['plr', 'param_grid'], {'n_jobs': 'N_JOBS', 'verbose': '(1)', 'return_train_score': '(True)'}), '(plr, param_grid, n_jobs=N_JOBS, verbose=1, return_train_score=True\n )\n', (10183, 10256), False, 'from sklearn.model_selection import train_test_split, GridSearchCV\n'), ((12077, 12162), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', (['knr', 'param_grid'], {'n_jobs': 'N_JOBS', 'verbose': '(1)', 'return_train_score': '(True)'}), '(knr, param_grid, n_jobs=N_JOBS, verbose=1, return_train_score=True\n )\n', (12089, 12162), False, 'from sklearn.model_selection import train_test_split, GridSearchCV\n'), ((2135, 2149), 'numpy.dot', 'np.dot', (['X.T', 'y'], {}), '(X.T, y)\n', (2141, 2149), True, 'import numpy as np\n'), ((5323, 5347), 'numpy.where', 'np.where', (['(y_train < 95.0)'], {}), '(y_train < 95.0)\n', (5331, 5347), True, 'import numpy as np\n'), ((5377, 5401), 'numpy.where', 'np.where', (['(y_train < 95.0)'], {}), '(y_train < 95.0)\n', (5385, 5401), True, 'import numpy as np\n'), ((9167, 9197), 'numpy.ones', 'np.ones', (['(X_train.shape[0], 1)'], {}), '((X_train.shape[0], 1))\n', (9174, 9197), True, 'import numpy as np\n'), ((9235, 9264), 'numpy.ones', 'np.ones', (['(X_test.shape[0], 1)'], {}), '((X_test.shape[0], 1))\n', (9242, 9264), True, 'import numpy as np\n'), ((2597, 2606), 'numpy.var', 'np.var', (['y'], {}), '(y)\n', (2603, 2606), True, 'import numpy as np\n'), ((5528, 5564), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '(2)', 'random_state': '(42)'}), '(n_components=2, random_state=42)\n', (5531, 5564), False, 'from sklearn.decomposition import PCA\n'), ((5993, 6025), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)', 'init': 'X_PCA'}), '(n_components=2, init=X_PCA)\n', (5997, 6025), False, 'from sklearn.manifold import TSNE\n'), ((2075, 2098), 'numpy.identity', 'np.identity', (['X.shape[1]'], {}), '(X.shape[1])\n', (2086, 2098), True, 'import numpy as np\n'), ((6688, 6707), 'sklearn.feature_selection.VarianceThreshold', 'VarianceThreshold', ([], {}), '()\n', (6705, 6707), False, 'from sklearn.feature_selection import VarianceThreshold\n'), ((9935, 9992), 'numpy.where', 'np.where', (["(cv_searcher.cv_results_['rank_test_score'] == 1)"], {}), "(cv_searcher.cv_results_['rank_test_score'] == 1)\n", (9943, 9992), True, 'import numpy as np\n'), ((10527, 10584), 'numpy.where', 'np.where', (["(cv_searcher.cv_results_['rank_test_score'] == 1)"], {}), "(cv_searcher.cv_results_['rank_test_score'] == 1)\n", (10535, 10584), True, 'import numpy as np\n'), ((12433, 12490), 'numpy.where', 'np.where', (["(cv_searcher.cv_results_['rank_test_score'] == 1)"], {}), "(cv_searcher.cv_results_['rank_test_score'] == 1)\n", (12441, 12490), True, 'import numpy as np\n')] |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from telemetry.core.platform.power_monitor import android_ds2784_power_monitor
class DS2784PowerMonitorMonitorTest(unittest.TestCase):
def testEnergyComsumption(self):
data = ('0000 1000 -10 12\n'
'1800 1000 -10 11\n'
'3600 1000 -10 09\n'
'5400 0000 -20 08\n'
'7200 0000 -20 11\n'
'9000 0000 -20 11\n')
results = (
android_ds2784_power_monitor.DS2784PowerMonitor.ParseSamplingOutput(
data))
self.assertEqual(results['power_samples_mw'], [1.2e-07, 1.1e-07, 9e-08,
1.6e-07, 2.2e-07, 2.2e-07])
self.assertEqual(results['energy_consumption_mwh'], 2.1e-07)
| [
"telemetry.core.platform.power_monitor.android_ds2784_power_monitor.DS2784PowerMonitor.ParseSamplingOutput"
] | [((576, 649), 'telemetry.core.platform.power_monitor.android_ds2784_power_monitor.DS2784PowerMonitor.ParseSamplingOutput', 'android_ds2784_power_monitor.DS2784PowerMonitor.ParseSamplingOutput', (['data'], {}), '(data)\n', (643, 649), False, 'from telemetry.core.platform.power_monitor import android_ds2784_power_monitor\n')] |
import logging, operator, functools, itertools, array, ptypes
from ptypes import *
from .headers import *
from . import portable
class Signature(pint.enum, uint16):
# We'll just store all signature types here
_values_ = [
('IMAGE_DOS_SIGNATURE', 0x5a4d),
('IMAGE_OS2_SIGNATURE', 0x454e),
('IMAGE_OS2_SIGNATURE_LE', 0x454c),
('IMAGE_NT_SIGNATURE', 0x4550),
]
class IMAGE_DOS_HEADER(pstruct.type):
class e_magic(Signature): pass
class Relocation(pstruct.type):
_fields_ = [
( uint16, 'offset' ),
( uint16, 'segment' ),
]
def linear(self):
return self['segment'].int()*0x10 + self['offset'].int()
def decode(self, **attrs):
p = self.getparent(ptype.boundary)
attrs.setdefault('offset', p['Stub'].getoffset()+self.linear())
return self.new(ptype.undefined, **attrs)
def summary(self):
seg, offset = self['segment'], self['offset']
return "(segment:offset) {:04x}:{:04x} (linear) {:05x}".format(seg.int(), offset.int(), (seg.int() * 0x10 + offset.int()) & 0xfffff)
def repr(self):
return self.summary()
class Oem(pstruct.type):
_fields_ = [
( dyn.array(uint16, 4), 'e_reserved' ),
( uint16, 'e_oemid' ),
( uint16, 'e_oeminfo' ),
( dyn.array(uint16, 10), 'e_reserved2' ),
]
# FIXME: this implementation should be properly tested as there's a chance it could be fucked with
def __e_oem(self):
res = self['e_lfarlc'].li
fields = ['e_magic', 'e_cblp', 'e_cp', 'e_crlc', 'e_cparhdr', 'e_minalloc', 'e_maxalloc', 'e_ss', 'e_sp', 'e_csum', 'e_ip', 'e_cs', 'e_lfarlc', 'e_ovno']
# if our calculated size for the field directly matches the Oem
# structure, then this for sure is going to be a PECOFF executable.
t = IMAGE_DOS_HEADER.Oem
if res.int() == sum(self[fld].li.size() for fld in fields) + t().a.size() + 4:
return t
# otherwise we need to pad it with whatever the input claims it should be
return dyn.block(max(0, res.int() - sum(self[fld].li.size() for fld in fields)))
def __e_lfanew(self):
paragraphs, relocations = self['e_cparhdr'].li, self['e_lfarlc'].li
fields = ['e_magic', 'e_cblp', 'e_cp', 'e_crlc', 'e_cparhdr', 'e_minalloc', 'e_maxalloc', 'e_ss', 'e_sp', 'e_csum', 'e_ip', 'e_cs', 'e_lfarlc', 'e_ovno', 'e_oem']
# if everything matches, then there's a pointer here for PECOFF executables
if 0x10 * paragraphs.int() == relocations.int() == sum(self[fld].li.size() for fld in fields) + 4:
return dyn.rpointer(Next, self, pint.uint32_t)
# otherwise, there isn't anything here.
return pint.uint_t
def __e_rlc(self):
res = self['e_crlc'].li
return dyn.array(IMAGE_DOS_HEADER.Relocation, res.int())
def __e_parhdr(self):
res = 0x10 * self['e_cparhdr'].li.int()
fields = ['e_magic', 'e_cblp', 'e_cp', 'e_crlc', 'e_cparhdr', 'e_minalloc', 'e_maxalloc', 'e_ss', 'e_sp', 'e_csum', 'e_ip', 'e_cs', 'e_lfarlc', 'e_ovno']
fields+= ['e_oem', 'e_rlc', 'e_lfanew']
return dyn.block(res - sum(self[fld].li.size() for fld in fields))
def filesize(self):
res = self['e_cp'].li.int()
if res > 0:
cp = res - 1
return cp * 0x200 + self['e_cblp'].li.int()
return 0
def headersize(self):
res = self['e_cparhdr'].li
return res.int() * 0x10
def datasize(self):
res = self.headersize()
return (self.filesize() - res) if res > 0 else 0
def __e_lfarlc(self):
res = self['e_crlc'].li
t = dyn.array(IMAGE_DOS_HEADER.Relocation, res.int())
return dyn.rpointer(t, self, uint16)
#e_cparhdr << 4
#e_cp << 9
_fields_ = [
( e_magic, 'e_magic' ),
( uint16, 'e_cblp' ), # bytes in last page / len mod 512 / UsedBytesInLastPage
( uint16, 'e_cp' ), # pages / 512b pagees / FileSizeInPages
( uint16, 'e_crlc' ), # relocation count / reloc entries count / NumberOfRelocationItems
( uint16, 'e_cparhdr' ), # header size in paragraphs (paragraph=0x10) / number of paragraphs before image / HeaderSizeInParagraphs
( uint16, 'e_minalloc' ), # required paragraphs / minimum number of bss paragraphs / MinimumExtraParagraphs
( uint16, 'e_maxalloc' ), # requested paragraphs / maximum number of bss paragraphs / MaximumExtraParagraphs
( uint16, 'e_ss' ), # ss / stack of image / InitialRelativeSS
( uint16, 'e_sp' ), # sp / sp of image / InitialSP
( uint16, 'e_csum' ), # checksum / checksum (ignored) / Checksum
( uint16, 'e_ip' ), # ip / ip of entry / InitialIP
( uint16, 'e_cs' ), # cs / cs of entry / InitialrmwwelativeIp
( __e_lfarlc, 'e_lfarlc' ), # relocation table
( uint16, 'e_ovno'), # overlay number
#( uint32, 'EXE_SYM_TAB'), # from inc/exe.inc
# all the data below here changes based on the linker:
# Borland, ARJ, LZEXE, PKLITE, LHARC, LHA, CRUNCH, BSA, LARC, etc..
( __e_oem, 'e_oem'), # oem and reserved data
( __e_lfanew, 'e_lfanew'),
( __e_rlc, 'e_rlc' ), # relocations?
( __e_parhdr, 'e_parhdr'),
]
### What file format the next header is
class NextHeader(ptype.definition):
cache = {}
### What file format the data is
class NextData(ptype.definition):
cache = {}
class Next(pstruct.type):
def __Header(self):
t = self['Signature'].li.serialize()
return NextHeader.withdefault(t, type=t)
def __Data(self):
t = self['Signature'].li.serialize()
return NextData.withdefault(t, type=t)
_fields_ = [
(Signature, 'Signature'),
(__Header, 'Header'),
(__Data, 'Data'),
]
def Header(self):
return self['Header']
def Data(self):
return self['Data']
## Portable Executable (PE)
@NextHeader.define
class IMAGE_NT_HEADERS(pstruct.type, Header):
type = b'PE'
def __Padding(self):
'''Figure out the PE header size and pad according to SizeOfHeaders'''
p = self.getparent(File)
sz = p['Header']['e_lfanew'].li.int()
opt = self['OptionalHeader'].li
f = functools.partial(operator.getitem, self)
res = map(f, ('SignaturePadding', 'FileHeader', 'OptionalHeader', 'DataDirectory', 'Sections'))
res = sum(map(operator.methodcaller('blocksize'), res))
res += 2
return dyn.block(opt['SizeOfHeaders'].int() - res - sz)
def __DataDirectory(self):
cls = self.__class__
length = self['OptionalHeader'].li['NumberOfRvaAndSizes'].int()
if length > 0x10: # XXX
logging.warning("{:s} : OptionalHeader.NumberOfRvaAndSizes specified >0x10 entries ({:#x}) for the DataDirectory. Assuming the maximum of 0x10.".format('.'.join((cls.__module__, cls.__name__)), length))
length = 0x10
return dyn.clone(portable.DataDirectory, length=length)
def __Sections(self):
header = self['FileHeader'].li
length = header['NumberOfSections'].int()
return dyn.clone(portable.SectionTableArray, length=length)
_fields_ = [
(uint16, 'SignaturePadding'),
(portable.IMAGE_FILE_HEADER, 'FileHeader'),
(portable.IMAGE_OPTIONAL_HEADER, 'OptionalHeader'),
(__DataDirectory, 'DataDirectory'),
(__Sections, 'Sections'),
(__Padding, 'Padding'),
]
def FileHeader(self):
'''Return the FileHeader which contains a number of sizes used by the file.'''
return self['FileHeader']
def getaddressbyoffset(self, offset):
section = self['Sections'].getsectionbyoffset(offset)
return section.getaddressbyoffset(offset)
def getoffsetbyaddress(self, address):
section = self['Sections'].getsectionbyaddress(address)
return section.getoffsetbyaddress(address)
def loadconfig(self):
return self['DataDirectory'][10]['Address'].d.li
def tls(self):
return self['DataDirectory'][9]['Address'].d.li
def relocateable(self):
characteristics = self['OptionalHeader']['DllCharacteristics']
return 'DYNAMIC_BASE' in characteristics
def has_seh(self):
characteristics = self['OptionalHeader']['DllCharacteristics']
return 'NO_SEH' not in characteristics
def has_nx(self):
characteristics = self['OptionalHeader']['DllCharacteristics']
return 'NX_COMPAT' in characteristics
def has_integrity(self):
characteristics = self['OptionalHeader']['DllCharacteristics']
return 'FORCE_INTEGRITY' in characteristics
def is64(self):
return self['OptionalHeader'].li.is64()
def checksum(self):
p = self.getparent(File)
res = self['OptionalHeader']['Checksum']
# Make a copy of our checksum initialized to 0
field = res.copy(offset=res.offset - p.offset).set(0)
# Make a copy of our File header, and overwrite the original
# checksum with 0 so that we can calculate what the checksum
# is supposed to be.
data = bytearray(p.serialize())
data[field.offset : field.offset + field.size()] = field.serialize()
# Pad the data so that it's a multiple of a dword
res = 4 - len(data) % 4
padding = b'\0' * (res % 4)
# Calculate 16-bit checksum
res = sum(array.array('I' if len(array.array('I', 4 * b'\0')) > 1 else 'H', bytes(data) + padding))
checksum = len(data)
checksum += res & 0xffff
checksum += res // 0x10000
checksum += checksum // 0x10000
checksum &= 0xffff
# Clamp the result to 32-bits
return checksum & 0xffffffff
def Machine(self):
return self['FileHeader']['Machine']
Portable = IMAGE_NT_HEADERS64 = IMAGE_NT_HEADERS
class SegmentEntry(pstruct.type):
'''
Base class for a section entry that both memory-backed and file-backed
entries inherit from.
'''
def properties(self):
res = super(SegmentEntry, self).properties()
if hasattr(self, 'Section'):
res['SectionName'] = self.Section['Name'].str()
return res
class MemorySegmentEntry(SegmentEntry):
'''
This SegmentEntry represents the structure of a segment that has been
already mapped into memory. This honors the SectionAlignment field from
the OptionalHeader when padding the segment's data.
'''
noncontiguous = True
def __Padding(self):
p = self.getparent(Next)
header = p.Header()
optionalheader = header['OptionalHeader'].li
return dyn.align(optionalheader['SectionAlignment'].int(), undefined=True)
_fields_ = [
(__Padding, 'Padding'),
(lambda self: dyn.block(self.Section.getloadedsize()), 'Data'),
]
class FileSegmentEntry(SegmentEntry):
'''
This SegmentEntry represents the structure of a segment that is on the
disk and hasn't been mapped into memory. This honors the FileAlignment
field from the OptionalHeader when padding the segment's data.
'''
def __Padding(self):
p = self.getparent(Next)
header = p.Header()
optionalheader = header['OptionalHeader'].li
return dyn.align(optionalheader['FileAlignment'].int(), undefined=True)
_fields_ = [
(__Padding, 'Padding'),
(lambda self: dyn.block(self.Section.getreadsize()), 'Data'),
]
class SegmentTableArray(parray.type):
'''
This is a simple array of segment entries where each entry is individually
tied directly to the SectionTableEntry that it is associated with. Each
entry is aligned depending on whether it is being loaded from disk or has
been already loaded into memory.
'''
def _object_(self):
p = self.getparent(Next)
header = p.Header()
sections = header['Sections']
entry = MemorySegmentEntry if isinstance(self.source, ptypes.provider.memorybase) else FileSegmentEntry
return dyn.clone(entry, Section=sections[len(self.value)])
@NextData.define
class IMAGE_NT_DATA(pstruct.type, Header):
type = b'PE'
def __Segments(self):
header = self.p.Header()
fileheader = header['FileHeader'].li
# Warn the user if we're unable to determine whether the source is a
# file-backed or memory-backed provider.
if all(not isinstance(self.source, item) for item in {ptypes.provider.memorybase, ptypes.provider.fileobj}):
cls = self.__class__
logging.warning("{:s} : Unknown ptype source.. treating as a fileobj : {!r}".format('.'.join((cls.__module__, cls.__name__)), self.source))
return dyn.clone(SegmentTableArray, length=fileheader['NumberOfSections'].int())
def __CertificatePadding(self):
header = self.p.Header()
if len(header['DataDirectory']) < 4:
return ptype.undefined
res = header['DataDirectory'][4]
offset, size = res['Address'].int(), res['Size'].int()
if offset == 0 or isinstance(self.source, ptypes.provider.memorybase):
return ptype.undefined
if isinstance(self.source, ptypes.provider.bounded) and offset < self.source.size():
res = self['Segments'].li.getoffset() + self['Segments'].blocksize()
return dyn.block(offset - res)
return ptype.undefined
def __Certificate(self):
header = self.p.Header()
if len(header['DataDirectory']) < 4:
return ptype.undefined
res = header['DataDirectory'][4]
offset, size = res['Address'].int(), res['Size'].int()
if offset == 0 or isinstance(self.source, ptypes.provider.memorybase):
return ptype.undefined
if isinstance(self.source, ptypes.provider.bounded) and offset < self.source.size():
return dyn.clone(parray.block, _object_=portable.headers.Certificate, blocksize=lambda self, size=size: size)
return ptype.undefined
_fields_ = [
(__Segments, 'Segments'),
(__CertificatePadding, 'CertificatePadding'),
(__Certificate, 'Certificate'),
]
@NextHeader.define
class DosExtender(pstruct.type, Header):
type = b'DX'
_fields_ = [
(word, 'MinRModeParams'),
(word, 'MaxRModeParams'),
(word, 'MinIBuffSize'),
(word, 'MaxIBuffSize'),
(word, 'NIStacks'),
(word, 'IStackSize'),
(dword, 'EndRModeOffset'),
(word, 'CallBuffSize'),
(word, 'Flags'),
(word, 'UnprivFlags'),
(dyn.block(104), 'Reserv'),
]
@NextHeader.define
class PharLap(pstruct.type, Header):
type = b'MP'
_fields_ = [
(word, 'SizeRemaind'),
(word, 'ImageSize'),
(word, 'NRelocs'),
(word, 'HeadSize'),
(word, 'MinExtraPages'),
(dword, 'ESP'),
(word, 'CheckSum'),
(dword, 'EIP'),
(word, 'FirstReloc'),
(word, 'NOverlay'),
(word, 'Reserved'),
]
class SegInfo(pstruct.type):
_fields_ = [
(word, 'Selector'),
(word, 'Flags'),
(dword, 'BaseOff'),
(dword, 'MinAlloc'),
]
class RunTimeParams(DosExtender): pass
class RepeatBlock(pstruct.type):
_fields_ = [
(word, 'Count'),
(lambda s: dyn.block(s['Count'].li.int()), 'String'),
]
@NextHeader.define
class PharLap3(PharLap, Header):
type = b'P3'
class OffsetSize(pstruct.type):
def __Offset(self):
t = getattr(self, '_object_', ptype.block)
return dyn.rpointer(lambda _: dyn.clone(t, blocksize=lambda _:self['Size'].li.int()), self.getparent(PharLap3), dword)
_fields_ = [
(__Offset, 'Offset'),
(dword, 'Size'),
]
def summary(self):
return '{:#x}:{:+#x}'.format(self['Offset'].int(), self['Size'].int())
_fields_ = [
(word, 'Level'),
(word, 'HeaderSize'),
(dword, 'FileSize'),
(word, 'CheckSum'),
(dyn.clone(OffsetSize, _object_=PharLap.RunTimeParams), 'RunTimeParams'),
(OffsetSize, 'Reloc'),
(dyn.clone(OffsetSize, _object_=dyn.clone(parray.block, _object_=PharLap.SegInfo)), 'SegInfo'),
(word, 'SegEntrySize'),
(OffsetSize, 'Image'),
(OffsetSize, 'SymTab'),
(OffsetSize, 'GDTLoc'),
(OffsetSize, 'LDTLoc'),
(OffsetSize, 'IDTLoc'),
(OffsetSize, 'TSSLoc'),
(dword, 'MinExtraPages'),
(dword, 'MaxExtraPages'),
(dword, 'Base'),
(dword, 'ESP'),
(word, 'SS'),
(dword, 'EIP'),
(word, 'CS'),
(word, 'LDT'),
(word, 'TSS'),
(word, 'Flags'),
(dword, 'MemReq'),
(dword, 'Checksum32'),
(dword, 'StackSize'),
(dyn.block(0x100), 'Reserv'),
]
@NextHeader.define
class NeHeader(pstruct.type):
type = b'NE'
class NE_Pointer(pstruct.type):
_fields_ = [
( uint16, 'Index' ),
( uint16, 'Offset' )
]
class NE_Version(pstruct.type):
_fields_ = [
( uint8, 'Minor' ),
( uint8, 'Major' )
]
_fields_ = [
( uint8, 'LinkVersion' ),
( uint8, 'LinkRevision' ),
( uint16, 'EntryOffset' ),
( uint16, 'EntryLength' ),
( uint32, 'CRC' ),
( uint8, 'ProgramFlags' ),
( uint8, 'ApplicationFlags' ),
( uint8, 'AutoDataSegmentIndex' ),
( uint16, 'HeapSize' ),
( uint16, 'StackSize' ),
( NE_Pointer, 'EntryPointer' ),
( NE_Pointer, 'StackPointer' ),
( uint16, 'SegmentCount' ),
( uint16, 'ModuleCount' ),
( uint16, 'NRNamesSize' ),
( uint16, 'SegmentOffset' ),
( uint16, 'ResourceOffset' ),
( uint16, 'RNamesOffset' ),
( uint16, 'ModuleOffset' ),
( uint16, 'ImportOffset' ),
( uint32, 'NRNamesOffset' ),
( uint16, 'MoveableEntryPointcount' ),
( uint16, 'AlignmentSize' ),
( uint16, 'ResourceCount' ),
( uint8, 'TargetOS' ),
( uint8, 'OS2_Flags' ),
( uint16, 'ReturnThunksOffset' ),
( uint16, 'SegmentThunksOffset' ),
( uint16, 'SwapMinimumSize' ),
( NE_Version, 'ExpectedVersion' )
]
### FileBase
class File(pstruct.type, ptype.boundary):
def __Padding(self):
dos = self['Header'].li
ofs = dos['e_lfarlc'].int()
return dyn.block(ofs - self.blocksize()) if ofs > 0 else dyn.block(0)
def __Relocations(self):
dos = self['Header'].li
ofs = dos['e_lfarlc'].int()
return dyn.array(Dos.Relocation, dos['e_crlc'].li.int() if ofs == self.blocksize() else 0)
def __Extra(self):
res = self['Header'].li.headersize()
if res > 0:
return dyn.block(res - self.blocksize())
return ptype.undefined
def __Stub(self):
# everything up to e_lfanew
dos = self['Header'].li
res = dos['e_lfanew'].int()
if res > 0:
return dyn.block(res - self.blocksize())
return ptype.undefined
def __Next(self):
dos = self['Header'].li
if dos['e_lfanew'].int() == self.blocksize():
return Next
return dyn.block(dos.filesize() - self.blocksize())
def __NotLoaded(self):
sz = self['Header'].blocksize()
sz+= self['Extra'].blocksize()
sz+= self['Stub'].blocksize()
sz+= self['Next'].blocksize()
if isinstance(self.source, ptypes.provider.bounded):
return dyn.block(self.source.size() - sz)
return ptype.undefined
_fields_ = [
(IMAGE_DOS_HEADER, 'Header'),
(__Extra, 'Extra'),
(__Stub, 'Stub'),
(__Next, 'Next'),
#(__NotLoaded, 'NotLoaded'),
]
if __name__ == '__main__':
import sys
import ptypes, pecoff.Executable
if len(sys.argv) == 2:
filename = sys.argv[1]
ptypes.setsource(ptypes.prov.file(filename, 'rb'))
z = pecoff.Executable.File()
z=z.l
else:
filename = 'obj/kernel32.dll'
ptypes.setsource(ptypes.prov.file(filename, 'rb'))
for x in range(10):
print(filename)
try:
z = pecoff.Executable.File()
z=z.l
break
except IOError:
pass
filename = '../'+filename
v=z['next']['header']
sections = v['Sections']
exports = v['DataDirectory'][0]
while exports['Address'].int() != 0:
exports = exports['Address'].d.l
print(exports.l)
break
imports = v['DataDirectory'][1]
while imports['Address'].int() != 0:
imports = imports['Address'].d.l
print(imports.l)
break
relo = v['DataDirectory'][5]['Address'].d.l
baseaddress = v['OptionalHeader']['ImageBase']
section = sections[0]
data = section.data().serialize()
for item in relo.filter(section):
for type, offset in item.getrelocations(section):
print(type, offset)
continue
| [
"array.array",
"operator.methodcaller",
"functools.partial",
"ptypes.prov.file"
] | [((6473, 6514), 'functools.partial', 'functools.partial', (['operator.getitem', 'self'], {}), '(operator.getitem, self)\n', (6490, 6514), False, 'import logging, operator, functools, itertools, array, ptypes\n'), ((20328, 20360), 'ptypes.prov.file', 'ptypes.prov.file', (['filename', '"""rb"""'], {}), "(filename, 'rb')\n", (20344, 20360), False, 'import ptypes, pecoff.Executable\n'), ((20486, 20518), 'ptypes.prov.file', 'ptypes.prov.file', (['filename', '"""rb"""'], {}), "(filename, 'rb')\n", (20502, 20518), False, 'import ptypes, pecoff.Executable\n'), ((6641, 6675), 'operator.methodcaller', 'operator.methodcaller', (['"""blocksize"""'], {}), "('blocksize')\n", (6662, 6675), False, 'import logging, operator, functools, itertools, array, ptypes\n'), ((9694, 9723), 'array.array', 'array.array', (['"""I"""', "(4 * b'\\x00')"], {}), "('I', 4 * b'\\x00')\n", (9705, 9723), False, 'import logging, operator, functools, itertools, array, ptypes\n')] |
import src.data_structures.heap
from src.algorithms.misc import powerfulIntegers
class Solution:
def balancedStringSplit(self, s: str) -> int:
bal = 0
stack = []
for c in s:
if c not in stack:
stack.append(c)
else:
stack.pop()
bal += 1
return bal
if __name__ == "__main__":
x = powerfulIntegers(2,3,10)
print(x)
else:
print("File one executed when imported") | [
"src.algorithms.misc.powerfulIntegers"
] | [((365, 391), 'src.algorithms.misc.powerfulIntegers', 'powerfulIntegers', (['(2)', '(3)', '(10)'], {}), '(2, 3, 10)\n', (381, 391), False, 'from src.algorithms.misc import powerfulIntegers\n')] |
from __future__ import print_function
from flask import Flask
from flask import request
import argparse
import json
import sys
from safirnotification.alarm.alarm_handler import AlarmHandler
from safirnotification.utils import log
from safirnotification.utils.opts import ConfigOpts
LOG = log.get_logger()
Flask.get = lambda self, path: self.route(path, methods=['get'])
app = Flask(__name__)
alarm_handler = None
@app.route('/alarm', methods=['POST'])
def alarm():
if request.method == 'POST':
try:
data = json.loads(request.data)
if 'alarm_id' not in data:
LOG.error("Failed processing alarm! " +
"Alarm ID not found", file=sys.stderr)
else:
LOG.info('ALARM RECEIVED. ID: ' + str(data['alarm_id']) +
' Current state: ' + data['current'] +
' Previous state: ' + data['previous'])
alarm_handler.handle_alarm(
alarm_id=data['alarm_id'],
current_state=data['current'],
previous_state=data['previous'],
reason=data['reason'])
except Exception as ex:
LOG.error("Failed processing alarm! " + ex.message)
return "AODH alarm received"
def main():
parser = argparse.ArgumentParser(prog='safirnotification')
parser.add_argument('-c', help='Config file path')
args = parser.parse_args()
config_file = args.c
if config_file is None:
print('usage: safirnotification -c <config-file-path>')
sys.exit(2)
global alarm_handler
alarm_handler = AlarmHandler(config_file)
config_opts = ConfigOpts(config_file)
host = config_opts.get_opt('api', 'host')
port = config_opts.get_opt('api', 'port')
app.run(host=host, port=port, threaded=True)
if __name__ == "__main__":
main()
| [
"safirnotification.alarm.alarm_handler.AlarmHandler",
"json.loads",
"safirnotification.utils.log.get_logger",
"argparse.ArgumentParser",
"flask.Flask",
"safirnotification.utils.opts.ConfigOpts",
"sys.exit"
] | [((291, 307), 'safirnotification.utils.log.get_logger', 'log.get_logger', ([], {}), '()\n', (305, 307), False, 'from safirnotification.utils import log\n'), ((381, 396), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (386, 396), False, 'from flask import Flask\n'), ((1357, 1406), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""safirnotification"""'}), "(prog='safirnotification')\n", (1380, 1406), False, 'import argparse\n'), ((1677, 1702), 'safirnotification.alarm.alarm_handler.AlarmHandler', 'AlarmHandler', (['config_file'], {}), '(config_file)\n', (1689, 1702), False, 'from safirnotification.alarm.alarm_handler import AlarmHandler\n'), ((1722, 1745), 'safirnotification.utils.opts.ConfigOpts', 'ConfigOpts', (['config_file'], {}), '(config_file)\n', (1732, 1745), False, 'from safirnotification.utils.opts import ConfigOpts\n'), ((1619, 1630), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (1627, 1630), False, 'import sys\n'), ((538, 562), 'json.loads', 'json.loads', (['request.data'], {}), '(request.data)\n', (548, 562), False, 'import json\n')] |
import logging
import click
import slack_sdk
from slack_primitive_cli.common.utils import TOKEN_ENVVAR, TOKEN_HELP_MESSAGE, set_logger
logger = logging.getLogger(__name__)
@click.command(
name="chat.postMessage", help="Sends a message to a channel. See https://api.slack.com/methods/chat.postMessage "
)
@click.option("--token", envvar=TOKEN_ENVVAR, required=True, help=TOKEN_HELP_MESSAGE)
@click.option(
"--channel",
required=True,
help="Channel, private group, or IM channel to send message to. "
"Can be an encoded ID, or a name. See below for more details.",
)
@click.option(
"--text",
required=True,
help="How this field works and whether it is required depends on other fields you use in your API call.",
)
@click.option("--as_user", type=bool, help="Pass true to post the message as the authed user, instead of as a bot.")
@click.option("--attachments", help="A JSON-based array of structured attachments, presented as a URL-encoded string.")
@click.option("--blocks", help="A JSON-based array of structured blocks, presented as a URL-encoded string.")
@click.option(
"--icon_emoji",
help="Emoji to use as the icon for this message. Overrides icon_url. "
"Must be used in conjunction with as_user set to false, otherwise ignored. See authorship below.",
)
@click.option(
"--icon_url",
help="URL to an image to use as the icon for this message. "
"Must be used in conjunction with as_user set to false, otherwise ignored. See authorship below.",
)
@click.option("--link_names", type=bool, help="Find and link channel names and usernames.")
@click.option("--mrkdwn", type=bool, help="Disable Slack markup parsing by setting to false.")
@click.option("--parse", type=bool, help="Change how messages are treated.")
@click.option(
"--reply_broadcast",
type=bool,
help="Used in conjunction with thread_ts and indicates "
"whether reply should be made visible to everyone in the channel or conversation.",
)
@click.option(
"--thread_ts",
help="Provide another message's ts value to make this message a reply. "
"Avoid using a reply's ts value; use its parent instead.",
)
@click.option("--unfurl_links", type=bool, help="Pass true to enable unfurling of primarily text-based content.")
@click.option("--unfurl_media", type=bool, help="Pass false to disable unfurling of media content.")
@click.option(
"--username",
help="Set your bot's user name. Must be used in conjunction with as_user set to false, otherwise ignored.",
)
def postMessage(
token: str,
channel: str,
text: str,
as_user,
attachments,
blocks,
icon_emoji,
icon_url,
link_names,
mrkdwn,
parse,
reply_broadcast,
thread_ts,
unfurl_links,
unfurl_media,
username,
):
set_logger()
client = slack_sdk.WebClient(token=token)
response = client.chat_postMessage(
channel=channel,
text=text,
as_user=as_user,
attachments=attachments,
blocks=blocks,
icon_emoji=icon_emoji,
icon_url=icon_url,
link_names=link_names,
mrkdwn=mrkdwn,
parse=parse,
reply_broadcast=reply_broadcast,
thread_ts=thread_ts,
unfurl_links=unfurl_links,
unfurl_media=unfurl_media,
username=username,
)
print(response)
return response
@click.command(name="chat.delete", help="Deletes a message. See https://api.slack.com/methods/chat.delete ")
@click.option("--token", envvar=TOKEN_ENVVAR, required=True, help=TOKEN_HELP_MESSAGE)
@click.option("--channel", required=True, help="Channel containing the message to be deleted.")
@click.option("--ts", required=True, help="Timestamp of the message to be deleted.")
@click.option(
"--as_user",
type=bool,
help="Pass true to delete the message as the authed user with chat:write:user scope. "
"Bot users in this context are considered authed users. "
"If unused or false, the message will be deleted with chat:write:bot scope.",
)
def delete(token: str, channel: str, ts: str, as_user):
set_logger()
client = slack_sdk.WebClient(token=token)
response = client.chat_delete(channel=channel, ts=ts, as_user=as_user)
print(response)
return response
| [
"logging.getLogger",
"slack_primitive_cli.common.utils.set_logger",
"click.option",
"slack_sdk.WebClient",
"click.command"
] | [((147, 174), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (164, 174), False, 'import logging\n'), ((178, 316), 'click.command', 'click.command', ([], {'name': '"""chat.postMessage"""', 'help': '"""Sends a message to a channel. See https://api.slack.com/methods/chat.postMessage """'}), "(name='chat.postMessage', help=\n 'Sends a message to a channel. See https://api.slack.com/methods/chat.postMessage '\n )\n", (191, 316), False, 'import click\n'), ((314, 403), 'click.option', 'click.option', (['"""--token"""'], {'envvar': 'TOKEN_ENVVAR', 'required': '(True)', 'help': 'TOKEN_HELP_MESSAGE'}), "('--token', envvar=TOKEN_ENVVAR, required=True, help=\n TOKEN_HELP_MESSAGE)\n", (326, 403), False, 'import click\n'), ((400, 577), 'click.option', 'click.option', (['"""--channel"""'], {'required': '(True)', 'help': '"""Channel, private group, or IM channel to send message to. Can be an encoded ID, or a name. See below for more details."""'}), "('--channel', required=True, help=\n 'Channel, private group, or IM channel to send message to. Can be an encoded ID, or a name. See below for more details.'\n )\n", (412, 577), False, 'import click\n'), ((591, 744), 'click.option', 'click.option', (['"""--text"""'], {'required': '(True)', 'help': '"""How this field works and whether it is required depends on other fields you use in your API call."""'}), "('--text', required=True, help=\n 'How this field works and whether it is required depends on other fields you use in your API call.'\n )\n", (603, 744), False, 'import click\n'), ((751, 871), 'click.option', 'click.option', (['"""--as_user"""'], {'type': 'bool', 'help': '"""Pass true to post the message as the authed user, instead of as a bot."""'}), "('--as_user', type=bool, help=\n 'Pass true to post the message as the authed user, instead of as a bot.')\n", (763, 871), False, 'import click\n'), ((868, 996), 'click.option', 'click.option', (['"""--attachments"""'], {'help': '"""A JSON-based array of structured attachments, presented as a URL-encoded string."""'}), "('--attachments', help=\n 'A JSON-based array of structured attachments, presented as a URL-encoded string.'\n )\n", (880, 996), False, 'import click\n'), ((988, 1106), 'click.option', 'click.option', (['"""--blocks"""'], {'help': '"""A JSON-based array of structured blocks, presented as a URL-encoded string."""'}), "('--blocks', help=\n 'A JSON-based array of structured blocks, presented as a URL-encoded string.'\n )\n", (1000, 1106), False, 'import click\n'), ((1098, 1303), 'click.option', 'click.option', (['"""--icon_emoji"""'], {'help': '"""Emoji to use as the icon for this message. Overrides icon_url. Must be used in conjunction with as_user set to false, otherwise ignored. See authorship below."""'}), "('--icon_emoji', help=\n 'Emoji to use as the icon for this message. Overrides icon_url. Must be used in conjunction with as_user set to false, otherwise ignored. See authorship below.'\n )\n", (1110, 1303), False, 'import click\n'), ((1313, 1506), 'click.option', 'click.option', (['"""--icon_url"""'], {'help': '"""URL to an image to use as the icon for this message. Must be used in conjunction with as_user set to false, otherwise ignored. See authorship below."""'}), "('--icon_url', help=\n 'URL to an image to use as the icon for this message. Must be used in conjunction with as_user set to false, otherwise ignored. See authorship below.'\n )\n", (1325, 1506), False, 'import click\n'), ((1516, 1611), 'click.option', 'click.option', (['"""--link_names"""'], {'type': 'bool', 'help': '"""Find and link channel names and usernames."""'}), "('--link_names', type=bool, help=\n 'Find and link channel names and usernames.')\n", (1528, 1611), False, 'import click\n'), ((1608, 1706), 'click.option', 'click.option', (['"""--mrkdwn"""'], {'type': 'bool', 'help': '"""Disable Slack markup parsing by setting to false."""'}), "('--mrkdwn', type=bool, help=\n 'Disable Slack markup parsing by setting to false.')\n", (1620, 1706), False, 'import click\n'), ((1703, 1778), 'click.option', 'click.option', (['"""--parse"""'], {'type': 'bool', 'help': '"""Change how messages are treated."""'}), "('--parse', type=bool, help='Change how messages are treated.')\n", (1715, 1778), False, 'import click\n'), ((1780, 1972), 'click.option', 'click.option', (['"""--reply_broadcast"""'], {'type': 'bool', 'help': '"""Used in conjunction with thread_ts and indicates whether reply should be made visible to everyone in the channel or conversation."""'}), "('--reply_broadcast', type=bool, help=\n 'Used in conjunction with thread_ts and indicates whether reply should be made visible to everyone in the channel or conversation.'\n )\n", (1792, 1972), False, 'import click\n'), ((1986, 2152), 'click.option', 'click.option', (['"""--thread_ts"""'], {'help': '"""Provide another message\'s ts value to make this message a reply. Avoid using a reply\'s ts value; use its parent instead."""'}), '(\'--thread_ts\', help=\n "Provide another message\'s ts value to make this message a reply. Avoid using a reply\'s ts value; use its parent instead."\n )\n', (1998, 2152), False, 'import click\n'), ((2162, 2279), 'click.option', 'click.option', (['"""--unfurl_links"""'], {'type': 'bool', 'help': '"""Pass true to enable unfurling of primarily text-based content."""'}), "('--unfurl_links', type=bool, help=\n 'Pass true to enable unfurling of primarily text-based content.')\n", (2174, 2279), False, 'import click\n'), ((2276, 2380), 'click.option', 'click.option', (['"""--unfurl_media"""'], {'type': 'bool', 'help': '"""Pass false to disable unfurling of media content."""'}), "('--unfurl_media', type=bool, help=\n 'Pass false to disable unfurling of media content.')\n", (2288, 2380), False, 'import click\n'), ((2377, 2521), 'click.option', 'click.option', (['"""--username"""'], {'help': '"""Set your bot\'s user name. Must be used in conjunction with as_user set to false, otherwise ignored."""'}), '(\'--username\', help=\n "Set your bot\'s user name. Must be used in conjunction with as_user set to false, otherwise ignored."\n )\n', (2389, 2521), False, 'import click\n'), ((3366, 3478), 'click.command', 'click.command', ([], {'name': '"""chat.delete"""', 'help': '"""Deletes a message. See https://api.slack.com/methods/chat.delete """'}), "(name='chat.delete', help=\n 'Deletes a message. See https://api.slack.com/methods/chat.delete ')\n", (3379, 3478), False, 'import click\n'), ((3475, 3564), 'click.option', 'click.option', (['"""--token"""'], {'envvar': 'TOKEN_ENVVAR', 'required': '(True)', 'help': 'TOKEN_HELP_MESSAGE'}), "('--token', envvar=TOKEN_ENVVAR, required=True, help=\n TOKEN_HELP_MESSAGE)\n", (3487, 3564), False, 'import click\n'), ((3561, 3660), 'click.option', 'click.option', (['"""--channel"""'], {'required': '(True)', 'help': '"""Channel containing the message to be deleted."""'}), "('--channel', required=True, help=\n 'Channel containing the message to be deleted.')\n", (3573, 3660), False, 'import click\n'), ((3657, 3745), 'click.option', 'click.option', (['"""--ts"""'], {'required': '(True)', 'help': '"""Timestamp of the message to be deleted."""'}), "('--ts', required=True, help=\n 'Timestamp of the message to be deleted.')\n", (3669, 3745), False, 'import click\n'), ((3742, 4005), 'click.option', 'click.option', (['"""--as_user"""'], {'type': 'bool', 'help': '"""Pass true to delete the message as the authed user with chat:write:user scope. Bot users in this context are considered authed users. If unused or false, the message will be deleted with chat:write:bot scope."""'}), "('--as_user', type=bool, help=\n 'Pass true to delete the message as the authed user with chat:write:user scope. Bot users in this context are considered authed users. If unused or false, the message will be deleted with chat:write:bot scope.'\n )\n", (3754, 4005), False, 'import click\n'), ((2793, 2805), 'slack_primitive_cli.common.utils.set_logger', 'set_logger', ([], {}), '()\n', (2803, 2805), False, 'from slack_primitive_cli.common.utils import TOKEN_ENVVAR, TOKEN_HELP_MESSAGE, set_logger\n'), ((2819, 2851), 'slack_sdk.WebClient', 'slack_sdk.WebClient', ([], {'token': 'token'}), '(token=token)\n', (2838, 2851), False, 'import slack_sdk\n'), ((4085, 4097), 'slack_primitive_cli.common.utils.set_logger', 'set_logger', ([], {}), '()\n', (4095, 4097), False, 'from slack_primitive_cli.common.utils import TOKEN_ENVVAR, TOKEN_HELP_MESSAGE, set_logger\n'), ((4111, 4143), 'slack_sdk.WebClient', 'slack_sdk.WebClient', ([], {'token': 'token'}), '(token=token)\n', (4130, 4143), False, 'import slack_sdk\n')] |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext as _
from jaseci_serv.base import models
class UserAdmin(BaseUserAdmin):
"""
Customized user listing for admin page
"""
ordering = ["time_created"]
list_display = ["email", "name", "time_created"]
fieldsets = (
(None, {"fields": ("email", "password")}),
(_("Personal Info"), {"fields": ("name",)}),
(
_("Permissions"),
{
"fields": (
"is_active",
"is_activated",
"is_staff",
"is_admin",
"is_superuser",
)
},
),
(_("Important dates"), {"fields": ("last_login",)}),
)
add_fieldsets = (
(None, {"classes": ("wide",), "fields": ("email", "<PASSWORD>", "<PASSWORD>")}),
)
admin.site.register(models.User, UserAdmin)
class JaseciObjectAdmin(admin.ModelAdmin):
ordering = ["j_timestamp"]
list_display = ("jid", "name", "j_type", "j_parent", "j_master", "j_timestamp")
search_fields = [
"jid",
"name",
"j_type",
"j_parent",
"j_master",
"j_timestamp",
]
admin.site.register(models.JaseciObject, JaseciObjectAdmin)
class GlobalVarsAdmin(admin.ModelAdmin):
ordering = ["name"]
list_display = ("name", "value")
search_fields = ["name", "value"]
admin.site.register(models.GlobalVars, GlobalVarsAdmin)
| [
"django.contrib.admin.site.register",
"django.utils.translation.gettext"
] | [((967, 1010), 'django.contrib.admin.site.register', 'admin.site.register', (['models.User', 'UserAdmin'], {}), '(models.User, UserAdmin)\n', (986, 1010), False, 'from django.contrib import admin\n'), ((1313, 1372), 'django.contrib.admin.site.register', 'admin.site.register', (['models.JaseciObject', 'JaseciObjectAdmin'], {}), '(models.JaseciObject, JaseciObjectAdmin)\n', (1332, 1372), False, 'from django.contrib import admin\n'), ((1517, 1572), 'django.contrib.admin.site.register', 'admin.site.register', (['models.GlobalVars', 'GlobalVarsAdmin'], {}), '(models.GlobalVars, GlobalVarsAdmin)\n', (1536, 1572), False, 'from django.contrib import admin\n'), ((442, 460), 'django.utils.translation.gettext', '_', (['"""Personal Info"""'], {}), "('Personal Info')\n", (443, 460), True, 'from django.utils.translation import gettext as _\n'), ((508, 524), 'django.utils.translation.gettext', '_', (['"""Permissions"""'], {}), "('Permissions')\n", (509, 524), True, 'from django.utils.translation import gettext as _\n'), ((790, 810), 'django.utils.translation.gettext', '_', (['"""Important dates"""'], {}), "('Important dates')\n", (791, 810), True, 'from django.utils.translation import gettext as _\n')] |
from re import match
with open("input.txt") as x:
lines = x.read().strip().split("\n\n")
lines = [line.replace("\n", " ") for line in lines]
valid = 0
fields = {
'byr': lambda x: 1920 <= int(x) <= 2002,
'iyr': lambda x: 2010 <= int(x) <= 2020,
'eyr': lambda x: 2020 <= int(x) <= 2030,
'hgt': lambda x: (x[-2:] == 'cm' and 150 <= int(x[:-2]) <= 193) or (x[-2:] == 'in' and 59 <= int(x[:-2]) <= 76),
'hcl': lambda x: match(r"^#[a-f0-9]{6}$", x), # match only matches from beginning of string
'ecl': lambda x: x in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'],
'pid': lambda x: x.isnumeric() and len(x) == 9
}
for passport in lines:
pd = dict(tuple(i.split(":")) for i in passport.split())
if all((field in pd.keys() and fields[field](pd[field])) for field in fields):
valid += 1
print(valid)
| [
"re.match"
] | [((462, 488), 're.match', 'match', (['"""^#[a-f0-9]{6}$"""', 'x'], {}), "('^#[a-f0-9]{6}$', x)\n", (467, 488), False, 'from re import match\n')] |
"""Test ImageNet pretrained DenseNet"""
import cv2
import numpy as np
from tensorflow.keras.optimizers import SGD
import tensorflow.keras.backend as K
# We only test DenseNet-121 in this script for demo purpose
from densenet121 import DenseNet
im = cv2.resize(cv2.imread('resources/cat.jpg'), (224, 224)).astype(np.float32)
#im = cv2.resize(cv2.imread('shark.jpg'), (224, 224)).astype(np.float32)
# Subtract mean pixel and multiple by scaling constant
# Reference: https://github.com/shicai/DenseNet-Caffe
im[:,:,0] = (im[:,:,0] - 103.94) * 0.017
im[:,:,1] = (im[:,:,1] - 116.78) * 0.017
im[:,:,2] = (im[:,:,2] - 123.68) * 0.017
print(K.image_data_format())
# Use pre-trained weights for Tensorflow backend
weights_path = 'imagenet_models/densenet121_weights_tf.h5'
# Insert a new dimension for the batch_size
im = np.expand_dims(im, axis=0)
# Test pretrained model
model = DenseNet(reduction=0.5, classes=1000, weights_path=weights_path)
sgd = SGD(lr=1e-2, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])
out = model.predict(im)
# Load ImageNet classes file
classes = []
with open('resources/classes.txt', 'r') as list_:
for line in list_:
classes.append(line.rstrip('\n'))
print('Prediction: '+str(classes[np.argmax(out)]))
| [
"numpy.argmax",
"tensorflow.keras.optimizers.SGD",
"densenet121.DenseNet",
"numpy.expand_dims",
"cv2.imread",
"tensorflow.keras.backend.image_data_format"
] | [((822, 848), 'numpy.expand_dims', 'np.expand_dims', (['im'], {'axis': '(0)'}), '(im, axis=0)\n', (836, 848), True, 'import numpy as np\n'), ((882, 946), 'densenet121.DenseNet', 'DenseNet', ([], {'reduction': '(0.5)', 'classes': '(1000)', 'weights_path': 'weights_path'}), '(reduction=0.5, classes=1000, weights_path=weights_path)\n', (890, 946), False, 'from densenet121 import DenseNet\n'), ((954, 1008), 'tensorflow.keras.optimizers.SGD', 'SGD', ([], {'lr': '(0.01)', 'decay': '(1e-06)', 'momentum': '(0.9)', 'nesterov': '(True)'}), '(lr=0.01, decay=1e-06, momentum=0.9, nesterov=True)\n', (957, 1008), False, 'from tensorflow.keras.optimizers import SGD\n'), ((641, 662), 'tensorflow.keras.backend.image_data_format', 'K.image_data_format', ([], {}), '()\n', (660, 662), True, 'import tensorflow.keras.backend as K\n'), ((264, 295), 'cv2.imread', 'cv2.imread', (['"""resources/cat.jpg"""'], {}), "('resources/cat.jpg')\n", (274, 295), False, 'import cv2\n'), ((1303, 1317), 'numpy.argmax', 'np.argmax', (['out'], {}), '(out)\n', (1312, 1317), True, 'import numpy as np\n')] |
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,SubmitField,BooleanField
from flask_wtf.file import FileAllowed,FileRequired,FileField
from wtforms.validators import DataRequired,Length,EqualTo,Email,ValidationError
from App.models import User
from App.extensions import file
class Register(FlaskForm):
username = StringField('用户名',validators=[DataRequired('用户名不能为空'),Length(min=6,max=12,message='用户名在6~12位之间')],render_kw={'placeholder':'请输入用户名','minlength':6,'maxlength':12})
userpass = PasswordField('密码',validators=[DataRequired('密码不能为空'),Length(min=6,max=12,message='密码在6~12位之间')],render_kw={'placeholder':'请输入密码','minlength':6,'maxlength':12})
confirm = PasswordField('确认密码',validators=[DataRequired('确认密码不能为空'),Length(min=6,max=12,message='密码在6~12位之间'),EqualTo('userpass',message='确认密码和密码不一致')],render_kw={'placeholder':'请输入确认密码','minlength':6,'maxlength':12})
email = StringField('邮箱',validators=[DataRequired('邮箱不能为空'),Email('请输入正确的邮箱地址')],render_kw={'placeholder':'请输入有效的邮箱地址'})
icon = FileField('选择头像',validators=[FileAllowed(file,message='该文件类型不允许上传!'),FileRequired('您还没有选择文件')])
submit = SubmitField('注册')
def validate_username(self,field):
if User.query.filter_by(username=field.data).first():
raise ValidationError('该用户名已存在,请重新输入')
def validate_email(self,field):
if User.query.filter_by(email=field.data).first():
raise ValidationError('该邮箱已存在,请重新输入')
class Login(FlaskForm):
username = StringField('用户名',validators=[DataRequired('用户名不能为空'),Length(min=6,max=12,message='用户名在6~12位之间')],render_kw={'placeholder':'请输入用户名','minlength':6,'maxlength':12})
userpass = PasswordField('密码',validators=[DataRequired('密码不能为空'),Length(min=6,max=12,message='密码在6~12位之间')],render_kw={'placeholder':'请输入密码','minlength':6,'maxlength':12})
remember = BooleanField('记住我')
submit = SubmitField('登录')
def validate_username(self,field):
if not User.query.filter_by(username=field.data).first():
raise ValidationError('该用户名不存在,请重新输入')
class Changeinfo(FlaskForm):
username = StringField('用户名',validators=[DataRequired('用户名不能为空'),Length(min=6,max=12,message='用户名在6~12位之间')],render_kw={'placeholder':'请输入用户名','minlength':6,'maxlength':12})
email = StringField('邮箱',validators=[DataRequired('邮箱不能为空'),Email('请输入正确的邮箱地址')],render_kw={'placeholder':'请输入有效的邮箱地址'})
icon = FileField('选择头像', validators=[FileAllowed(file, message='该文件类型不允许上传!'), FileRequired('您还没有选择文件')])
submit = SubmitField('修改')
def validate_username(self,field):
if User.query.filter_by(username=field.data).first():
raise ValidationError('该用户名已存在,请重新输入')
def validate_email(self,field):
if User.query.filter_by(email=field.data).first():
raise ValidationError('该邮箱已存在,请重新输入') | [
"wtforms.validators.Email",
"wtforms.validators.ValidationError",
"flask_wtf.file.FileAllowed",
"wtforms.BooleanField",
"wtforms.SubmitField",
"wtforms.validators.EqualTo",
"App.models.User.query.filter_by",
"flask_wtf.file.FileRequired",
"wtforms.validators.Length",
"wtforms.validators.DataRequir... | [((1156, 1173), 'wtforms.SubmitField', 'SubmitField', (['"""注册"""'], {}), "('注册')\n", (1167, 1173), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((1867, 1886), 'wtforms.BooleanField', 'BooleanField', (['"""记住我"""'], {}), "('记住我')\n", (1879, 1886), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((1900, 1917), 'wtforms.SubmitField', 'SubmitField', (['"""登录"""'], {}), "('登录')\n", (1911, 1917), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((2532, 2549), 'wtforms.SubmitField', 'SubmitField', (['"""修改"""'], {}), "('修改')\n", (2543, 2549), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((1294, 1326), 'wtforms.validators.ValidationError', 'ValidationError', (['"""该用户名已存在,请重新输入"""'], {}), "('该用户名已存在,请重新输入')\n", (1309, 1326), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((1441, 1472), 'wtforms.validators.ValidationError', 'ValidationError', (['"""该邮箱已存在,请重新输入"""'], {}), "('该邮箱已存在,请重新输入')\n", (1456, 1472), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((2042, 2074), 'wtforms.validators.ValidationError', 'ValidationError', (['"""该用户名不存在,请重新输入"""'], {}), "('该用户名不存在,请重新输入')\n", (2057, 2074), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((2670, 2702), 'wtforms.validators.ValidationError', 'ValidationError', (['"""该用户名已存在,请重新输入"""'], {}), "('该用户名已存在,请重新输入')\n", (2685, 2702), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((2817, 2848), 'wtforms.validators.ValidationError', 'ValidationError', (['"""该邮箱已存在,请重新输入"""'], {}), "('该邮箱已存在,请重新输入')\n", (2832, 2848), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((386, 409), 'wtforms.validators.DataRequired', 'DataRequired', (['"""用户名不能为空"""'], {}), "('用户名不能为空')\n", (398, 409), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((424, 468), 'wtforms.validators.Length', 'Length', ([], {'min': '(6)', 'max': '(12)', 'message': '"""用户名在6~12位之间"""'}), "(min=6, max=12, message='用户名在6~12位之间')\n", (430, 468), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((563, 585), 'wtforms.validators.DataRequired', 'DataRequired', (['"""密码不能为空"""'], {}), "('密码不能为空')\n", (575, 585), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((598, 641), 'wtforms.validators.Length', 'Length', ([], {'min': '(6)', 'max': '(12)', 'message': '"""密码在6~12位之间"""'}), "(min=6, max=12, message='密码在6~12位之间')\n", (604, 641), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((744, 768), 'wtforms.validators.DataRequired', 'DataRequired', (['"""确认密码不能为空"""'], {}), "('确认密码不能为空')\n", (756, 768), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((785, 828), 'wtforms.validators.Length', 'Length', ([], {'min': '(6)', 'max': '(12)', 'message': '"""密码在6~12位之间"""'}), "(min=6, max=12, message='密码在6~12位之间')\n", (791, 828), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((839, 880), 'wtforms.validators.EqualTo', 'EqualTo', (['"""userpass"""'], {'message': '"""确认密码和密码不一致"""'}), "('userpass', message='确认密码和密码不一致')\n", (846, 880), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((956, 978), 'wtforms.validators.DataRequired', 'DataRequired', (['"""邮箱不能为空"""'], {}), "('邮箱不能为空')\n", (968, 978), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((991, 1010), 'wtforms.validators.Email', 'Email', (['"""请输入正确的邮箱地址"""'], {}), "('请输入正确的邮箱地址')\n", (996, 1010), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((1084, 1124), 'flask_wtf.file.FileAllowed', 'FileAllowed', (['file'], {'message': '"""该文件类型不允许上传!"""'}), "(file, message='该文件类型不允许上传!')\n", (1095, 1124), False, 'from flask_wtf.file import FileAllowed, FileRequired, FileField\n'), ((1142, 1166), 'flask_wtf.file.FileRequired', 'FileRequired', (['"""您还没有选择文件"""'], {}), "('您还没有选择文件')\n", (1154, 1166), False, 'from flask_wtf.file import FileAllowed, FileRequired, FileField\n'), ((1225, 1266), 'App.models.User.query.filter_by', 'User.query.filter_by', ([], {'username': 'field.data'}), '(username=field.data)\n', (1245, 1266), False, 'from App.models import User\n'), ((1375, 1413), 'App.models.User.query.filter_by', 'User.query.filter_by', ([], {'email': 'field.data'}), '(email=field.data)\n', (1395, 1413), False, 'from App.models import User\n'), ((1549, 1572), 'wtforms.validators.DataRequired', 'DataRequired', (['"""用户名不能为空"""'], {}), "('用户名不能为空')\n", (1561, 1572), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((1587, 1631), 'wtforms.validators.Length', 'Length', ([], {'min': '(6)', 'max': '(12)', 'message': '"""用户名在6~12位之间"""'}), "(min=6, max=12, message='用户名在6~12位之间')\n", (1593, 1631), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((1726, 1748), 'wtforms.validators.DataRequired', 'DataRequired', (['"""密码不能为空"""'], {}), "('密码不能为空')\n", (1738, 1748), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((1761, 1804), 'wtforms.validators.Length', 'Length', ([], {'min': '(6)', 'max': '(12)', 'message': '"""密码在6~12位之间"""'}), "(min=6, max=12, message='密码在6~12位之间')\n", (1767, 1804), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((2157, 2180), 'wtforms.validators.DataRequired', 'DataRequired', (['"""用户名不能为空"""'], {}), "('用户名不能为空')\n", (2169, 2180), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((2195, 2239), 'wtforms.validators.Length', 'Length', ([], {'min': '(6)', 'max': '(12)', 'message': '"""用户名在6~12位之间"""'}), "(min=6, max=12, message='用户名在6~12位之间')\n", (2201, 2239), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((2329, 2351), 'wtforms.validators.DataRequired', 'DataRequired', (['"""邮箱不能为空"""'], {}), "('邮箱不能为空')\n", (2341, 2351), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((2364, 2383), 'wtforms.validators.Email', 'Email', (['"""请输入正确的邮箱地址"""'], {}), "('请输入正确的邮箱地址')\n", (2369, 2383), False, 'from wtforms.validators import DataRequired, Length, EqualTo, Email, ValidationError\n'), ((2458, 2498), 'flask_wtf.file.FileAllowed', 'FileAllowed', (['file'], {'message': '"""该文件类型不允许上传!"""'}), "(file, message='该文件类型不允许上传!')\n", (2469, 2498), False, 'from flask_wtf.file import FileAllowed, FileRequired, FileField\n'), ((2518, 2542), 'flask_wtf.file.FileRequired', 'FileRequired', (['"""您还没有选择文件"""'], {}), "('您还没有选择文件')\n", (2530, 2542), False, 'from flask_wtf.file import FileAllowed, FileRequired, FileField\n'), ((2601, 2642), 'App.models.User.query.filter_by', 'User.query.filter_by', ([], {'username': 'field.data'}), '(username=field.data)\n', (2621, 2642), False, 'from App.models import User\n'), ((2751, 2789), 'App.models.User.query.filter_by', 'User.query.filter_by', ([], {'email': 'field.data'}), '(email=field.data)\n', (2771, 2789), False, 'from App.models import User\n'), ((1973, 2014), 'App.models.User.query.filter_by', 'User.query.filter_by', ([], {'username': 'field.data'}), '(username=field.data)\n', (1993, 2014), False, 'from App.models import User\n')] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Class that manages a UQtie application's stylesheet
There are advantages and disadvantages to Qt stylesheets, Qt settings, and
Qt Style. They aren't mutually exclusive, and they don't all play together
either.
This module attempts to make it possible to use a stylesheet while still
using the QFontDialog to select fonts, and zoom-in/zoom-out shortcuts such
as CTRL-+.
The idea is that we have variables (which come from somewhere, right now a
pickled dictionary, but later could be elsewhere, or multiple elsewheres).
These variables can be used in the stylesheet, such that the dynamic changes in
appearance can be made at runtime without requiring stylesheet changes, and the
changes can be persisted also without changing the stylesheet.
Font, font size and widget sizes (e.g QScrollBar:vertical { width } ) seem like
good candidates to be determined dynamically instead of via hardcoded values
in a stylesheet. That way, when you have high-DPI monitor and less-than-perfect
vision, you can adjust easily.
Part of my motivation for doing this is because PyQt running on Windows, Linux,
MacOS and Cygwin doesn't behave identically, not even close to identical in
some ways. If they would all have identical QScreens given identical monitors
and graphics cards, then you could just make reasonable choices for your stylesheet,
and rely on the OS GUI settings.
Variables you can use in a QSS file are:
$main_font_family
$main_font_weight (not supported yet)
$main_font_size
$scroll_bar_width
Futures:
1) Add more variables
2) Make an inspector widget for stylesheet variables
"""
from __future__ import print_function
from pathlib import Path
import os,re,pickle
from PyQt5.QtCore import QSettings
class StylesheetManager(object):
"""
Class that manages a UQtie application's stylesheet
"""
# If no stylesheet has been provided, use this one. Should this
# really have scroll bar dimensions?
defaultStylesheet = """
QWidget {
font-family: $main_font_family;
font-weight: $main_font_weight;
font-size: $main_font_size;
}
QScrollBar:vertical {
width: $scroll_bar_width;
}
QScrollBar:horizontal {
height: $scroll_bar_width;
}
"""
def __init__(self, app, settings, appName ):
self.stylesheetFileName = None
self.stylesheetVarsFileName = None
self.app = app
self.appName = appName
self.appSettings = settings
self.varsDict = {}
self.defaultVarsDict = {
'main_font_family': 'Arial',
'main_font_weight': 'Regular',
'main_font_size' : '16pt',
'scroll_bar_width': '15px',
}
self.determine_stylesheet_filenames(appName)
def determine_stylesheet_path(self):
"""
Fill in self.appDirPath appropriately
"""
self.appDirPath = None
if os.name == 'nt':
# running on Windows
appDirPath = Path(os.path.expanduser('~')) / 'Application Files'
if not appDirPath.is_dir():
print ( '{p} is not a directory'.format(p=appDirPath))
return
appDirPath /= self.appName
if not appDirPath.is_dir():
try:
appDirPath.mkdir()
except:
print ( 'Could not create directory {p}'.format(p=appdirPath))
return
self.appDirPath = appDirPath
else:
# On other OS, we use Settings to determine where stylesheet lives
if self.appSettings:
self.appDirPath = Path(os.path.dirname(self.appSettings.fileName()))
def determine_stylesheet_filenames(self, appName):
"""
Fill in stylesheet filenames appropriately
"""
self.determine_stylesheet_path()
if self.appDirPath:
#print ("self.appDirPath: {}".format(self.appDirPath))
baseName = str(self.appDirPath / appName)
self.stylesheetFileName = baseName + '.qss'
self.stylesheetVarsFileName = baseName + 'Vars.pickle'
def apply(self):
"""
Apply the application window stylesheet, including variable value substitution
"""
# This means:
# 1) Read it from a file
# 2) Replace all '{' and '}' which are QSS syntax (e.g. 'QWidget {') with
# '{{' and '}}'. This protects the QSS syntax during the next steps.
# 3) Replace all $word with {word} thus turning the string into a Python
# string with argument specifiers (e.g. '{main_font_family}').
# 4) Replace all the format-string argument specifiers with variables
# 5) Apply the resulting stylesheet to the App
#print ( "apply: {}".format(self.stylesheetFileName))
stylesheetText = None
try:
with open(self.stylesheetFileName, 'r') as content_file:
stylesheetText = content_file.read()
except:
pass
if not stylesheetText:
print(f'No file {self.stylesheetFileName}')
stylesheetText = self.defaultStylesheet
try:
with open(self.stylesheetFileName, 'w') as content_file:
content_file.write(stylesheetText)
except:
print(f'Could not write default stylesheet file {self.stylesheetFileName}')
# These next two could be done in one pass using the cool multiple_replace() from
# https://stackoverflow.com/questions/15175142/how-can-i-do-multiple-substitutions-using-regex-in-python
# But this is easier to read
stylesheetText = stylesheetText.replace('{', '{{')
stylesheetText = stylesheetText.replace('}', '}}')
# Turn all $word into {word}
stylesheetText = re.sub(r'\$(([a-z]|[A-Z])\w*)', r'{\1}', stylesheetText)
# for k, v in self.varsDict.items():
# print ( f'{k}: {v}' )
# substitute everything from our variables dict
result = stylesheetText.format_map(self.varsDict)
# apply
self.app.setStyleSheet(result)
def save_stylesheet_vars(self ):
"""Write our variables dict out to a file"""
with open(self.stylesheetVarsFileName, 'wb') as h:
pickle.dump(self.varsDict, h)
def set_missing_stylesheet_vars(self ):
"""Set all the missing variables in the variables dict to default values"""
for k in self.defaultVarsDict:
self.varsDict.setdefault(k, self.defaultVarsDict[k])
def read_stylesheet_vars(self ):
"""Read all the variables from saved file into our dict"""
try:
with open(self.stylesheetVarsFileName, 'rb') as h:
self.varsDict = pickle.loads(h.read())
except FileNotFoundError as e:
print(e)
# Maybe some values are missing, fix it up
self.set_missing_stylesheet_vars()
def zoom_in(self):
"""Increase the value of variables that influence the size of the UI"""
# Trim off 'pt' at the end of the string. Maybe a little fragile...
fontSize = int(self.varsDict['main_font_size'][0:-2])
fontSize += 1
self.varsDict['main_font_size'] = f'{fontSize}pt'
# Trim off 'px' at the end of the string. Also a little fragile...
scrollBarWidth = int(self.varsDict['scroll_bar_width'][0:-2])
scrollBarWidth += 1
self.varsDict['scroll_bar_width'] = f'{scrollBarWidth}px'
def zoom_out(self):
"""Decrease the value of variables that influence the size of the UI"""
# Trim off 'pt' at the end of the string. Maybe a little fragile...
fontSize = int(self.varsDict['main_font_size'][0:-2])
if fontSize > 0:
fontSize -= 1
self.varsDict['main_font_size'] = f'{fontSize}pt'
# Trim off 'px' at the end of the string. Also a little fragile...
scrollBarWidth = int(self.varsDict['scroll_bar_width'][0:-2])
if scrollBarWidth > 0:
scrollBarWidth -= 1
self.varsDict['scroll_bar_width'] = f'{scrollBarWidth}px'
# Variable setters / Properties - don't want to keep adding these for every variable
# and the way it is evolving, it seems like we don't have to
def set_main_font_family(self, family):
self.varsDict['main_font_family'] = family
def set_main_font_weight(self, weight):
self.varsDict['main_font_weight'] = weight
def set_main_font_size(self, size):
self.varsDict['main_font_size'] = size
## Test Code
import argparse, sys
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QMainWindow
class TestAppMainWindow(QMainWindow):
def __init__(self, parsedArgs, **kwargs ):
super(TestAppMainWindow, self).__init__()
self.setup_ui()
self.show()
def setup_ui(self):
vbox = QVBoxLayout(self.centralWidget())
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-w', '--test-write-vars', action='store_const', const=True,
help='Test writing variables to file')
parser.add_argument('-r', '--test-read-vars', action='store_const', const=True,
help='Test reading variables from file')
parsedArgs,unparsedArgs = parser.parse_known_args()
organizationName='Craton'
appName='StyMgrTest'
# Pass unparsed args to Qt, might have some X Windows args, like --display
qtArgs = sys.argv[:1] + unparsedArgs
app = QApplication(qtArgs)
settings = QSettings(organizationName, appName)
styMgr = StylesheetManager(app, settings, appName)
if parsedArgs.test_write_vars:
print('write')
styMgr.save_stylesheet_vars()
sys.exit(0)
if parsedArgs.test_read_vars:
print('read')
styMgr.read_stylesheet_vars()
for k, v in styMgr.varsDict.items():
print(k, v)
sys.exit(0)
mainw = TestAppMainWindow(parsedArgs, app=app, organizationName=organizationName, appName=appName)
sys.exit(app.exec_())
| [
"pickle.dump",
"argparse.ArgumentParser",
"PyQt5.QtCore.QSettings",
"PyQt5.QtWidgets.QApplication",
"sys.exit",
"re.sub",
"os.path.expanduser"
] | [((9201, 9226), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (9224, 9226), False, 'import argparse, sys\n'), ((9767, 9787), 'PyQt5.QtWidgets.QApplication', 'QApplication', (['qtArgs'], {}), '(qtArgs)\n', (9779, 9787), False, 'from PyQt5.QtWidgets import QApplication, QVBoxLayout, QMainWindow\n'), ((9804, 9840), 'PyQt5.QtCore.QSettings', 'QSettings', (['organizationName', 'appName'], {}), '(organizationName, appName)\n', (9813, 9840), False, 'from PyQt5.QtCore import QSettings\n'), ((6045, 6102), 're.sub', 're.sub', (['"""\\\\$(([a-z]|[A-Z])\\\\w*)"""', '"""{\\\\1}"""', 'stylesheetText'], {}), "('\\\\$(([a-z]|[A-Z])\\\\w*)', '{\\\\1}', stylesheetText)\n", (6051, 6102), False, 'import os, re, pickle\n'), ((10002, 10013), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (10010, 10013), False, 'import argparse, sys\n'), ((10186, 10197), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (10194, 10197), False, 'import argparse, sys\n'), ((6516, 6545), 'pickle.dump', 'pickle.dump', (['self.varsDict', 'h'], {}), '(self.varsDict, h)\n', (6527, 6545), False, 'import os, re, pickle\n'), ((3155, 3178), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (3173, 3178), False, 'import os, re, pickle\n')] |
##########################################################################
# NSAp - Copyright (C) CEA, 2013
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
##########################################################################
# System import
from packaging import version
# Cubicweb import
import cubicweb
cw_version = version.parse(cubicweb.__version__)
if cw_version >= version.parse("3.21.0"):
from cubicweb import _
from cubicweb.predicates import is_instance
from cubicweb.predicates import authenticated_user
from cubicweb.web.action import Action
from cubicweb.web.views.wdoc import HelpAction, AboutAction
from cubicweb.web.views.actions import PoweredByAction
from cubicweb.web.views.actions import UserPreferencesAction
from cubicweb.web.views.actions import UserInfoAction
from logilab.common.registry import yes
###############################################################################
# ACTIONS
###############################################################################
class NeurospinAction(Action):
__regid__ = "neurospin"
__select__ = yes()
category = "footer"
order = 1
title = _("NeuroSpin")
def url(self):
return "http://i2bm.cea.fr/drf/i2bm/NeuroSpin"
class LicenseAction(Action):
__regid__ = "license"
__select__ = yes()
category = "footer"
order = 2
title = _("License")
def url(self):
return self._cw.build_url("license")
class PIWSPoweredByAction(Action):
__regid__ = "poweredby"
__select__ = yes()
category = "footer"
order = 3
title = _("Powered by NSAp")
def url(self):
return "https://github.com/neurospin/piws"
def registration_callback(vreg):
# Update the footer
vreg.register_and_replace(PIWSPoweredByAction, PoweredByAction)
vreg.register(NeurospinAction)
vreg.register(LicenseAction)
vreg.unregister(HelpAction)
vreg.unregister(AboutAction)
vreg.unregister(UserPreferencesAction)
vreg.unregister(UserInfoAction)
| [
"cubicweb._",
"packaging.version.parse",
"logilab.common.registry.yes"
] | [((480, 515), 'packaging.version.parse', 'version.parse', (['cubicweb.__version__'], {}), '(cubicweb.__version__)\n', (493, 515), False, 'from packaging import version\n'), ((533, 556), 'packaging.version.parse', 'version.parse', (['"""3.21.0"""'], {}), "('3.21.0')\n", (546, 556), False, 'from packaging import version\n'), ((1240, 1245), 'logilab.common.registry.yes', 'yes', ([], {}), '()\n', (1243, 1245), False, 'from logilab.common.registry import yes\n'), ((1296, 1310), 'cubicweb._', '_', (['"""NeuroSpin"""'], {}), "('NeuroSpin')\n", (1297, 1310), False, 'from cubicweb import _\n'), ((1460, 1465), 'logilab.common.registry.yes', 'yes', ([], {}), '()\n', (1463, 1465), False, 'from logilab.common.registry import yes\n'), ((1516, 1528), 'cubicweb._', '_', (['"""License"""'], {}), "('License')\n", (1517, 1528), False, 'from cubicweb import _\n'), ((1676, 1681), 'logilab.common.registry.yes', 'yes', ([], {}), '()\n', (1679, 1681), False, 'from logilab.common.registry import yes\n'), ((1733, 1753), 'cubicweb._', '_', (['"""Powered by NSAp"""'], {}), "('Powered by NSAp')\n", (1734, 1753), False, 'from cubicweb import _\n')] |
# Generated by Django 2.0 on 2018-08-25 14:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("events", "0042_allow_team_without_country")]
operations = [
migrations.RemoveField(model_name="team", name="is_premium"),
migrations.RemoveField(model_name="team", name="premium_by"),
migrations.RemoveField(model_name="team", name="premium_expires"),
migrations.RemoveField(model_name="team", name="premium_started"),
]
| [
"django.db.migrations.RemoveField"
] | [((217, 277), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""team"""', 'name': '"""is_premium"""'}), "(model_name='team', name='is_premium')\n", (239, 277), False, 'from django.db import migrations\n'), ((287, 347), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""team"""', 'name': '"""premium_by"""'}), "(model_name='team', name='premium_by')\n", (309, 347), False, 'from django.db import migrations\n'), ((357, 422), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""team"""', 'name': '"""premium_expires"""'}), "(model_name='team', name='premium_expires')\n", (379, 422), False, 'from django.db import migrations\n'), ((432, 497), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""team"""', 'name': '"""premium_started"""'}), "(model_name='team', name='premium_started')\n", (454, 497), False, 'from django.db import migrations\n')] |
from hypatia import Model,Plotter
#%%
utopia = Model(
path = 'sets',
mode = 'Planning'
)
#%%
#utopia.create_data_excels(
# path = r'parameters'
#)
#%%
utopia.read_input_data(
path = r'parameters'
)
#%%
utopia.run(
solver = 'scipy',
verbosity = True,
)
#%%
utopia.to_csv(path='results')
#%%
#utopia.create_config_file(path=r'config.xlsx')
#%%
results = Plotter(utopia,config=r'config.xlsx',hourly_resolution=False)
#%%
# Sketching the new installed capacity of different technologies for given tech group
results.plot_new_capacity(
path = r'plots/newcapacity.html',
tech_group = 'Power Generation',
cummulative=False,
)
#%%
# Sketching the total installed capacity of different technologies for given tech group (considering the decommissioned capacities)
results.plot_total_capacity(
path = r'plots/totalcapacity.html',
tech_group = 'Power Generation',
kind="bar",
decom_cap=True,
)
#%%
# Sketching the annual production of each technology
results.plot_prod_by_tech(
tech_group ='Power Generation',
path = r'plots/productionbytech.html',
)
#%%
# Sketching the annual production of each technology
results.plot_prod_by_tech(
tech_group ='Refinery',
path = r'plots/productionbytech_oil.html',
)
#%%
# Skething the prduction and consumption share of each technology including the imports and exports
results.plot_fuel_prod_cons(
path = r'plots/prod_con_share.html',
years = [2030],
fuel_group = 'Electricity',
trade=False,
)
#%%
# Skething the prduction and consumption share of each technology including the imports and exports
results.plot_fuel_prod_cons(
path = r'plots/prod_con_share_oil.html',
years = [2030],
fuel_group = 'Fuel',
trade=False,
)
#%%
# Sketching the annual CO2-equivalent emissions
results.plot_emissions(
path = r'plots/emissions.html',
tech_group = 'Resource Extraction',
) | [
"hypatia.Plotter",
"hypatia.Model"
] | [((48, 83), 'hypatia.Model', 'Model', ([], {'path': '"""sets"""', 'mode': '"""Planning"""'}), "(path='sets', mode='Planning')\n", (53, 83), False, 'from hypatia import Model, Plotter\n'), ((378, 440), 'hypatia.Plotter', 'Plotter', (['utopia'], {'config': '"""config.xlsx"""', 'hourly_resolution': '(False)'}), "(utopia, config='config.xlsx', hourly_resolution=False)\n", (385, 440), False, 'from hypatia import Model, Plotter\n')] |
from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser
try:
from .etoken import token
except:
from etoken import token
import re
namespace = globals()
recurSearcher = set()
PrimaryDefList = AstParser([Ref('FieldDef'), SeqParser([LiteralParser(',', name='\',\''), Ref('FieldDef')])],
name='PrimaryDefList', toIgnore=[{}, {','}])
FieldDefList = AstParser([SeqParser([Ref('FieldDef'), SeqParser([LiteralParser('\n', name='\'\n\'')])]),
SeqParser([LiteralParser('\n', name='\'\n\'')])], name='FieldDefList', toIgnore=[{}, {'\n'}])
TableDef = AstParser(
[Ref('Symbol'), LiteralParser('(', name='\'(\''), Ref('PrimaryDefList'), LiteralParser(')', name='\')\''),
SeqParser([LiteralParser('\n', name='\'\n\'')]), LiteralParser('{', name='\'{\''),
SeqParser([LiteralParser('\n', name='\'\n\'')]), Ref('FieldDefList'),
SeqParser([Ref('ReprDef'), SeqParser([LiteralParser('\n', name='\'\n\'')])], atmost=1),
LiteralParser('}', name='\'}\'')], name='TableDef', toIgnore=[{}, {'{', '}', '(', ')', '\n'}])
FieldDef = AstParser([Ref('Symbol'), LiteralParser(':', name='\':\''), Ref('Type')], name='FieldDef',
toIgnore=[{}, {':'}])
Type = AstParser([Ref('Symbol'), SeqParser([Ref('Option')]),
SeqParser([LiteralParser('=', name='\'=\''), Ref('Default')], atmost=1)], name='Type',
toIgnore=[{}, {'='}])
Option = AstParser([LiteralParser('?', name='\'?\'')], [LiteralParser('!', name='\'!\'')],
[LiteralParser('~', name='\'~\'')], name='Option')
Default = AstParser([SeqParser([LiteralParser('.+', name='\'.+\'', isRegex=True)], atleast=1)], name='Default')
ReprDef = AstParser([LiteralParser('repr', name='\'repr\''), DependentAstParser(
[LiteralParser('{', name='\'{\''), SeqParser([LiteralParser('\n', name='\'\n\'')]), Ref('SymbolList'),
SeqParser([LiteralParser('\n', name='\'\n\'')]), LiteralParser('}', name='\'}\'')],
[LiteralParser('=', name='\'=\''), LiteralParser('all', name='\'all\'')])], name='ReprDef',
toIgnore=[{}, {'=', '{', '}', 'all', 'repr', '\n'}])
SymbolList = AstParser([Ref('Symbol'), SeqParser([LiteralParser(',', name='\',\''), Ref('Symbol')])], name='SymbolList',
toIgnore=[{}, {','}])
Comment = AstParser([LiteralParser('#', name='\'#\''), Ref('Default')], name='Comment')
Symbol = AstParser([LiteralParser('[a-zA-Z][a-zA-Z_]*', name='\'[a-zA-Z][a-zA-Z_]*\'', isRegex=True)], name='Symbol')
WeightedSymbol = AstParser([Ref('Symbol'), SeqParser([LiteralParser('^', name='\'^\'')])], name='WeightedSymbol')
Relation = AstParser(
[Ref('WeightedSymbol'), Ref('Left'), LiteralParser('-', name='\'-\''), Ref('Right'), Ref('WeightedSymbol'),
SeqParser([LiteralParser('\n', name='\'\n\'')]), LiteralParser('{', name='\'{\''),
SeqParser([LiteralParser('\n', name='\'\n\'')]), SeqParser([Ref('FieldDefList')], atmost=1),
LiteralParser('}', name='\'}\'')], name='Relation', toIgnore=[{}, {'-', '}', '{', '\n'}])
Left = AstParser([SeqParser([LiteralParser('<', name='\'<\'')], atleast=1, atmost=2)], name='Left')
Right = AstParser([SeqParser([LiteralParser('>', name='\'>\'')], atleast=1, atmost=2)], name='Right')
Stmts = AstParser(
[SeqParser([DependentAstParser([LiteralParser('\n', name='\'\n\'')], [Ref('Relation')], [Ref('TableDef')])])],
name='Stmts', toIgnore=[{}, {'\n'}])
PrimaryDefList.compile(namespace, recurSearcher)
FieldDefList.compile(namespace, recurSearcher)
TableDef.compile(namespace, recurSearcher)
FieldDef.compile(namespace, recurSearcher)
Type.compile(namespace, recurSearcher)
Option.compile(namespace, recurSearcher)
Default.compile(namespace, recurSearcher)
ReprDef.compile(namespace, recurSearcher)
SymbolList.compile(namespace, recurSearcher)
Comment.compile(namespace, recurSearcher)
Symbol.compile(namespace, recurSearcher)
WeightedSymbol.compile(namespace, recurSearcher)
Relation.compile(namespace, recurSearcher)
Left.compile(namespace, recurSearcher)
Right.compile(namespace, recurSearcher)
Stmts.compile(namespace, recurSearcher)
| [
"Ruikowa.ObjectRegex.Node.LiteralParser",
"Ruikowa.ObjectRegex.Node.Ref"
] | [((276, 291), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""FieldDef"""'], {}), "('FieldDef')\n", (279, 291), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((682, 695), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""Symbol"""'], {}), "('Symbol')\n", (685, 695), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((697, 727), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""("""'], {'name': '"""\'(\'"""'}), '(\'(\', name="\'(\'")\n', (710, 727), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((731, 752), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""PrimaryDefList"""'], {}), "('PrimaryDefList')\n", (734, 752), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((754, 784), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['""")"""'], {'name': '"""\')\'"""'}), '(\')\', name="\')\'")\n', (767, 784), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((842, 872), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""{"""'], {'name': '"""\'{\'"""'}), '(\'{\', name="\'{\'")\n', (855, 872), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((930, 949), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""FieldDefList"""'], {}), "('FieldDefList')\n", (933, 949), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1049, 1079), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""}"""'], {'name': '"""\'}\'"""'}), '(\'}\', name="\'}\'")\n', (1062, 1079), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1166, 1179), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""Symbol"""'], {}), "('Symbol')\n", (1169, 1179), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1181, 1211), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['""":"""'], {'name': '"""\':\'"""'}), '(\':\', name="\':\'")\n', (1194, 1211), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1215, 1226), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""Type"""'], {}), "('Type')\n", (1218, 1226), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1307, 1320), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""Symbol"""'], {}), "('Symbol')\n", (1310, 1320), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1514, 1544), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""?"""'], {'name': '"""\'?\'"""'}), '(\'?\', name="\'?\'")\n', (1527, 1544), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1550, 1580), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""!"""'], {'name': '"""\'!\'"""'}), '(\'!\', name="\'!\'")\n', (1563, 1580), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1605, 1635), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""~"""'], {'name': '"""\'~\'"""'}), '(\'~\', name="\'~\'")\n', (1618, 1635), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1788, 1824), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""repr"""'], {'name': '"""\'repr\'"""'}), '(\'repr\', name="\'repr\'")\n', (1801, 1824), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2237, 2250), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""Symbol"""'], {}), "('Symbol')\n", (2240, 2250), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2400, 2430), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""#"""'], {'name': '"""\'#\'"""'}), '(\'#\', name="\'#\'")\n', (2413, 2430), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2434, 2448), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""Default"""'], {}), "('Default')\n", (2437, 2448), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2487, 2565), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""[a-zA-Z][a-zA-Z_]*"""'], {'name': '"""\'[a-zA-Z][a-zA-Z_]*\'"""', 'isRegex': '(True)'}), '(\'[a-zA-Z][a-zA-Z_]*\', name="\'[a-zA-Z][a-zA-Z_]*\'", isRegex=True)\n', (2500, 2565), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2613, 2626), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""Symbol"""'], {}), "('Symbol')\n", (2616, 2626), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2726, 2747), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""WeightedSymbol"""'], {}), "('WeightedSymbol')\n", (2729, 2747), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2749, 2760), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""Left"""'], {}), "('Left')\n", (2752, 2760), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2762, 2792), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""-"""'], {'name': '"""\'-\'"""'}), '(\'-\', name="\'-\'")\n', (2775, 2792), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2796, 2808), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""Right"""'], {}), "('Right')\n", (2799, 2808), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2810, 2831), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""WeightedSymbol"""'], {}), "('WeightedSymbol')\n", (2813, 2831), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2887, 2917), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""{"""'], {'name': '"""\'{\'"""'}), '(\'{\', name="\'{\'")\n', (2900, 2917), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((3024, 3054), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""}"""'], {'name': '"""\'}\'"""'}), '(\'}\', name="\'}\'")\n', (3037, 3054), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((304, 334), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['""","""'], {'name': '"""\',\'"""'}), '(\',\', name="\',\'")\n', (317, 334), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((338, 353), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""FieldDef"""'], {}), "('FieldDef')\n", (341, 353), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((467, 482), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""FieldDef"""'], {}), "('FieldDef')\n", (470, 482), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((572, 604), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""\n"""'], {'name': '"""\'\n\'"""'}), '(\'\\n\', name="\'\\n\'")\n', (585, 604), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((804, 836), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""\n"""'], {'name': '"""\'\n\'"""'}), '(\'\\n\', name="\'\\n\'")\n', (817, 836), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((892, 924), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""\n"""'], {'name': '"""\'\n\'"""'}), '(\'\\n\', name="\'\\n\'")\n', (905, 924), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((967, 981), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""ReprDef"""'], {}), "('ReprDef')\n", (970, 981), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1333, 1346), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""Option"""'], {}), "('Option')\n", (1336, 1346), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1379, 1409), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""="""'], {'name': '"""\'=\'"""'}), '(\'=\', name="\'=\'")\n', (1392, 1409), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1413, 1427), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""Default"""'], {}), "('Default')\n", (1416, 1427), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1687, 1733), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['""".+"""'], {'name': '"""\'.+\'"""', 'isRegex': '(True)'}), '(\'.+\', name="\'.+\'", isRegex=True)\n', (1700, 1733), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1853, 1883), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""{"""'], {'name': '"""\'{\'"""'}), '(\'{\', name="\'{\'")\n', (1866, 1883), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1936, 1953), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""SymbolList"""'], {}), "('SymbolList')\n", (1939, 1953), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2009, 2039), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""}"""'], {'name': '"""\'}\'"""'}), '(\'}\', name="\'}\'")\n', (2022, 2039), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2049, 2079), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""="""'], {'name': '"""\'=\'"""'}), '(\'=\', name="\'=\'")\n', (2062, 2079), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2083, 2117), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""all"""'], {'name': '"""\'all\'"""'}), '(\'all\', name="\'all\'")\n', (2096, 2117), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2263, 2293), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['""","""'], {'name': '"""\',\'"""'}), '(\',\', name="\',\'")\n', (2276, 2293), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2297, 2310), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""Symbol"""'], {}), "('Symbol')\n", (2300, 2310), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2639, 2669), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""^"""'], {'name': '"""\'^\'"""'}), '(\'^\', name="\'^\'")\n', (2652, 2669), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2849, 2881), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""\n"""'], {'name': '"""\'\n\'"""'}), '(\'\\n\', name="\'\\n\'")\n', (2862, 2881), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2937, 2969), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""\n"""'], {'name': '"""\'\n\'"""'}), '(\'\\n\', name="\'\\n\'")\n', (2950, 2969), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((2986, 3005), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""FieldDefList"""'], {}), "('FieldDefList')\n", (2989, 3005), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((3143, 3173), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""<"""'], {'name': '"""\'<\'"""'}), '(\'<\', name="\'<\'")\n', (3156, 3173), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((3244, 3274), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['""">"""'], {'name': '"""\'>\'"""'}), '(\'>\', name="\'>\'")\n', (3257, 3274), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((495, 527), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""\n"""'], {'name': '"""\'\n\'"""'}), '(\'\\n\', name="\'\\n\'")\n', (508, 527), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((994, 1026), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""\n"""'], {'name': '"""\'\n\'"""'}), '(\'\\n\', name="\'\\n\'")\n', (1007, 1026), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1898, 1930), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""\n"""'], {'name': '"""\'\n\'"""'}), '(\'\\n\', name="\'\\n\'")\n', (1911, 1930), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((1971, 2003), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""\n"""'], {'name': '"""\'\n\'"""'}), '(\'\\n\', name="\'\\n\'")\n', (1984, 2003), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((3371, 3403), 'Ruikowa.ObjectRegex.Node.LiteralParser', 'LiteralParser', (['"""\n"""'], {'name': '"""\'\n\'"""'}), '(\'\\n\', name="\'\\n\'")\n', (3384, 3403), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((3409, 3424), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""Relation"""'], {}), "('Relation')\n", (3412, 3424), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n'), ((3428, 3443), 'Ruikowa.ObjectRegex.Node.Ref', 'Ref', (['"""TableDef"""'], {}), "('TableDef')\n", (3431, 3443), False, 'from Ruikowa.ObjectRegex.Node import Ref, AstParser, SeqParser, LiteralParser, CharParser, MetaInfo, DependentAstParser\n')] |
import heapq
class Solution:
"""
@param matrix: a matrix of integers
@param k: An integer
@return: the kth smallest number in the matrix
在一个排序矩阵中找从小到大的第 k 个整数。
排序矩阵的定义为:每一行递增,每一列也递增。
Example
样例 1:
输入:
[
[1 ,5 ,7],
[3 ,7 ,8],
[4 ,8 ,9],
]
k = 4
输出: 5
样例 2:
输入:
[
[1, 2],
[3, 4]
]
k = 3
输出: 3
Challenge
时间复杂度 O(klogn), n 是矩阵的宽度和高度的最大值
"""
# todo 用java的treeset 自带排序 remove还是log的
def kthSmallest(self, nums, k):
# write your code here
self.minheap, self.maxheap = [], []
medians = []
for i in range(len(nums)):
self.add(nums[i], i, k)
medians.append(self.median)
return medians
@property
def median(self):
if len(self.minheap) > len(self.maxheap):
return self.minheap[0]
return -self.maxheap[0]
def add(self, value, index, winsize):
if len(self.maxheap) + len(self.minheap) > winsize: # todo
self.remove(index - winsize)
if len(self.maxheap) == 0:
heapq.heappush(self.maxheap, -value)
return
if -self.maxheap[0] < value:
heapq.heappush(self.minheap, value)
else:
heapq.heappush(self.maxheap, -value)
self.modifyTwoHeapsSize()
def remove(self, idx):
if idx in self.minheap:
self.minheap.remove(idx)
else:
self.maxheap.remove(idx)
def modifyTwoHeapsSize(self):
if len(self.maxheap) + 2 == len(self.minheap):
heapq.heappush(self.maxheap, -heapq.heappop(self.minheap))
if len(self.minheap) + 2 == len(self.maxheap):
heapq.heappush(self.minheap, -heapq.heappop(self.maxheap))
| [
"heapq.heappush",
"heapq.heappop"
] | [((1121, 1157), 'heapq.heappush', 'heapq.heappush', (['self.maxheap', '(-value)'], {}), '(self.maxheap, -value)\n', (1135, 1157), False, 'import heapq\n'), ((1226, 1261), 'heapq.heappush', 'heapq.heappush', (['self.minheap', 'value'], {}), '(self.minheap, value)\n', (1240, 1261), False, 'import heapq\n'), ((1288, 1324), 'heapq.heappush', 'heapq.heappush', (['self.maxheap', '(-value)'], {}), '(self.maxheap, -value)\n', (1302, 1324), False, 'import heapq\n'), ((1639, 1666), 'heapq.heappop', 'heapq.heappop', (['self.minheap'], {}), '(self.minheap)\n', (1652, 1666), False, 'import heapq\n'), ((1765, 1792), 'heapq.heappop', 'heapq.heappop', (['self.maxheap'], {}), '(self.maxheap)\n', (1778, 1792), False, 'import heapq\n')] |
import _recurrence_map
import numpy as np
def poincare_map(ts, ts2=None, threshold=0.1):
rec_dist = poincare_recurrence_dist(ts, ts2)
return (rec_dist < threshold).astype(int)
def poincare_recurrence_dist(ts, ts2=None):
if ts2 is None:
return _recurrence_map.recurrence_map(ts, ts)
else:
return _recurrence_map.recurrence_map(ts, ts2)
| [
"_recurrence_map.recurrence_map"
] | [((267, 305), '_recurrence_map.recurrence_map', '_recurrence_map.recurrence_map', (['ts', 'ts'], {}), '(ts, ts)\n', (297, 305), False, 'import _recurrence_map\n'), ((331, 370), '_recurrence_map.recurrence_map', '_recurrence_map.recurrence_map', (['ts', 'ts2'], {}), '(ts, ts2)\n', (361, 370), False, 'import _recurrence_map\n')] |
import cv2
import math
import numpy as np
import os
import matplotlib.pyplot as plt
from scipy import ndimage
from utils import ValueInvert
# TO-DO: Refactor this with np.nonzero??
def find_center_image(img):
left = 0
right = img.shape[1] - 1
empty_left = True
empty_right = True
for col in range(int(img.shape[1])):
if empty_left == False and empty_right == False:
break
for row in range(img.shape[0] - 1):
if img[row, col] > 0 and empty_left == True:
empty_left = False
left = col
if img[row, img.shape[1] - col - 1] > 0 and empty_right == True:
empty_right = False
right = img.shape[1] - col
top = 0
bottom = img.shape[0] - 1
empty_top = True
empty_bottom = True
for row in range(int(img.shape[0])):
if empty_top == False and empty_bottom == False:
break
for col in range(img.shape[1] - 1):
if img[row, col] > 0 and empty_top == True:
empty_top = False
top = row
if img[img.shape[0] - row - 1, col] > 0 and empty_bottom == True:
empty_bottom = False
bottom = img.shape[0] - row
return top, right, bottom, left
def getBestShift(img):
cy, cx = ndimage.measurements.center_of_mass(img)
rows, cols = img.shape
shiftx = np.round(cols/2.0-cx).astype(int)
shifty = np.round(rows/2.0-cy).astype(int)
return shiftx, shifty
def shift(img, sx, sy):
rows, cols = img.shape
M = np.float32([[1, 0, sx], [0, 1, sy]])
shifted = cv2.warpAffine(img, M, (cols, rows))
return shifted
def process_image(img):
img = ValueInvert(img)
img = cv2.resize(img, (28, 28))
(thresh, gray) = cv2.threshold(img, 128,
255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
top, right, bottom, left = find_center_image(img)
cropped_img = img[top:bottom, left:right]
rows, cols = cropped_img.shape
# resize 20x20 keeping ratio
if rows > cols:
rows = 20
factor = cols/rows
cols = int(round(rows*factor))
else:
cols = 20
factor = rows/cols
rows = int(round(cols*factor))
gray = cv2.resize(cropped_img, (cols, rows))
# plt.imshow(gray)
# plt.show()
colsPadding = (int(math.ceil((28-cols)/2.0)),
int(math.floor((28-cols)/2.0)))
rowsPadding = (int(math.ceil((28-rows)/2.0)),
int(math.floor((28-rows)/2.0)))
gray = np.lib.pad(gray, (rowsPadding, colsPadding), 'constant')
shiftx, shifty = getBestShift(gray)
shifted = shift(gray, shiftx, shifty)
gray = shifted
return gray
| [
"cv2.warpAffine",
"math.ceil",
"math.floor",
"cv2.threshold",
"utils.ValueInvert",
"numpy.lib.pad",
"scipy.ndimage.measurements.center_of_mass",
"cv2.resize",
"numpy.float32",
"numpy.round"
] | [((1339, 1379), 'scipy.ndimage.measurements.center_of_mass', 'ndimage.measurements.center_of_mass', (['img'], {}), '(img)\n', (1374, 1379), False, 'from scipy import ndimage\n'), ((1590, 1626), 'numpy.float32', 'np.float32', (['[[1, 0, sx], [0, 1, sy]]'], {}), '([[1, 0, sx], [0, 1, sy]])\n', (1600, 1626), True, 'import numpy as np\n'), ((1641, 1677), 'cv2.warpAffine', 'cv2.warpAffine', (['img', 'M', '(cols, rows)'], {}), '(img, M, (cols, rows))\n', (1655, 1677), False, 'import cv2\n'), ((1733, 1749), 'utils.ValueInvert', 'ValueInvert', (['img'], {}), '(img)\n', (1744, 1749), False, 'from utils import ValueInvert\n'), ((1760, 1785), 'cv2.resize', 'cv2.resize', (['img', '(28, 28)'], {}), '(img, (28, 28))\n', (1770, 1785), False, 'import cv2\n'), ((1807, 1872), 'cv2.threshold', 'cv2.threshold', (['img', '(128)', '(255)', '(cv2.THRESH_BINARY | cv2.THRESH_OTSU)'], {}), '(img, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n', (1820, 1872), False, 'import cv2\n'), ((2288, 2325), 'cv2.resize', 'cv2.resize', (['cropped_img', '(cols, rows)'], {}), '(cropped_img, (cols, rows))\n', (2298, 2325), False, 'import cv2\n'), ((2579, 2635), 'numpy.lib.pad', 'np.lib.pad', (['gray', '(rowsPadding, colsPadding)', '"""constant"""'], {}), "(gray, (rowsPadding, colsPadding), 'constant')\n", (2589, 2635), True, 'import numpy as np\n'), ((1421, 1446), 'numpy.round', 'np.round', (['(cols / 2.0 - cx)'], {}), '(cols / 2.0 - cx)\n', (1429, 1446), True, 'import numpy as np\n'), ((1468, 1493), 'numpy.round', 'np.round', (['(rows / 2.0 - cy)'], {}), '(rows / 2.0 - cy)\n', (1476, 1493), True, 'import numpy as np\n'), ((2389, 2417), 'math.ceil', 'math.ceil', (['((28 - cols) / 2.0)'], {}), '((28 - cols) / 2.0)\n', (2398, 2417), False, 'import math\n'), ((2439, 2468), 'math.floor', 'math.floor', (['((28 - cols) / 2.0)'], {}), '((28 - cols) / 2.0)\n', (2449, 2468), False, 'import math\n'), ((2490, 2518), 'math.ceil', 'math.ceil', (['((28 - rows) / 2.0)'], {}), '((28 - rows) / 2.0)\n', (2499, 2518), False, 'import math\n'), ((2540, 2569), 'math.floor', 'math.floor', (['((28 - rows) / 2.0)'], {}), '((28 - rows) / 2.0)\n', (2550, 2569), False, 'import math\n')] |
import numpy as np
from collections import namedtuple, deque
import random
Transition = namedtuple('Transition', ('state', 'action', 'next_state', 'reward', 'not_done'))
class ReplayBuffer(object):
def __init__(self, capacity):
self.memory = deque([], maxlen=capacity)
def push(self, *args):
self.memory.append([*args])
def sample(self, batch_size):
batch = random.sample(self.memory, batch_size)
batch = list(map(np.asarray, zip(*batch)))[
0].T # FIXME: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
states, actions, rewards, next_states, done = np.vstack(batch[0]), np.vstack(batch[1]), np.vstack(batch[2]), np.vstack(batch[3]), \
np.vstack(batch[4])
return states, actions, rewards, next_states, done
def sample_last(self):
batch = self.memory[-1]
return batch
def __len__(self):
return len(self.memory)
| [
"random.sample",
"collections.namedtuple",
"collections.deque",
"numpy.vstack"
] | [((93, 178), 'collections.namedtuple', 'namedtuple', (['"""Transition"""', "('state', 'action', 'next_state', 'reward', 'not_done')"], {}), "('Transition', ('state', 'action', 'next_state', 'reward',\n 'not_done'))\n", (103, 178), False, 'from collections import namedtuple, deque\n'), ((268, 294), 'collections.deque', 'deque', (['[]'], {'maxlen': 'capacity'}), '([], maxlen=capacity)\n', (273, 294), False, 'from collections import namedtuple, deque\n'), ((416, 454), 'random.sample', 'random.sample', (['self.memory', 'batch_size'], {}), '(self.memory, batch_size)\n', (429, 454), False, 'import random\n'), ((857, 876), 'numpy.vstack', 'np.vstack', (['batch[0]'], {}), '(batch[0])\n', (866, 876), True, 'import numpy as np\n'), ((878, 897), 'numpy.vstack', 'np.vstack', (['batch[1]'], {}), '(batch[1])\n', (887, 897), True, 'import numpy as np\n'), ((899, 918), 'numpy.vstack', 'np.vstack', (['batch[2]'], {}), '(batch[2])\n', (908, 918), True, 'import numpy as np\n'), ((920, 939), 'numpy.vstack', 'np.vstack', (['batch[3]'], {}), '(batch[3])\n', (929, 939), True, 'import numpy as np\n'), ((998, 1017), 'numpy.vstack', 'np.vstack', (['batch[4]'], {}), '(batch[4])\n', (1007, 1017), True, 'import numpy as np\n')] |
# SPDX-License-Identifier: MIT
# Copyright (c) 2022 MBition GmbH
from dataclasses import dataclass, field
from typing import List, Literal, Optional
from .nameditemlist import NamedItemList
from .utils import read_description_from_odx
UnitGroupCategory = Literal["COUNTRY", "EQUIV-UNITS"]
@dataclass
class PhysicalDimension:
"""A physical dimension is a formal definition of a unit.
It consists of the exponents for the SI units:
| Symbol | Name | Quantity | Property |
| --- | --- | --- | --- |
| s | second | time | `time_exp` |
| m | metre | length | `length_exp` |
| kg | kilogram | mass | `mass_exp` |
| A | ampere | electric current | `current_exp` |
| K | kelvin | thermodynamic temperature | `temperature_exp` |
| mol | mole | amount of substance | `molar_amount_exp` |
| cd | candela | luminous intensity | `luminous_intensity_exp` |
(The first three columns are from https://en.wikipedia.org/wiki/International_System_of_Units.)
Examples
--------
The unit `m/s` (or `m**1 * s**(-1)`) can be represented as
```
PhysicalDimension(
id="velocity",
short_name="metre_per_second",
length_exp=1,
time_exp=-1
)
```
"""
id: str
short_name: str
oid: Optional[str] = None
long_name: Optional[str] = None
description: Optional[str] = None
length_exp: int = 0
mass_exp: int = 0
time_exp: int = 0
current_exp: int = 0
temperature_exp: int = 0
molar_amount_exp: int = 0
luminous_intensity_exp: int = 0
@dataclass
class Unit:
"""
A unit consists of an ID, short name and a display name.
Additionally, a unit may reference an SI unit (`.physical_dimension`)
and an offset to that unit (`factor_si_to_unit`, `offset_si_to_unit`).
The factor and offset are defined such that the following equation holds true:
UNIT = FACTOR-SI-TO-UNIT * SI-UNIT + OFFSET-SI-TO-UNIT
For example: 1km = 1000 * 1m + 0
Examples
--------
A minimal unit representing kilometres:
```
Unit(
id="kilometre",
short_name="kilometre",
display_name="km"
)
```
A unit that also references a physical dimension:
```
Unit(
id="ID.kilometre",
short_name="Kilometre",
display_name="km",
physical_dimension_ref="ID.metre",
factor_si_to_unit=1000,
offset_si_to_unit=0
)
# where the physical_dimension_ref references, e.g.:
PhysicalDimension(id="ID.metre", short_name="metre", length_exp=1)
```
"""
id: str
short_name: str
display_name: str
oid: Optional[str] = None
long_name: Optional[str] = None
description: Optional[str] = None
factor_si_to_unit: Optional[float] = None
offset_si_to_unit: Optional[float] = None
physical_dimension_ref: Optional[str] = None
def __post_init__(self):
self._physical_dimension = None
if self.factor_si_to_unit is not None or self.offset_si_to_unit is not None or self.physical_dimension_ref is not None:
assert self.factor_si_to_unit is not None and self.offset_si_to_unit is not None and self.physical_dimension_ref is not None, (
f"Error 54: If one of factor_si_to_unit, offset_si_to_unit and physical_dimension_ref is defined,"
f" all of them must be defined: {self.factor_si_to_unit} and {self.offset_si_to_unit} and {self.physical_dimension_ref}"
)
@property
def physical_dimension(self) -> PhysicalDimension:
return self._physical_dimension
def _resolve_references(self, id_lookup):
if self.physical_dimension_ref:
self._physical_dimension = id_lookup[self.physical_dimension_ref]
assert isinstance(self._physical_dimension, PhysicalDimension), (
f"The physical_dimension_ref must be resolved to a PhysicalDimension."
f" {self.physical_dimension_ref} referenced {self._physical_dimension}"
)
@dataclass
class UnitGroup:
"""A group of units.
There are two categories of groups: COUNTRY and EQUIV-UNITS.
"""
short_name: str
category: UnitGroupCategory
unit_refs: List[str] = field(default_factory=list)
oid: Optional[str] = None
long_name: Optional[str] = None
description: Optional[str] = None
def __post_init__(self):
self._units = NamedItemList[Unit](lambda unit: unit.short_name)
def _resolve_references(self, id_lookup):
self._units = NamedItemList[Unit](
lambda unit: unit.short_name,
[id_lookup[ref] for ref in self.unit_refs]
)
@property
def units(self) -> NamedItemList[Unit]:
return self._units
@dataclass
class UnitSpec:
"""
A unit spec encapsulates three lists:
* unit groups
* units
* physical_dimensions
The following odx elements are not internalized: ADMIN-DATA, SDGS
"""
unit_groups: NamedItemList[UnitGroup] = field(default_factory=list)
units: NamedItemList[Unit] = field(default_factory=list)
physical_dimensions: NamedItemList[PhysicalDimension] = field(
default_factory=list)
def __post_init__(self):
self.unit_groups = NamedItemList(lambda x: x.short_name,
self.unit_groups)
self.units = NamedItemList(lambda x: x.short_name, self.units)
self.physical_dimensions = NamedItemList(lambda x: x.short_name,
self.physical_dimensions)
def _build_id_lookup(self):
id_lookup = {}
id_lookup.update({
unit.id: unit for unit in self.units
})
id_lookup.update({
dim.id: dim for dim in self.physical_dimensions
})
return id_lookup
def _resolve_references(self, id_lookup):
for unit in self.units:
unit._resolve_references(id_lookup)
for group in self.unit_groups:
group._resolve_references(id_lookup)
def read_unit_from_odx(et_element):
id = et_element.get("ID")
oid = et_element.get("OID")
short_name = et_element.find("SHORT-NAME").text
long_name = et_element.findtext("LONG-NAME")
description = read_description_from_odx(et_element.find("DESC"))
display_name = et_element.find("DISPLAY-NAME").text
def read_optional_float(element, name):
if element.findtext(name):
return float(element.findtext(name))
else:
return None
factor_si_to_unit = read_optional_float(et_element, "FACTOR-SI-TO-UNIT")
offset_si_to_unit = read_optional_float(et_element, "OFFSET-SI-TO-UNIT")
ref_element = et_element.find("PHYSICAL-DIMENSION-REF")
if ref_element is not None:
physical_dimension_ref = ref_element.get("ID-REF")
else:
physical_dimension_ref = None
return Unit(
id=id,
short_name=short_name,
display_name=display_name,
oid=oid,
long_name=long_name,
description=description,
factor_si_to_unit=factor_si_to_unit,
offset_si_to_unit=offset_si_to_unit,
physical_dimension_ref=physical_dimension_ref
)
def read_physical_dimension_from_odx(et_element):
id = et_element.get("ID")
oid = et_element.get("OID")
short_name = et_element.find("SHORT-NAME").text
long_name = et_element.findtext("LONG-NAME")
description = read_description_from_odx(et_element.find("DESC"))
def read_optional_int(element, name):
if element.findtext(name):
return int(element.findtext(name))
else:
return 0
length_exp = read_optional_int(et_element, "LENGTH-EXP")
mass_exp = read_optional_int(et_element, "MASS-EXP")
time_exp = read_optional_int(et_element, "TIME-EXP")
current_exp = read_optional_int(et_element, "CURRENT-EXP")
temperature_exp = read_optional_int(et_element, "TEMPERATURE-EXP")
molar_amount_exp = read_optional_int(et_element, "MOLAR-AMOUNT-EXP")
luminous_intensity_exp = read_optional_int(et_element,
"LUMINOUS-INTENSITY-EXP")
return PhysicalDimension(
id=id,
short_name=short_name,
oid=oid,
long_name=long_name,
description=description,
length_exp=length_exp,
mass_exp=mass_exp,
time_exp=time_exp,
current_exp=current_exp,
temperature_exp=temperature_exp,
molar_amount_exp=molar_amount_exp,
luminous_intensity_exp=luminous_intensity_exp
)
def read_unit_group_from_odx(et_element):
oid = et_element.get("OID")
short_name = et_element.find("SHORT-NAME").text
long_name = et_element.findtext("LONG-NAME")
description = read_description_from_odx(et_element.find("DESC"))
category = et_element.findtext("CATEGORY")
assert category in [
"COUNTRY", "EQUIV-UNITS"], f'A UNIT-GROUP-CATEGORY must be "COUNTRY" or "EQUIV-UNITS". It was {category}.'
unit_refs = [el.get("ID-REF")
for el in et_element.iterfind("UNIT-REFS/UNIT-REF")]
return UnitGroup(
short_name=short_name,
category=category,
unit_refs=unit_refs,
oid=oid,
long_name=long_name,
description=description
)
def read_unit_spec_from_odx(et_element):
unit_groups = [read_unit_group_from_odx(el)
for el in et_element.iterfind("UNIT-GROUPS/UNIT-GROUP")]
units = [read_unit_from_odx(el)
for el in et_element.iterfind("UNITS/UNIT")]
physical_dimensions = [read_physical_dimension_from_odx(el)
for el in et_element.iterfind("PHYSICAL-DIMENSIONS/PHYSICAL-DIMENSION")]
return UnitSpec(
unit_groups=unit_groups,
units=units,
physical_dimensions=physical_dimensions
)
| [
"dataclasses.field"
] | [((4528, 4555), 'dataclasses.field', 'field', ([], {'default_factory': 'list'}), '(default_factory=list)\n', (4533, 4555), False, 'from dataclasses import dataclass, field\n'), ((5304, 5331), 'dataclasses.field', 'field', ([], {'default_factory': 'list'}), '(default_factory=list)\n', (5309, 5331), False, 'from dataclasses import dataclass, field\n'), ((5365, 5392), 'dataclasses.field', 'field', ([], {'default_factory': 'list'}), '(default_factory=list)\n', (5370, 5392), False, 'from dataclasses import dataclass, field\n'), ((5453, 5480), 'dataclasses.field', 'field', ([], {'default_factory': 'list'}), '(default_factory=list)\n', (5458, 5480), False, 'from dataclasses import dataclass, field\n')] |
import os
from test import test_support
# Skip this test if _tkinter does not exist.
test_support.import_module('_tkinter')
this_dir = os.path.dirname(os.path.abspath(__file__))
lib_tk_test = os.path.abspath(os.path.join(this_dir, '..', 'lib-tk', 'test'))
with test_support.DirsOnSysPath(lib_tk_test):
import runtktests
def test_main():
with test_support.DirsOnSysPath(lib_tk_test):
test_support.run_unittest(
*runtktests.get_tests(gui=False, packages=['test_ttk']))
if __name__ == '__main__':
test_main()
| [
"runtktests.get_tests",
"os.path.join",
"test.test_support.DirsOnSysPath",
"os.path.abspath",
"test.test_support.import_module"
] | [((90, 128), 'test.test_support.import_module', 'test_support.import_module', (['"""_tkinter"""'], {}), "('_tkinter')\n", (116, 128), False, 'from test import test_support\n'), ((159, 184), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (174, 184), False, 'import os\n'), ((217, 263), 'os.path.join', 'os.path.join', (['this_dir', '""".."""', '"""lib-tk"""', '"""test"""'], {}), "(this_dir, '..', 'lib-tk', 'test')\n", (229, 263), False, 'import os\n'), ((273, 312), 'test.test_support.DirsOnSysPath', 'test_support.DirsOnSysPath', (['lib_tk_test'], {}), '(lib_tk_test)\n', (299, 312), False, 'from test import test_support\n'), ((367, 406), 'test.test_support.DirsOnSysPath', 'test_support.DirsOnSysPath', (['lib_tk_test'], {}), '(lib_tk_test)\n', (393, 406), False, 'from test import test_support\n'), ((458, 512), 'runtktests.get_tests', 'runtktests.get_tests', ([], {'gui': '(False)', 'packages': "['test_ttk']"}), "(gui=False, packages=['test_ttk'])\n", (478, 512), False, 'import runtktests\n')] |
from flask_wtf import FlaskForm
from wtforms import StringField,BooleanField,PasswordField,SubmitField
from wtforms.validators import Email,Required,EqualTo
from wtforms import ValidationError
from ..models import User
class LoginForm(FlaskForm):
email = StringField("enter your email adress",validators = [Required(),Email()])
password = PasswordField("enter password", validators = [Required()])
remember = BooleanField("remember me")
login = SubmitField("login ")
class Signup(FlaskForm):
username = StringField("enter your username", validators=[Required()])
email = StringField("enter your email", validators=[Required(),Email()])
password = PasswordField("enter password" ,validators=[Required(),EqualTo("confirm_password", message= "password must be the same")])
confirm_password = PasswordField ("confirm password", validators=[Required()])
submit = SubmitField("signup")
# def validate_email(self,data_field):
# if User.query.filter_by(email=data_field.data):
# raise ValidationError("invalid email")
# def validate_username(self,data_field):
# if User.query.filter_by(username=data_field.data):
# raise ValidationError("username already taken")
| [
"wtforms.validators.Email",
"wtforms.BooleanField",
"wtforms.SubmitField",
"wtforms.validators.EqualTo",
"wtforms.validators.Required"
] | [((423, 450), 'wtforms.BooleanField', 'BooleanField', (['"""remember me"""'], {}), "('remember me')\n", (435, 450), False, 'from wtforms import StringField, BooleanField, PasswordField, SubmitField\n'), ((463, 484), 'wtforms.SubmitField', 'SubmitField', (['"""login """'], {}), "('login ')\n", (474, 484), False, 'from wtforms import StringField, BooleanField, PasswordField, SubmitField\n'), ((899, 920), 'wtforms.SubmitField', 'SubmitField', (['"""signup"""'], {}), "('signup')\n", (910, 920), False, 'from wtforms import StringField, BooleanField, PasswordField, SubmitField\n'), ((313, 323), 'wtforms.validators.Required', 'Required', ([], {}), '()\n', (321, 323), False, 'from wtforms.validators import Email, Required, EqualTo\n'), ((324, 331), 'wtforms.validators.Email', 'Email', ([], {}), '()\n', (329, 331), False, 'from wtforms.validators import Email, Required, EqualTo\n'), ((395, 405), 'wtforms.validators.Required', 'Required', ([], {}), '()\n', (403, 405), False, 'from wtforms.validators import Email, Required, EqualTo\n'), ((575, 585), 'wtforms.validators.Required', 'Required', ([], {}), '()\n', (583, 585), False, 'from wtforms.validators import Email, Required, EqualTo\n'), ((644, 654), 'wtforms.validators.Required', 'Required', ([], {}), '()\n', (652, 654), False, 'from wtforms.validators import Email, Required, EqualTo\n'), ((655, 662), 'wtforms.validators.Email', 'Email', ([], {}), '()\n', (660, 662), False, 'from wtforms.validators import Email, Required, EqualTo\n'), ((724, 734), 'wtforms.validators.Required', 'Required', ([], {}), '()\n', (732, 734), False, 'from wtforms.validators import Email, Required, EqualTo\n'), ((735, 799), 'wtforms.validators.EqualTo', 'EqualTo', (['"""confirm_password"""'], {'message': '"""password must be the same"""'}), "('confirm_password', message='password must be the same')\n", (742, 799), False, 'from wtforms.validators import Email, Required, EqualTo\n'), ((873, 883), 'wtforms.validators.Required', 'Required', ([], {}), '()\n', (881, 883), False, 'from wtforms.validators import Email, Required, EqualTo\n')] |
#!/usr/bin/python2.6
# (c) [2013] LinkedIn Corp. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
from optparse import OptionParser
import sys
sys.path.append("/usr/local/admin")
import sysopsapi.cache_extractor
##########################################################################
def main():
parser = OptionParser(usage="usage: %prog [options]",
version="%prog 1.0")
parser.add_option("--verbose",
action="store_true",
dest="verbose",
default=False,
help="Enable verbose execution")
parser.add_option("--range-query",
action="store",
dest="range_query",
help="Specify a range cluster of hosts you which to use to use to make queries against.")
parser.add_option("--user",
action="store",
dest="user",
help="Specify a unix user uid or id that you are interested in searching for.")
(options, args) = parser.parse_args()
ina_groups = []
ina_group_file = open(
'/etc/sudo.d/sudoers-USERS_GROUP_WORLD_READABLE', 'r').readlines()
for line in ina_group_file:
if options.user in line:
ina_groups.append(line.split()[1])
sudoers_rules = {}
sudoers_file = open('/etc/sudo.d/sudoers_WORLD_READABLE', 'r').readlines()
for line in sudoers_file:
if " = " in line:
ina_group = line.split()[0].strip()
machine_group = line.split()[1].strip()
privs = line.split('=')[1].strip()
if ina_group in ina_groups:
sudoers_rules[machine_group] = privs
cache_results = sysopsapi.cache_extractor.CacheExtractor(verbose=options.verbose,
scope='global',
contents=True,
range_query=options.range_query,
search_string='sudoers-MACHINE_GROUP')
for key in cache_results._gold.iterkeys():
host = key.split('#')[0]
for line in cache_results._gold[key].splitlines():
if "Host_Alias" in line:
system_machine_group = line.split()[1]
if sudoers_rules.get(system_machine_group):
print ("user: " + options.user).ljust(0) + \
("privs: " + sudoers_rules.get(system_machine_group)).center(40) + \
("host: " + host).center(40) + \
("machine_group: " + system_machine_group).rjust(10)
##########################################################################
if __name__ == '__main__':
main()
| [
"sys.path.append",
"optparse.OptionParser"
] | [((545, 580), 'sys.path.append', 'sys.path.append', (['"""/usr/local/admin"""'], {}), "('/usr/local/admin')\n", (560, 580), False, 'import sys\n'), ((717, 782), 'optparse.OptionParser', 'OptionParser', ([], {'usage': '"""usage: %prog [options]"""', 'version': '"""%prog 1.0"""'}), "(usage='usage: %prog [options]', version='%prog 1.0')\n", (729, 782), False, 'from optparse import OptionParser\n')] |
from django.db import models
from lbworkflow.models import BaseWFObj
class Purchase(BaseWFObj):
title = models.CharField("Title", max_length=255)
reason = models.CharField("Reason", max_length=255)
def __str__(self):
return self.reason
class Item(models.Model):
purchase = models.ForeignKey(
Purchase,
on_delete=models.CASCADE,
)
name = models.CharField("Name", max_length=255)
qty = models.IntegerField("Qty")
note = models.CharField("Note", max_length=255)
class Meta:
verbose_name = "Purchase Item"
def __str__(self):
return self.name
| [
"django.db.models.IntegerField",
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((111, 152), 'django.db.models.CharField', 'models.CharField', (['"""Title"""'], {'max_length': '(255)'}), "('Title', max_length=255)\n", (127, 152), False, 'from django.db import models\n'), ((166, 208), 'django.db.models.CharField', 'models.CharField', (['"""Reason"""'], {'max_length': '(255)'}), "('Reason', max_length=255)\n", (182, 208), False, 'from django.db import models\n'), ((303, 356), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Purchase'], {'on_delete': 'models.CASCADE'}), '(Purchase, on_delete=models.CASCADE)\n', (320, 356), False, 'from django.db import models\n'), ((391, 431), 'django.db.models.CharField', 'models.CharField', (['"""Name"""'], {'max_length': '(255)'}), "('Name', max_length=255)\n", (407, 431), False, 'from django.db import models\n'), ((442, 468), 'django.db.models.IntegerField', 'models.IntegerField', (['"""Qty"""'], {}), "('Qty')\n", (461, 468), False, 'from django.db import models\n'), ((480, 520), 'django.db.models.CharField', 'models.CharField', (['"""Note"""'], {'max_length': '(255)'}), "('Note', max_length=255)\n", (496, 520), False, 'from django.db import models\n')] |
from sanic import Request, Sanic
from sanic.response import text
from sanic_ext import openapi
from sanic_ext.extensions.openapi.definitions import ExternalDocumentation
from utils import get_spec
def test_external_docs(app: Sanic):
@app.route("/test0")
@openapi.document("http://example.com/more", "Find more info here")
async def handler0(request: Request):
return text("ok")
@app.route("/test1")
@openapi.definition(
document=ExternalDocumentation(
"http://example.com/more", "Find more info here"
)
)
async def handler1(request: Request):
return text("ok")
@app.route("/test2")
@openapi.definition(document="http://example.com/more")
async def handler2(request: Request):
return text("ok")
@app.route("/test3")
async def handler3(request: Request):
"""
openapi:
---
summary: This is a summary.
externalDocs:
description: Find more info here
url: http://example.com/more
"""
return text("ok")
@app.route("/test4")
@openapi.document(
ExternalDocumentation("http://example.com/more", "Find more info here")
)
async def handler4(request: Request):
return text("ok")
spec = get_spec(app)
paths = spec["paths"]
assert len(paths) == 5
for i in range(5):
doc_obj = paths[f"/test{i}"]["get"]["externalDocs"]
assert doc_obj["url"] == "http://example.com/more"
if i != 2:
assert doc_obj["description"] == "Find more info here"
| [
"utils.get_spec",
"sanic_ext.openapi.document",
"sanic_ext.extensions.openapi.definitions.ExternalDocumentation",
"sanic_ext.openapi.definition",
"sanic.response.text"
] | [((266, 332), 'sanic_ext.openapi.document', 'openapi.document', (['"""http://example.com/more"""', '"""Find more info here"""'], {}), "('http://example.com/more', 'Find more info here')\n", (282, 332), False, 'from sanic_ext import openapi\n'), ((668, 722), 'sanic_ext.openapi.definition', 'openapi.definition', ([], {'document': '"""http://example.com/more"""'}), "(document='http://example.com/more')\n", (686, 722), False, 'from sanic_ext import openapi\n'), ((1293, 1306), 'utils.get_spec', 'get_spec', (['app'], {}), '(app)\n', (1301, 1306), False, 'from utils import get_spec\n'), ((390, 400), 'sanic.response.text', 'text', (['"""ok"""'], {}), "('ok')\n", (394, 400), False, 'from sanic.response import text\n'), ((626, 636), 'sanic.response.text', 'text', (['"""ok"""'], {}), "('ok')\n", (630, 636), False, 'from sanic.response import text\n'), ((780, 790), 'sanic.response.text', 'text', (['"""ok"""'], {}), "('ok')\n", (784, 790), False, 'from sanic.response import text\n'), ((1067, 1077), 'sanic.response.text', 'text', (['"""ok"""'], {}), "('ok')\n", (1071, 1077), False, 'from sanic.response import text\n'), ((1270, 1280), 'sanic.response.text', 'text', (['"""ok"""'], {}), "('ok')\n", (1274, 1280), False, 'from sanic.response import text\n'), ((1135, 1206), 'sanic_ext.extensions.openapi.definitions.ExternalDocumentation', 'ExternalDocumentation', (['"""http://example.com/more"""', '"""Find more info here"""'], {}), "('http://example.com/more', 'Find more info here')\n", (1156, 1206), False, 'from sanic_ext.extensions.openapi.definitions import ExternalDocumentation\n'), ((469, 540), 'sanic_ext.extensions.openapi.definitions.ExternalDocumentation', 'ExternalDocumentation', (['"""http://example.com/more"""', '"""Find more info here"""'], {}), "('http://example.com/more', 'Find more info here')\n", (490, 540), False, 'from sanic_ext.extensions.openapi.definitions import ExternalDocumentation\n')] |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
--------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from django.utils.translation import ugettext_lazy as _ # noqa
from apps.api.modules.utils import add_esb_info_before_request_for_bkdata_user # noqa
from config.domains import AIOPS_APIGATEWAY_ROOT, AIOPS_MODEL_APIGATEWAY_ROOT # noqa
from apps.api.base import DataAPI, DataApiRetryClass # noqa
class _BkDataAIOPSApi:
MODULE = _("数据平台aiops模块")
def __init__(self):
self.create_sample_set = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "sample_set/",
module=self.MODULE,
description=u"创建样本集",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.add_rt_to_sample_set = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "sample_set/{sample_set_id}/result_table/",
module=self.MODULE,
url_keys=["sample_set_id"],
description=u"RT提交, 把RT添加到 stage表中",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.collect_configs = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "sample_set/{sample_set_id}/collect_configs/",
module=self.MODULE,
url_keys=["sample_set_id"],
description=u"创建或更新样本采集配置",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.auto_collect = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT
+ "sample_set/{sample_set_id}/result_table/{result_table_id}/extract/auto_collect/",
module=self.MODULE,
url_keys=["sample_set_id", "result_table_id"],
description=u"创建或更新自动修改样本集配置",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.apply_sample_set = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "sample_set/{sample_set_id}/submit/apply/",
module=self.MODULE,
url_keys=["sample_set_id"],
description=u"执行样本集提交",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.submit_status = DataAPI(
method="GET",
url=AIOPS_APIGATEWAY_ROOT + "sample_set/{sample_set_id}/submit/status/",
module=self.MODULE,
url_keys=["sample_set_id"],
description=u"查询提交后的固化任务执行状态",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.delete_sample_set = DataAPI(
method="DELETE",
url=AIOPS_APIGATEWAY_ROOT + "sample_set/{sample_set_id}/",
module=self.MODULE,
url_keys=["sample_set_id"],
description=u"删除样本集",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.create_model = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "models/",
module=self.MODULE,
description=u"模型创建",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.create_experiment = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "models/{model_id}/experiments/",
module=self.MODULE,
url_keys=["model_id"],
description=u"AIOps 创建实验",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.experiments_config = DataAPI(
method="GET",
url=AIOPS_APIGATEWAY_ROOT + "models/{model_id}/experiments/{experiment_id}/config/",
module=self.MODULE,
url_keys=["model_id", "experiment_id"],
description=u"获取实验配置信息",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.retrieve_execute_config = DataAPI(
method="GET",
url=AIOPS_APIGATEWAY_ROOT + "meta_data/retrieve_execute_config/",
module=self.MODULE,
description=u"获取实验执行配置信息",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.update_execute_config = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "meta_data/update_execute_config/",
module=self.MODULE,
description=u"更新实验执行配置",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.execute_experiments = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "models/{model_id}/experiments/{experiment_id}/node/execute/",
module=self.MODULE,
url_keys=["model_id", "experiment_id"],
description=u"执行实验配置",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.execute_experiments_node_status = DataAPI(
method="GET",
url=AIOPS_APIGATEWAY_ROOT + "models/{model_id}/experiments/{experiment_id}/node/execute/status/",
module=self.MODULE,
url_keys=["model_id", "experiment_id"],
description=u"实验步骤状态 (当前用于切分状态捕获)",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.basic_models_training_status = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "models/{model_id}/experiments/{experiment_id}/basic_models/training_status/",
module=self.MODULE,
url_keys=["model_id", "experiment_id"],
description=u"备选模型训练状态列表",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.aiops_get_costum_algorithm = DataAPI(
method="GET",
url=AIOPS_APIGATEWAY_ROOT + "algorithm/{algorithm_name}/",
module=self.MODULE,
url_keys=["algorithm_name"],
description=u"获取单个自定义算法(最新版本)",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.basic_models_evaluation_status = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "models/{model_id}/experiments/{experiment_id}/basic_models/evaluation_status/",
module=self.MODULE,
url_keys=["model_id", "experiment_id"],
description=u"备选模型评估状态列表",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.basic_model_evaluation_result = DataAPI(
method="GET",
url=AIOPS_MODEL_APIGATEWAY_ROOT
+ "models/{model_id}/experiments/{experiment_id}/basic_models/{basic_model_id}/evaluation_result/",
module=self.MODULE,
url_keys=["model_id", "experiment_id", "basic_model_id"],
description=u"备选模型评估结果",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.pre_commit = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "models/{model_id}/experiments/{experiment_id}/pre_commit/",
module=self.MODULE,
url_keys=["model_id", "experiment_id"],
description=u"实验提交前查看配置",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.experiment_commit = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "models/{model_id}/experiments/{experiment_id}/commit/",
module=self.MODULE,
url_keys=["model_id", "experiment_id"],
description=u"实验提交",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.release_config = DataAPI(
method="GET",
url=AIOPS_APIGATEWAY_ROOT + "models/{model_id}/release/{experiment_id}/{basic_model_id}/config/",
module=self.MODULE,
url_keys=["model_id", "experiment_id", "basic_model_id"],
description=u"获取模型发布配置",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.release = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "models/{model_id}/release/{experiment_id}/{basic_model_id}",
module=self.MODULE,
url_keys=["model_id", "experiment_id", "basic_model_id"],
description=u"模型发布",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.update_model_info = DataAPI(
method="PUT",
url=AIOPS_APIGATEWAY_ROOT + "models/{model_id}/",
module=self.MODULE,
url_keys=["model_id"],
description=u"修改模型",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.aiops_release = DataAPI(
method="GET",
url=AIOPS_APIGATEWAY_ROOT + "models/{model_id}/release/",
module=self.MODULE,
url_keys=["model_id"],
description=u"备选模型列表",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.aiops_release_model_release_id_model_file = DataAPI(
method="GET",
url=AIOPS_APIGATEWAY_ROOT + "models/{model_id}/release/{model_release_id}/model_file/",
module=self.MODULE,
url_keys=["model_id", "model_release_id"],
description=u"获取发布的模型对应的模型文件",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.aiops_experiments_debug = DataAPI(
method="POST",
url=AIOPS_APIGATEWAY_ROOT + "experiments/debug/",
module=self.MODULE,
description=u"训练和预测调试",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
self.serving_data_processing_id_config = DataAPI(
method="GET",
url=AIOPS_APIGATEWAY_ROOT + "serving/{data_processing_id}/config/",
module=self.MODULE,
url_keys=["data_processing_id"],
description=u"AIOps 模型实例信息",
before_request=add_esb_info_before_request_for_bkdata_user,
after_request=None,
default_timeout=300,
)
BkDataAIOPSApi = _BkDataAIOPSApi()
| [
"apps.api.base.DataAPI",
"django.utils.translation.ugettext_lazy"
] | [((1703, 1719), 'django.utils.translation.ugettext_lazy', '_', (['"""数据平台aiops模块"""'], {}), "('数据平台aiops模块')\n", (1704, 1719), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1778, 2000), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'sample_set/')", 'module': 'self.MODULE', 'description': 'u"""创建样本集"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT + 'sample_set/', module=\n self.MODULE, description=u'创建样本集', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (1785, 2000), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((2118, 2414), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'sample_set/{sample_set_id}/result_table/')", 'module': 'self.MODULE', 'url_keys': "['sample_set_id']", 'description': 'u"""RT提交, 把RT添加到 stage表中"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT +\n 'sample_set/{sample_set_id}/result_table/', module=self.MODULE,\n url_keys=['sample_set_id'], description=u'RT提交, 把RT添加到 stage表中',\n before_request=add_esb_info_before_request_for_bkdata_user,\n after_request=None, default_timeout=300)\n", (2125, 2414), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((2537, 2828), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'sample_set/{sample_set_id}/collect_configs/')", 'module': 'self.MODULE', 'url_keys': "['sample_set_id']", 'description': 'u"""创建或更新样本采集配置"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT +\n 'sample_set/{sample_set_id}/collect_configs/', module=self.MODULE,\n url_keys=['sample_set_id'], description=u'创建或更新样本采集配置', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (2544, 2828), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((2947, 3301), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT +\n 'sample_set/{sample_set_id}/result_table/{result_table_id}/extract/auto_collect/'\n )", 'module': 'self.MODULE', 'url_keys': "['sample_set_id', 'result_table_id']", 'description': 'u"""创建或更新自动修改样本集配置"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT +\n 'sample_set/{sample_set_id}/result_table/{result_table_id}/extract/auto_collect/'\n , module=self.MODULE, url_keys=['sample_set_id', 'result_table_id'],\n description=u'创建或更新自动修改样本集配置', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (2954, 3301), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((3431, 3715), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'sample_set/{sample_set_id}/submit/apply/')", 'module': 'self.MODULE', 'url_keys': "['sample_set_id']", 'description': 'u"""执行样本集提交"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT +\n 'sample_set/{sample_set_id}/submit/apply/', module=self.MODULE,\n url_keys=['sample_set_id'], description=u'执行样本集提交', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (3438, 3715), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((3835, 4125), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""GET"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'sample_set/{sample_set_id}/submit/status/')", 'module': 'self.MODULE', 'url_keys': "['sample_set_id']", 'description': 'u"""查询提交后的固化任务执行状态"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='GET', url=AIOPS_APIGATEWAY_ROOT +\n 'sample_set/{sample_set_id}/submit/status/', module=self.MODULE,\n url_keys=['sample_set_id'], description=u'查询提交后的固化任务执行状态',\n before_request=add_esb_info_before_request_for_bkdata_user,\n after_request=None, default_timeout=300)\n", (3842, 4125), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((4250, 4522), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""DELETE"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'sample_set/{sample_set_id}/')", 'module': 'self.MODULE', 'url_keys': "['sample_set_id']", 'description': 'u"""删除样本集"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='DELETE', url=AIOPS_APIGATEWAY_ROOT +\n 'sample_set/{sample_set_id}/', module=self.MODULE, url_keys=[\n 'sample_set_id'], description=u'删除样本集', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (4257, 4522), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((4640, 4857), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'models/')", 'module': 'self.MODULE', 'description': 'u"""模型创建"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT + 'models/', module=self.\n MODULE, description=u'模型创建', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (4647, 4857), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((4972, 5245), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'models/{model_id}/experiments/')", 'module': 'self.MODULE', 'url_keys': "['model_id']", 'description': 'u"""AIOps 创建实验"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/', module=self.MODULE, url_keys=[\n 'model_id'], description=u'AIOps 创建实验', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (4979, 5245), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((5369, 5678), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""GET"""', 'url': "(AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/config/')", 'module': 'self.MODULE', 'url_keys': "['model_id', 'experiment_id']", 'description': 'u"""获取实验配置信息"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='GET', url=AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/config/', module=self.\n MODULE, url_keys=['model_id', 'experiment_id'], description=u'获取实验配置信息',\n before_request=add_esb_info_before_request_for_bkdata_user,\n after_request=None, default_timeout=300)\n", (5376, 5678), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((5808, 6061), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""GET"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'meta_data/retrieve_execute_config/')", 'module': 'self.MODULE', 'description': 'u"""获取实验执行配置信息"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='GET', url=AIOPS_APIGATEWAY_ROOT +\n 'meta_data/retrieve_execute_config/', module=self.MODULE, description=\n u'获取实验执行配置信息', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (5815, 6061), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((6176, 6421), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'meta_data/update_execute_config/')", 'module': 'self.MODULE', 'description': 'u"""更新实验执行配置"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT +\n 'meta_data/update_execute_config/', module=self.MODULE, description=\n u'更新实验执行配置', before_request=add_esb_info_before_request_for_bkdata_user,\n after_request=None, default_timeout=300)\n", (6183, 6421), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((6539, 6854), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/node/execute/')", 'module': 'self.MODULE', 'url_keys': "['model_id', 'experiment_id']", 'description': 'u"""执行实验配置"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/node/execute/', module=\n self.MODULE, url_keys=['model_id', 'experiment_id'], description=\n u'执行实验配置', before_request=add_esb_info_before_request_for_bkdata_user,\n after_request=None, default_timeout=300)\n", (6546, 6854), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((6991, 7329), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""GET"""', 'url': "(AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/node/execute/status/')", 'module': 'self.MODULE', 'url_keys': "['model_id', 'experiment_id']", 'description': 'u"""实验步骤状态 (当前用于切分状态捕获)"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='GET', url=AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/node/execute/status/',\n module=self.MODULE, url_keys=['model_id', 'experiment_id'], description\n =u'实验步骤状态 (当前用于切分状态捕获)', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (6998, 7329), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((7459, 7798), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/basic_models/training_status/'\n )", 'module': 'self.MODULE', 'url_keys': "['model_id', 'experiment_id']", 'description': 'u"""备选模型训练状态列表"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/basic_models/training_status/'\n , module=self.MODULE, url_keys=['model_id', 'experiment_id'],\n description=u'备选模型训练状态列表', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (7466, 7798), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((7926, 8206), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""GET"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'algorithm/{algorithm_name}/')", 'module': 'self.MODULE', 'url_keys': "['algorithm_name']", 'description': 'u"""获取单个自定义算法(最新版本)"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='GET', url=AIOPS_APIGATEWAY_ROOT +\n 'algorithm/{algorithm_name}/', module=self.MODULE, url_keys=[\n 'algorithm_name'], description=u'获取单个自定义算法(最新版本)', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (7933, 8206), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((8342, 8683), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/basic_models/evaluation_status/'\n )", 'module': 'self.MODULE', 'url_keys': "['model_id', 'experiment_id']", 'description': 'u"""备选模型评估状态列表"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/basic_models/evaluation_status/'\n , module=self.MODULE, url_keys=['model_id', 'experiment_id'],\n description=u'备选模型评估状态列表', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (8349, 8683), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((8814, 9193), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""GET"""', 'url': "(AIOPS_MODEL_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/basic_models/{basic_model_id}/evaluation_result/'\n )", 'module': 'self.MODULE', 'url_keys': "['model_id', 'experiment_id', 'basic_model_id']", 'description': 'u"""备选模型评估结果"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='GET', url=AIOPS_MODEL_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/basic_models/{basic_model_id}/evaluation_result/'\n , module=self.MODULE, url_keys=['model_id', 'experiment_id',\n 'basic_model_id'], description=u'备选模型评估结果', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (8821, 9193), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((9317, 9638), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/pre_commit/')", 'module': 'self.MODULE', 'url_keys': "['model_id', 'experiment_id']", 'description': 'u"""实验提交前查看配置"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/pre_commit/', module=\n self.MODULE, url_keys=['model_id', 'experiment_id'], description=\n u'实验提交前查看配置', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (9324, 9638), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((9756, 10062), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/commit/')", 'module': 'self.MODULE', 'url_keys': "['model_id', 'experiment_id']", 'description': 'u"""实验提交"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/experiments/{experiment_id}/commit/', module=self.\n MODULE, url_keys=['model_id', 'experiment_id'], description=u'实验提交',\n before_request=add_esb_info_before_request_for_bkdata_user,\n after_request=None, default_timeout=300)\n", (9763, 10062), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((10183, 10527), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""GET"""', 'url': "(AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/release/{experiment_id}/{basic_model_id}/config/')", 'module': 'self.MODULE', 'url_keys': "['model_id', 'experiment_id', 'basic_model_id']", 'description': 'u"""获取模型发布配置"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='GET', url=AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/release/{experiment_id}/{basic_model_id}/config/',\n module=self.MODULE, url_keys=['model_id', 'experiment_id',\n 'basic_model_id'], description=u'获取模型发布配置', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (10190, 10527), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((10637, 10971), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/release/{experiment_id}/{basic_model_id}')", 'module': 'self.MODULE', 'url_keys': "['model_id', 'experiment_id', 'basic_model_id']", 'description': 'u"""模型发布"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/release/{experiment_id}/{basic_model_id}', module=\n self.MODULE, url_keys=['model_id', 'experiment_id', 'basic_model_id'],\n description=u'模型发布', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (10644, 10971), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((11090, 11338), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""PUT"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'models/{model_id}/')", 'module': 'self.MODULE', 'url_keys': "['model_id']", 'description': 'u"""修改模型"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='PUT', url=AIOPS_APIGATEWAY_ROOT + 'models/{model_id}/',\n module=self.MODULE, url_keys=['model_id'], description=u'修改模型',\n before_request=add_esb_info_before_request_for_bkdata_user,\n after_request=None, default_timeout=300)\n", (11097, 11338), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((11464, 11727), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""GET"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'models/{model_id}/release/')", 'module': 'self.MODULE', 'url_keys': "['model_id']", 'description': 'u"""备选模型列表"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='GET', url=AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/release/', module=self.MODULE, url_keys=['model_id'],\n description=u'备选模型列表', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (11471, 11727), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((11876, 12203), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""GET"""', 'url': "(AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/release/{model_release_id}/model_file/')", 'module': 'self.MODULE', 'url_keys': "['model_id', 'model_release_id']", 'description': 'u"""获取发布的模型对应的模型文件"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='GET', url=AIOPS_APIGATEWAY_ROOT +\n 'models/{model_id}/release/{model_release_id}/model_file/', module=self\n .MODULE, url_keys=['model_id', 'model_release_id'], description=\n u'获取发布的模型对应的模型文件', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (11883, 12203), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((12327, 12557), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""POST"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'experiments/debug/')", 'module': 'self.MODULE', 'description': 'u"""训练和预测调试"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='POST', url=AIOPS_APIGATEWAY_ROOT + 'experiments/debug/',\n module=self.MODULE, description=u'训练和预测调试', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (12334, 12557), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n'), ((12689, 12979), 'apps.api.base.DataAPI', 'DataAPI', ([], {'method': '"""GET"""', 'url': "(AIOPS_APIGATEWAY_ROOT + 'serving/{data_processing_id}/config/')", 'module': 'self.MODULE', 'url_keys': "['data_processing_id']", 'description': 'u"""AIOps 模型实例信息"""', 'before_request': 'add_esb_info_before_request_for_bkdata_user', 'after_request': 'None', 'default_timeout': '(300)'}), "(method='GET', url=AIOPS_APIGATEWAY_ROOT +\n 'serving/{data_processing_id}/config/', module=self.MODULE, url_keys=[\n 'data_processing_id'], description=u'AIOps 模型实例信息', before_request=\n add_esb_info_before_request_for_bkdata_user, after_request=None,\n default_timeout=300)\n", (12696, 12979), False, 'from apps.api.base import DataAPI, DataApiRetryClass\n')] |
"""
Hypothesis data generator helpers.
"""
from datetime import datetime
from hypothesis import strategies as st
from hypothesis.extra.dateutil import timezones as dateutil_timezones
from hypothesis.extra.pytz import timezones as pytz_timezones
from pandas.compat import is_platform_windows
import pandas as pd
from pandas.tseries.offsets import (
BMonthBegin,
BMonthEnd,
BQuarterBegin,
BQuarterEnd,
BYearBegin,
BYearEnd,
MonthBegin,
MonthEnd,
QuarterBegin,
QuarterEnd,
YearBegin,
YearEnd,
)
OPTIONAL_INTS = st.lists(st.one_of(st.integers(), st.none()), max_size=10, min_size=3)
OPTIONAL_FLOATS = st.lists(st.one_of(st.floats(), st.none()), max_size=10, min_size=3)
OPTIONAL_TEXT = st.lists(st.one_of(st.none(), st.text()), max_size=10, min_size=3)
OPTIONAL_DICTS = st.lists(
st.one_of(st.none(), st.dictionaries(st.text(), st.integers())),
max_size=10,
min_size=3,
)
OPTIONAL_LISTS = st.lists(
st.one_of(st.none(), st.lists(st.text(), max_size=10, min_size=3)),
max_size=10,
min_size=3,
)
if is_platform_windows():
DATETIME_NO_TZ = st.datetimes(min_value=datetime(1900, 1, 1))
else:
DATETIME_NO_TZ = st.datetimes()
DATETIME_JAN_1_1900_OPTIONAL_TZ = st.datetimes(
min_value=pd.Timestamp(1900, 1, 1).to_pydatetime(),
max_value=pd.Timestamp(1900, 1, 1).to_pydatetime(),
timezones=st.one_of(st.none(), dateutil_timezones(), pytz_timezones()),
)
DATETIME_IN_PD_TIMESTAMP_RANGE_NO_TZ = st.datetimes(
min_value=pd.Timestamp.min.to_pydatetime(warn=False),
max_value=pd.Timestamp.max.to_pydatetime(warn=False),
)
INT_NEG_999_TO_POS_999 = st.integers(-999, 999)
# The strategy for each type is registered in conftest.py, as they don't carry
# enough runtime information (e.g. type hints) to infer how to build them.
YQM_OFFSET = st.one_of(
*map(
st.from_type,
[
MonthBegin,
MonthEnd,
BMonthBegin,
BMonthEnd,
QuarterBegin,
QuarterEnd,
BQuarterBegin,
BQuarterEnd,
YearBegin,
YearEnd,
BYearBegin,
BYearEnd,
],
)
)
| [
"hypothesis.strategies.text",
"datetime.datetime",
"hypothesis.strategies.none",
"hypothesis.strategies.integers",
"pandas.Timestamp",
"pandas.Timestamp.max.to_pydatetime",
"hypothesis.strategies.floats",
"hypothesis.strategies.datetimes",
"pandas.compat.is_platform_windows",
"hypothesis.extra.dat... | [((1075, 1096), 'pandas.compat.is_platform_windows', 'is_platform_windows', ([], {}), '()\n', (1094, 1096), False, 'from pandas.compat import is_platform_windows\n'), ((1643, 1665), 'hypothesis.strategies.integers', 'st.integers', (['(-999)', '(999)'], {}), '(-999, 999)\n', (1654, 1665), True, 'from hypothesis import strategies as st\n'), ((1191, 1205), 'hypothesis.strategies.datetimes', 'st.datetimes', ([], {}), '()\n', (1203, 1205), True, 'from hypothesis import strategies as st\n'), ((580, 593), 'hypothesis.strategies.integers', 'st.integers', ([], {}), '()\n', (591, 593), True, 'from hypothesis import strategies as st\n'), ((595, 604), 'hypothesis.strategies.none', 'st.none', ([], {}), '()\n', (602, 604), True, 'from hypothesis import strategies as st\n'), ((670, 681), 'hypothesis.strategies.floats', 'st.floats', ([], {}), '()\n', (679, 681), True, 'from hypothesis import strategies as st\n'), ((683, 692), 'hypothesis.strategies.none', 'st.none', ([], {}), '()\n', (690, 692), True, 'from hypothesis import strategies as st\n'), ((756, 765), 'hypothesis.strategies.none', 'st.none', ([], {}), '()\n', (763, 765), True, 'from hypothesis import strategies as st\n'), ((767, 776), 'hypothesis.strategies.text', 'st.text', ([], {}), '()\n', (774, 776), True, 'from hypothesis import strategies as st\n'), ((846, 855), 'hypothesis.strategies.none', 'st.none', ([], {}), '()\n', (853, 855), True, 'from hypothesis import strategies as st\n'), ((978, 987), 'hypothesis.strategies.none', 'st.none', ([], {}), '()\n', (985, 987), True, 'from hypothesis import strategies as st\n'), ((1513, 1555), 'pandas.Timestamp.min.to_pydatetime', 'pd.Timestamp.min.to_pydatetime', ([], {'warn': '(False)'}), '(warn=False)\n', (1543, 1555), True, 'import pandas as pd\n'), ((1571, 1613), 'pandas.Timestamp.max.to_pydatetime', 'pd.Timestamp.max.to_pydatetime', ([], {'warn': '(False)'}), '(warn=False)\n', (1601, 1613), True, 'import pandas as pd\n'), ((873, 882), 'hypothesis.strategies.text', 'st.text', ([], {}), '()\n', (880, 882), True, 'from hypothesis import strategies as st\n'), ((884, 897), 'hypothesis.strategies.integers', 'st.integers', ([], {}), '()\n', (895, 897), True, 'from hypothesis import strategies as st\n'), ((998, 1007), 'hypothesis.strategies.text', 'st.text', ([], {}), '()\n', (1005, 1007), True, 'from hypothesis import strategies as st\n'), ((1142, 1162), 'datetime.datetime', 'datetime', (['(1900)', '(1)', '(1)'], {}), '(1900, 1, 1)\n', (1150, 1162), False, 'from datetime import datetime\n'), ((1391, 1400), 'hypothesis.strategies.none', 'st.none', ([], {}), '()\n', (1398, 1400), True, 'from hypothesis import strategies as st\n'), ((1402, 1422), 'hypothesis.extra.dateutil.timezones', 'dateutil_timezones', ([], {}), '()\n', (1420, 1422), True, 'from hypothesis.extra.dateutil import timezones as dateutil_timezones\n'), ((1424, 1440), 'hypothesis.extra.pytz.timezones', 'pytz_timezones', ([], {}), '()\n', (1438, 1440), True, 'from hypothesis.extra.pytz import timezones as pytz_timezones\n'), ((1269, 1293), 'pandas.Timestamp', 'pd.Timestamp', (['(1900)', '(1)', '(1)'], {}), '(1900, 1, 1)\n', (1281, 1293), True, 'import pandas as pd\n'), ((1325, 1349), 'pandas.Timestamp', 'pd.Timestamp', (['(1900)', '(1)', '(1)'], {}), '(1900, 1, 1)\n', (1337, 1349), True, 'import pandas as pd\n')] |
# coding: utf-8
# Copyright 2013 The Font Bakery Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# See AUTHORS.txt for the list of Authors and LICENSE.txt for the License.
import lxml.etree
import os
import os.path as op
import re
class RedisFd(object):
""" Redis File Descriptor class, publish writen data to redis channel
in parallel to file """
def __init__(self, name, mode='a', write_pipeline=None):
self.filed = open(name, mode)
self.filed.write("Start: Start of log\n") # end of log
self.write_pipeline = write_pipeline
if write_pipeline and not isinstance(write_pipeline, list):
self.write_pipeline = [write_pipeline]
def write(self, data, prefix=''):
if self.write_pipeline:
for pipeline in self.write_pipeline:
data = pipeline(data)
if not data.endswith('\n'):
data += '\n'
data = re.sub('\n{3,}', '\n\n', data)
if data:
self.filed.write("%s%s" % (prefix, data))
self.filed.flush()
def close(self):
self.filed.write("End: End of log\n") # end of log
self.filed.close()
class UpstreamDirectory(object):
""" Describes structure of upstream directory
>>> upstream = UpstreamDirectory("tests/fixtures/upstream-example")
>>> upstream.UFO
['Font-Regular.ufo']
>>> upstream.TTX
['Font-Light.ttx']
>>> upstream.BIN
['Font-SemiBold.ttf']
>>> upstream.METADATA
['METADATA.json']
>>> sorted(upstream.LICENSE)
['APACHE.txt', 'LICENSE.txt']
>>> upstream.SFD
['Font-Bold.sfd']
>>> sorted(upstream.TXT)
['APACHE.txt', 'LICENSE.txt']
"""
OFL = ['open font license.markdown', 'ofl.txt', 'ofl.md']
LICENSE = ['license.txt', 'license.md', 'copyright.txt']
APACHE = ['apache.txt', 'apache.md']
UFL = ['ufl.txt', 'ufl.md']
ALL_LICENSES = OFL + LICENSE + APACHE + UFL
def __init__(self, upstream_path):
self.upstream_path = upstream_path
self.UFO = []
self.TTX = []
self.BIN = []
self.LICENSE = []
self.METADATA = []
self.SFD = []
self.TXT = []
self.walk()
def get_fonts(self):
return self.UFO + self.TTX + self.BIN + self.SFD
ALL_FONTS = property(get_fonts)
def walk(self):
l = len(self.upstream_path)
for root, dirs, files in os.walk(self.upstream_path):
for f in files:
fullpath = op.join(root, f)
if f[-4:].lower() == '.ttx':
try:
doc = lxml.etree.parse(fullpath)
el = doc.xpath('//ttFont[@sfntVersion]')
if not el:
continue
except:
continue
self.TTX.append(fullpath[l:].strip('/'))
if op.basename(f).lower() == 'metadata.json':
self.METADATA.append(fullpath[l:].strip('/'))
if f[-4:].lower() in ['.ttf', '.otf']:
self.BIN.append(fullpath[l:].strip('/'))
if f[-4:].lower() == '.sfd':
self.SFD.append(fullpath[l:].strip('/'))
if f[-4:].lower() in ['.txt', '.markdown', '.md', '.LICENSE']:
self.TXT.append(fullpath[l:].strip('/'))
if op.basename(f).lower() in UpstreamDirectory.ALL_LICENSES:
self.LICENSE.append(fullpath[l:].strip('/'))
for d in dirs:
fullpath = op.join(root, d)
if op.splitext(fullpath)[1].lower() == '.ufo':
self.UFO.append(fullpath[l:].strip('/'))
def nameTableRead(font, NameID, fallbackNameID=False):
for record in font['name'].names:
if record.nameID == NameID:
if b'\000' in record.string:
return record.string.decode('utf-16-be').encode('utf-8')
else:
return record.string
if fallbackNameID:
return nameTableRead(font, fallbackNameID)
return ''
| [
"os.path.splitext",
"os.path.join",
"os.path.basename",
"re.sub",
"os.walk"
] | [((1456, 1486), 're.sub', 're.sub', (['"""\n{3,}"""', '"""\n\n"""', 'data'], {}), "('\\n{3,}', '\\n\\n', data)\n", (1462, 1486), False, 'import re\n'), ((2945, 2972), 'os.walk', 'os.walk', (['self.upstream_path'], {}), '(self.upstream_path)\n', (2952, 2972), False, 'import os\n'), ((3029, 3045), 'os.path.join', 'op.join', (['root', 'f'], {}), '(root, f)\n', (3036, 3045), True, 'import os.path as op\n'), ((4125, 4141), 'os.path.join', 'op.join', (['root', 'd'], {}), '(root, d)\n', (4132, 4141), True, 'import os.path as op\n'), ((3453, 3467), 'os.path.basename', 'op.basename', (['f'], {}), '(f)\n', (3464, 3467), True, 'import os.path as op\n'), ((3947, 3961), 'os.path.basename', 'op.basename', (['f'], {}), '(f)\n', (3958, 3961), True, 'import os.path as op\n'), ((4161, 4182), 'os.path.splitext', 'op.splitext', (['fullpath'], {}), '(fullpath)\n', (4172, 4182), True, 'import os.path as op\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-26 12:31
from __future__ import unicode_literals
import json
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('annotations', '0005_auto_20170826_1424'),
]
def forward_func(apps, schema_editor):
Annotation = apps.get_model("annotations", "Annotation")
db_alias = schema_editor.connection.alias
# Copy all valid annotations from raw_vector to vector
for annotation in Annotation.objects.using(db_alias).all():
try:
vector = json.loads(annotation.raw_vector)
for key, value in vector.items():
try:
# try to convert all numeric vector values to integer
vector[key] = int(value)
except ValueError:
continue
annotation.vector = vector
annotation.save()
except ValueError:
# Annotation is invalid, delete it
annotation.delete()
def backward_func(apps, schema_editor):
Annotation = apps.get_model("annotations", "Annotation")
db_alias = schema_editor.connection.alias
# Copy all annotations from vector to raw_vector
for annotation in Annotation.objects.using(db_alias).all():
annotation.raw_vector = json.dumps(annotation.vector)
annotation.save()
operations = [
migrations.RenameField(
model_name='annotation',
old_name='vector',
new_name='raw_vector',
),
migrations.AddField(
model_name='annotation',
name='vector',
field=django.contrib.postgres.fields.jsonb.JSONField(null=True),
),
migrations.RunPython(forward_func, backward_func, atomic=True),
]
| [
"json.dumps",
"json.loads",
"django.db.migrations.RunPython",
"django.db.migrations.RenameField"
] | [((1571, 1665), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""annotation"""', 'old_name': '"""vector"""', 'new_name': '"""raw_vector"""'}), "(model_name='annotation', old_name='vector', new_name\n ='raw_vector')\n", (1593, 1665), False, 'from django.db import migrations\n'), ((1898, 1960), 'django.db.migrations.RunPython', 'migrations.RunPython', (['forward_func', 'backward_func'], {'atomic': '(True)'}), '(forward_func, backward_func, atomic=True)\n', (1918, 1960), False, 'from django.db import migrations\n'), ((1483, 1512), 'json.dumps', 'json.dumps', (['annotation.vector'], {}), '(annotation.vector)\n', (1493, 1512), False, 'import json\n'), ((658, 691), 'json.loads', 'json.loads', (['annotation.raw_vector'], {}), '(annotation.raw_vector)\n', (668, 691), False, 'import json\n')] |
import os
import statistics
import sys
def get_mean_std(out_csv):
with open(out_csv) as f:
lines = f.readlines()
tests = dict()
for t in lines[1:]:
t = t.split(",")
test_name = t[0].strip()
opt = float(t[2].strip())
tests[test_name] = tests.get(test_name, list()) + [opt]
means = {t: sum(v)/len(v) for t, v in tests.items()}
std = {t: statistics.stdev(v) for t, v in tests.items()}
return means
def get_tests(out_csv):
tests = set()
orig = dict()
with open(out_csv) as f:
lines = f.readlines()
for l in lines[1:]:
l = l.split(",")
name = l[0].strip()
original_runtime = float(l[1].strip())
tests.add(name)
orig[name] = orig.get(name, list()) + [original_runtime]
tests = sorted(list(tests))
means = {t: sum(v)/len(v) for t, v in orig.items()}
std = {t: statistics.stdev(v) for t, v in orig.items()}
return [[t, str(means[t])] for t in tests]
if __name__ == '__main__':
if len(sys.argv) != 2:
print("Usage: python3 process_csv.py [output_csv_path]")
sys.exit(1)
num_runs = (1, 2, 3)
thresholds = (10, 100, 1000)
filename = lambda runs, threshold: f'out-{runs}-{threshold}.csv'
output_file = sys.argv[1]
header = ['test', 'original']
tests = get_tests('out-1-10.csv')
for threshold in thresholds:
for run in num_runs:
out_csv = filename(run, threshold)
stat = get_mean_std(out_csv)
header += [f'runs:{run}+thresh:{threshold}']
tests = [row + [str(stat[row[0]])] for row in tests]
with open(output_file, 'w') as f:
f.write(', '.join(header) + '\n')
for row in tests:
f.write(', '.join(row) + '\n')
| [
"statistics.stdev",
"sys.exit"
] | [((396, 415), 'statistics.stdev', 'statistics.stdev', (['v'], {}), '(v)\n', (412, 415), False, 'import statistics\n'), ((895, 914), 'statistics.stdev', 'statistics.stdev', (['v'], {}), '(v)\n', (911, 914), False, 'import statistics\n'), ((1116, 1127), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1124, 1127), False, 'import sys\n')] |
# Copyright <NAME> and contributors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django import forms
from hosts.models import Host
from images.models import Image
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit, Button
from crispy_forms.bootstrap import FieldWithButtons, StrictButton, FormActions
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
def get_available_hosts():
return Host.objects.filter(enabled=True)
def get_image_choices():
hosts = get_available_hosts()
choices = []
images = Image.objects.filter(host__in=hosts).order_by('repository').values_list(
'repository', flat=True).order_by('repository').distinct()
for i in images:
repo = i
if repo.find('<none>') == -1:
d = (repo, repo)
choices.append(d)
return choices
class CreateContainerForm(forms.Form):
image = forms.ChoiceField(required=True)
name = forms.CharField(required=False, help_text=_('container name (used in links)'))
hostname = forms.CharField(required=False)
description = forms.CharField(required=False)
command = forms.CharField(required=False)
memory = forms.CharField(required=False, max_length=8,
help_text='Memory in MB')
environment = forms.CharField(required=False,
help_text='key=value space separated pairs')
ports = forms.CharField(required=False, help_text=_('space separated (i.e. 8000 8001:8001 127.0.0.1:80:80 )'))
links = forms.CharField(required=False, help_text=_('space separated (i.e. redis:db)'))
volume = forms.CharField(required=False, help_text='container volume (i.e. /mnt/volume)')
volumes_from = forms.CharField(required=False,
help_text='mount volumes from specified container')
hosts = forms.MultipleChoiceField(required=True)
private = forms.BooleanField(required=False)
privileged = forms.BooleanField(required=False)
def __init__(self, *args, **kwargs):
super(CreateContainerForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.layout = Layout(
Fieldset(
None,
'image',
'name',
'hostname',
'command',
'description',
'memory',
'environment',
'ports',
'links',
'volume',
'volumes_from',
'hosts',
'private',
'privileged',
),
FormActions(
Submit('save', _('Create'), css_class="btn btn-lg btn-success"),
)
)
self.helper.form_id = 'form-create-container'
self.helper.form_class = 'form-horizontal'
self.helper.form_action = reverse('containers.views.create_container')
self.helper.help_text_inline = True
self.fields['image'].choices = [('', '----------')] + \
[x for x in get_image_choices()]
self.fields['hosts'].choices = \
[(x.id, x.name) for x in get_available_hosts()]
class ImportRepositoryForm(forms.Form):
repository = forms.CharField(help_text='i.e. ehazlett/logstash')
hosts = forms.MultipleChoiceField()
def __init__(self, *args, **kwargs):
super(ImportRepositoryForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'form-import-repository'
self.helper.form_class = 'form-horizontal'
self.helper.form_action = reverse('containers.views.import_image')
self.helper.help_text_inline = True
self.fields['hosts'].choices = \
[(x.id, x.name) for x in get_available_hosts()]
class ContainerForm(forms.Form):
image = forms.ChoiceField()
command = forms.CharField(required=False)
def __init__(self, *args, **kwargs):
super(CreateContainerForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'form-create-container'
self.helper.form_class = 'form-horizontal'
self.helper.form_action = reverse('containers.views.create_container')
self.helper.help_text_inline = True
self.fields['image'].widget.attrs['readonly'] = True
class ImageBuildForm(forms.Form):
dockerfile = forms.FileField(required=False)
url = forms.URLField(help_text='Dockerfile URL', required=False)
tag = forms.CharField(help_text='i.e. app-v1', required=False)
hosts = forms.MultipleChoiceField()
def __init__(self, *args, **kwargs):
super(ImageBuildForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'form-build-image'
self.helper.form_class = 'form-horizontal'
self.helper.form_action = reverse('containers.views.build_image')
self.helper.help_text_inline = True
self.fields['hosts'].choices = \
[(x.id, x.name) for x in get_available_hosts()]
| [
"django.forms.BooleanField",
"crispy_forms.helper.FormHelper",
"django.forms.CharField",
"images.models.Image.objects.filter",
"django.forms.URLField",
"django.core.urlresolvers.reverse",
"django.forms.ChoiceField",
"hosts.models.Host.objects.filter",
"django.utils.translation.ugettext",
"django.f... | [((1004, 1037), 'hosts.models.Host.objects.filter', 'Host.objects.filter', ([], {'enabled': '(True)'}), '(enabled=True)\n', (1023, 1037), False, 'from hosts.models import Host\n'), ((1478, 1510), 'django.forms.ChoiceField', 'forms.ChoiceField', ([], {'required': '(True)'}), '(required=True)\n', (1495, 1510), False, 'from django import forms\n'), ((1616, 1647), 'django.forms.CharField', 'forms.CharField', ([], {'required': '(False)'}), '(required=False)\n', (1631, 1647), False, 'from django import forms\n'), ((1666, 1697), 'django.forms.CharField', 'forms.CharField', ([], {'required': '(False)'}), '(required=False)\n', (1681, 1697), False, 'from django import forms\n'), ((1712, 1743), 'django.forms.CharField', 'forms.CharField', ([], {'required': '(False)'}), '(required=False)\n', (1727, 1743), False, 'from django import forms\n'), ((1757, 1828), 'django.forms.CharField', 'forms.CharField', ([], {'required': '(False)', 'max_length': '(8)', 'help_text': '"""Memory in MB"""'}), "(required=False, max_length=8, help_text='Memory in MB')\n", (1772, 1828), False, 'from django import forms\n'), ((1855, 1931), 'django.forms.CharField', 'forms.CharField', ([], {'required': '(False)', 'help_text': '"""key=value space separated pairs"""'}), "(required=False, help_text='key=value space separated pairs')\n", (1870, 1931), False, 'from django import forms\n'), ((2160, 2245), 'django.forms.CharField', 'forms.CharField', ([], {'required': '(False)', 'help_text': '"""container volume (i.e. /mnt/volume)"""'}), "(required=False, help_text='container volume (i.e. /mnt/volume)'\n )\n", (2175, 2245), False, 'from django import forms\n'), ((2260, 2348), 'django.forms.CharField', 'forms.CharField', ([], {'required': '(False)', 'help_text': '"""mount volumes from specified container"""'}), "(required=False, help_text=\n 'mount volumes from specified container')\n", (2275, 2348), False, 'from django import forms\n'), ((2364, 2404), 'django.forms.MultipleChoiceField', 'forms.MultipleChoiceField', ([], {'required': '(True)'}), '(required=True)\n', (2389, 2404), False, 'from django import forms\n'), ((2419, 2453), 'django.forms.BooleanField', 'forms.BooleanField', ([], {'required': '(False)'}), '(required=False)\n', (2437, 2453), False, 'from django import forms\n'), ((2471, 2505), 'django.forms.BooleanField', 'forms.BooleanField', ([], {'required': '(False)'}), '(required=False)\n', (2489, 2505), False, 'from django import forms\n'), ((3758, 3809), 'django.forms.CharField', 'forms.CharField', ([], {'help_text': '"""i.e. ehazlett/logstash"""'}), "(help_text='i.e. ehazlett/logstash')\n", (3773, 3809), False, 'from django import forms\n'), ((3822, 3849), 'django.forms.MultipleChoiceField', 'forms.MultipleChoiceField', ([], {}), '()\n', (3847, 3849), False, 'from django import forms\n'), ((4367, 4386), 'django.forms.ChoiceField', 'forms.ChoiceField', ([], {}), '()\n', (4384, 4386), False, 'from django import forms\n'), ((4401, 4432), 'django.forms.CharField', 'forms.CharField', ([], {'required': '(False)'}), '(required=False)\n', (4416, 4432), False, 'from django import forms\n'), ((4918, 4949), 'django.forms.FileField', 'forms.FileField', ([], {'required': '(False)'}), '(required=False)\n', (4933, 4949), False, 'from django import forms\n'), ((4960, 5018), 'django.forms.URLField', 'forms.URLField', ([], {'help_text': '"""Dockerfile URL"""', 'required': '(False)'}), "(help_text='Dockerfile URL', required=False)\n", (4974, 5018), False, 'from django import forms\n'), ((5029, 5085), 'django.forms.CharField', 'forms.CharField', ([], {'help_text': '"""i.e. app-v1"""', 'required': '(False)'}), "(help_text='i.e. app-v1', required=False)\n", (5044, 5085), False, 'from django import forms\n'), ((5098, 5125), 'django.forms.MultipleChoiceField', 'forms.MultipleChoiceField', ([], {}), '()\n', (5123, 5125), False, 'from django import forms\n'), ((2637, 2653), 'crispy_forms.helper.FormHelper', 'FormHelper', (['self'], {}), '(self)\n', (2647, 2653), False, 'from crispy_forms.helper import FormHelper\n'), ((3401, 3445), 'django.core.urlresolvers.reverse', 'reverse', (['"""containers.views.create_container"""'], {}), "('containers.views.create_container')\n", (3408, 3445), False, 'from django.core.urlresolvers import reverse\n'), ((3982, 3994), 'crispy_forms.helper.FormHelper', 'FormHelper', ([], {}), '()\n', (3992, 3994), False, 'from crispy_forms.helper import FormHelper\n'), ((4135, 4175), 'django.core.urlresolvers.reverse', 'reverse', (['"""containers.views.import_image"""'], {}), "('containers.views.import_image')\n", (4142, 4175), False, 'from django.core.urlresolvers import reverse\n'), ((4564, 4576), 'crispy_forms.helper.FormHelper', 'FormHelper', ([], {}), '()\n', (4574, 4576), False, 'from crispy_forms.helper import FormHelper\n'), ((4716, 4760), 'django.core.urlresolvers.reverse', 'reverse', (['"""containers.views.create_container"""'], {}), "('containers.views.create_container')\n", (4723, 4760), False, 'from django.core.urlresolvers import reverse\n'), ((5252, 5264), 'crispy_forms.helper.FormHelper', 'FormHelper', ([], {}), '()\n', (5262, 5264), False, 'from crispy_forms.helper import FormHelper\n'), ((5399, 5438), 'django.core.urlresolvers.reverse', 'reverse', (['"""containers.views.build_image"""'], {}), "('containers.views.build_image')\n", (5406, 5438), False, 'from django.core.urlresolvers import reverse\n'), ((1564, 1599), 'django.utils.translation.ugettext', '_', (['"""container name (used in links)"""'], {}), "('container name (used in links)')\n", (1565, 1599), True, 'from django.utils.translation import ugettext as _\n'), ((1994, 2053), 'django.utils.translation.ugettext', '_', (['"""space separated (i.e. 8000 8001:8001 127.0.0.1:80:80 )"""'], {}), "('space separated (i.e. 8000 8001:8001 127.0.0.1:80:80 )')\n", (1995, 2053), True, 'from django.utils.translation import ugettext as _\n'), ((2109, 2145), 'django.utils.translation.ugettext', '_', (['"""space separated (i.e. redis:db)"""'], {}), "('space separated (i.e. redis:db)')\n", (2110, 2145), True, 'from django.utils.translation import ugettext as _\n'), ((2703, 2883), 'crispy_forms.layout.Fieldset', 'Fieldset', (['None', '"""image"""', '"""name"""', '"""hostname"""', '"""command"""', '"""description"""', '"""memory"""', '"""environment"""', '"""ports"""', '"""links"""', '"""volume"""', '"""volumes_from"""', '"""hosts"""', '"""private"""', '"""privileged"""'], {}), "(None, 'image', 'name', 'hostname', 'command', 'description',\n 'memory', 'environment', 'ports', 'links', 'volume', 'volumes_from',\n 'hosts', 'private', 'privileged')\n", (2711, 2883), False, 'from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit, Button\n'), ((3188, 3199), 'django.utils.translation.ugettext', '_', (['"""Create"""'], {}), "('Create')\n", (3189, 3199), True, 'from django.utils.translation import ugettext as _\n'), ((1128, 1164), 'images.models.Image.objects.filter', 'Image.objects.filter', ([], {'host__in': 'hosts'}), '(host__in=hosts)\n', (1148, 1164), False, 'from images.models import Image\n')] |
#!/usr/bin/python
from http.server import BaseHTTPRequestHandler, HTTPServer
from os import curdir, sep
PORT_NUMBER = 8080
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','image/png')
self.end_headers()
with open(curdir + sep + 'logo.png', 'rb') as f:
self.wfile.write(f.read())
try:
server = HTTPServer(('', PORT_NUMBER), myHandler)
print('Started httpserver on port' , PORT_NUMBER)
server.serve_forever()
except KeyboardInterrupt:
server.server_close()
print('Stopping server')
| [
"http.server.HTTPServer"
] | [((409, 449), 'http.server.HTTPServer', 'HTTPServer', (["('', PORT_NUMBER)", 'myHandler'], {}), "(('', PORT_NUMBER), myHandler)\n", (419, 449), False, 'from http.server import BaseHTTPRequestHandler, HTTPServer\n')] |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def hello(request):
return HttpResponse("Hello world")
def date(request, year, month, day):
return HttpResponse({
year: year,
month: month,
day: day
})
| [
"django.http.HttpResponse"
] | [((133, 160), 'django.http.HttpResponse', 'HttpResponse', (['"""Hello world"""'], {}), "('Hello world')\n", (145, 160), False, 'from django.http import HttpResponse\n'), ((211, 261), 'django.http.HttpResponse', 'HttpResponse', (['{year: year, month: month, day: day}'], {}), '({year: year, month: month, day: day})\n', (223, 261), False, 'from django.http import HttpResponse\n')] |
# Generated by Django 2.2.1 on 2019-05-22 08:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('insta', '0002_pictures'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('comment', models.CharField(max_length=400)),
],
),
migrations.RenameField(
model_name='profile',
old_name='bio',
new_name='about',
),
]
| [
"django.db.models.AutoField",
"django.db.migrations.RenameField",
"django.db.models.CharField"
] | [((508, 586), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""profile"""', 'old_name': '"""bio"""', 'new_name': '"""about"""'}), "(model_name='profile', old_name='bio', new_name='about')\n", (530, 586), False, 'from django.db import migrations, models\n'), ((319, 412), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (335, 412), False, 'from django.db import migrations, models\n'), ((439, 471), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(400)'}), '(max_length=400)\n', (455, 471), False, 'from django.db import migrations, models\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import enum
import json
import os
import plistlib
import subprocess
import time
import tools
import requests
python_script_debug_enable = False # 是否开启debug模式 用于测试脚本
pwd = os.getcwd() # 当前文件的路径
ios_project_path = os.path.abspath(os.path.dirname(
pwd) + os.path.sep + ".") # ios项目路径,默认为当前文件的父路径, 如果修改请填写项目绝对路径
system_home_dir = os.path.expanduser('~') # home路径
build_directory = os.path.join(pwd, 'build') # 打包输出的文件夹
auth_key_dir_name = 'private_keys'
auth_key_copy_dir = os.path.join(pwd, auth_key_dir_name)
auth_key_destination = '~/private_keys/'
pgy_upload_url = 'https://www.pgyer.com/apiv2/app/upload'
testflights_url = 'https://appstoreconnect.apple.com/apps'
qr_code_img_path = os.path.join(build_directory, 'qrCode.jpg')
log_directory = os.path.join(pwd, 'log') # 日志文件夹
packaging_log_path = os.path.join(log_directory, 'packaging.log')
@enum.unique
class DistributionMethodType(enum.Enum):
Development = 'development'
AppStoreConnect = 'app-store'
AdHoc = 'ad-hoc'
class Config(object):
project_name: str
project_scheme_list: list
project_scheme_index: int
apple_account_team_id: str
development_provisioning_profiles: dict
distribution_provisioning_profiles: dict
adhoc_provisioning_profiles: dict
distribution_method: DistributionMethodType
upload_pgy_enable: bool
pgy_api_key: str
upload_app_sotre_enable: bool
upload_app_store_account_type: int # 1 使用apple账号 2 使用apiKey
apple_account_user: str
apple_account_password: str
auth_key_file_name: str
apple_account_apiKey: str
apple_account_apiIssuer: str
send_email_enable: bool
email_host: str
email_port: int
email_sender_user: str
email_sender_psw: str
email_receivers: list
add_build_number_enable: bool
log_enable: bool
app_update_message = ''
github_access_token: str
github_repo_url: str
testflight_external_group_name: str
xcodeproj_path = None
xcworkspace_path = None
is_workspace_project = True
def get_product_scheme():
return Config.project_scheme_list[Config.project_scheme_index]
def get_export_options_plist_path():
plist_path = os.path.join(
build_directory, Config.distribution_method.value+'_ExportOptions.plist')
return plist_path
def get_signing_certificate():
if Config.distribution_method == DistributionMethodType.Development:
return 'Apple Development'
elif Config.distribution_method == DistributionMethodType.AppStoreConnect:
return 'Apple Distribution'
elif Config.distribution_method == DistributionMethodType.AdHoc:
return 'Apple Distribution'
def get_provisioning_profile():
if Config.distribution_method == DistributionMethodType.Development:
return Config.development_provisioning_profiles
elif Config.distribution_method == DistributionMethodType.AppStoreConnect:
return Config.distribution_provisioning_profiles
elif Config.distribution_method == DistributionMethodType.AdHoc:
return Config.adhoc_provisioning_profiles
def get_export_path():
export_path = os.path.join(
build_directory, Config.distribution_method.value)
if export_path in os.listdir(build_directory):
print("%s exists" % (export_path))
else:
print("create dir %s" % (export_path))
subprocess.call('mkdir %s' % (export_path), shell=True)
time.sleep(1)
return export_path
def get_xcode_workspace_path():
if Config.xcworkspace_path is None:
path = search_project_file(
ios_project_path, '%s.xcworkspace' % (Config.project_name))
Config.xcworkspace_path = path
return os.path.join(path)
else:
return os.path.join(Config.xcworkspace_path)
def get_xcode_project_path():
if Config.xcodeproj_path is None:
path = search_project_file(
ios_project_path, '%s.xcodeproj' % (Config.project_name))
Config.xcodeproj_path = path
return os.path.join(path)
else:
return os.path.join(Config.xcodeproj_path)
def get_xcode_project_pbxproj_path():
return os.path.join(get_xcode_project_path(), 'project.pbxproj')
def search_project_file(path, target):
target_path = ''
for root, dirs, fs in os.walk(path):
for d in dirs:
if d == target:
target_path = os.path.join(root, d)
return target_path
for f in fs:
if f == target:
target_path = os.path.join(root, f)
return target_path
if target_path == '':
tools.fail_print('没有找到%s文件' % (target))
return target_path
def get_target_name():
return Config.project_name # 默认target name和project name一致
def get_exported_ipa_path():
ipa_path = os.path.join(
build_directory, '%s/%s.ipa' % (Config.distribution_method.value, Config.project_name))
return ipa_path
def prepare_config():
config_path = os.path.join(pwd, 'config.json')
with open(config_path, 'r') as config_file:
config_json_dic = json.load(config_file)
Config.project_name = config_json_dic['project_name']
Config.project_scheme_list = config_json_dic['project_scheme_list']
Config.project_scheme_index = config_json_dic['project_scheme_index']
Config.apple_account_team_id = config_json_dic['apple_account_team_id']
Config.development_provisioning_profiles = config_json_dic[
'development_provisioning_profiles']
Config.distribution_provisioning_profiles = config_json_dic[
'distribution_provisioning_profiles']
Config.adhoc_provisioning_profiles = config_json_dic['adhoc_provisioning_profiles']
Config.distribution_method = DistributionMethodType(
config_json_dic['distribution_method'])
Config.upload_pgy_enable = config_json_dic['upload_pgy_enable']
Config.pgy_api_key = config_json_dic['pgy_api_key']
Config.upload_app_sotre_enable = config_json_dic['upload_app_sotre_enable']
Config.upload_app_store_account_type = config_json_dic['upload_app_store_account_type']
Config.apple_account_user = config_json_dic['apple_account_user']
Config.apple_account_password = config_json_dic['apple_account_password']
Config.auth_key_file_name = config_json_dic['auth_key_file_name']
Config.apple_account_apiKey = config_json_dic['apple_account_apiKey']
Config.apple_account_apiIssuer = config_json_dic['apple_account_apiIssuer']
Config.send_email_enable = config_json_dic['send_email_enable']
Config.email_host = config_json_dic['email_host']
Config.email_port = config_json_dic['email_port']
Config.email_sender_user = config_json_dic['email_sender_user']
Config.email_sender_psw = config_json_dic['email_sender_psw']
Config.email_receivers = config_json_dic['email_receivers']
Config.add_build_number_enable = config_json_dic['add_build_number_enable']
Config.log_enable = config_json_dic['log_enable']
Config.github_access_token = config_json_dic['github_access_token']
Config.github_repo_url = config_json_dic['github_repo_url']
Config.testflight_external_group_name = config_json_dic['testflight_external_group_name']
if get_xcode_workspace_path() != '':
Config.is_workspace_project = True
else:
Config.is_workspace_project = False
if get_xcode_project_path() != '':
tools.fail_print('没有找到%s.xcodeproj文件, 请将脚本文件放到项目目录下')
# check project_scheme_list
if len(Config.project_scheme_list) == 0:
tools.warn_print("project_scheme_list未配置,正在获取project的schemes...")
list_project_command_run = subprocess.Popen(
'xcodebuild -list -project %s -json' % (get_xcode_project_path()), shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
stdout, stderr = list_project_command_run.communicate()
project_info = stdout.decode('utf-8')
project_dict = json.loads(project_info)
print('projec info:\n %s' % (project_dict))
Config.project_scheme_list = project_dict['project']['schemes']
print('project_scheme_lis:\n%s' % (Config.project_scheme_list))
list_project_command_run.wait()
save_packaging_config()
def save_packaging_config():
dic = {
"project_name": Config.project_name,
"project_scheme_list": Config.project_scheme_list,
"project_scheme_index": Config.project_scheme_index,
"apple_account_team_id": Config.apple_account_team_id,
"development_provisioning_profiles": Config.development_provisioning_profiles,
"distribution_provisioning_profiles": Config.distribution_provisioning_profiles,
"distribution_method": Config.distribution_method.value,
"upload_pgy_enable": Config.upload_pgy_enable,
"pgy_api_key": Config.pgy_api_key,
"upload_app_sotre_enable": Config.upload_app_sotre_enable,
"upload_app_store_account_type": Config.upload_app_store_account_type,
"apple_account_user": Config.apple_account_user,
"apple_account_password": Config.apple_account_password,
"auth_key_file_name": Config.auth_key_file_name,
"apple_account_apiKey": Config.apple_account_apiKey,
"apple_account_apiIssuer": Config.apple_account_apiIssuer,
"send_email_enable": Config.send_email_enable,
"email_host": Config.email_host,
"email_port": Config.email_port,
"email_sender_user": Config.email_sender_user,
"email_sender_psw": Config.email_sender_psw,
"email_receivers": Config.email_receivers,
"add_build_number_enable": Config.add_build_number_enable,
"log_enable": Config.log_enable,
"github_access_token": Config.github_access_token,
"github_repo_url": Config.github_repo_url,
"testflight_external_group_name": Config.testflight_external_group_name
}
tools.warn_print('back up configs')
json_str = json.dumps(dic, ensure_ascii=False, indent=4) # 缩进4字符
config_path = os.path.join(pwd, 'config.json')
with open(config_path, 'w+') as config_file:
config_file.truncate(0)
config_file.write(json_str)
config_file.close()
def create_export_options_plist_file():
plist_value = {
'method': Config.distribution_method.value,
'destination': 'export',
'teamID': Config.apple_account_team_id,
'stripSwiftSymbols': True,
'compileBitcode': True,
'thinning': '<none>',
'signingCertificate': get_signing_certificate(),
'signingStyle': 'manual',
'provisioningProfiles': get_provisioning_profile(),
}
plist_path = get_export_options_plist_path()
print('ExportOptions.plist:\n'+plist_path+'\n')
print(plist_value)
with open(plist_path, 'wb') as fp:
plistlib.dump(plist_value, fp)
return plist_path
def prepare_packaging_dir():
tools.notice_print('prepare build dir: ' + build_directory)
subprocess.call(['rm', '-rf', '%s' % (build_directory)])
time.sleep(1)
subprocess.call(['mkdir', '-p', '%s' % (build_directory)])
time.sleep(1)
def prepare_log_dir():
tools.notice_print('prepare log dir: ' + log_directory)
subprocess.call(['rm', '-rf', '%s' % (log_directory)])
time.sleep(1)
subprocess.call(['mkdir', '-p', '%s' % (log_directory)])
time.sleep(1)
def prepare_app_store_upload():
if Config.upload_app_store_account_type == 1:
if len(Config.apple_account_user) == 0 or len(Config.apple_account_password) == 0:
tools.warn_print(
'上传App Store Connect需要 账号/密码 或者 apiKey/apiIssuer, upload_app_store_account_type值为 1 或者 2, 请在config.json中填写相关信息')
tools.end_program(2)
elif Config.upload_app_store_account_type == 2:
if len(Config.apple_account_apiKey) == 0 or len(Config.apple_account_apiIssuer) == 0:
tools.warn_print(
'上传App Store Connect需要 账号/密码 或者 apiKey/apiIssuer, upload_app_store_account_type值为 1 或者 2, 请在config.json中填写相关信息')
tools.end_program(2)
prepare_authkey_dir()
else:
tools.warn_print(
'上传App Store Connect需要 账号/密码 或者 apiKey/apiIssuer, upload_app_store_account_type值为 1 或者 2, 请在config.json中填写相关信息')
tools.end_program(2)
def prepare_authkey_dir():
if Config.auth_key_file_name is None or Config.auth_key_file_name not in os.listdir(auth_key_copy_dir):
tools.warn_print(
'使用apiKey/apiIssuer来上传App Store Connect时需要配置*.p8文件, 请先将*.p8文件复制到private_keys目录下, 具体详情可参考: https://developer.apple.com/documentation/appstoreconnectapi/creating_api_keys_for_app_store_connect_api')
tools.end_program(2)
if auth_key_dir_name in os.listdir(system_home_dir):
print("%s exists" % (auth_key_destination))
else:
print("create dir: %s" % (auth_key_destination))
subprocess.call('cd ~ && mkdir %s' %
(auth_key_destination), shell=True)
time.sleep(1)
key_dir = os.path.expanduser(auth_key_destination)
if Config.auth_key_file_name in os.listdir(key_dir):
print("%s/%s file exists" %
(auth_key_destination, Config.auth_key_file_name))
else:
print("copy file: %s/%s" %
(auth_key_destination, Config.auth_key_file_name))
subprocess.call('cp -r %s %s' %
(auth_key_copy_dir, auth_key_destination), shell=True)
time.sleep(1)
def save_qr_code(qr_code_url):
r = requests.get(qr_code_url)
with open(qr_code_img_path, 'wb') as f:
f.write(r.content)
return qr_code_img_path
def save_packaging_log(start_time='', end_time='', error_message=''):
if Config.log_enable:
prepare_log_dir()
version = tools.get_xcode_project_info(
project_pbxproj_path=get_xcode_project_pbxproj_path(), target_name=get_target_name())
log = {
"strat_time": start_time,
"end_time": end_time,
"erro_message": error_message,
"app_name": Config.project_name,
"scheme": get_product_scheme(),
"update_message": Config.app_update_message,
"version": version[0]+'('+version[1]+')',
"upload_to_pgy": Config.upload_pgy_enable,
"upload_to_app_store": Config.upload_app_sotre_enable,
"auto_add_build": Config.add_build_number_enable,
'signingCertificate': get_signing_certificate(),
"distribution_method": Config.distribution_method.value,
"ipa_path": get_exported_ipa_path(),
"xcodeproj_path": get_xcode_project_path(),
"xcworkspace_path": get_xcode_workspace_path()
}
json_str = json.dumps(log, ensure_ascii=False, indent=4)
with open(packaging_log_path, "w+") as log_file:
log_file.truncate(0)
log_file.write(json_str)
log_file.close()
return json_str
| [
"os.path.expanduser",
"json.loads",
"os.listdir",
"json.dumps",
"os.path.join",
"plistlib.dump",
"time.sleep",
"os.getcwd",
"requests.get",
"os.path.dirname",
"subprocess.call",
"tools.end_program",
"tools.notice_print",
"json.load",
"tools.warn_print",
"tools.fail_print",
"os.walk"
... | [((222, 233), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (231, 233), False, 'import os\n'), ((385, 408), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (403, 408), False, 'import os\n'), ((437, 463), 'os.path.join', 'os.path.join', (['pwd', '"""build"""'], {}), "(pwd, 'build')\n", (449, 463), False, 'import os\n'), ((534, 570), 'os.path.join', 'os.path.join', (['pwd', 'auth_key_dir_name'], {}), '(pwd, auth_key_dir_name)\n', (546, 570), False, 'import os\n'), ((750, 793), 'os.path.join', 'os.path.join', (['build_directory', '"""qrCode.jpg"""'], {}), "(build_directory, 'qrCode.jpg')\n", (762, 793), False, 'import os\n'), ((811, 835), 'os.path.join', 'os.path.join', (['pwd', '"""log"""'], {}), "(pwd, 'log')\n", (823, 835), False, 'import os\n'), ((866, 910), 'os.path.join', 'os.path.join', (['log_directory', '"""packaging.log"""'], {}), "(log_directory, 'packaging.log')\n", (878, 910), False, 'import os\n'), ((2235, 2327), 'os.path.join', 'os.path.join', (['build_directory', "(Config.distribution_method.value + '_ExportOptions.plist')"], {}), "(build_directory, Config.distribution_method.value +\n '_ExportOptions.plist')\n", (2247, 2327), False, 'import os\n'), ((3175, 3238), 'os.path.join', 'os.path.join', (['build_directory', 'Config.distribution_method.value'], {}), '(build_directory, Config.distribution_method.value)\n', (3187, 3238), False, 'import os\n'), ((4333, 4346), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (4340, 4346), False, 'import os\n'), ((4853, 4958), 'os.path.join', 'os.path.join', (['build_directory', "('%s/%s.ipa' % (Config.distribution_method.value, Config.project_name))"], {}), "(build_directory, '%s/%s.ipa' % (Config.distribution_method.\n value, Config.project_name))\n", (4865, 4958), False, 'import os\n'), ((5025, 5057), 'os.path.join', 'os.path.join', (['pwd', '"""config.json"""'], {}), "(pwd, 'config.json')\n", (5037, 5057), False, 'import os\n'), ((10068, 10103), 'tools.warn_print', 'tools.warn_print', (['"""back up configs"""'], {}), "('back up configs')\n", (10084, 10103), False, 'import tools\n'), ((10119, 10164), 'json.dumps', 'json.dumps', (['dic'], {'ensure_ascii': '(False)', 'indent': '(4)'}), '(dic, ensure_ascii=False, indent=4)\n', (10129, 10164), False, 'import json\n'), ((10192, 10224), 'os.path.join', 'os.path.join', (['pwd', '"""config.json"""'], {}), "(pwd, 'config.json')\n", (10204, 10224), False, 'import os\n'), ((11079, 11138), 'tools.notice_print', 'tools.notice_print', (["('prepare build dir: ' + build_directory)"], {}), "('prepare build dir: ' + build_directory)\n", (11097, 11138), False, 'import tools\n'), ((11143, 11197), 'subprocess.call', 'subprocess.call', (["['rm', '-rf', '%s' % build_directory]"], {}), "(['rm', '-rf', '%s' % build_directory])\n", (11158, 11197), False, 'import subprocess\n'), ((11204, 11217), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (11214, 11217), False, 'import time\n'), ((11222, 11278), 'subprocess.call', 'subprocess.call', (["['mkdir', '-p', '%s' % build_directory]"], {}), "(['mkdir', '-p', '%s' % build_directory])\n", (11237, 11278), False, 'import subprocess\n'), ((11285, 11298), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (11295, 11298), False, 'import time\n'), ((11328, 11383), 'tools.notice_print', 'tools.notice_print', (["('prepare log dir: ' + log_directory)"], {}), "('prepare log dir: ' + log_directory)\n", (11346, 11383), False, 'import tools\n'), ((11388, 11440), 'subprocess.call', 'subprocess.call', (["['rm', '-rf', '%s' % log_directory]"], {}), "(['rm', '-rf', '%s' % log_directory])\n", (11403, 11440), False, 'import subprocess\n'), ((11447, 11460), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (11457, 11460), False, 'import time\n'), ((11465, 11519), 'subprocess.call', 'subprocess.call', (["['mkdir', '-p', '%s' % log_directory]"], {}), "(['mkdir', '-p', '%s' % log_directory])\n", (11480, 11519), False, 'import subprocess\n'), ((11526, 11539), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (11536, 11539), False, 'import time\n'), ((13187, 13227), 'os.path.expanduser', 'os.path.expanduser', (['auth_key_destination'], {}), '(auth_key_destination)\n', (13205, 13227), False, 'import os\n'), ((13679, 13704), 'requests.get', 'requests.get', (['qr_code_url'], {}), '(qr_code_url)\n', (13691, 13704), False, 'import requests\n'), ((3271, 3298), 'os.listdir', 'os.listdir', (['build_directory'], {}), '(build_directory)\n', (3281, 3298), False, 'import os\n'), ((3408, 3461), 'subprocess.call', 'subprocess.call', (["('mkdir %s' % export_path)"], {'shell': '(True)'}), "('mkdir %s' % export_path, shell=True)\n", (3423, 3461), False, 'import subprocess\n'), ((3472, 3485), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (3482, 3485), False, 'import time\n'), ((3746, 3764), 'os.path.join', 'os.path.join', (['path'], {}), '(path)\n', (3758, 3764), False, 'import os\n'), ((3790, 3827), 'os.path.join', 'os.path.join', (['Config.xcworkspace_path'], {}), '(Config.xcworkspace_path)\n', (3802, 3827), False, 'import os\n'), ((4056, 4074), 'os.path.join', 'os.path.join', (['path'], {}), '(path)\n', (4068, 4074), False, 'import os\n'), ((4100, 4135), 'os.path.join', 'os.path.join', (['Config.xcodeproj_path'], {}), '(Config.xcodeproj_path)\n', (4112, 4135), False, 'import os\n'), ((4656, 4693), 'tools.fail_print', 'tools.fail_print', (["('没有找到%s文件' % target)"], {}), "('没有找到%s文件' % target)\n", (4672, 4693), False, 'import tools\n'), ((5132, 5154), 'json.load', 'json.load', (['config_file'], {}), '(config_file)\n', (5141, 5154), False, 'import json\n'), ((7717, 7782), 'tools.warn_print', 'tools.warn_print', (['"""project_scheme_list未配置,正在获取project的schemes..."""'], {}), "('project_scheme_list未配置,正在获取project的schemes...')\n", (7733, 7782), False, 'import tools\n'), ((8107, 8131), 'json.loads', 'json.loads', (['project_info'], {}), '(project_info)\n', (8117, 8131), False, 'import json\n'), ((10991, 11021), 'plistlib.dump', 'plistlib.dump', (['plist_value', 'fp'], {}), '(plist_value, fp)\n', (11004, 11021), False, 'import plistlib\n'), ((12612, 12835), 'tools.warn_print', 'tools.warn_print', (['"""使用apiKey/apiIssuer来上传App Store Connect时需要配置*.p8文件, 请先将*.p8文件复制到private_keys目录下, 具体详情可参考: https://developer.apple.com/documentation/appstoreconnectapi/creating_api_keys_for_app_store_connect_api"""'], {}), "(\n '使用apiKey/apiIssuer来上传App Store Connect时需要配置*.p8文件, 请先将*.p8文件复制到private_keys目录下, 具体详情可参考: https://developer.apple.com/documentation/appstoreconnectapi/creating_api_keys_for_app_store_connect_api'\n )\n", (12628, 12835), False, 'import tools\n'), ((12847, 12867), 'tools.end_program', 'tools.end_program', (['(2)'], {}), '(2)\n', (12864, 12867), False, 'import tools\n'), ((12897, 12924), 'os.listdir', 'os.listdir', (['system_home_dir'], {}), '(system_home_dir)\n', (12907, 12924), False, 'import os\n'), ((13053, 13123), 'subprocess.call', 'subprocess.call', (["('cd ~ && mkdir %s' % auth_key_destination)"], {'shell': '(True)'}), "('cd ~ && mkdir %s' % auth_key_destination, shell=True)\n", (13068, 13123), False, 'import subprocess\n'), ((13158, 13171), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (13168, 13171), False, 'import time\n'), ((13265, 13284), 'os.listdir', 'os.listdir', (['key_dir'], {}), '(key_dir)\n', (13275, 13284), False, 'import os\n'), ((13505, 13595), 'subprocess.call', 'subprocess.call', (["('cp -r %s %s' % (auth_key_copy_dir, auth_key_destination))"], {'shell': '(True)'}), "('cp -r %s %s' % (auth_key_copy_dir, auth_key_destination),\n shell=True)\n", (13520, 13595), False, 'import subprocess\n'), ((13624, 13637), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (13634, 13637), False, 'import time\n'), ((14912, 14957), 'json.dumps', 'json.dumps', (['log'], {'ensure_ascii': '(False)', 'indent': '(4)'}), '(log, ensure_ascii=False, indent=4)\n', (14922, 14957), False, 'import json\n'), ((281, 301), 'os.path.dirname', 'os.path.dirname', (['pwd'], {}), '(pwd)\n', (296, 301), False, 'import os\n'), ((7577, 7630), 'tools.fail_print', 'tools.fail_print', (['"""没有找到%s.xcodeproj文件, 请将脚本文件放到项目目录下"""'], {}), "('没有找到%s.xcodeproj文件, 请将脚本文件放到项目目录下')\n", (7593, 7630), False, 'import tools\n'), ((11727, 11866), 'tools.warn_print', 'tools.warn_print', (['"""上传App Store Connect需要 账号/密码 或者 apiKey/apiIssuer, upload_app_store_account_type值为 1 或者 2, 请在config.json中填写相关信息"""'], {}), "(\n '上传App Store Connect需要 账号/密码 或者 apiKey/apiIssuer, upload_app_store_account_type值为 1 或者 2, 请在config.json中填写相关信息'\n )\n", (11743, 11866), False, 'import tools\n'), ((11886, 11906), 'tools.end_program', 'tools.end_program', (['(2)'], {}), '(2)\n', (11903, 11906), False, 'import tools\n'), ((12295, 12434), 'tools.warn_print', 'tools.warn_print', (['"""上传App Store Connect需要 账号/密码 或者 apiKey/apiIssuer, upload_app_store_account_type值为 1 或者 2, 请在config.json中填写相关信息"""'], {}), "(\n '上传App Store Connect需要 账号/密码 或者 apiKey/apiIssuer, upload_app_store_account_type值为 1 或者 2, 请在config.json中填写相关信息'\n )\n", (12311, 12434), False, 'import tools\n'), ((12446, 12466), 'tools.end_program', 'tools.end_program', (['(2)'], {}), '(2)\n', (12463, 12466), False, 'import tools\n'), ((12573, 12602), 'os.listdir', 'os.listdir', (['auth_key_copy_dir'], {}), '(auth_key_copy_dir)\n', (12583, 12602), False, 'import os\n'), ((4429, 4450), 'os.path.join', 'os.path.join', (['root', 'd'], {}), '(root, d)\n', (4441, 4450), False, 'import os\n'), ((4565, 4586), 'os.path.join', 'os.path.join', (['root', 'f'], {}), '(root, f)\n', (4577, 4586), False, 'import os\n'), ((12066, 12205), 'tools.warn_print', 'tools.warn_print', (['"""上传App Store Connect需要 账号/密码 或者 apiKey/apiIssuer, upload_app_store_account_type值为 1 或者 2, 请在config.json中填写相关信息"""'], {}), "(\n '上传App Store Connect需要 账号/密码 或者 apiKey/apiIssuer, upload_app_store_account_type值为 1 或者 2, 请在config.json中填写相关信息'\n )\n", (12082, 12205), False, 'import tools\n'), ((12225, 12245), 'tools.end_program', 'tools.end_program', (['(2)'], {}), '(2)\n', (12242, 12245), False, 'import tools\n')] |
import pdfplumber
import re
import csv
from tqdm import tqdm
print('(When entering file paths on windows, use \'/\' in the place of \'\\\')')
pdf_path = input('Enter the file path of the 1099 pdf:\n')
# open up the pdf file, keep trying until user enters valid file
valid_pdf = False
while not valid_pdf:
try:
pdf = pdfplumber.open(pdf_path)
valid_pdf = True
except FileNotFoundError:
pdf_path = input('The file entered is not a valid file, please try again:\n')
# open up csv file, use default.csv if nothing is entered
csv_path = input('Enter the file path of the output csv:\n')
if csv_path == '':
print('Nothing was entered, using default file and location: ./default.csv')
csv_path = 'default.csv'
valid_csv = False
while not valid_csv:
try:
csv_file = open(csv_path, 'w', newline='')
csv_writer = csv.writer(csv_file, delimiter=',')
valid_csv = True
except FileNotFoundError:
csv_path = input('The file entered is not a valid file, please try again:\n')
# ask the user if they want to compile multiple transactions into one
# mainly for the 'xxx transactions for xx/xx/xx' lines
compile_multiple = input('Compile multiple transactions? (Y/n):\n').lower()
if compile_multiple == '':
print('Nothing was entered, using default \'n\'')
compile_multiple = 'n'
while not (compile_multiple == 'y' or compile_multiple == 'n'):
compile_multiple = input('Invalid input, try again. Enter \'Y\' or \'n\':\n').lower()
# regex for the symbol line
symbol_re = re.compile(r'.*\/ Symbol:\s*$')
# regex for date line
date_re = re.compile(r'^\d{2}\/\d{2}\/\d{2} .*')
# regex for transaction line
transaction_re = re.compile(r'^\d* transactions for \d{2}\/\d{2}\/\d{2}.*')
# regex for transaction child line
transaction_child_re = re.compile(r'^\d*\.\d* .*')
print('Transforming to csv...')
# write csv headers
csv_writer.writerow(['Security', 'Date sold or disposed', 'Quantity', 'Proceeds/Reported gross or net', 'Date acquired', 'Cost or other basis', 'Accrued mkt disc/Wash sale loss disallowed', 'Gain or loss', 'Additional Information'])
for page in tqdm(pdf.pages):
# extract each line from each page
text = page.extract_text()
lines = text.split('\n')
i = 0
while i < len(lines):
symbol_line = lines[i]
# attempt to match symbol line which signals start of a security block
if symbol_re.match(symbol_line):
# once we found symbol look at next lines to figure out what to do next
i += 1
date_line = lines[i]
while i < len(lines) and not symbol_re.match(date_line):
# if we are not compiling multiple transactions, we want to write out each one
if compile_multiple == 'n':
# attemp to match transaction line to see if this security has multiple transactions
if transaction_re.match(date_line):
# if it is, we pull out the number, and the date for all of them
num_transactions = int(date_line.split(' ')[0])
date_dis = date_line.split(' ')[3][:8]
trans_counter = 0
# next we iterate through to capture all the individual transactions
while trans_counter < num_transactions:
i += 1
date_line = lines[i]
if transaction_child_re.match(date_line):
split_date_line = date_line.split(' ')
accrued_disc = '...' if split_date_line[4] == '...' else ' '.join(split_date_line[4:6])
additional_info = ' '.join(split_date_line[6:]) if split_date_line[4] == '...' else ' '.join(split_date_line[7:])
csv_writer.writerow([symbol_line.split(' / ')[0]] + [date_dis] + split_date_line[:4] + [accrued_disc] + [additional_info])
trans_counter += 1
# after we are done, we skip to the next symbol line
while i < len(lines) and not symbol_re.match(date_line):
i += 1
if i < len(lines):
date_line = lines[i]
continue
# if we are not compiling multiple transactions, just write out the lines that
# match the dateline regex which includes compiled transactions
if date_re.match(date_line):
split_date_line = date_line.split(' ')
accrued_disc = '...' if split_date_line[5] == '...' else ' '.join(split_date_line[5:7])
additional_info = ' '.join(split_date_line[7:]) if split_date_line[5] == '...' else ' '.join(split_date_line[8:])
csv_writer.writerow([symbol_line.split(' / ')[0]] + split_date_line[:5] + [accrued_disc] +[additional_info] )
i+= 1
if i < len(lines):
date_line = lines[i]
i -= 1
i += 1
# close files
csv_file.close()
pdf.close() | [
"csv.writer",
"pdfplumber.open",
"tqdm.tqdm",
"re.compile"
] | [((1480, 1512), 're.compile', 're.compile', (['""".*\\\\/ Symbol:\\\\s*$"""'], {}), "('.*\\\\/ Symbol:\\\\s*$')\n", (1490, 1512), False, 'import re\n'), ((1544, 1586), 're.compile', 're.compile', (['"""^\\\\d{2}\\\\/\\\\d{2}\\\\/\\\\d{2} .*"""'], {}), "('^\\\\d{2}\\\\/\\\\d{2}\\\\/\\\\d{2} .*')\n", (1554, 1586), False, 'import re\n'), ((1629, 1692), 're.compile', 're.compile', (['"""^\\\\d* transactions for \\\\d{2}\\\\/\\\\d{2}\\\\/\\\\d{2}.*"""'], {}), "('^\\\\d* transactions for \\\\d{2}\\\\/\\\\d{2}\\\\/\\\\d{2}.*')\n", (1639, 1692), False, 'import re\n'), ((1746, 1775), 're.compile', 're.compile', (['"""^\\\\d*\\\\.\\\\d* .*"""'], {}), "('^\\\\d*\\\\.\\\\d* .*')\n", (1756, 1775), False, 'import re\n'), ((2074, 2089), 'tqdm.tqdm', 'tqdm', (['pdf.pages'], {}), '(pdf.pages)\n', (2078, 2089), False, 'from tqdm import tqdm\n'), ((321, 346), 'pdfplumber.open', 'pdfplumber.open', (['pdf_path'], {}), '(pdf_path)\n', (336, 346), False, 'import pdfplumber\n'), ((821, 856), 'csv.writer', 'csv.writer', (['csv_file'], {'delimiter': '""","""'}), "(csv_file, delimiter=',')\n", (831, 856), False, 'import csv\n')] |
import torch
import torch.nn as nn
import torch.nn.functional as F
def _make_residual(channels): # Nawid- Performs a 3x3 convolution followed by a 1x1 convolution - The 3x3 convolution is padded and so the overall shape is the same.
return nn.Sequential(
nn.ReLU(),
nn.Conv2d(channels, channels, 3, padding=1),
nn.ReLU(),
nn.Conv2d(channels, channels, 1),
)
class HalfEncoder(nn.Module):
"""
An encoder that cuts the input size in half in both
dimensions.
"""
def __init__(self, in_channels, out_channels):
super(HalfEncoder,self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels,3, stride=2, padding=1)
self.residual1 = _make_residual(out_channels)
self.residual2 = _make_residual(out_channels)
def forward(self,x):
x = self.conv(x)
x = x + self.residual1(x)
x = x + self.residual2(x)
return x
class HalfQuarterDecoder(nn.Module):
"""
A decoder that takes two inputs. The first one is
upsampled by a factor of two, and then combined with
the second input which is further upsampled by a
factor of four.
"""
def __init__(self,in_channels, out_channels):
super(HalfQuarterDecoder, self).__init__()
self.residual1 = _make_residual(in_channels)
self.residual2 = _make_residual(in_channels)
self.conv1 = nn.ConvTranspose2d(in_channels, in_channels, 4, stride=2, padding=1)
self.conv2 = nn.Conv2d(in_channels * 2, in_channels, 3, padding=1)
self.residual3 = _make_residual(in_channels)
self.residual4 = _make_residual(in_channels)
self.conv3 = nn.ConvTranspose2d(in_channels, in_channels, 4, stride=2, padding=1)
self.conv4 = nn.ConvTranspose2d(in_channels, out_channels, 4, stride=2, padding=1)
def forward(self,inputs):
assert len(inputs) == 2
# Upsample the top input to match the shape of the
# bottom input.
x = inputs[0]
x = x + self.residual1(x)
x = x + self.residual2(x)
x = F.relu(x)
x = self.conv1(x) # Nawid - This is a convolution transpose which make the top input match the shape of the bottom input
x = F.relu(x)
# Mix together the bottom and top inputs.
x = torch.cat([x, inputs[1]], dim=1) # Nawid - Concatentate the upsample top feature map with the bottom feature map
x = self.conv2(x) # Nawid - Downsamples
x = x + self.residual3(x)
x = x + self.residual4(x)
x = F.relu(x)
x = self.conv3(x) # Nawid - Upsamples
x = F.relu(x)
x = self.conv4(x) # Nawid - Upsamples
return x
class VQ_VAE_Decoder(nn.Module):
'''
Performs the encoder to get the second input and then performs the decoder with both of the different inputs
'''
def __init__(self,in_channels,intermediate_channels, out_channels):
super(VQ_VAE_Decoder, self).__init__()
self.conv = nn.Conv2d(in_channels, intermediate_channels,3, stride=1, padding=1)
self.residual1 = _make_residual(intermediate_channels)
self.encoder =HalfEncoder(intermediate_channels,intermediate_channels)
self.halfquarterdecoder = HalfQuarterDecoder(intermediate_channels, out_channels)
def forward(self,x):
half_quarter_inputs = []
x = x.view(-1, 4, 16, 16)
x = self.conv(x) # Nawid - This gives c x 16 x 16
#print('conv1',x.size())
x = self.residual1(x) # Nawid - This should give c x 16 x 16
#print('first residual',x.size())
half_x = self.encoder(x) # Nawid - This should give c x 8 x 8
#print('encoded shape',half_x.size())
half_quarter_inputs.append(half_x) # Nawid - half_x into the network
half_quarter_inputs.append(x) # Nawid - Places x into the inputs
reconstruction = self.halfquarterdecoder(half_quarter_inputs)
return reconstruction
| [
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.functional.relu",
"torch.nn.ConvTranspose2d",
"torch.cat"
] | [((268, 277), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (275, 277), True, 'import torch.nn as nn\n'), ((287, 330), 'torch.nn.Conv2d', 'nn.Conv2d', (['channels', 'channels', '(3)'], {'padding': '(1)'}), '(channels, channels, 3, padding=1)\n', (296, 330), True, 'import torch.nn as nn\n'), ((340, 349), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (347, 349), True, 'import torch.nn as nn\n'), ((359, 391), 'torch.nn.Conv2d', 'nn.Conv2d', (['channels', 'channels', '(1)'], {}), '(channels, channels, 1)\n', (368, 391), True, 'import torch.nn as nn\n'), ((632, 692), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'out_channels', '(3)'], {'stride': '(2)', 'padding': '(1)'}), '(in_channels, out_channels, 3, stride=2, padding=1)\n', (641, 692), True, 'import torch.nn as nn\n'), ((1402, 1470), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['in_channels', 'in_channels', '(4)'], {'stride': '(2)', 'padding': '(1)'}), '(in_channels, in_channels, 4, stride=2, padding=1)\n', (1420, 1470), True, 'import torch.nn as nn\n'), ((1492, 1545), 'torch.nn.Conv2d', 'nn.Conv2d', (['(in_channels * 2)', 'in_channels', '(3)'], {'padding': '(1)'}), '(in_channels * 2, in_channels, 3, padding=1)\n', (1501, 1545), True, 'import torch.nn as nn\n'), ((1673, 1741), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['in_channels', 'in_channels', '(4)'], {'stride': '(2)', 'padding': '(1)'}), '(in_channels, in_channels, 4, stride=2, padding=1)\n', (1691, 1741), True, 'import torch.nn as nn\n'), ((1763, 1832), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['in_channels', 'out_channels', '(4)'], {'stride': '(2)', 'padding': '(1)'}), '(in_channels, out_channels, 4, stride=2, padding=1)\n', (1781, 1832), True, 'import torch.nn as nn\n'), ((2081, 2090), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (2087, 2090), True, 'import torch.nn.functional as F\n'), ((2232, 2241), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (2238, 2241), True, 'import torch.nn.functional as F\n'), ((2305, 2337), 'torch.cat', 'torch.cat', (['[x, inputs[1]]'], {'dim': '(1)'}), '([x, inputs[1]], dim=1)\n', (2314, 2337), False, 'import torch\n'), ((2547, 2556), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (2553, 2556), True, 'import torch.nn.functional as F\n'), ((2615, 2624), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (2621, 2624), True, 'import torch.nn.functional as F\n'), ((2990, 3059), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'intermediate_channels', '(3)'], {'stride': '(1)', 'padding': '(1)'}), '(in_channels, intermediate_channels, 3, stride=1, padding=1)\n', (2999, 3059), True, 'import torch.nn as nn\n')] |
import os
import csv
import librosa
import numpy as np
import pandas as pd
from spider.featurization.audio_featurization import AudioFeaturization
# Read the test data csv
csv_file='data/testAudioData.csv'
df = pd.read_csv(csv_file)
# Read in the audio data specified by the csv
data = []
for idx, row in df.iterrows():
filename = os.path.join('data/raw_data', row['filename'])
datum, sampling_rate = librosa.load(filename)
data.append(datum)
# Optional audio featurization parameter specification
frame_length = 0.050
overlap = 0.025
# Request feature generation
print("Generating features...")
featurizer = AudioFeaturization(
sampling_rate=sampling_rate,
frame_length=frame_length,
overlap=overlap
)
features = featurizer.produce(data)
# Save features to disk
with open('features.csv', 'w+') as f:
for feature in features:
np.savetxt(f, feature) | [
"pandas.read_csv",
"os.path.join",
"numpy.savetxt",
"spider.featurization.audio_featurization.AudioFeaturization",
"librosa.load"
] | [((212, 233), 'pandas.read_csv', 'pd.read_csv', (['csv_file'], {}), '(csv_file)\n', (223, 233), True, 'import pandas as pd\n'), ((616, 711), 'spider.featurization.audio_featurization.AudioFeaturization', 'AudioFeaturization', ([], {'sampling_rate': 'sampling_rate', 'frame_length': 'frame_length', 'overlap': 'overlap'}), '(sampling_rate=sampling_rate, frame_length=frame_length,\n overlap=overlap)\n', (634, 711), False, 'from spider.featurization.audio_featurization import AudioFeaturization\n'), ((334, 380), 'os.path.join', 'os.path.join', (['"""data/raw_data"""', "row['filename']"], {}), "('data/raw_data', row['filename'])\n", (346, 380), False, 'import os\n'), ((405, 427), 'librosa.load', 'librosa.load', (['filename'], {}), '(filename)\n', (417, 427), False, 'import librosa\n'), ((841, 863), 'numpy.savetxt', 'np.savetxt', (['f', 'feature'], {}), '(f, feature)\n', (851, 863), True, 'import numpy as np\n')] |
import scipy.io as sio
import numpy as np
class MatWrapper(object):
def __init__(self,mat_file):
self.mat_fp = mat_file
self.data = None
class NeuroSurgMat(MatWrapper):
def __init__(self, mat_file):
self.mat_fp = mat_file
self.data = None
self._clfp = None
self._cmacro_lfp = None
self._metadata = None
@property
def CLFP(self):
# Lazy load CLFP files
if self.data is None:
self.data = sio.loadmat(self.mat_fp)
if self._clfp is None:
clfp = np.empty((3,self.data['CLFP_01'].shape[1]))
for i in np.arange(3):
clfp[i,:] = np.squeeze(self.data['CLFP_0'+str(i+1)])
self._clfp = clfp
return self._clfp
@property
def CMacro_LFP(self):
if self.data is None:
self.data = sio.loadmat(self.mat_fp)
if self._cmacro_lfp is None:
cmacro_lfp = np.empty((3,self.data['CMacro_LFP_01'].shape[1]))
for i in np.arange(3):
cmacro_lfp[i,:] = np.squeeze(self.data['CMacro_LFP_0'+str(i+1)])
self._cmacro_lfp = cmacro_lfp
return self._cmacro_lfp
@property
def metadata(self):
if self.data is None:
self.data = sio.loadmat(self.mat_fp)
if self._metadata is None:
self._metadata = {
'lfp':{'sampFreqHz':None,'timeStart':None,'timeEnd':None},
'mer':{'sampFreqHz':None,'timeStart':None,'timeEnd':None},
'eeg':{'sampFreqHz':None,'timeStart':None,'timeEnd':None},
}
for rec in list(self._metadata.keys()):
self._metadata[rec]['sampFreqHz']=self.data[rec][0][0][0][0][0]
self._metadata[rec]['timeStart']=np.squeeze(self.data[rec][0][0][1]).item()
self._metadata[rec]['timeEnd']=np.squeeze(self.data[rec][0][0][2]).item()
return self._metadata
class NeuroSurgDataset(object):
def __init__(self, data_dir):
self.data_dir = data_dir
# TODO Check if manifest file exists, if not create empty one
| [
"scipy.io.loadmat",
"numpy.empty",
"numpy.arange",
"numpy.squeeze"
] | [((492, 516), 'scipy.io.loadmat', 'sio.loadmat', (['self.mat_fp'], {}), '(self.mat_fp)\n', (503, 516), True, 'import scipy.io as sio\n'), ((567, 611), 'numpy.empty', 'np.empty', (["(3, self.data['CLFP_01'].shape[1])"], {}), "((3, self.data['CLFP_01'].shape[1]))\n", (575, 611), True, 'import numpy as np\n'), ((632, 644), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (641, 644), True, 'import numpy as np\n'), ((866, 890), 'scipy.io.loadmat', 'sio.loadmat', (['self.mat_fp'], {}), '(self.mat_fp)\n', (877, 890), True, 'import scipy.io as sio\n'), ((953, 1003), 'numpy.empty', 'np.empty', (["(3, self.data['CMacro_LFP_01'].shape[1])"], {}), "((3, self.data['CMacro_LFP_01'].shape[1]))\n", (961, 1003), True, 'import numpy as np\n'), ((1024, 1036), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (1033, 1036), True, 'import numpy as np\n'), ((1286, 1310), 'scipy.io.loadmat', 'sio.loadmat', (['self.mat_fp'], {}), '(self.mat_fp)\n', (1297, 1310), True, 'import scipy.io as sio\n'), ((1817, 1852), 'numpy.squeeze', 'np.squeeze', (['self.data[rec][0][0][1]'], {}), '(self.data[rec][0][0][1])\n', (1827, 1852), True, 'import numpy as np\n'), ((1907, 1942), 'numpy.squeeze', 'np.squeeze', (['self.data[rec][0][0][2]'], {}), '(self.data[rec][0][0][2])\n', (1917, 1942), True, 'import numpy as np\n')] |
# Copyright 2019,2020,2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import nnabla.initializer as I
import numpy as np
np.random.seed(1)
class ResidualStack(object):
def __init__(self, in_channels, num_hidden, num_res_layers, rng=313):
self.in_channels = in_channels
self.num_hidden = num_hidden
self.num_res_layers = num_res_layers
self.rng = rng
def __call__(self, x, test):
out = x
for i in range(self.num_res_layers):
out = self.res_block(out, scope_name='res_block_'+str(i))
return F.relu(out)
def res_block(self, x, scope_name='res_block', test=False):
with nn.parameter_scope(scope_name):
out = F.relu(x)
out = PF.convolution(out, self.num_hidden, (3, 3),
stride=(1, 1), pad=(1, 1), with_bias=False, name='conv_1', rng=self.rng)
out = PF.batch_normalization(out, name='bn_1', batch_stat=not test)
out = F.relu(out)
out = PF.convolution(out, self.num_hidden, (1, 1),
stride=(1, 1), with_bias=False, name='conv_2', rng=self.rng)
out = PF.batch_normalization(out, name='bn_2', batch_stat=not test)
return x + out
class VectorQuantizer(object):
def __init__(self, embedding_dim, num_embedding, commitment_cost, rng,
scope_name='vector_quantizer'):
self.embedding_dim = embedding_dim
self.num_embedding = num_embedding
self.commitment_cost = commitment_cost
self.rng = rng
self.scope_name = scope_name
with nn.parameter_scope(scope_name):
self.embedding_weight = nn.parameter.get_parameter_or_create('W', shape=(self.num_embedding, self.embedding_dim),
initializer=I.UniformInitializer((-1./self.num_embedding, 1./self.num_embedding), rng=self.rng), need_grad=True)
def __call__(self, x, return_encoding_indices=False):
x = F.transpose(x, (0, 2, 3, 1))
x_flat = x.reshape((-1, self.embedding_dim))
x_flat_squared = F.broadcast(
F.sum(x_flat**2, axis=1, keepdims=True), (x_flat.shape[0], self.num_embedding))
emb_wt_squared = F.transpose(
F.sum(self.embedding_weight**2, axis=1, keepdims=True), (1, 0))
distances = x_flat_squared + emb_wt_squared - 2 * \
F.affine(x_flat, F.transpose(self.embedding_weight, (1, 0)))
encoding_indices = F.min(
distances, only_index=True, axis=1, keepdims=True)
encoding_indices.need_grad = False
quantized = F.embed(encoding_indices.reshape(
encoding_indices.shape[:-1]), self.embedding_weight).reshape(x.shape)
if return_encoding_indices:
return encoding_indices, F.transpose(quantized, (0, 3, 1, 2))
encodings = F.one_hot(encoding_indices, (self.num_embedding,))
e_latent_loss = F.mean(F.squared_error(
quantized.get_unlinked_variable(need_grad=False), x))
q_latent_loss = F.mean(F.squared_error(
quantized, x.get_unlinked_variable(need_grad=False)))
loss = q_latent_loss + self.commitment_cost*e_latent_loss
quantized = x + (quantized - x).get_unlinked_variable(need_grad=False)
avg_probs = F.mean(encodings, axis=0)
perplexity = F.exp(-F.sum(avg_probs*F.log(avg_probs+1.0e-10)))
return loss, F.transpose(quantized, (0, 3, 1, 2)), perplexity, encodings
class VQVAE(object):
def __init__(self, config, training=True):
self.in_channels = config['model']['in_channels']
self.num_hidden = config['model']['num_hidden']
self.num_res_layers = config['model']['num_res_layers']
self.rng = np.random.RandomState(config['model']['rng'])
self.encoder_res_stack = ResidualStack(in_channels=self.num_hidden,
num_hidden=self.num_hidden, num_res_layers=self.num_res_layers,
rng=self.rng)
self.decoder_res_stack = ResidualStack(in_channels=self.num_hidden,
num_hidden=self.num_hidden, num_res_layers=self.num_res_layers,
rng=self.rng)
self.num_embedding = config['model']['num_embeddings']
self.embedding_dim = config['model']['embedding_dim']
self.commitment_cost = config['model']['commitment_cost']
self.decay = config['model']['decay']
self.training = training
self.vq = VectorQuantizer(
self.embedding_dim, self.num_embedding, self.commitment_cost, self.rng)
def encoder(self, x, test):
with nn.parameter_scope('encoder'):
out = PF.convolution(x, self.num_hidden, (4, 4), stride=(2, 2),
pad=(1, 1), name='conv_1', rng=self.rng)
out = PF.batch_normalization(out, batch_stat=not test)
out = F.relu(out)
out = PF.convolution(out, self.num_hidden, (4, 4), stride=(2, 2),
pad=(1, 1), name='conv_2', rng=self.rng)
out = self.encoder_res_stack(out, test=test)
return out
def decoder(self, x, test):
with nn.parameter_scope('decoder'):
out = self.decoder_res_stack(x, test=test)
out = F.relu(out)
out = PF.deconvolution(out, self.num_hidden, (4, 4), stride=(2, 2),
pad=(1, 1), name='deconv_1', rng=self.rng)
out = PF.batch_normalization(out, batch_stat=not test)
out = F.relu(out)
out = PF.deconvolution(out, self.in_channels, (4, 4), stride=(2, 2),
pad=(1, 1), name='deconv_2', rng=self.rng)
out = F.tanh(out)
return out
def __call__(self, img, return_encoding_indices=False, quantized_as_input=False, test=False):
with nn.parameter_scope('vq_vae'):
# import pdb; pdb.set_trace()
if quantized_as_input:
return self.decoder(img, test)
z = self.encoder(img, test)
z = PF.convolution(z, self.embedding_dim, (1, 1), stride=(1, 1))
if return_encoding_indices:
return self.vq(z, return_encoding_indices=True)
loss, quantized, perplexity, encodings = self.vq(z)
img_recon = self.decoder(quantized, test)
return loss, img_recon, perplexity
| [
"nnabla.functions.transpose",
"nnabla.functions.one_hot",
"nnabla.parametric_functions.convolution",
"nnabla.functions.log",
"nnabla.parametric_functions.deconvolution",
"nnabla.parametric_functions.batch_normalization",
"nnabla.parameter_scope",
"nnabla.functions.sum",
"numpy.random.seed",
"nnabl... | [((774, 791), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (788, 791), True, 'import numpy as np\n'), ((1222, 1233), 'nnabla.functions.relu', 'F.relu', (['out'], {}), '(out)\n', (1228, 1233), True, 'import nnabla.functions as F\n'), ((2692, 2720), 'nnabla.functions.transpose', 'F.transpose', (['x', '(0, 2, 3, 1)'], {}), '(x, (0, 2, 3, 1))\n', (2703, 2720), True, 'import nnabla.functions as F\n'), ((3189, 3245), 'nnabla.functions.min', 'F.min', (['distances'], {'only_index': '(True)', 'axis': '(1)', 'keepdims': '(True)'}), '(distances, only_index=True, axis=1, keepdims=True)\n', (3194, 3245), True, 'import nnabla.functions as F\n'), ((3575, 3625), 'nnabla.functions.one_hot', 'F.one_hot', (['encoding_indices', '(self.num_embedding,)'], {}), '(encoding_indices, (self.num_embedding,))\n', (3584, 3625), True, 'import nnabla.functions as F\n'), ((4030, 4055), 'nnabla.functions.mean', 'F.mean', (['encodings'], {'axis': '(0)'}), '(encodings, axis=0)\n', (4036, 4055), True, 'import nnabla.functions as F\n'), ((4477, 4522), 'numpy.random.RandomState', 'np.random.RandomState', (["config['model']['rng']"], {}), "(config['model']['rng'])\n", (4498, 4522), True, 'import numpy as np\n'), ((1312, 1342), 'nnabla.parameter_scope', 'nn.parameter_scope', (['scope_name'], {}), '(scope_name)\n', (1330, 1342), True, 'import nnabla as nn\n'), ((1362, 1371), 'nnabla.functions.relu', 'F.relu', (['x'], {}), '(x)\n', (1368, 1371), True, 'import nnabla.functions as F\n'), ((1390, 1511), 'nnabla.parametric_functions.convolution', 'PF.convolution', (['out', 'self.num_hidden', '(3, 3)'], {'stride': '(1, 1)', 'pad': '(1, 1)', 'with_bias': '(False)', 'name': '"""conv_1"""', 'rng': 'self.rng'}), "(out, self.num_hidden, (3, 3), stride=(1, 1), pad=(1, 1),\n with_bias=False, name='conv_1', rng=self.rng)\n", (1404, 1511), True, 'import nnabla.parametric_functions as PF\n'), ((1559, 1620), 'nnabla.parametric_functions.batch_normalization', 'PF.batch_normalization', (['out'], {'name': '"""bn_1"""', 'batch_stat': '(not test)'}), "(out, name='bn_1', batch_stat=not test)\n", (1581, 1620), True, 'import nnabla.parametric_functions as PF\n'), ((1639, 1650), 'nnabla.functions.relu', 'F.relu', (['out'], {}), '(out)\n', (1645, 1650), True, 'import nnabla.functions as F\n'), ((1669, 1778), 'nnabla.parametric_functions.convolution', 'PF.convolution', (['out', 'self.num_hidden', '(1, 1)'], {'stride': '(1, 1)', 'with_bias': '(False)', 'name': '"""conv_2"""', 'rng': 'self.rng'}), "(out, self.num_hidden, (1, 1), stride=(1, 1), with_bias=False,\n name='conv_2', rng=self.rng)\n", (1683, 1778), True, 'import nnabla.parametric_functions as PF\n'), ((1826, 1887), 'nnabla.parametric_functions.batch_normalization', 'PF.batch_normalization', (['out'], {'name': '"""bn_2"""', 'batch_stat': '(not test)'}), "(out, name='bn_2', batch_stat=not test)\n", (1848, 1887), True, 'import nnabla.parametric_functions as PF\n'), ((2276, 2306), 'nnabla.parameter_scope', 'nn.parameter_scope', (['scope_name'], {}), '(scope_name)\n', (2294, 2306), True, 'import nnabla as nn\n'), ((2829, 2870), 'nnabla.functions.sum', 'F.sum', (['(x_flat ** 2)'], {'axis': '(1)', 'keepdims': '(True)'}), '(x_flat ** 2, axis=1, keepdims=True)\n', (2834, 2870), True, 'import nnabla.functions as F\n'), ((2963, 3019), 'nnabla.functions.sum', 'F.sum', (['(self.embedding_weight ** 2)'], {'axis': '(1)', 'keepdims': '(True)'}), '(self.embedding_weight ** 2, axis=1, keepdims=True)\n', (2968, 3019), True, 'import nnabla.functions as F\n'), ((4149, 4185), 'nnabla.functions.transpose', 'F.transpose', (['quantized', '(0, 3, 1, 2)'], {}), '(quantized, (0, 3, 1, 2))\n', (4160, 4185), True, 'import nnabla.functions as F\n'), ((5458, 5487), 'nnabla.parameter_scope', 'nn.parameter_scope', (['"""encoder"""'], {}), "('encoder')\n", (5476, 5487), True, 'import nnabla as nn\n'), ((5507, 5610), 'nnabla.parametric_functions.convolution', 'PF.convolution', (['x', 'self.num_hidden', '(4, 4)'], {'stride': '(2, 2)', 'pad': '(1, 1)', 'name': '"""conv_1"""', 'rng': 'self.rng'}), "(x, self.num_hidden, (4, 4), stride=(2, 2), pad=(1, 1), name=\n 'conv_1', rng=self.rng)\n", (5521, 5610), True, 'import nnabla.parametric_functions as PF\n'), ((5657, 5705), 'nnabla.parametric_functions.batch_normalization', 'PF.batch_normalization', (['out'], {'batch_stat': '(not test)'}), '(out, batch_stat=not test)\n', (5679, 5705), True, 'import nnabla.parametric_functions as PF\n'), ((5724, 5735), 'nnabla.functions.relu', 'F.relu', (['out'], {}), '(out)\n', (5730, 5735), True, 'import nnabla.functions as F\n'), ((5754, 5858), 'nnabla.parametric_functions.convolution', 'PF.convolution', (['out', 'self.num_hidden', '(4, 4)'], {'stride': '(2, 2)', 'pad': '(1, 1)', 'name': '"""conv_2"""', 'rng': 'self.rng'}), "(out, self.num_hidden, (4, 4), stride=(2, 2), pad=(1, 1),\n name='conv_2', rng=self.rng)\n", (5768, 5858), True, 'import nnabla.parametric_functions as PF\n'), ((6011, 6040), 'nnabla.parameter_scope', 'nn.parameter_scope', (['"""decoder"""'], {}), "('decoder')\n", (6029, 6040), True, 'import nnabla as nn\n'), ((6115, 6126), 'nnabla.functions.relu', 'F.relu', (['out'], {}), '(out)\n', (6121, 6126), True, 'import nnabla.functions as F\n'), ((6145, 6253), 'nnabla.parametric_functions.deconvolution', 'PF.deconvolution', (['out', 'self.num_hidden', '(4, 4)'], {'stride': '(2, 2)', 'pad': '(1, 1)', 'name': '"""deconv_1"""', 'rng': 'self.rng'}), "(out, self.num_hidden, (4, 4), stride=(2, 2), pad=(1, 1),\n name='deconv_1', rng=self.rng)\n", (6161, 6253), True, 'import nnabla.parametric_functions as PF\n'), ((6303, 6351), 'nnabla.parametric_functions.batch_normalization', 'PF.batch_normalization', (['out'], {'batch_stat': '(not test)'}), '(out, batch_stat=not test)\n', (6325, 6351), True, 'import nnabla.parametric_functions as PF\n'), ((6370, 6381), 'nnabla.functions.relu', 'F.relu', (['out'], {}), '(out)\n', (6376, 6381), True, 'import nnabla.functions as F\n'), ((6400, 6509), 'nnabla.parametric_functions.deconvolution', 'PF.deconvolution', (['out', 'self.in_channels', '(4, 4)'], {'stride': '(2, 2)', 'pad': '(1, 1)', 'name': '"""deconv_2"""', 'rng': 'self.rng'}), "(out, self.in_channels, (4, 4), stride=(2, 2), pad=(1, 1),\n name='deconv_2', rng=self.rng)\n", (6416, 6509), True, 'import nnabla.parametric_functions as PF\n'), ((6559, 6570), 'nnabla.functions.tanh', 'F.tanh', (['out'], {}), '(out)\n', (6565, 6570), True, 'import nnabla.functions as F\n'), ((6704, 6732), 'nnabla.parameter_scope', 'nn.parameter_scope', (['"""vq_vae"""'], {}), "('vq_vae')\n", (6722, 6732), True, 'import nnabla as nn\n'), ((6914, 6974), 'nnabla.parametric_functions.convolution', 'PF.convolution', (['z', 'self.embedding_dim', '(1, 1)'], {'stride': '(1, 1)'}), '(z, self.embedding_dim, (1, 1), stride=(1, 1))\n', (6928, 6974), True, 'import nnabla.parametric_functions as PF\n'), ((3517, 3553), 'nnabla.functions.transpose', 'F.transpose', (['quantized', '(0, 3, 1, 2)'], {}), '(quantized, (0, 3, 1, 2))\n', (3528, 3553), True, 'import nnabla.functions as F\n'), ((2519, 2612), 'nnabla.initializer.UniformInitializer', 'I.UniformInitializer', (['(-1.0 / self.num_embedding, 1.0 / self.num_embedding)'], {'rng': 'self.rng'}), '((-1.0 / self.num_embedding, 1.0 / self.num_embedding),\n rng=self.rng)\n', (2539, 2612), True, 'import nnabla.initializer as I\n'), ((3117, 3159), 'nnabla.functions.transpose', 'F.transpose', (['self.embedding_weight', '(1, 0)'], {}), '(self.embedding_weight, (1, 0))\n', (3128, 3159), True, 'import nnabla.functions as F\n'), ((4100, 4124), 'nnabla.functions.log', 'F.log', (['(avg_probs + 1e-10)'], {}), '(avg_probs + 1e-10)\n', (4105, 4124), True, 'import nnabla.functions as F\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project : StreamlitApp.
# @File : utils
# @Time : 2020/11/3 12:17 下午
# @Author : yuanjie
# @Email : <EMAIL>
# @Software : PyCharm
# @Description : https://share.streamlit.io/daniellewisdl/streamlit-cheat-sheet/app.py
import pandas as pd
import streamlit as st
from io import StringIO
def sidebar(st):
st.sidebar.radio('R:', [1, 2])
def file_uploader(st):
uploaded_file = st.file_uploader(
'File uploader') # <streamlit.uploaded_file_manager.UploadedFile object at 0x1779c5938>
if uploaded_file is not None:
bytes_data = uploaded_file.read()
with open("uploaded_file", "wb") as f:
f.write(bytes_data)
return "uploaded_file"
# bytes_data = uploaded_file.read()
# st.write(bytes_data)
# # To convert to a string based IO:
# stringio = StringIO(uploaded_file.decode("utf-8"))
# st.write(stringio)
# # To read file as string:
# string_data = stringio.read()
# st.write(string_data)
# # Can be used wherever a "file-like" object is accepted:
# dataframe = pd.read_csv(uploaded_file)
# st.write(dataframe)
def image_display(st, header2image=[('header', 'image')], **kwargs):
image_num = len(header2image)
cols = st.beta_columns(image_num)
for col, (header, image) in zip(cols, header2image):
with col:
# st.header
st.subheader(header)
st.image(image, **kwargs)
| [
"streamlit.image",
"streamlit.beta_columns",
"streamlit.file_uploader",
"streamlit.subheader",
"streamlit.sidebar.radio"
] | [((396, 426), 'streamlit.sidebar.radio', 'st.sidebar.radio', (['"""R:"""', '[1, 2]'], {}), "('R:', [1, 2])\n", (412, 426), True, 'import streamlit as st\n'), ((472, 505), 'streamlit.file_uploader', 'st.file_uploader', (['"""File uploader"""'], {}), "('File uploader')\n", (488, 505), True, 'import streamlit as st\n'), ((1360, 1386), 'streamlit.beta_columns', 'st.beta_columns', (['image_num'], {}), '(image_num)\n', (1375, 1386), True, 'import streamlit as st\n'), ((1498, 1518), 'streamlit.subheader', 'st.subheader', (['header'], {}), '(header)\n', (1510, 1518), True, 'import streamlit as st\n'), ((1531, 1556), 'streamlit.image', 'st.image', (['image'], {}), '(image, **kwargs)\n', (1539, 1556), True, 'import streamlit as st\n')] |
import multiprocessing
from time import sleep
from datetime import datetime, time
from logging import INFO
from vnpy.event import EventEngine
from vnpy.trader.setting import SETTINGS
from vnpy.trader.engine import MainEngine
from vnpy.gateway.hbdm import HbdmGateway
from vnpy.gateway.hbsdm import HbsdmGateway
from vnpy.app.cta_strategy import CtaStrategyApp
from vnpy.app.cta_strategy.base import EVENT_CTA_LOG
from vnpy.trader.constant import (
Direction,
Offset,
Exchange,
Product,
Status,
OrderType,
Interval
)
from vnpy.trader.object import (
OrderRequest,
)
SETTINGS["log.active"] = True
SETTINGS["log.level"] = INFO
SETTINGS["log.console"] = True
ctp_setting = {
"用户名": "",
"密码": "",
"经纪商代码": "",
"交易服务器": "",
"行情服务器": "",
"产品名称": "",
"授权编码": "",
"产品信息": ""
}
hb_setting = {
"API Key": "",
"Secret Key": "",
"会话数": 3,
"代理地址": "",
"代理端口": ""
}
def main():
SETTINGS["log.file"] = True
event_engine = EventEngine()
main_engine = MainEngine(event_engine)
hbdm = main_engine.add_gateway(HbdmGateway)
hbsdm = main_engine.add_gateway(HbsdmGateway)
cta_engine = main_engine.add_app(CtaStrategyApp)
main_engine.write_log("主引擎创建成功")
log_engine = main_engine.get_engine("log")
event_engine.register(EVENT_CTA_LOG, log_engine.process_log_event)
main_engine.write_log("注册日志事件监听")
main_engine.connect(hb_setting, "HBDM")
main_engine.connect(hb_setting, "HBSDM")
main_engine.write_log("连接CTP接口")
sleep(10)
cta_engine.init_engine()
main_engine.write_log("CTA策略初始化完成")
cta_engine.init_all_strategies()
sleep(60) # Leave enough time to complete strategy initialization
main_engine.write_log("CTA策略全部初始化")
cta_engine.start_all_strategies()
main_engine.write_log("CTA策略全部启动")
if __name__ == "__main__":
main()
| [
"vnpy.trader.engine.MainEngine",
"vnpy.event.EventEngine",
"time.sleep"
] | [((1036, 1049), 'vnpy.event.EventEngine', 'EventEngine', ([], {}), '()\n', (1047, 1049), False, 'from vnpy.event import EventEngine\n'), ((1068, 1092), 'vnpy.trader.engine.MainEngine', 'MainEngine', (['event_engine'], {}), '(event_engine)\n', (1078, 1092), False, 'from vnpy.trader.engine import MainEngine\n'), ((1570, 1579), 'time.sleep', 'sleep', (['(10)'], {}), '(10)\n', (1575, 1579), False, 'from time import sleep\n'), ((1692, 1701), 'time.sleep', 'sleep', (['(60)'], {}), '(60)\n', (1697, 1701), False, 'from time import sleep\n')] |
# Copyright 2016, IBM US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django.utils.decorators import method_decorator # noqa
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_post_parameters # noqa
from horizon import exceptions
from horizon import forms
from horizon import messages
from horizon import tables
from horizon import tabs
from horizon.utils import memoized
import logging
from operational_mgmt import resource
from operational_mgmt.inventory import forms as project_forms
from operational_mgmt.inventory import tables as project_tables
from operational_mgmt.inventory import tabs as inventoryRacks_tabs
import opsmgr.inventory.rack_mgr as rack_mgr
import opsmgr.inventory.resource_mgr as resource_mgr
class IndexView(tabs.TabbedTableView):
tab_group_class = inventoryRacks_tabs.InventoryRacksTabs
table_class = project_tables.ResourcesTable
template_name = 'op_mgmt/inventory/index.html'
page_title = _("Inventory")
class DetailView(tabs.TabView):
tab_group_class = inventoryRacks_tabs.ResourceDetailTabs
template_name = 'horizon/common/_detail.html'
page_title = "{{ resource.name|default:resource.id }}"
def get_context_data(self, **kwargs):
context = super(DetailView, self).get_context_data(**kwargs)
resource = self.get_data()
table = project_tables.ResourcesTable(self.request)
context["resource"] = resource
context["url"] = self.get_redirect_url()
context["actions"] = table.render_row_actions(resource)
return context
@memoized.memoized_method
def get_data(self):
try:
__method__ = 'views.DetailView.get_data'
failure_message = str("Unable to retrieve detailed data for the resource")
if "resource_id" in self.kwargs:
try:
(rc, result_dict) = resource_mgr.list_resources(
None, False, None, [self.kwargs['resource_id']])
except Exception as e:
logging.error("%s: Exception received trying to retrieve"
" resource information. Exception is: %s",
__method__, e)
exceptions.handle(self.request, failure_message)
return
else:
# This is unexpected. Resource details called with no context
# of what to display. Need to display an error message because the
# view will not be primed with required data
logging.error("%s: DetailView called with no resource id"
" context.", __method__)
messages.error(self.request, failure_message)
return
if rc != 0:
messages.error(self.request, failure_message)
return
else:
# We should have at least one resource in the results...just
# return the first value
if len(result_dict['resources']) > 0:
return resource.Resource(result_dict['resources'][0])
else:
logging.error("%s: list_resources returned no information for"
" resource with resource id %s",
__method__, self.kwargs["resource_id"])
messages.error(self.request, failure_message)
return
except Exception:
redirect = self.get_redirect_url()
exceptions.handle(self.request,
_('Unable to retrieve resource details.'),
redirect=redirect)
def get_redirect_url(self):
return reverse('horizon:op_mgmt:inventory:index')
def get_tabs(self, request, *args, **kwargs):
resource = self.get_data()
return self.tab_group_class(request, resource=resource, **kwargs)
class AddResourceView(forms.ModalFormView):
template_name = 'op_mgmt/inventory/addResource.html'
modal_header = _("Add Resource")
form_id = "add_resource_form"
form_class = project_forms.AddResourceForm
submit_label = _("Add Resource")
submit_url = "horizon:op_mgmt:inventory:addResource"
success_url = reverse_lazy('horizon:op_mgmt:inventory:index')
page_title = _("Add Resource")
def get_initial(self):
# Need the rack for the active tab
rack = self.get_object()
# Prime the rack information on our AddResourceForm
if rack:
return {'rackid': rack['rackid'],
'rack_label': rack['label']}
else:
return
@memoized.memoized_method
def get_object(self):
__method__ = 'views.AddResourceView.get_object'
failure_message = str("Unable to retrieve rack information " +
" for the resource being added.")
if "rack_id" in self.kwargs:
try:
(rc, result_dict) = rack_mgr.list_racks(
None, False, [self.kwargs["rack_id"]])
except Exception as e:
logging.error("%s: Exception received trying to retrieve rack"
" information. Exception is: %s",
__method__, e)
exceptions.handle(self.request, failure_message)
return
else:
# This is unexpected. AddResourceView called with no context of
# what rack the resource is being added. Need to display an error
# message because the dialog will not be primed with required data
logging.error("%s: AddResourceView called with no rack id"
" context.", __method__)
messages.error(self.request, failure_message)
return
if rc != 0:
messages.error(self.request, failure_message)
return
else:
# We should have at least one rack in the results...just return
# the first value
if len(result_dict['racks']) > 0:
return result_dict['racks'][0]
else:
logging.error("%s: list_rack returned no information for"
" rack with rack id %s",
__method__, self.kwargs["rack_id"])
messages.error(self.request, failure_message)
return
def get_context_data(self, **kwargs):
# place the rack id onto the submit url
context = super(AddResourceView, self).get_context_data(**kwargs)
args = (self.get_object()['rackid'],)
context['submit_url'] = reverse(self.submit_url, args=args)
return context
class EditResourceView(forms.ModalFormView):
template_name = 'op_mgmt/inventory/editResource.html'
modal_header = _("Edit Resource")
form_id = "edit_resource_form"
form_class = project_forms.EditResourceForm
submit_label = _("Edit Resource")
submit_url = "horizon:op_mgmt:inventory:editResource"
success_url = reverse_lazy('horizon:op_mgmt:inventory:index')
page_title = _("Edit Resource")
def get_initial(self):
# Need the resource being edited
selected_resource = self.get_object()
if selected_resource:
return {'label': selected_resource['label'],
'auth_method': selected_resource['auth_method'],
'rackid': selected_resource['rackid'],
'eiaLocation': selected_resource['rack-eia-location'],
'ip_address': selected_resource['ip-address'],
'userID': selected_resource['userid'],
'resourceId': selected_resource['resourceid']}
else:
return
@memoized.memoized_method
def get_object(self):
__method__ = 'views.EditResourceView.get_object'
failure_message = str("Unable to retrieve resource information" +
" for the resource being edited.")
if "resource_id" in self.kwargs:
try:
(rc, result_dict) = resource_mgr.list_resources(
None, False, None, [self.kwargs['resource_id']])
except Exception as e:
logging.error("%s: Exception received trying to retrieve"
" resource information. Exception is: %s",
__method__, e)
exceptions.handle(self.request, failure_message)
return
else:
# This is unexpected. EditResourceView called with no context
# of what to edit. Need to display an error message because the
# dialog will not be primed with required data
logging.error("%s: EditResourceView called with no resource id"
" context.", __method__)
messages.error(self.request, failure_message)
return
if rc != 0:
messages.error(self.request, failure_message)
return
else:
# We should have at least one resource in the results...just
# return the first value
if len(result_dict['resources']) > 0:
return result_dict['resources'][0]
else:
logging.error("%s: list_resources returned no information for"
" resource with resource id %s",
__method__, self.kwargs["resource_id"])
messages.error(self.request, failure_message)
return
def get_context_data(self, **kwargs):
# place the resource id on to the submit url
context = super(EditResourceView, self).get_context_data(**kwargs)
args = (self.get_object()['resourceid'],)
context['submit_url'] = reverse(self.submit_url, args=args)
return context
class ChangePasswordView(forms.ModalFormView):
template_name = 'op_mgmt/inventory/changePassword.html'
modal_header = _("Change Password")
form_id = "change_password_form"
form_class = project_forms.ChangePasswordForm
submit_label = _("Change Password")
submit_url = "horizon:op_mgmt:inventory:changePassword"
success_url = reverse_lazy('horizon:op_mgmt:inventory:index')
page_title = _("Change Password")
@method_decorator(sensitive_post_parameters('password',
'confirm_password'))
def dispatch(self, *args, **kwargs):
return super(ChangePasswordView, self).dispatch(*args, **kwargs)
def get_initial(self):
# Need the resource and user information to prime the dialog
selected_resource = self.get_object()
if selected_resource:
return {'label': selected_resource['label'],
'userID': selected_resource['userid'],
'resourceid': selected_resource['resourceid']}
else:
return
@memoized.memoized_method
def get_object(self):
__method__ = 'views.ChangePasswordView.get_object'
failure_message = str("Unable to retrieve resource information for" +
" the resource having password changed.")
if "resource_id" in self.kwargs:
try:
(rc, result_dict) = resource_mgr.list_resources(
None, False, None, [self.kwargs['resource_id']])
except Exception as e:
logging.error("%s: Exception received trying to retrieve"
" resource information. Exception is: %s",
__method__, e)
exceptions.handle(self.request, failure_message)
return
else:
# This is unexpected. ChangePasswordView called with no context
# of what to edit. Need to display an error message because the
# dialog will not be primed with required data
logging.error("%s: ChangePasswordView called with no context.",
__method__)
messages.error(self.request, failure_message)
return
if rc != 0:
messages.error(self.request, failure_message)
return
else:
# We should have at least one resource in the results...just
# return the first value
if len(result_dict['resources']) > 0:
return result_dict['resources'][0]
else:
logging.error("%s: list_resources returned no information for"
" resource with resource id %s",
__method__, self.kwargs["resource_id"])
messages.error(self.request, failure_message)
return
def get_context_data(self, **kwargs):
# place the resource id on the submit url
context = super(ChangePasswordView, self).get_context_data(**kwargs)
args = (self.get_object()['resourceid'],)
context['submit_url'] = reverse(self.submit_url, args=args)
return context
class EditRackView(forms.ModalFormView):
template_name = 'op_mgmt/inventory/editRack.html'
modal_header = _("Edit Rack Details")
form_id = "edit_rack"
form_class = project_forms.EditRackForm
submit_label = _("Edit Rack")
submit_url = "horizon:op_mgmt:inventory:editRack"
success_url = reverse_lazy("horizon:op_mgmt:inventory:index")
def get_initial(self):
# Need the rack being edited
rack = self.get_object()
if rack:
return {'rack_id': rack['rackid'],
'label': rack['label'],
'data_center': rack['data-center'],
'room': rack['room'],
'row': rack['row'],
'notes': rack['notes']}
else:
return
@memoized.memoized_method
def get_object(self):
__method__ = 'views.EditRackView.get_object'
failure_message = str("Unable to retrieve rack information" +
" for the rack being edited.")
if "rack_id" in self.kwargs:
try:
(rc, result_dict) = rack_mgr.list_racks(
None, False, [self.kwargs["rack_id"]])
except Exception as e:
logging.error("%s: Exception received trying to retrieve"
" rack information. Exception is: %s",
__method__, e)
exceptions.handle(self.request, failure_message)
return
else:
# This is unexpected. EditRackView called with no context
# of what to edit. Need to display an error message because
# the dialog will not be primed with required data
logging.error("%s: EditRackView called with no context.",
__method__)
messages.error(self.request, failure_message)
return
if rc != 0:
messages.error(self.request, failure_message)
return
else:
# We should have at least one resource in the results...just
# return the first value
if len(result_dict['racks']) > 0:
return result_dict['racks'][0]
else:
logging.error("%s: list_racks returned no information for"
" rack with rack id %s",
__method__, self.kwargs["rack_id"])
messages.error(self.request, failure_message)
return
def get_context_data(self, **kwargs):
# place the rack id on to the submit url
context = super(EditRackView, self).get_context_data(**kwargs)
args = (self.get_object()['rackid'],)
context['submit_url'] = reverse(self.submit_url, args=args)
return context
class RemoveRackView(forms.ModalFormView):
template_name = 'op_mgmt/inventory/removeRack.html'
modal_header = _("Confirm Remove Rack")
form_id = "remove_rack_form"
form_class = project_forms.RemoveRackForm
submit_label = _("Remove Rack")
submit_url = "horizon:op_mgmt:inventory:removeRack"
success_url = reverse_lazy("horizon:op_mgmt:inventory:index")
page_title = _("Confirm Remove Rack")
def get_initial(self):
# Need the rack being edited
rack = self.get_object()
if rack:
return {'rack_id': rack['rackid'],
'label': rack['label']}
else:
return
@memoized.memoized_method
def get_object(self):
__method__ = 'views.RemoveRackView.get_object'
failure_message = str("Unable to retrieve rack information" +
" for the rack being removed.")
if "rack_id" in self.kwargs:
try:
(rc, result_dict) = rack_mgr.list_racks(
None, False, [self.kwargs["rack_id"]])
except Exception as e:
logging.error("%s: Exception received trying to retrieve"
" rack information. Exception is: %s",
__method__, e)
exceptions.handle(self.request, failure_message)
return
else:
# This is unexpected. RemoveRackView called with no context
# of what to edit. Need to display an error message because
# the dialog will not be primed with required data
logging.error("%s: RemoveRackView called with no context.",
__method__)
messages.error(self.request, failure_message)
return
if rc != 0:
messages.error(self.request, failure_message)
return
else:
# We should have at least one resource in the results...just
# return the first value
if len(result_dict['racks']) > 0:
return result_dict['racks'][0]
else:
logging.error("%s: list_racks returned no information for"
" rack with rack id %s",
__method__, self.kwargs["rack_id"])
messages.error(self.request, failure_message)
return
def get_context_data(self, **kwargs):
# place the rack id on to the submit url
context = super(RemoveRackView, self).get_context_data(**kwargs)
args = (self.get_object()['rackid'],)
context['submit_url'] = reverse(self.submit_url, args=args)
return context
class RemoveResourcesView(tables.DataTableView, forms.ModalFormView):
table_class = project_tables.RemoveResourcesTable
modal_header = _("Remove Resources")
modal_id = "remove_resources_modal"
template_name = 'op_mgmt/inventory/removeResources.html'
submit_url = reverse_lazy('horizon:op_mgmt:inventory:index')
submit_label = _("Close")
page_title = _("Remove Resources")
@memoized.memoized_method
def get_object(self):
__method__ = 'views.RemoveResourcesView.get_object'
failure_message = str("Unable to retrieve rack information" +
" for the resources being removed.")
if "rack_id" in self.kwargs:
try:
(rc, result_dict) = rack_mgr.list_racks(
None, False, [self.kwargs["rack_id"]])
except Exception as e:
logging.error("%s: Exception received trying to retrieve"
" resource information. Exception is: %s",
__method__, e)
exceptions.handle(self.request, failure_message)
return
else:
# This is unexpected. RemoveResourcesView called with no context
# of what to edit. Need to display an error message because
# the dialog will not be primed with required data
logging.error("%s: RemoveResourcesView called with no context.",
__method__)
messages.error(self.request, failure_message)
return
if rc != 0:
messages.error(self.request, failure_message)
return
else:
# We should have at least one rack in the results...just
# return the first value
if len(result_dict['racks']) > 0:
return result_dict['racks'][0]
else:
logging.error("%s: list_racks returned no information for"
" rack with rack id %s",
__method__, self.kwargs["rack_id"])
messages.error(self.request, failure_message)
return
# Used to populate the table of resources to remove (for the given rack)
def get_data(self):
__method__ = 'views.RemoveResourcesView.get_data'
resources = []
rack_id = int(self.kwargs["rack_id"])
logging.debug("%s: before retrieving resources for rack: %s",
__method__, rack_id)
# retrieve resources for the rack id passed in (rack_id may be -1 on
# the initial pass)
(rc, result_dict) = resource_mgr.list_resources(None, False, None,
None, False, False,
[rack_id])
if rc != 0:
messages.error(self.request, _('Unable to retrieve Operational'
' Management inventory information'
' for resources.'))
logging.error('%s: Unable to retrieve Operational Management'
'inventory information. A Non-0 return code returned'
' from resource_mgr.list_resources. The return code'
' is: %s', __method__, rc)
else:
all_resources = result_dict['resources']
for raw_resource in all_resources:
resources.append(resource.Resource(raw_resource))
logging.debug("%s: Found %s resources",
__method__, len(resources))
return resources
| [
"opsmgr.inventory.rack_mgr.list_racks",
"horizon.exceptions.handle",
"operational_mgmt.inventory.tables.ResourcesTable",
"django.utils.translation.ugettext_lazy",
"logging.debug",
"django.views.decorators.debug.sensitive_post_parameters",
"opsmgr.inventory.resource_mgr.list_resources",
"django.core.ur... | [((1606, 1620), 'django.utils.translation.ugettext_lazy', '_', (['"""Inventory"""'], {}), "('Inventory')\n", (1607, 1620), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4745, 4762), 'django.utils.translation.ugettext_lazy', '_', (['"""Add Resource"""'], {}), "('Add Resource')\n", (4746, 4762), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4863, 4880), 'django.utils.translation.ugettext_lazy', '_', (['"""Add Resource"""'], {}), "('Add Resource')\n", (4864, 4880), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4956, 5003), 'django.core.urlresolvers.reverse_lazy', 'reverse_lazy', (['"""horizon:op_mgmt:inventory:index"""'], {}), "('horizon:op_mgmt:inventory:index')\n", (4968, 5003), False, 'from django.core.urlresolvers import reverse_lazy\n'), ((5021, 5038), 'django.utils.translation.ugettext_lazy', '_', (['"""Add Resource"""'], {}), "('Add Resource')\n", (5022, 5038), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((7561, 7579), 'django.utils.translation.ugettext_lazy', '_', (['"""Edit Resource"""'], {}), "('Edit Resource')\n", (7562, 7579), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((7682, 7700), 'django.utils.translation.ugettext_lazy', '_', (['"""Edit Resource"""'], {}), "('Edit Resource')\n", (7683, 7700), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((7777, 7824), 'django.core.urlresolvers.reverse_lazy', 'reverse_lazy', (['"""horizon:op_mgmt:inventory:index"""'], {}), "('horizon:op_mgmt:inventory:index')\n", (7789, 7824), False, 'from django.core.urlresolvers import reverse_lazy\n'), ((7842, 7860), 'django.utils.translation.ugettext_lazy', '_', (['"""Edit Resource"""'], {}), "('Edit Resource')\n", (7843, 7860), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((10760, 10780), 'django.utils.translation.ugettext_lazy', '_', (['"""Change Password"""'], {}), "('Change Password')\n", (10761, 10780), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((10887, 10907), 'django.utils.translation.ugettext_lazy', '_', (['"""Change Password"""'], {}), "('Change Password')\n", (10888, 10907), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((10986, 11033), 'django.core.urlresolvers.reverse_lazy', 'reverse_lazy', (['"""horizon:op_mgmt:inventory:index"""'], {}), "('horizon:op_mgmt:inventory:index')\n", (10998, 11033), False, 'from django.core.urlresolvers import reverse_lazy\n'), ((11051, 11071), 'django.utils.translation.ugettext_lazy', '_', (['"""Change Password"""'], {}), "('Change Password')\n", (11052, 11071), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((13962, 13984), 'django.utils.translation.ugettext_lazy', '_', (['"""Edit Rack Details"""'], {}), "('Edit Rack Details')\n", (13963, 13984), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((14074, 14088), 'django.utils.translation.ugettext_lazy', '_', (['"""Edit Rack"""'], {}), "('Edit Rack')\n", (14075, 14088), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((14161, 14208), 'django.core.urlresolvers.reverse_lazy', 'reverse_lazy', (['"""horizon:op_mgmt:inventory:index"""'], {}), "('horizon:op_mgmt:inventory:index')\n", (14173, 14208), False, 'from django.core.urlresolvers import reverse_lazy\n'), ((16793, 16817), 'django.utils.translation.ugettext_lazy', '_', (['"""Confirm Remove Rack"""'], {}), "('Confirm Remove Rack')\n", (16794, 16817), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((16916, 16932), 'django.utils.translation.ugettext_lazy', '_', (['"""Remove Rack"""'], {}), "('Remove Rack')\n", (16917, 16932), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((17007, 17054), 'django.core.urlresolvers.reverse_lazy', 'reverse_lazy', (['"""horizon:op_mgmt:inventory:index"""'], {}), "('horizon:op_mgmt:inventory:index')\n", (17019, 17054), False, 'from django.core.urlresolvers import reverse_lazy\n'), ((17072, 17096), 'django.utils.translation.ugettext_lazy', '_', (['"""Confirm Remove Rack"""'], {}), "('Confirm Remove Rack')\n", (17073, 17096), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((19533, 19554), 'django.utils.translation.ugettext_lazy', '_', (['"""Remove Resources"""'], {}), "('Remove Resources')\n", (19534, 19554), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((19673, 19720), 'django.core.urlresolvers.reverse_lazy', 'reverse_lazy', (['"""horizon:op_mgmt:inventory:index"""'], {}), "('horizon:op_mgmt:inventory:index')\n", (19685, 19720), False, 'from django.core.urlresolvers import reverse_lazy\n'), ((19740, 19750), 'django.utils.translation.ugettext_lazy', '_', (['"""Close"""'], {}), "('Close')\n", (19741, 19750), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((19768, 19789), 'django.utils.translation.ugettext_lazy', '_', (['"""Remove Resources"""'], {}), "('Remove Resources')\n", (19769, 19789), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1988, 2031), 'operational_mgmt.inventory.tables.ResourcesTable', 'project_tables.ResourcesTable', (['self.request'], {}), '(self.request)\n', (2017, 2031), True, 'from operational_mgmt.inventory import tables as project_tables\n'), ((4420, 4462), 'django.core.urlresolvers.reverse', 'reverse', (['"""horizon:op_mgmt:inventory:index"""'], {}), "('horizon:op_mgmt:inventory:index')\n", (4427, 4462), False, 'from django.core.urlresolvers import reverse\n'), ((7378, 7413), 'django.core.urlresolvers.reverse', 'reverse', (['self.submit_url'], {'args': 'args'}), '(self.submit_url, args=args)\n', (7385, 7413), False, 'from django.core.urlresolvers import reverse\n'), ((10573, 10608), 'django.core.urlresolvers.reverse', 'reverse', (['self.submit_url'], {'args': 'args'}), '(self.submit_url, args=args)\n', (10580, 10608), False, 'from django.core.urlresolvers import reverse\n'), ((11095, 11152), 'django.views.decorators.debug.sensitive_post_parameters', 'sensitive_post_parameters', (['"""password"""', '"""confirm_password"""'], {}), "('password', 'confirm_password')\n", (11120, 11152), False, 'from django.views.decorators.debug import sensitive_post_parameters\n'), ((13787, 13822), 'django.core.urlresolvers.reverse', 'reverse', (['self.submit_url'], {'args': 'args'}), '(self.submit_url, args=args)\n', (13794, 13822), False, 'from django.core.urlresolvers import reverse\n'), ((16614, 16649), 'django.core.urlresolvers.reverse', 'reverse', (['self.submit_url'], {'args': 'args'}), '(self.submit_url, args=args)\n', (16621, 16649), False, 'from django.core.urlresolvers import reverse\n'), ((19329, 19364), 'django.core.urlresolvers.reverse', 'reverse', (['self.submit_url'], {'args': 'args'}), '(self.submit_url, args=args)\n', (19336, 19364), False, 'from django.core.urlresolvers import reverse\n'), ((21798, 21884), 'logging.debug', 'logging.debug', (['"""%s: before retrieving resources for rack: %s"""', '__method__', 'rack_id'], {}), "('%s: before retrieving resources for rack: %s', __method__,\n rack_id)\n", (21811, 21884), False, 'import logging\n'), ((22037, 22114), 'opsmgr.inventory.resource_mgr.list_resources', 'resource_mgr.list_resources', (['None', '(False)', 'None', 'None', '(False)', '(False)', '[rack_id]'], {}), '(None, False, None, None, False, False, [rack_id])\n', (22064, 22114), True, 'import opsmgr.inventory.resource_mgr as resource_mgr\n'), ((6339, 6424), 'logging.error', 'logging.error', (['"""%s: AddResourceView called with no rack id context."""', '__method__'], {}), "('%s: AddResourceView called with no rack id context.', __method__\n )\n", (6352, 6424), False, 'import logging\n'), ((6461, 6506), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (6475, 6506), False, 'from horizon import messages\n'), ((6559, 6604), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (6573, 6604), False, 'from horizon import messages\n'), ((9490, 9579), 'logging.error', 'logging.error', (['"""%s: EditResourceView called with no resource id context."""', '__method__'], {}), "('%s: EditResourceView called with no resource id context.',\n __method__)\n", (9503, 9579), False, 'import logging\n'), ((9617, 9662), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (9631, 9662), False, 'from horizon import messages\n'), ((9715, 9760), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (9729, 9760), False, 'from horizon import messages\n'), ((12718, 12793), 'logging.error', 'logging.error', (['"""%s: ChangePasswordView called with no context."""', '__method__'], {}), "('%s: ChangePasswordView called with no context.', __method__)\n", (12731, 12793), False, 'import logging\n'), ((12832, 12877), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (12846, 12877), False, 'from horizon import messages\n'), ((12930, 12975), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (12944, 12975), False, 'from horizon import messages\n'), ((15586, 15655), 'logging.error', 'logging.error', (['"""%s: EditRackView called with no context."""', '__method__'], {}), "('%s: EditRackView called with no context.', __method__)\n", (15599, 15655), False, 'import logging\n'), ((15694, 15739), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (15708, 15739), False, 'from horizon import messages\n'), ((15792, 15837), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (15806, 15837), False, 'from horizon import messages\n'), ((18297, 18368), 'logging.error', 'logging.error', (['"""%s: RemoveRackView called with no context."""', '__method__'], {}), "('%s: RemoveRackView called with no context.', __method__)\n", (18310, 18368), False, 'import logging\n'), ((18407, 18452), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (18421, 18452), False, 'from horizon import messages\n'), ((18505, 18550), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (18519, 18550), False, 'from horizon import messages\n'), ((20770, 20846), 'logging.error', 'logging.error', (['"""%s: RemoveResourcesView called with no context."""', '__method__'], {}), "('%s: RemoveResourcesView called with no context.', __method__)\n", (20783, 20846), False, 'import logging\n'), ((20885, 20930), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (20899, 20930), False, 'from horizon import messages\n'), ((20983, 21028), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (20997, 21028), False, 'from horizon import messages\n'), ((22477, 22674), 'logging.error', 'logging.error', (['"""%s: Unable to retrieve Operational Managementinventory information. A Non-0 return code returned from resource_mgr.list_resources. The return code is: %s"""', '__method__', 'rc'], {}), "(\n '%s: Unable to retrieve Operational Managementinventory information. A Non-0 return code returned from resource_mgr.list_resources. The return code is: %s'\n , __method__, rc)\n", (22490, 22674), False, 'import logging\n'), ((3222, 3301), 'logging.error', 'logging.error', (['"""%s: DetailView called with no resource id context."""', '__method__'], {}), "('%s: DetailView called with no resource id context.', __method__)\n", (3235, 3301), False, 'import logging\n'), ((3351, 3396), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (3365, 3396), False, 'from horizon import messages\n'), ((3461, 3506), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (3475, 3506), False, 'from horizon import messages\n'), ((5686, 5744), 'opsmgr.inventory.rack_mgr.list_racks', 'rack_mgr.list_racks', (['None', '(False)', "[self.kwargs['rack_id']]"], {}), "(None, False, [self.kwargs['rack_id']])\n", (5705, 5744), True, 'import opsmgr.inventory.rack_mgr as rack_mgr\n'), ((6871, 6990), 'logging.error', 'logging.error', (['"""%s: list_rack returned no information for rack with rack id %s"""', '__method__', "self.kwargs['rack_id']"], {}), "('%s: list_rack returned no information for rack with rack id %s',\n __method__, self.kwargs['rack_id'])\n", (6884, 6990), False, 'import logging\n'), ((7066, 7111), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (7080, 7111), False, 'from horizon import messages\n'), ((8839, 8915), 'opsmgr.inventory.resource_mgr.list_resources', 'resource_mgr.list_resources', (['None', '(False)', 'None', "[self.kwargs['resource_id']]"], {}), "(None, False, None, [self.kwargs['resource_id']])\n", (8866, 8915), True, 'import opsmgr.inventory.resource_mgr as resource_mgr\n'), ((10039, 10181), 'logging.error', 'logging.error', (['"""%s: list_resources returned no information for resource with resource id %s"""', '__method__', "self.kwargs['resource_id']"], {}), "(\n '%s: list_resources returned no information for resource with resource id %s'\n , __method__, self.kwargs['resource_id'])\n", (10052, 10181), False, 'import logging\n'), ((10251, 10296), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (10265, 10296), False, 'from horizon import messages\n'), ((12065, 12141), 'opsmgr.inventory.resource_mgr.list_resources', 'resource_mgr.list_resources', (['None', '(False)', 'None', "[self.kwargs['resource_id']]"], {}), "(None, False, None, [self.kwargs['resource_id']])\n", (12092, 12141), True, 'import opsmgr.inventory.resource_mgr as resource_mgr\n'), ((13254, 13396), 'logging.error', 'logging.error', (['"""%s: list_resources returned no information for resource with resource id %s"""', '__method__', "self.kwargs['resource_id']"], {}), "(\n '%s: list_resources returned no information for resource with resource id %s'\n , __method__, self.kwargs['resource_id'])\n", (13267, 13396), False, 'import logging\n'), ((13466, 13511), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (13480, 13511), False, 'from horizon import messages\n'), ((14961, 15019), 'opsmgr.inventory.rack_mgr.list_racks', 'rack_mgr.list_racks', (['None', '(False)', "[self.kwargs['rack_id']]"], {}), "(None, False, [self.kwargs['rack_id']])\n", (14980, 15019), True, 'import opsmgr.inventory.rack_mgr as rack_mgr\n'), ((16108, 16229), 'logging.error', 'logging.error', (['"""%s: list_racks returned no information for rack with rack id %s"""', '__method__', "self.kwargs['rack_id']"], {}), "('%s: list_racks returned no information for rack with rack id %s'\n , __method__, self.kwargs['rack_id'])\n", (16121, 16229), False, 'import logging\n'), ((16304, 16349), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (16318, 16349), False, 'from horizon import messages\n'), ((17670, 17728), 'opsmgr.inventory.rack_mgr.list_racks', 'rack_mgr.list_racks', (['None', '(False)', "[self.kwargs['rack_id']]"], {}), "(None, False, [self.kwargs['rack_id']])\n", (17689, 17728), True, 'import opsmgr.inventory.rack_mgr as rack_mgr\n'), ((18821, 18942), 'logging.error', 'logging.error', (['"""%s: list_racks returned no information for rack with rack id %s"""', '__method__', "self.kwargs['rack_id']"], {}), "('%s: list_racks returned no information for rack with rack id %s'\n , __method__, self.kwargs['rack_id'])\n", (18834, 18942), False, 'import logging\n'), ((19017, 19062), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (19031, 19062), False, 'from horizon import messages\n'), ((20134, 20192), 'opsmgr.inventory.rack_mgr.list_racks', 'rack_mgr.list_racks', (['None', '(False)', "[self.kwargs['rack_id']]"], {}), "(None, False, [self.kwargs['rack_id']])\n", (20153, 20192), True, 'import opsmgr.inventory.rack_mgr as rack_mgr\n'), ((21295, 21416), 'logging.error', 'logging.error', (['"""%s: list_racks returned no information for rack with rack id %s"""', '__method__', "self.kwargs['rack_id']"], {}), "('%s: list_racks returned no information for rack with rack id %s'\n , __method__, self.kwargs['rack_id'])\n", (21308, 21416), False, 'import logging\n'), ((21491, 21536), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (21505, 21536), False, 'from horizon import messages\n'), ((22288, 22376), 'django.utils.translation.ugettext_lazy', '_', (['"""Unable to retrieve Operational Management inventory information for resources."""'], {}), "('Unable to retrieve Operational Management inventory information for resources.'\n )\n", (22289, 22376), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((2522, 2598), 'opsmgr.inventory.resource_mgr.list_resources', 'resource_mgr.list_resources', (['None', '(False)', 'None', "[self.kwargs['resource_id']]"], {}), "(None, False, None, [self.kwargs['resource_id']])\n", (2549, 2598), True, 'import opsmgr.inventory.resource_mgr as resource_mgr\n'), ((3747, 3793), 'operational_mgmt.resource.Resource', 'resource.Resource', (["result_dict['resources'][0]"], {}), "(result_dict['resources'][0])\n", (3764, 3793), False, 'from operational_mgmt import resource\n'), ((3836, 3978), 'logging.error', 'logging.error', (['"""%s: list_resources returned no information for resource with resource id %s"""', '__method__', "self.kwargs['resource_id']"], {}), "(\n '%s: list_resources returned no information for resource with resource id %s'\n , __method__, self.kwargs['resource_id'])\n", (3849, 3978), False, 'import logging\n'), ((4060, 4105), 'horizon.messages.error', 'messages.error', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (4074, 4105), False, 'from horizon import messages\n'), ((4280, 4321), 'django.utils.translation.ugettext_lazy', '_', (['"""Unable to retrieve resource details."""'], {}), "('Unable to retrieve resource details.')\n", (4281, 4321), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((5817, 5936), 'logging.error', 'logging.error', (['"""%s: Exception received trying to retrieve rack information. Exception is: %s"""', '__method__', 'e'], {}), "(\n '%s: Exception received trying to retrieve rack information. Exception is: %s'\n , __method__, e)\n", (5830, 5936), False, 'import logging\n'), ((6006, 6054), 'horizon.exceptions.handle', 'exceptions.handle', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (6023, 6054), False, 'from horizon import exceptions\n'), ((8988, 9111), 'logging.error', 'logging.error', (['"""%s: Exception received trying to retrieve resource information. Exception is: %s"""', '__method__', 'e'], {}), "(\n '%s: Exception received trying to retrieve resource information. Exception is: %s'\n , __method__, e)\n", (9001, 9111), False, 'import logging\n'), ((9181, 9229), 'horizon.exceptions.handle', 'exceptions.handle', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (9198, 9229), False, 'from horizon import exceptions\n'), ((12214, 12337), 'logging.error', 'logging.error', (['"""%s: Exception received trying to retrieve resource information. Exception is: %s"""', '__method__', 'e'], {}), "(\n '%s: Exception received trying to retrieve resource information. Exception is: %s'\n , __method__, e)\n", (12227, 12337), False, 'import logging\n'), ((12407, 12455), 'horizon.exceptions.handle', 'exceptions.handle', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (12424, 12455), False, 'from horizon import exceptions\n'), ((15092, 15211), 'logging.error', 'logging.error', (['"""%s: Exception received trying to retrieve rack information. Exception is: %s"""', '__method__', 'e'], {}), "(\n '%s: Exception received trying to retrieve rack information. Exception is: %s'\n , __method__, e)\n", (15105, 15211), False, 'import logging\n'), ((15281, 15329), 'horizon.exceptions.handle', 'exceptions.handle', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (15298, 15329), False, 'from horizon import exceptions\n'), ((17801, 17920), 'logging.error', 'logging.error', (['"""%s: Exception received trying to retrieve rack information. Exception is: %s"""', '__method__', 'e'], {}), "(\n '%s: Exception received trying to retrieve rack information. Exception is: %s'\n , __method__, e)\n", (17814, 17920), False, 'import logging\n'), ((17990, 18038), 'horizon.exceptions.handle', 'exceptions.handle', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (18007, 18038), False, 'from horizon import exceptions\n'), ((20265, 20388), 'logging.error', 'logging.error', (['"""%s: Exception received trying to retrieve resource information. Exception is: %s"""', '__method__', 'e'], {}), "(\n '%s: Exception received trying to retrieve resource information. Exception is: %s'\n , __method__, e)\n", (20278, 20388), False, 'import logging\n'), ((20458, 20506), 'horizon.exceptions.handle', 'exceptions.handle', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (20475, 20506), False, 'from horizon import exceptions\n'), ((22899, 22930), 'operational_mgmt.resource.Resource', 'resource.Resource', (['raw_resource'], {}), '(raw_resource)\n', (22916, 22930), False, 'from operational_mgmt import resource\n'), ((2683, 2806), 'logging.error', 'logging.error', (['"""%s: Exception received trying to retrieve resource information. Exception is: %s"""', '__method__', 'e'], {}), "(\n '%s: Exception received trying to retrieve resource information. Exception is: %s'\n , __method__, e)\n", (2696, 2806), False, 'import logging\n'), ((2888, 2936), 'horizon.exceptions.handle', 'exceptions.handle', (['self.request', 'failure_message'], {}), '(self.request, failure_message)\n', (2905, 2936), False, 'from horizon import exceptions\n')] |
import csv
def carregar_acessos():
dados = []#lado direito
marcacoes =[]#as classificaçoes lado esquerdo
#abrir o arquivo
arquivo = open('acesso.csv', 'r')
#leitor de csv
leitor = csv.reader(arquivo)
#ler cada linha
for acessou_home,acessou_como_funciona,acessou_contato,comprou in leitor:
dados.append([acessou_home,acessou_como_funciona,acessou_contato])
marcacoes.append(comprou)
return dados, marcacoes
| [
"csv.reader"
] | [((207, 226), 'csv.reader', 'csv.reader', (['arquivo'], {}), '(arquivo)\n', (217, 226), False, 'import csv\n')] |
import time
import numpy as np
import torch
class Profiler:
def __init__(self, dummy=False, device=None):
self.events = []
self.dummy = dummy
self.device = device if device != torch.device('cpu') else None
self.log('start')
def log(self, name):
if self.dummy:
return
# Optionally synchronize cuda before logging time
if self.device is not None:
torch.cuda.synchronize(self.device)
self.events.append((name, time.time()))
def print_profile_summary(self, step, detailed=False):
event_names, event_times = zip(*self.events)
total_duration = event_times[-1] - event_times[0]
print(
"-------------- Step {} total duration: {:.3f} ms -------------------".format(step, total_duration * 1000))
event_durations = np.diff(event_times)
event_names = event_names[1:]
total_generate = sum(d for e, d in zip(event_names, event_durations) if "expansion" in e)
total_reduce = sum(d for e, d in zip(event_names, event_durations) if "reduced" in e)
print("Total generate expansions time {:.3f} ms".format(total_generate * 1000))
print("Total topk selection time {:.3f} ms".format(total_reduce * 1000))
print(
"Total rest time {:.3f} ms".format((total_duration - total_generate - total_reduce) * 1000))
maxlen = max(len(en) for en in event_names)
if detailed:
for i in np.argsort(-event_durations): # Sort descending by duration
print(("{:" + str(maxlen) + "s} {:.3f} ms").format(event_names[i], event_durations[i] * 1000))
def debug_memory(device=None):
print('*' * 20, "Memory Dump", '*' * 20)
if device is not None:
print(torch.cuda.memory_summary(device))
import gc
for obj in gc.get_objects():
try:
if torch.is_tensor(obj) or (hasattr(obj, 'data') and torch.is_tensor(obj.data)):
print(type(obj), obj.device, obj.dtype, obj.size())
except:
pass | [
"numpy.diff",
"torch.cuda.synchronize",
"numpy.argsort",
"torch.is_tensor",
"gc.get_objects",
"time.time",
"torch.cuda.memory_summary",
"torch.device"
] | [((1863, 1879), 'gc.get_objects', 'gc.get_objects', ([], {}), '()\n', (1877, 1879), False, 'import gc\n'), ((853, 873), 'numpy.diff', 'np.diff', (['event_times'], {}), '(event_times)\n', (860, 873), True, 'import numpy as np\n'), ((437, 472), 'torch.cuda.synchronize', 'torch.cuda.synchronize', (['self.device'], {}), '(self.device)\n', (459, 472), False, 'import torch\n'), ((1508, 1536), 'numpy.argsort', 'np.argsort', (['(-event_durations)'], {}), '(-event_durations)\n', (1518, 1536), True, 'import numpy as np\n'), ((1799, 1832), 'torch.cuda.memory_summary', 'torch.cuda.memory_summary', (['device'], {}), '(device)\n', (1824, 1832), False, 'import torch\n'), ((207, 226), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (219, 226), False, 'import torch\n'), ((507, 518), 'time.time', 'time.time', ([], {}), '()\n', (516, 518), False, 'import time\n'), ((1909, 1929), 'torch.is_tensor', 'torch.is_tensor', (['obj'], {}), '(obj)\n', (1924, 1929), False, 'import torch\n'), ((1959, 1984), 'torch.is_tensor', 'torch.is_tensor', (['obj.data'], {}), '(obj.data)\n', (1974, 1984), False, 'import torch\n')] |
"""
WLS filter: Edge-preserving smoothing based onthe weightd least squares
optimization framework, as described in Farbman, Fattal, Lischinski, and
Szeliski, "Edge-Preserving Decompositions for Multi-Scale Tone and Detail
Manipulation", ACM Transactions on Graphics, 27(3), August 2008.
Given an input image IN, we seek a new image OUT, which, on the one hand,
is as close as possible to IN, and, at the same time, is as smooth as
possible everywhere, except across significant gradients in L.
"""
import cv2
import numpy as np
from scipy.sparse import spdiags
from scipy.sparse.linalg import spsolve, lsqr
def wlsFilter(IN, Lambda=1.0, Alpha=1.2):
"""
IN : Input image (2D grayscale image, type float)
Lambda : Balances between the data term and the smoothness term.
Increasing lbda will produce smoother images.
Default value is 1.0
Alpha : Gives a degree of control over the affinities by
non-lineary scaling the gradients. Increasing alpha
will result in sharper preserved edges. Default value: 1.2
"""
L = np.log(IN+1e-22) # Source image for the affinity matrix. log_e(IN)
smallNum = 1e-6
height, width = IN.shape
k = height * width
# Compute affinities between adjacent pixels based on gradients of L
dy = np.diff(L, n=1, axis=0) # axis=0 is vertical direction
dy = -Lambda/(np.abs(dy)**Alpha + smallNum)
dy = np.pad(dy, ((0,1),(0,0)), 'constant') # add zeros row
dy = dy.flatten(order='F')
dx = np.diff(L, n=1, axis=1)
dx = -Lambda/(np.abs(dx)**Alpha + smallNum)
dx = np.pad(dx, ((0,0),(0,1)), 'constant') # add zeros col
dx = dx.flatten(order='F')
# Construct a five-point spatially inhomogeneous Laplacian matrix
B = np.concatenate([[dx], [dy]], axis=0)
d = np.array([-height, -1])
A = spdiags(B, d, k, k)
e = dx
w = np.pad(dx, (height, 0), 'constant'); w = w[0:-height]
s = dy
n = np.pad(dy, (1, 0), 'constant'); n = n[0:-1]
D = 1.0 - (e + w + s + n)
A = A + A.transpose() + spdiags(D, 0, k, k)
# Solve
OUT = spsolve(A, IN.flatten(order='F'))
return np.reshape(OUT, (height, width), order='F')
# Unit test
if __name__ == '__main__':
image = cv2.imread('1.png')
if image.shape[2] == 4: # Format RGBA
image = image[:,:, 0:3] # Discard alpha channel
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image1 = 1.0*image / np.max(image)
result = wlsFilter(image1)
cv2.imshow('1', result)
cv2.waitKey(0)
| [
"numpy.abs",
"numpy.reshape",
"numpy.log",
"numpy.diff",
"cv2.imshow",
"numpy.max",
"numpy.array",
"cv2.waitKey",
"numpy.concatenate",
"cv2.cvtColor",
"numpy.pad",
"scipy.sparse.spdiags",
"cv2.imread"
] | [((1124, 1142), 'numpy.log', 'np.log', (['(IN + 1e-22)'], {}), '(IN + 1e-22)\n', (1130, 1142), True, 'import numpy as np\n'), ((1353, 1376), 'numpy.diff', 'np.diff', (['L'], {'n': '(1)', 'axis': '(0)'}), '(L, n=1, axis=0)\n', (1360, 1376), True, 'import numpy as np\n'), ((1468, 1508), 'numpy.pad', 'np.pad', (['dy', '((0, 1), (0, 0))', '"""constant"""'], {}), "(dy, ((0, 1), (0, 0)), 'constant')\n", (1474, 1508), True, 'import numpy as np\n'), ((1566, 1589), 'numpy.diff', 'np.diff', (['L'], {'n': '(1)', 'axis': '(1)'}), '(L, n=1, axis=1)\n', (1573, 1589), True, 'import numpy as np\n'), ((1648, 1688), 'numpy.pad', 'np.pad', (['dx', '((0, 0), (0, 1))', '"""constant"""'], {}), "(dx, ((0, 0), (0, 1)), 'constant')\n", (1654, 1688), True, 'import numpy as np\n'), ((1820, 1856), 'numpy.concatenate', 'np.concatenate', (['[[dx], [dy]]'], {'axis': '(0)'}), '([[dx], [dy]], axis=0)\n', (1834, 1856), True, 'import numpy as np\n'), ((1865, 1888), 'numpy.array', 'np.array', (['[-height, -1]'], {}), '([-height, -1])\n', (1873, 1888), True, 'import numpy as np\n'), ((1899, 1918), 'scipy.sparse.spdiags', 'spdiags', (['B', 'd', 'k', 'k'], {}), '(B, d, k, k)\n', (1906, 1918), False, 'from scipy.sparse import spdiags\n'), ((1941, 1976), 'numpy.pad', 'np.pad', (['dx', '(height, 0)', '"""constant"""'], {}), "(dx, (height, 0), 'constant')\n", (1947, 1976), True, 'import numpy as np\n'), ((2014, 2044), 'numpy.pad', 'np.pad', (['dy', '(1, 0)', '"""constant"""'], {}), "(dy, (1, 0), 'constant')\n", (2020, 2044), True, 'import numpy as np\n'), ((2206, 2249), 'numpy.reshape', 'np.reshape', (['OUT', '(height, width)'], {'order': '"""F"""'}), "(OUT, (height, width), order='F')\n", (2216, 2249), True, 'import numpy as np\n'), ((2304, 2323), 'cv2.imread', 'cv2.imread', (['"""1.png"""'], {}), "('1.png')\n", (2314, 2323), False, 'import cv2\n'), ((2445, 2484), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (2457, 2484), False, 'import cv2\n'), ((2559, 2582), 'cv2.imshow', 'cv2.imshow', (['"""1"""', 'result'], {}), "('1', result)\n", (2569, 2582), False, 'import cv2\n'), ((2587, 2601), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (2598, 2601), False, 'import cv2\n'), ((2118, 2137), 'scipy.sparse.spdiags', 'spdiags', (['D', '(0)', 'k', 'k'], {}), '(D, 0, k, k)\n', (2125, 2137), False, 'from scipy.sparse import spdiags\n'), ((2510, 2523), 'numpy.max', 'np.max', (['image'], {}), '(image)\n', (2516, 2523), True, 'import numpy as np\n'), ((1429, 1439), 'numpy.abs', 'np.abs', (['dy'], {}), '(dy)\n', (1435, 1439), True, 'import numpy as np\n'), ((1609, 1619), 'numpy.abs', 'np.abs', (['dx'], {}), '(dx)\n', (1615, 1619), True, 'import numpy as np\n')] |
from typing import Dict, List, Tuple, Union
from collections import OrderedDict
from functools import lru_cache
import warnings
from torch.utils.data import BatchSampler, DataLoader
from catalyst.core.callback import (
Callback,
CallbackWrapper,
IBackwardCallback,
ICriterionCallback,
IOptimizerCallback,
ISchedulerCallback,
)
from catalyst.typing import RunnerCriterion, RunnerOptimizer, RunnerScheduler
def get_original_callback(callback: Callback) -> Callback:
"""Docs."""
while isinstance(callback, CallbackWrapper):
callback = callback.callback
return callback
def callback_isinstance(callback: Callback, class_or_tuple) -> bool:
"""Check if callback is the same type as required ``class_or_tuple``
Args:
callback: callback to check
class_or_tuple: class_or_tuple to compare with
Returns:
bool: true if first object has the required type
"""
callback = get_original_callback(callback)
return isinstance(callback, class_or_tuple)
def sort_callbacks_by_order(
callbacks: Union[List, Dict, OrderedDict]
) -> "OrderedDict[str, Callback]":
"""Creates an sequence of callbacks and sort them.
Args:
callbacks: either list of callbacks or ordered dict
Returns:
sequence of callbacks sorted by ``callback order``
Raises:
TypeError: if `callbacks` is out of `None`, `dict`, `OrderedDict`, `list`
"""
if callbacks is None:
output = OrderedDict()
elif isinstance(callbacks, (dict, OrderedDict)):
output = [(k, v) for k, v in callbacks.items()]
output = sorted(output, key=lambda x: x[1].order)
output = OrderedDict(output)
elif isinstance(callbacks, list):
output = sorted(callbacks, key=lambda x: x.order)
output = OrderedDict([(i, value) for i, value in enumerate(output)])
else:
raise TypeError(
f"Callbacks must be either Dict/OrderedDict or list, "
f"got {type(callbacks)}"
)
return output
@lru_cache(maxsize=42)
def is_str_intersections(origin_string: str, strings: Tuple):
"""Docs."""
return any(x in origin_string for x in strings)
def get_loader_batch_size(loader: DataLoader):
"""Docs."""
batch_size = loader.batch_size
if batch_size is not None:
return batch_size
batch_size = loader.batch_sampler.batch_size
if batch_size is not None:
return batch_size
raise NotImplementedError(
"No `batch_size` found,"
"please specify it with `loader.batch_size`,"
"or `loader.batch_sampler.batch_size`"
)
def get_loader_num_samples(loader: DataLoader):
"""Docs."""
batch_size = get_loader_batch_size(loader)
if isinstance(loader.batch_sampler, BatchSampler):
# pytorch default item-based samplers
if loader.drop_last:
return (len(loader.dataset) // batch_size) * batch_size
else:
return len(loader.dataset)
else:
# pytorch batch-based samplers
return len(loader) * batch_size
def check_callbacks(
callbacks: OrderedDict,
criterion: RunnerCriterion = None,
optimizer: RunnerOptimizer = None,
scheduler: RunnerScheduler = None,
):
"""Docs."""
callback_exists = lambda callback_fn: any(
callback_isinstance(x, callback_fn) for x in callbacks.values()
)
if criterion is not None and not callback_exists(ICriterionCallback):
warnings.warn(
"No ``ICriterionCallback/CriterionCallback`` were found "
"while runner.criterion is not None."
"Do you compute the loss during ``runner.handle_batch``?"
)
if (criterion is not None or optimizer is not None) and not callback_exists(
IBackwardCallback
):
warnings.warn(
"No ``IBackwardCallback/BackwardCallback`` were found "
"while runner.criterion/optimizer is not None."
"Do you backward the loss during ``runner.handle_batch``?"
)
if optimizer is not None and not callback_exists(IOptimizerCallback):
warnings.warn(
"No ``IOptimizerCallback/OptimizerCallback`` were found "
"while runner.optimizer is not None."
"Do run optimisation step pass during ``runner.handle_batch``?"
)
if scheduler is not None and not callback_exists(ISchedulerCallback):
warnings.warn(
"No ``ISchedulerCallback/SchedulerCallback`` were found "
"while runner.scheduler is not None."
"Do you make scheduler step during ``runner.handle_batch``?"
)
__all__ = [
"get_original_callback",
"callback_isinstance",
"check_callbacks",
"is_str_intersections",
"get_loader_batch_size",
"get_loader_num_samples",
"sort_callbacks_by_order",
]
| [
"warnings.warn",
"functools.lru_cache",
"collections.OrderedDict"
] | [((2053, 2074), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': '(42)'}), '(maxsize=42)\n', (2062, 2074), False, 'from functools import lru_cache\n'), ((1491, 1504), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1502, 1504), False, 'from collections import OrderedDict\n'), ((3487, 3659), 'warnings.warn', 'warnings.warn', (['"""No ``ICriterionCallback/CriterionCallback`` were found while runner.criterion is not None.Do you compute the loss during ``runner.handle_batch``?"""'], {}), "(\n 'No ``ICriterionCallback/CriterionCallback`` were found while runner.criterion is not None.Do you compute the loss during ``runner.handle_batch``?'\n )\n", (3500, 3659), False, 'import warnings\n'), ((3824, 4005), 'warnings.warn', 'warnings.warn', (['"""No ``IBackwardCallback/BackwardCallback`` were found while runner.criterion/optimizer is not None.Do you backward the loss during ``runner.handle_batch``?"""'], {}), "(\n 'No ``IBackwardCallback/BackwardCallback`` were found while runner.criterion/optimizer is not None.Do you backward the loss during ``runner.handle_batch``?'\n )\n", (3837, 4005), False, 'import warnings\n'), ((4130, 4308), 'warnings.warn', 'warnings.warn', (['"""No ``IOptimizerCallback/OptimizerCallback`` were found while runner.optimizer is not None.Do run optimisation step pass during ``runner.handle_batch``?"""'], {}), "(\n 'No ``IOptimizerCallback/OptimizerCallback`` were found while runner.optimizer is not None.Do run optimisation step pass during ``runner.handle_batch``?'\n )\n", (4143, 4308), False, 'import warnings\n'), ((4433, 4608), 'warnings.warn', 'warnings.warn', (['"""No ``ISchedulerCallback/SchedulerCallback`` were found while runner.scheduler is not None.Do you make scheduler step during ``runner.handle_batch``?"""'], {}), "(\n 'No ``ISchedulerCallback/SchedulerCallback`` were found while runner.scheduler is not None.Do you make scheduler step during ``runner.handle_batch``?'\n )\n", (4446, 4608), False, 'import warnings\n'), ((1689, 1708), 'collections.OrderedDict', 'OrderedDict', (['output'], {}), '(output)\n', (1700, 1708), False, 'from collections import OrderedDict\n')] |
import numpy as np
def place_mirror(im, x1, x2, y1, y2, mr):
""" Place an image mr in specified locations of an image im. The edge locations in im where mr is to be placed are
(x1,y1) and (x2,y2)
Programmer
---------
<NAME> (JHU/APL, 10/12/05)
"""
nxa = np.zeros(2)
nya = np.zeros(2)
res = im[x1:x2 + 1, y1:y2 + 1].shape
nxa[0] = res[0]
nya[0] = res[1]
res = mr.shape
nxa[1] = res[0]
nya[1] = res[1]
nx = np.min(nxa)
ny = np.min(nya)
im[x1:x1 + nx, y1:y1 + ny] = mr[0:nx, 0:ny]
return im
def expand_image(im, ext_x, ext_y, mirror=0):
"""Enlarge the linear dimensions of an image by a (ext_x,ext_y) and put the initial image at the center.
If the keyword /mirror is set, the additional space corresponds to a mirror image of the initial image.
Programmer
----------
<NAME> (JHU/APL, 09/30/05)
"""
res = im.shape
id1 = res[0]
id2 = res[1]
mim = np.zeros((int(id1 + ext_x), int(id2 + ext_y)))
stx = np.fix(np.float(ext_x) / 2. + 0.5)
sty = np.fix(np.float(ext_y) / 2. + 0.5)
mim[int(stx):int(stx + id1), int(sty):int(sty + id2)] = im
if mirror != 0:
if stx <= id1:
xmr = int(stx)
else:
xmr = int(id1)
mr1 = im[0:xmr, :]
mr1 = np.flip(mr1, axis=0)
mr2 = im[id1 - xmr:id1, :]
mr2 = np.flip(mr2, axis=0)
mim = place_mirror(mim, 0, stx - 1, sty, sty + id2 - 1, mr1)
mim = place_mirror(mim, stx + id1, id1 + ext_x - 1, sty, sty + id2 - 1, mr2)
if sty <= id2:
ymr = int(sty)
else:
ymr = int(id2)
mr1 = mim[:, ymr:2 * ymr]
mr1 = np.flip(mr1, axis=1)
mr2 = mim[:, id2:ymr + id2]
mr2 = np.flip(mr2, axis=1)
mim = place_mirror(mim, 0, id1 + ext_x - 1, 0, sty - 1, mr1)
mim = place_mirror(mim, 0, id1 + ext_x - 1, sty + id2, id2 + ext_y - 1, mr2)
return mim, stx, sty
| [
"numpy.flip",
"numpy.zeros",
"numpy.float",
"numpy.min"
] | [((290, 301), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (298, 301), True, 'import numpy as np\n'), ((312, 323), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (320, 323), True, 'import numpy as np\n'), ((474, 485), 'numpy.min', 'np.min', (['nxa'], {}), '(nxa)\n', (480, 485), True, 'import numpy as np\n'), ((495, 506), 'numpy.min', 'np.min', (['nya'], {}), '(nya)\n', (501, 506), True, 'import numpy as np\n'), ((1327, 1347), 'numpy.flip', 'np.flip', (['mr1'], {'axis': '(0)'}), '(mr1, axis=0)\n', (1334, 1347), True, 'import numpy as np\n'), ((1397, 1417), 'numpy.flip', 'np.flip', (['mr2'], {'axis': '(0)'}), '(mr2, axis=0)\n', (1404, 1417), True, 'import numpy as np\n'), ((1711, 1731), 'numpy.flip', 'np.flip', (['mr1'], {'axis': '(1)'}), '(mr1, axis=1)\n', (1718, 1731), True, 'import numpy as np\n'), ((1782, 1802), 'numpy.flip', 'np.flip', (['mr2'], {'axis': '(1)'}), '(mr2, axis=1)\n', (1789, 1802), True, 'import numpy as np\n'), ((1038, 1053), 'numpy.float', 'np.float', (['ext_x'], {}), '(ext_x)\n', (1046, 1053), True, 'import numpy as np\n'), ((1083, 1098), 'numpy.float', 'np.float', (['ext_y'], {}), '(ext_y)\n', (1091, 1098), True, 'import numpy as np\n')] |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: protobufs/services/team/actions/get_teams.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from protobufs.services.common import containers_pb2 as protobufs_dot_services_dot_common_dot_containers__pb2
from protobufs.services.team import containers_pb2 as protobufs_dot_services_dot_team_dot_containers__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='protobufs/services/team/actions/get_teams.proto',
package='services.team.actions.get_teams',
syntax='proto3',
serialized_pb=b'\n/protobufs/services/team/actions/get_teams.proto\x12\x1fservices.team.actions.get_teams\x1a*protobufs/services/common/containers.proto\x1a(protobufs/services/team/containers.proto\"\x8c\x01\n\tRequestV1\x12<\n\ninflations\x18\x01 \x01(\x0b\x32(.services.common.containers.InflationsV1\x12\x34\n\x06\x66ields\x18\x02 \x01(\x0b\x32$.services.common.containers.FieldsV1\x12\x0b\n\x03ids\x18\x03 \x03(\t\"=\n\nResponseV1\x12/\n\x05teams\x18\x01 \x03(\x0b\x32 .services.team.containers.TeamV1b\x06proto3'
,
dependencies=[protobufs_dot_services_dot_common_dot_containers__pb2.DESCRIPTOR,protobufs_dot_services_dot_team_dot_containers__pb2.DESCRIPTOR,])
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_REQUESTV1 = _descriptor.Descriptor(
name='RequestV1',
full_name='services.team.actions.get_teams.RequestV1',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='inflations', full_name='services.team.actions.get_teams.RequestV1.inflations', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='fields', full_name='services.team.actions.get_teams.RequestV1.fields', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='ids', full_name='services.team.actions.get_teams.RequestV1.ids', index=2,
number=3, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=171,
serialized_end=311,
)
_RESPONSEV1 = _descriptor.Descriptor(
name='ResponseV1',
full_name='services.team.actions.get_teams.ResponseV1',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='teams', full_name='services.team.actions.get_teams.ResponseV1.teams', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=313,
serialized_end=374,
)
_REQUESTV1.fields_by_name['inflations'].message_type = protobufs_dot_services_dot_common_dot_containers__pb2._INFLATIONSV1
_REQUESTV1.fields_by_name['fields'].message_type = protobufs_dot_services_dot_common_dot_containers__pb2._FIELDSV1
_RESPONSEV1.fields_by_name['teams'].message_type = protobufs_dot_services_dot_team_dot_containers__pb2._TEAMV1
DESCRIPTOR.message_types_by_name['RequestV1'] = _REQUESTV1
DESCRIPTOR.message_types_by_name['ResponseV1'] = _RESPONSEV1
RequestV1 = _reflection.GeneratedProtocolMessageType('RequestV1', (_message.Message,), dict(
DESCRIPTOR = _REQUESTV1,
__module__ = 'protobufs.services.team.actions.get_teams_pb2'
# @@protoc_insertion_point(class_scope:services.team.actions.get_teams.RequestV1)
))
_sym_db.RegisterMessage(RequestV1)
ResponseV1 = _reflection.GeneratedProtocolMessageType('ResponseV1', (_message.Message,), dict(
DESCRIPTOR = _RESPONSEV1,
__module__ = 'protobufs.services.team.actions.get_teams_pb2'
# @@protoc_insertion_point(class_scope:services.team.actions.get_teams.ResponseV1)
))
_sym_db.RegisterMessage(ResponseV1)
# @@protoc_insertion_point(module_scope)
| [
"google.protobuf.symbol_database.Default",
"google.protobuf.descriptor.FieldDescriptor",
"google.protobuf.descriptor.FileDescriptor"
] | [((428, 454), 'google.protobuf.symbol_database.Default', '_symbol_database.Default', ([], {}), '()\n', (452, 454), True, 'from google.protobuf import symbol_database as _symbol_database\n'), ((688, 1507), 'google.protobuf.descriptor.FileDescriptor', '_descriptor.FileDescriptor', ([], {'name': '"""protobufs/services/team/actions/get_teams.proto"""', 'package': '"""services.team.actions.get_teams"""', 'syntax': '"""proto3"""', 'serialized_pb': 'b\'\\n/protobufs/services/team/actions/get_teams.proto\\x12\\x1fservices.team.actions.get_teams\\x1a*protobufs/services/common/containers.proto\\x1a(protobufs/services/team/containers.proto"\\x8c\\x01\\n\\tRequestV1\\x12<\\n\\ninflations\\x18\\x01 \\x01(\\x0b2(.services.common.containers.InflationsV1\\x124\\n\\x06fields\\x18\\x02 \\x01(\\x0b2$.services.common.containers.FieldsV1\\x12\\x0b\\n\\x03ids\\x18\\x03 \\x03(\\t"=\\n\\nResponseV1\\x12/\\n\\x05teams\\x18\\x01 \\x03(\\x0b2 .services.team.containers.TeamV1b\\x06proto3\'', 'dependencies': '[protobufs_dot_services_dot_common_dot_containers__pb2.DESCRIPTOR,\n protobufs_dot_services_dot_team_dot_containers__pb2.DESCRIPTOR]'}), '(name=\n \'protobufs/services/team/actions/get_teams.proto\', package=\n \'services.team.actions.get_teams\', syntax=\'proto3\', serialized_pb=\n b\'\\n/protobufs/services/team/actions/get_teams.proto\\x12\\x1fservices.team.actions.get_teams\\x1a*protobufs/services/common/containers.proto\\x1a(protobufs/services/team/containers.proto"\\x8c\\x01\\n\\tRequestV1\\x12<\\n\\ninflations\\x18\\x01 \\x01(\\x0b2(.services.common.containers.InflationsV1\\x124\\n\\x06fields\\x18\\x02 \\x01(\\x0b2$.services.common.containers.FieldsV1\\x12\\x0b\\n\\x03ids\\x18\\x03 \\x03(\\t"=\\n\\nResponseV1\\x12/\\n\\x05teams\\x18\\x01 \\x03(\\x0b2 .services.team.containers.TeamV1b\\x06proto3\'\n , dependencies=[protobufs_dot_services_dot_common_dot_containers__pb2.\n DESCRIPTOR, protobufs_dot_services_dot_team_dot_containers__pb2.DESCRIPTOR]\n )\n', (714, 1507), True, 'from google.protobuf import descriptor as _descriptor\n'), ((1745, 2084), 'google.protobuf.descriptor.FieldDescriptor', '_descriptor.FieldDescriptor', ([], {'name': '"""inflations"""', 'full_name': '"""services.team.actions.get_teams.RequestV1.inflations"""', 'index': '(0)', 'number': '(1)', 'type': '(11)', 'cpp_type': '(10)', 'label': '(1)', 'has_default_value': '(False)', 'default_value': 'None', 'message_type': 'None', 'enum_type': 'None', 'containing_type': 'None', 'is_extension': '(False)', 'extension_scope': 'None', 'options': 'None'}), "(name='inflations', full_name=\n 'services.team.actions.get_teams.RequestV1.inflations', index=0, number\n =1, type=11, cpp_type=10, label=1, has_default_value=False,\n default_value=None, message_type=None, enum_type=None, containing_type=\n None, is_extension=False, extension_scope=None, options=None)\n", (1772, 2084), True, 'from google.protobuf import descriptor as _descriptor\n'), ((2108, 2438), 'google.protobuf.descriptor.FieldDescriptor', '_descriptor.FieldDescriptor', ([], {'name': '"""fields"""', 'full_name': '"""services.team.actions.get_teams.RequestV1.fields"""', 'index': '(1)', 'number': '(2)', 'type': '(11)', 'cpp_type': '(10)', 'label': '(1)', 'has_default_value': '(False)', 'default_value': 'None', 'message_type': 'None', 'enum_type': 'None', 'containing_type': 'None', 'is_extension': '(False)', 'extension_scope': 'None', 'options': 'None'}), "(name='fields', full_name=\n 'services.team.actions.get_teams.RequestV1.fields', index=1, number=2,\n type=11, cpp_type=10, label=1, has_default_value=False, default_value=\n None, message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None, options=None)\n", (2135, 2438), True, 'from google.protobuf import descriptor as _descriptor\n'), ((2463, 2783), 'google.protobuf.descriptor.FieldDescriptor', '_descriptor.FieldDescriptor', ([], {'name': '"""ids"""', 'full_name': '"""services.team.actions.get_teams.RequestV1.ids"""', 'index': '(2)', 'number': '(3)', 'type': '(9)', 'cpp_type': '(9)', 'label': '(3)', 'has_default_value': '(False)', 'default_value': '[]', 'message_type': 'None', 'enum_type': 'None', 'containing_type': 'None', 'is_extension': '(False)', 'extension_scope': 'None', 'options': 'None'}), "(name='ids', full_name=\n 'services.team.actions.get_teams.RequestV1.ids', index=2, number=3,\n type=9, cpp_type=9, label=3, has_default_value=False, default_value=[],\n message_type=None, enum_type=None, containing_type=None, is_extension=\n False, extension_scope=None, options=None)\n", (2490, 2783), True, 'from google.protobuf import descriptor as _descriptor\n'), ((3207, 3534), 'google.protobuf.descriptor.FieldDescriptor', '_descriptor.FieldDescriptor', ([], {'name': '"""teams"""', 'full_name': '"""services.team.actions.get_teams.ResponseV1.teams"""', 'index': '(0)', 'number': '(1)', 'type': '(11)', 'cpp_type': '(10)', 'label': '(3)', 'has_default_value': '(False)', 'default_value': '[]', 'message_type': 'None', 'enum_type': 'None', 'containing_type': 'None', 'is_extension': '(False)', 'extension_scope': 'None', 'options': 'None'}), "(name='teams', full_name=\n 'services.team.actions.get_teams.ResponseV1.teams', index=0, number=1,\n type=11, cpp_type=10, label=3, has_default_value=False, default_value=[\n ], message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None, options=None)\n", (3234, 3534), True, 'from google.protobuf import descriptor as _descriptor\n')] |
# -*- coding: utf-8 -*-
"""
:author: <NAME> (徐天明)
:url: http://greyli.com
:copyright: © 2021 <NAME> <<EMAIL>>
:license: MIT, see LICENSE for more details.
"""
from flask import render_template, current_app, request, Blueprint
from albumy.models import User, Photo
user_bp = Blueprint('user', __name__)
@user_bp.route('/<username>')
def index(username):
user = User.query.filter_by(username=username).first_or_404()
page = request.args.get('page', 1, type=int)
per_page = current_app.config['ALBUMY_PHOTO_PER_PAGE']
pagination = Photo.query.with_parent(user).order_by(Photo.timestamp.desc()).paginate(page, per_page)
photos = pagination.items
return render_template('user/index.html', user=user, pagination=pagination, photos=photos)
| [
"flask.render_template",
"flask.request.args.get",
"albumy.models.Photo.timestamp.desc",
"albumy.models.Photo.query.with_parent",
"albumy.models.User.query.filter_by",
"flask.Blueprint"
] | [((292, 319), 'flask.Blueprint', 'Blueprint', (['"""user"""', '__name__'], {}), "('user', __name__)\n", (301, 319), False, 'from flask import render_template, current_app, request, Blueprint\n'), ((450, 487), 'flask.request.args.get', 'request.args.get', (['"""page"""', '(1)'], {'type': 'int'}), "('page', 1, type=int)\n", (466, 487), False, 'from flask import render_template, current_app, request, Blueprint\n'), ((693, 781), 'flask.render_template', 'render_template', (['"""user/index.html"""'], {'user': 'user', 'pagination': 'pagination', 'photos': 'photos'}), "('user/index.html', user=user, pagination=pagination, photos\n =photos)\n", (708, 781), False, 'from flask import render_template, current_app, request, Blueprint\n'), ((384, 423), 'albumy.models.User.query.filter_by', 'User.query.filter_by', ([], {'username': 'username'}), '(username=username)\n', (404, 423), False, 'from albumy.models import User, Photo\n'), ((603, 625), 'albumy.models.Photo.timestamp.desc', 'Photo.timestamp.desc', ([], {}), '()\n', (623, 625), False, 'from albumy.models import User, Photo\n'), ((564, 593), 'albumy.models.Photo.query.with_parent', 'Photo.query.with_parent', (['user'], {}), '(user)\n', (587, 593), False, 'from albumy.models import User, Photo\n')] |
from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, cast
import kubernetes
import dagster._check as check
from dagster.config.validate import process_config
from dagster.core.errors import DagsterInvalidConfigError
from dagster.core.storage.pipeline_run import PipelineRun
from dagster.core.utils import parse_env_var
from dagster.utils import make_readonly_value, merge_dicts
if TYPE_CHECKING:
from . import K8sRunLauncher
from .job import DagsterK8sJobConfig
from .models import k8s_snake_case_dict
def _dedupe_list(values):
return list(set([make_readonly_value(value) for value in values]))
class K8sContainerContext(
NamedTuple(
"_K8sContainerContext",
[
("image_pull_policy", Optional[str]),
("image_pull_secrets", List[Dict[str, str]]),
("service_account_name", Optional[str]),
("env_config_maps", List[str]),
("env_secrets", List[str]),
("env_vars", List[str]),
("volume_mounts", List[Dict[str, Any]]),
("volumes", List[Dict[str, Any]]),
("labels", Dict[str, str]),
("namespace", Optional[str]),
("resources", Dict[str, Any]),
],
)
):
"""Encapsulates configuration that can be applied to a K8s job running Dagster code.
Can be persisted on a PipelineRun at run submission time based on metadata from the
code location and then included in the job's configuration at run launch time or step
launch time."""
def __new__(
cls,
image_pull_policy: Optional[str] = None,
image_pull_secrets: Optional[List[Dict[str, str]]] = None,
service_account_name: Optional[str] = None,
env_config_maps: Optional[List[str]] = None,
env_secrets: Optional[List[str]] = None,
env_vars: Optional[List[str]] = None,
volume_mounts: Optional[List[Dict[str, Any]]] = None,
volumes: Optional[List[Dict[str, Any]]] = None,
labels: Optional[Dict[str, str]] = None,
namespace: Optional[str] = None,
resources: Optional[Dict[str, Any]] = None,
):
return super(K8sContainerContext, cls).__new__(
cls,
image_pull_policy=check.opt_str_param(image_pull_policy, "image_pull_policy"),
image_pull_secrets=check.opt_list_param(image_pull_secrets, "image_pull_secrets"),
service_account_name=check.opt_str_param(service_account_name, "service_account_name"),
env_config_maps=check.opt_list_param(env_config_maps, "env_config_maps"),
env_secrets=check.opt_list_param(env_secrets, "env_secrets"),
env_vars=check.opt_list_param(env_vars, "env_vars"),
volume_mounts=[
k8s_snake_case_dict(kubernetes.client.V1VolumeMount, mount)
for mount in check.opt_list_param(volume_mounts, "volume_mounts")
],
volumes=[
k8s_snake_case_dict(kubernetes.client.V1Volume, volume)
for volume in check.opt_list_param(volumes, "volumes")
],
labels=check.opt_dict_param(labels, "labels"),
namespace=check.opt_str_param(namespace, "namespace"),
resources=check.opt_dict_param(resources, "resources"),
)
def merge(self, other: "K8sContainerContext") -> "K8sContainerContext":
# Lists of attributes that can be combined are combined, scalar values are replaced
# prefering the passed in container context
return K8sContainerContext(
image_pull_policy=(
other.image_pull_policy if other.image_pull_policy else self.image_pull_policy
),
image_pull_secrets=_dedupe_list(other.image_pull_secrets + self.image_pull_secrets),
service_account_name=(
other.service_account_name
if other.service_account_name
else self.service_account_name
),
env_config_maps=_dedupe_list(other.env_config_maps + self.env_config_maps),
env_secrets=_dedupe_list(other.env_secrets + self.env_secrets),
env_vars=_dedupe_list(other.env_vars + self.env_vars),
volume_mounts=_dedupe_list(other.volume_mounts + self.volume_mounts),
volumes=_dedupe_list(other.volumes + self.volumes),
labels=merge_dicts(other.labels, self.labels),
namespace=other.namespace if other.namespace else self.namespace,
resources=other.resources if other.resources else self.resources,
)
def get_environment_dict(self) -> Dict[str, str]:
parsed_env_var_tuples = [parse_env_var(env_var) for env_var in self.env_vars]
return {env_var_tuple[0]: env_var_tuple[1] for env_var_tuple in parsed_env_var_tuples}
@staticmethod
def create_for_run(
pipeline_run: PipelineRun, run_launcher: Optional["K8sRunLauncher"]
) -> "K8sContainerContext":
context = K8sContainerContext()
if run_launcher:
context = context.merge(
K8sContainerContext(
image_pull_policy=run_launcher.image_pull_policy,
image_pull_secrets=run_launcher.image_pull_secrets,
service_account_name=run_launcher.service_account_name,
env_config_maps=run_launcher.env_config_maps,
env_secrets=run_launcher.env_secrets,
env_vars=run_launcher.env_vars,
volume_mounts=run_launcher.volume_mounts,
volumes=run_launcher.volumes,
labels=run_launcher.labels,
namespace=run_launcher.job_namespace,
resources=run_launcher.resources,
)
)
run_container_context = (
pipeline_run.pipeline_code_origin.repository_origin.container_context
if pipeline_run.pipeline_code_origin
else None
)
if not run_container_context:
return context
return context.merge(K8sContainerContext.create_from_config(run_container_context))
@staticmethod
def create_from_config(run_container_context) -> "K8sContainerContext":
run_k8s_container_context = (
run_container_context.get("k8s", {}) if run_container_context else {}
)
if not run_k8s_container_context:
return K8sContainerContext()
processed_container_context = process_config(
DagsterK8sJobConfig.config_type_container_context(), run_k8s_container_context
)
if not processed_container_context.success:
raise DagsterInvalidConfigError(
"Errors while parsing k8s container context",
processed_container_context.errors,
run_k8s_container_context,
)
processed_context_value = cast(Dict, processed_container_context.value)
return K8sContainerContext(
image_pull_policy=processed_context_value.get("image_pull_policy"),
image_pull_secrets=processed_context_value.get("image_pull_secrets"),
service_account_name=processed_context_value.get("service_account_name"),
env_config_maps=processed_context_value.get("env_config_maps"),
env_secrets=processed_context_value.get("env_secrets"),
env_vars=processed_context_value.get("env_vars"),
volume_mounts=processed_context_value.get("volume_mounts"),
volumes=processed_context_value.get("volumes"),
labels=processed_context_value.get("labels"),
namespace=processed_context_value.get("namespace"),
resources=processed_context_value.get("resources"),
)
def get_k8s_job_config(self, job_image, run_launcher) -> DagsterK8sJobConfig:
return DagsterK8sJobConfig(
job_image=job_image if job_image else run_launcher.job_image,
dagster_home=run_launcher.dagster_home,
image_pull_policy=self.image_pull_policy,
image_pull_secrets=self.image_pull_secrets,
service_account_name=self.service_account_name,
instance_config_map=run_launcher.instance_config_map,
postgres_password_secret=run_launcher.postgres_password_secret,
env_config_maps=self.env_config_maps,
env_secrets=self.env_secrets,
env_vars=self.env_vars,
volume_mounts=self.volume_mounts,
volumes=self.volumes,
labels=self.labels,
resources=self.resources,
)
| [
"dagster.core.errors.DagsterInvalidConfigError",
"dagster._check.opt_str_param",
"dagster.utils.merge_dicts",
"dagster._check.opt_list_param",
"dagster.utils.make_readonly_value",
"dagster.core.utils.parse_env_var",
"typing.NamedTuple",
"dagster._check.opt_dict_param",
"typing.cast"
] | [((662, 1096), 'typing.NamedTuple', 'NamedTuple', (['"""_K8sContainerContext"""', "[('image_pull_policy', Optional[str]), ('image_pull_secrets', List[Dict[str,\n str]]), ('service_account_name', Optional[str]), ('env_config_maps',\n List[str]), ('env_secrets', List[str]), ('env_vars', List[str]), (\n 'volume_mounts', List[Dict[str, Any]]), ('volumes', List[Dict[str, Any]\n ]), ('labels', Dict[str, str]), ('namespace', Optional[str]), (\n 'resources', Dict[str, Any])]"], {}), "('_K8sContainerContext', [('image_pull_policy', Optional[str]), (\n 'image_pull_secrets', List[Dict[str, str]]), ('service_account_name',\n Optional[str]), ('env_config_maps', List[str]), ('env_secrets', List[\n str]), ('env_vars', List[str]), ('volume_mounts', List[Dict[str, Any]]),\n ('volumes', List[Dict[str, Any]]), ('labels', Dict[str, str]), (\n 'namespace', Optional[str]), ('resources', Dict[str, Any])])\n", (672, 1096), False, 'from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, cast\n'), ((6948, 6993), 'typing.cast', 'cast', (['Dict', 'processed_container_context.value'], {}), '(Dict, processed_container_context.value)\n', (6952, 6993), False, 'from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, cast\n'), ((4685, 4707), 'dagster.core.utils.parse_env_var', 'parse_env_var', (['env_var'], {}), '(env_var)\n', (4698, 4707), False, 'from dagster.core.utils import parse_env_var\n'), ((6715, 6853), 'dagster.core.errors.DagsterInvalidConfigError', 'DagsterInvalidConfigError', (['"""Errors while parsing k8s container context"""', 'processed_container_context.errors', 'run_k8s_container_context'], {}), "('Errors while parsing k8s container context',\n processed_container_context.errors, run_k8s_container_context)\n", (6740, 6853), False, 'from dagster.core.errors import DagsterInvalidConfigError\n'), ((579, 605), 'dagster.utils.make_readonly_value', 'make_readonly_value', (['value'], {}), '(value)\n', (598, 605), False, 'from dagster.utils import make_readonly_value, merge_dicts\n'), ((2247, 2306), 'dagster._check.opt_str_param', 'check.opt_str_param', (['image_pull_policy', '"""image_pull_policy"""'], {}), "(image_pull_policy, 'image_pull_policy')\n", (2266, 2306), True, 'import dagster._check as check\n'), ((2339, 2401), 'dagster._check.opt_list_param', 'check.opt_list_param', (['image_pull_secrets', '"""image_pull_secrets"""'], {}), "(image_pull_secrets, 'image_pull_secrets')\n", (2359, 2401), True, 'import dagster._check as check\n'), ((2436, 2501), 'dagster._check.opt_str_param', 'check.opt_str_param', (['service_account_name', '"""service_account_name"""'], {}), "(service_account_name, 'service_account_name')\n", (2455, 2501), True, 'import dagster._check as check\n'), ((2531, 2587), 'dagster._check.opt_list_param', 'check.opt_list_param', (['env_config_maps', '"""env_config_maps"""'], {}), "(env_config_maps, 'env_config_maps')\n", (2551, 2587), True, 'import dagster._check as check\n'), ((2613, 2661), 'dagster._check.opt_list_param', 'check.opt_list_param', (['env_secrets', '"""env_secrets"""'], {}), "(env_secrets, 'env_secrets')\n", (2633, 2661), True, 'import dagster._check as check\n'), ((2684, 2726), 'dagster._check.opt_list_param', 'check.opt_list_param', (['env_vars', '"""env_vars"""'], {}), "(env_vars, 'env_vars')\n", (2704, 2726), True, 'import dagster._check as check\n'), ((3128, 3166), 'dagster._check.opt_dict_param', 'check.opt_dict_param', (['labels', '"""labels"""'], {}), "(labels, 'labels')\n", (3148, 3166), True, 'import dagster._check as check\n'), ((3190, 3233), 'dagster._check.opt_str_param', 'check.opt_str_param', (['namespace', '"""namespace"""'], {}), "(namespace, 'namespace')\n", (3209, 3233), True, 'import dagster._check as check\n'), ((3257, 3301), 'dagster._check.opt_dict_param', 'check.opt_dict_param', (['resources', '"""resources"""'], {}), "(resources, 'resources')\n", (3277, 3301), True, 'import dagster._check as check\n'), ((4391, 4429), 'dagster.utils.merge_dicts', 'merge_dicts', (['other.labels', 'self.labels'], {}), '(other.labels, self.labels)\n', (4402, 4429), False, 'from dagster.utils import make_readonly_value, merge_dicts\n'), ((2861, 2913), 'dagster._check.opt_list_param', 'check.opt_list_param', (['volume_mounts', '"""volume_mounts"""'], {}), "(volume_mounts, 'volume_mounts')\n", (2881, 2913), True, 'import dagster._check as check\n'), ((3053, 3093), 'dagster._check.opt_list_param', 'check.opt_list_param', (['volumes', '"""volumes"""'], {}), "(volumes, 'volumes')\n", (3073, 3093), True, 'import dagster._check as check\n')] |
import random
from src.datastruct.bin_treenode import TreeNode
import unittest
class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
num = random.randint(0, 1)
d = {
0: self.dfs,
1: self.postorder,
2: self.bfs,
}
return d[num](root, targetSum)
def bfs(self, root: TreeNode, targetSum: int) -> bool:
if root is None:
return False
stack = [(root, root.val)]
while len(stack) > 0:
node, path_sum = stack.pop()
if node.left is None and node.right is None and path_sum == targetSum:
return True
if node.right is not None:
stack.append((node.right, path_sum + node.right.val))
if node.left is not None:
stack.append((node.left, path_sum + node.left.val))
return False
def postorder(self, root: TreeNode, targetSum: int) -> bool:
node = root
stack = []
pre_node = None
path_sum = 0
while True:
while node is not None:
path_sum += node.val
stack.append(node)
node = node.left
if len(stack) <= 0:
break
if stack[-1].right != pre_node:
node = stack[-1].right
pre_node = None
else:
pre_node = stack.pop()
if pre_node.left is None and pre_node.right is None and path_sum == targetSum:
return True
path_sum -= pre_node.val
return False
def dfs(self, root: TreeNode, targetSum: int) -> bool:
def _dfs(node: TreeNode, path_sum: int) -> bool:
if node is None:
return False
if node.left is None and node.right is None:
return path_sum + node.val == targetSum
path_sum += node.val
return _dfs(node.left, path_sum) or _dfs(node.right, path_sum)
return _dfs(root, 0)
class TestSolution(unittest.TestCase):
def setUp(self):
self.test_case = [
([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1], 22, True),
([1, 2, 3], 5, False),
([], 1, False)
]
self.s = Solution()
def test_solution(self):
for nums, target, answer in self.test_case:
root = TreeNode.create(nums)
ans = self.s.hasPathSum(root, target)
self.assertEqual(answer, ans)
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"random.randint",
"src.datastruct.bin_treenode.TreeNode.create"
] | [((2575, 2590), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2588, 2590), False, 'import unittest\n'), ((177, 197), 'random.randint', 'random.randint', (['(0)', '(1)'], {}), '(0, 1)\n', (191, 197), False, 'import random\n'), ((2428, 2449), 'src.datastruct.bin_treenode.TreeNode.create', 'TreeNode.create', (['nums'], {}), '(nums)\n', (2443, 2449), False, 'from src.datastruct.bin_treenode import TreeNode\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "<NAME> <<EMAIL>>"
from setuptools import setup, find_packages
setup(
name='python-highcharts_df',
version='0.1.0',
description='python-highcharts_df wrapper for customizable pretty plotting quickly from pandas dataframes',
author="<NAME>",
author_email='<EMAIL>',
license='GNU',
packages=find_packages(),
zip_safe=False,
install_requires=[
"colour>=0.1.2",
"python-highcharts>=0.3.0"
],
dependency_links=[],
# include_package_data=True, # should work, but doesn't, I think pip does not recognize git automatically
package_data={
'data': ['*/*'],
}
)
| [
"setuptools.find_packages"
] | [((379, 394), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (392, 394), False, 'from setuptools import setup, find_packages\n')] |
from django.db import models
# Description of an object in the arena
class Entity(models.Model):
entityId = models.AutoField(primary_key=True)
entityClass = models.CharField(max_length=30)
entityName = models.CharField(max_length=30, null=True, blank=True)
entityCategory = models.CharField(max_length=30, null=True, blank=True)
entityColor = models.CharField(max_length=30, null=True, blank=True)
entityWeight = models.FloatField(default=None, null=True, blank=True)
entitySize = models.FloatField(default=None, null=True, blank=True)
entityIsRoom = models.BooleanField(default=False, blank=True)
entityIsWaypoint = models.BooleanField(default=False, blank=True)
entityIsContainer = models.BooleanField(default=False, blank=True)
entityGotPosition = models.BooleanField(default=False, blank=True)
# The position of the object in space if available
entityPosX = models.FloatField(default=None, null=True, blank=True)
entityPosY = models.FloatField(default=None, null=True, blank=True)
entityPosZ = models.FloatField(default=None, null=True, blank=True)
entityPosYaw = models.FloatField(default=None, null=True, blank=True)
entityPosPitch = models.FloatField(default=None, null=True, blank=True)
entityPosRoll = models.FloatField(default=None, null=True, blank=True)
# The position to reach to be able to catch the object
entityWaypointX = models.FloatField(default=None, null=True, blank=True)
entityWaypointY = models.FloatField(default=None, null=True, blank=True)
entityWaypointYaw = models.FloatField(default=None, null=True, blank=True)
# Just for serializer
depth_waypoint = models.IntegerField(null=True, blank=True)
depth_position = models.IntegerField(null=True, blank=True)
entityContainer = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True)
def __str__(self):
return self.entityClass + " - " + str(self.entityId)
# Description of an object in the arena
class People(models.Model):
peopleId = models.AutoField(primary_key=True)
peopleRecognitionId = models.IntegerField(null=True, blank=True, unique=True)
peopleName = models.CharField(max_length=30, null=True, blank=True)
peopleAge = models.IntegerField(null=True, blank=True)
peopleColor = models.CharField(max_length=30, null=True, blank=True)
peoplePose = models.CharField(max_length=30, null=True, blank=True)
peoplePoseAccuracy = models.FloatField(default=None, null=True, blank=True)
peopleEmotion = models.CharField(max_length=30, null=True, blank=True)
peopleEmotionAccuracy = models.FloatField(default=None, null=True, blank=True)
peopleGender = models.CharField(max_length=10, null=True, blank=True)
peopleGenderAccuracy = models.FloatField(default=None, null=True, blank=True)
peopleIsOperator = models.BooleanField(default=False)
def __str__(self):
return str(self.peopleId) + "(" + str(
self.peopleRecognitionId) + ") - " + self.peopleGender + " - " + self.peopleColor + " - " + self.peoplePose
| [
"django.db.models.FloatField",
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.CharField"
] | [((114, 148), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)'}), '(primary_key=True)\n', (130, 148), False, 'from django.db import models\n'), ((167, 198), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)'}), '(max_length=30)\n', (183, 198), False, 'from django.db import models\n'), ((216, 270), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'null': '(True)', 'blank': '(True)'}), '(max_length=30, null=True, blank=True)\n', (232, 270), False, 'from django.db import models\n'), ((292, 346), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'null': '(True)', 'blank': '(True)'}), '(max_length=30, null=True, blank=True)\n', (308, 346), False, 'from django.db import models\n'), ((365, 419), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'null': '(True)', 'blank': '(True)'}), '(max_length=30, null=True, blank=True)\n', (381, 419), False, 'from django.db import models\n'), ((439, 493), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (456, 493), False, 'from django.db import models\n'), ((511, 565), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (528, 565), False, 'from django.db import models\n'), ((586, 632), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'blank': '(True)'}), '(default=False, blank=True)\n', (605, 632), False, 'from django.db import models\n'), ((656, 702), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'blank': '(True)'}), '(default=False, blank=True)\n', (675, 702), False, 'from django.db import models\n'), ((727, 773), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'blank': '(True)'}), '(default=False, blank=True)\n', (746, 773), False, 'from django.db import models\n'), ((798, 844), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'blank': '(True)'}), '(default=False, blank=True)\n', (817, 844), False, 'from django.db import models\n'), ((918, 972), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (935, 972), False, 'from django.db import models\n'), ((990, 1044), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (1007, 1044), False, 'from django.db import models\n'), ((1062, 1116), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (1079, 1116), False, 'from django.db import models\n'), ((1136, 1190), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (1153, 1190), False, 'from django.db import models\n'), ((1212, 1266), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (1229, 1266), False, 'from django.db import models\n'), ((1287, 1341), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (1304, 1341), False, 'from django.db import models\n'), ((1424, 1478), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (1441, 1478), False, 'from django.db import models\n'), ((1501, 1555), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (1518, 1555), False, 'from django.db import models\n'), ((1580, 1634), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (1597, 1634), False, 'from django.db import models\n'), ((1683, 1725), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (1702, 1725), False, 'from django.db import models\n'), ((1747, 1789), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (1766, 1789), False, 'from django.db import models\n'), ((1813, 1888), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""self"""'], {'on_delete': 'models.SET_NULL', 'null': '(True)', 'blank': '(True)'}), "('self', on_delete=models.SET_NULL, null=True, blank=True)\n", (1830, 1888), False, 'from django.db import models\n'), ((2059, 2093), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)'}), '(primary_key=True)\n', (2075, 2093), False, 'from django.db import models\n'), ((2120, 2175), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(True)', 'blank': '(True)', 'unique': '(True)'}), '(null=True, blank=True, unique=True)\n', (2139, 2175), False, 'from django.db import models\n'), ((2194, 2248), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'null': '(True)', 'blank': '(True)'}), '(max_length=30, null=True, blank=True)\n', (2210, 2248), False, 'from django.db import models\n'), ((2265, 2307), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (2284, 2307), False, 'from django.db import models\n'), ((2327, 2381), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'null': '(True)', 'blank': '(True)'}), '(max_length=30, null=True, blank=True)\n', (2343, 2381), False, 'from django.db import models\n'), ((2400, 2454), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'null': '(True)', 'blank': '(True)'}), '(max_length=30, null=True, blank=True)\n', (2416, 2454), False, 'from django.db import models\n'), ((2480, 2534), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (2497, 2534), False, 'from django.db import models\n'), ((2556, 2610), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'null': '(True)', 'blank': '(True)'}), '(max_length=30, null=True, blank=True)\n', (2572, 2610), False, 'from django.db import models\n'), ((2639, 2693), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (2656, 2693), False, 'from django.db import models\n'), ((2714, 2768), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(10)', 'null': '(True)', 'blank': '(True)'}), '(max_length=10, null=True, blank=True)\n', (2730, 2768), False, 'from django.db import models\n'), ((2796, 2850), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': 'None', 'null': '(True)', 'blank': '(True)'}), '(default=None, null=True, blank=True)\n', (2813, 2850), False, 'from django.db import models\n'), ((2875, 2909), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (2894, 2909), False, 'from django.db import models\n')] |
import os
import psycopg2
DATABASE_URL = os.environ.get('DATABASE_URL')
def test_db():
conn = psycopg2.connect(DATABASE_URL)
cur = conn.cursor()
cur.execute("SELECT * FROM country;")
for country in cur:
print(country)
cur.close()
conn.close()
if __name__ == '__main__':
test_db()
| [
"psycopg2.connect",
"os.environ.get"
] | [((42, 72), 'os.environ.get', 'os.environ.get', (['"""DATABASE_URL"""'], {}), "('DATABASE_URL')\n", (56, 72), False, 'import os\n'), ((101, 131), 'psycopg2.connect', 'psycopg2.connect', (['DATABASE_URL'], {}), '(DATABASE_URL)\n', (117, 131), False, 'import psycopg2\n')] |
from requests_html import HTMLSession
from sys import argv
if len(argv) != 2:
print("Usage: python3 VanillaGift.py VanillaGift.txt")
else: # VanillaGift card balance checker
for card in reversed(list(open(argv[1]))):
cardNumber, expMonth, expYear, cvv = card.rstrip().split(':')
c = cardNumber + ' ' + expMonth + ' ' + expYear + ' ' + cvv
ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit" + \
"/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"
with HTMLSession() as s:
s.get('https://www.vanillagift.com/',
headers={'User-Agent': ua},
timeout=15) # get incapsula cookie, bypasses rate limiting waf?
x = s.post("https://www.vanillagift.com/loginCard",
headers={'User-Agent': ua},
data={
'cardNumber': cardNumber,
'expMonth': expMonth,
'expYear': expYear,
'cvv': cvv,
'origin': 'homeLogin' # this one isn't required...
}, # ...but may help to look more nonchalant...
timeout=15)
try:
b = x.html.find('div.SSaccountAmount', first=True).text
print(b, c)
except:
print("$.err", c) | [
"requests_html.HTMLSession"
] | [((496, 509), 'requests_html.HTMLSession', 'HTMLSession', ([], {}), '()\n', (507, 509), False, 'from requests_html import HTMLSession\n')] |
# -*- coding: utf-8 -*-
#
# Testing module for ACME's `ParallelMap` interface
#
# Builtin/3rd party package imports
from multiprocessing import Value
import os
import sys
import pickle
import shutil
import inspect
import subprocess
import getpass
import time
import itertools
import logging
from typing import Type
import h5py
import pytest
import signal as sys_signal
import numpy as np
import dask.distributed as dd
from glob import glob
from scipy import signal
# Import main actors here
from acme import ParallelMap, cluster_cleanup, esi_cluster_setup
from acme.shared import is_slurm_node
# Construct decorators for skipping certain tests
skip_in_win32 = pytest.mark.skipif(sys.platform == "win32", reason="Not running in Windows")
# Functions that act as stand-ins for user-funcs
def simple_func(x, y, z=3):
return (x + y) * z
def medium_func(x, y, z=3, w=np.ones((3, 3))):
return (sum(x) + y) * z * w.max()
def hard_func(x, y, z=3, w=np.zeros((3, 1)), **kwargs):
return sum(x) + y, z * w
def lowpass_simple(h5name, channel_no):
with h5py.File(h5name, "r") as h5f:
channel = h5f["data"][:, channel_no]
b = h5f["data"].attrs["b"]
a = h5f["data"].attrs["a"]
res = signal.filtfilt(b, a, channel, padlen=200)
return res
def lowpass_hard(arr_like, b, a, res_dir, res_base="lowpass_hard_", dset_name="custom_dset_name", padlen=200, taskID=None):
channel = arr_like[:, taskID]
res = signal.filtfilt(b, a, channel, padlen=padlen)
h5name = os.path.join(res_dir, res_base +"{}.h5".format(taskID))
with h5py.File(h5name, "w") as h5f:
h5f.create_dataset(dset_name, data=res)
return
def pickle_func(arr, b, a, channel_no, sabotage_hdf5=False):
res = signal.filtfilt(b, a, arr[:, channel_no], padlen=200)
if sabotage_hdf5:
if channel_no % 2 == 0:
return {"b" : b}
return res
# Perform SLURM-specific tests only on cluster nodes
useSLURM = is_slurm_node()
# Main testing class
class TestParallelMap():
# Construct linear combination of low- and high-frequency sine waves
# and use an IIR filter to reconstruct the low-frequency component
nChannels = 32
nTrials = 8
fData = 2
fNoise = 64
fs = 1000
t = np.linspace(-1, 1, fs)
orig = np.sin(2 * np.pi * fData * t)
sig = orig + np.sin(2 * np.pi * fNoise * t)
cutoff = 50
b, a = signal.butter(8, 2 * cutoff / fs)
# Blow up the signal to have "channels" and "trials": even/odd channels have
# opposing periodicity; do the same to the low-freq component
sig = np.repeat(sig.reshape(-1, 1), axis=1, repeats=nChannels)
sig[:, ::2] *= -1
sig = np.tile(sig, (nTrials, 1))
orig = np.repeat(orig.reshape(-1, 1), axis=1, repeats=nChannels)
orig[:, ::2] *= -1
orig = np.tile(orig, (nTrials, 1))
# Error tolerance for low-pass filtered results
tol = 1e-3
# Test setup of `ParallelMap` w/different functions args/kwargs
def test_init(self):
# Collected auto-generated output directories in list for later cleanup
outDirs = []
# Basic functionality w/simplest conceivable user-func
pmap = ParallelMap(simple_func, [2, 4, 6, 8], 4, setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
pmap = ParallelMap(simple_func, [2, 4, 6, 8], y=4, setup_interactive=False) # pos arg referenced via kwarg, cfg #2
outDirs.append(pmap.kwargv["outDir"][0])
pmap = ParallelMap(simple_func, 0, 4, z=[3, 4, 5, 6], setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
pmap = ParallelMap(simple_func, [2, 4, 6, 8], [2, 2], n_inputs=2, setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
# User func has `np.ndarray` as keyword
pmap = ParallelMap(medium_func, [2, 4, 6, 8], y=[2, 2], n_inputs=2, setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
pmap = ParallelMap(medium_func, None, None, w=[np.ones((3, 3)), 2 * np.ones((3,3))], setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
pmap = ParallelMap(medium_func, None, None, z=np.zeros((3,)), setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
pmap = ParallelMap(medium_func, None, None, z=np.zeros((3, 1)), setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
# Lots of ways for this to go wrong...
pmap = ParallelMap(hard_func, [2, 4, 6, 8], 2, w=np.ones((3,)), setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
pmap = ParallelMap(hard_func, [2, 4, 6, 8], y=22, w=np.ones((7, 1)), setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
pmap = ParallelMap(hard_func, np.ones((3,)), 1, w=np.ones((7, 1)), setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
pmap = ParallelMap(hard_func, [2, 4, 6, 8], [2, 2], z=np.array([1, 2]), w=np.ones((8, 1)), n_inputs=2, setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
pmap = ParallelMap(hard_func, [2, 4, 6, 8], [2, 2], w=np.ones((8, 1)), n_inputs=4, setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
# Ensure erroneous/ambiguous setups trigger the appropriate errors:
# not enough positional args
with pytest.raises(ValueError) as valerr:
ParallelMap(simple_func, 4, setup_interactive=False)
assert "simple_func expects 2 positional arguments ('x', 'y'), found 1" in str(valerr.value)
# invalid kwargs
with pytest.raises(ValueError) as valerr:
ParallelMap(simple_func, 4, 4, z=3, w=4, setup_interactive=False)
assert "simple_func accepts at maximum 1 keyword arguments ('z'), found 2" in str(valerr.value)
# ill-posed parallelization: two candidate lists for input distribution
with pytest.raises(ValueError) as valerr:
ParallelMap(simple_func, [2, 4, 6, 8], [2, 2], setup_interactive=False)
assert "automatic input distribution failed: found 2 objects containing 2 to 4 elements" in str(valerr.value)
# ill-posed parallelization: two candidate lists for input distribution (`x` and `w`)
with pytest.raises(ValueError) as valerr:
ParallelMap(medium_func, [1, 2, 3], None, w=[np.ones((3,3)), 2 * np.ones((3,3))], setup_interactive=False)
assert "automatic input distribution failed: found 2 objects containing 2 to 3 elements." in str(valerr.value)
# invalid input spec
with pytest.raises(ValueError) as valerr:
ParallelMap(simple_func, [2, 4, 6, 8], [2, 2], n_inputs=3, setup_interactive=False)
assert "No object has required length of 3 matching `n_inputs`" in str(valerr.value)
# invalid input spec: `w` expects a NumPy array, thus it is not considered for input distribution
with pytest.raises(ValueError) as valerr:
ParallelMap(hard_func, [2, 4, 6, 8], [2, 2], w=np.ones((8, 1)), n_inputs=8, setup_interactive=False)
assert "No object has required length of 8 matching `n_inputs`" in str(valerr.value)
# Clean up testing folder and any running clients
cluster_cleanup()
for folder in outDirs:
shutil.rmtree(folder, ignore_errors=True)
# Functionality tests: perform channel-concurrent low-pass filtering
def test_filter_example(self):
# If called by `test_existing_cluster` use pre-allocated client for all computations
try:
dd.get_client()
existingClient = True
except ValueError:
existingClient = False
# Create tmp directory and create data-containers
tempDir = os.path.join(os.path.abspath(os.path.expanduser("~")), "acme_tmp")
if useSLURM:
tempDir = "/cs/home/{}/acme_tmp".format(getpass.getuser())
os.makedirs(tempDir, exist_ok=True)
sigName = os.path.join(tempDir, "sigdata.h5")
origName = os.path.join(tempDir, "origdata.h5")
with h5py.File(sigName, "w") as sigFile:
dset = sigFile.create_dataset("data", data=self.sig)
dset.attrs["b"] = self.b
dset.attrs["a"] = self.a
with h5py.File(origName, "w") as origFile:
origFile.create_dataset("data", data=self.orig)
# Collected auto-generated output directories in list for later cleanup
outDirs = []
# Parallelize across channels, write results to disk
with ParallelMap(lowpass_simple, sigName, range(self.nChannels), setup_interactive=False) as pmap:
resOnDisk = pmap.compute()
outDirs.append(pmap.kwargv["outDir"][0])
assert len(pmap.kwargv["outFile"]) == pmap.n_calls
resFiles = [os.path.join(pmap.kwargv["outDir"][0], outFile) for outFile in pmap.kwargv["outFile"]]
assert resOnDisk == resFiles
assert all(os.path.isfile(fle) for fle in resOnDisk)
# Compare computed single-channel results to expected low-freq signal
for chNo, h5name in enumerate(resOnDisk):
with h5py.File(h5name, "r") as h5f:
assert np.mean(np.abs(h5f["result_0"][()] - self.orig[:, chNo])) < self.tol
# Same, but collect results in memory: ensure nothing freaky happens
with ParallelMap(lowpass_simple,
sigName,
range(self.nChannels),
write_worker_results=False,
setup_interactive=False) as pmap:
resInMem = pmap.compute()
for chNo in range(self.nChannels):
assert np.mean(np.abs(resInMem[chNo] - self.orig[:, chNo])) < self.tol
# Be double-paranoid: ensure on-disk and in-memory results match up
for chNo, h5name in enumerate(resOnDisk):
with h5py.File(h5name, "r") as h5f:
assert np.array_equal(h5f["result_0"][()], resInMem[chNo])
# Simulate user-defined results-directory
tempDir2 = os.path.join(os.path.abspath(os.path.expanduser("~")), "acme_tmp_lowpass_hard")
if useSLURM:
tempDir2 = "/cs/home/{}/acme_tmp_lowpass_hard".format(getpass.getuser())
shutil.rmtree(tempDir2, ignore_errors=True)
os.makedirs(tempDir2, exist_ok=True)
# Same task, different function: simulate user-defined saving scheme and "weird" inputs
sigData = h5py.File(sigName, "r")["data"]
res_base = "lowpass_hard_"
dset_name = "custom_dset_name"
with ParallelMap(lowpass_hard,
sigData,
self.b,
self.a,
res_dir=tempDir2,
res_base=res_base,
dset_name=dset_name,
padlen=[200] * self.nChannels,
n_inputs=self.nChannels,
write_worker_results=False,
setup_interactive=False) as pmap:
pmap.compute()
resFiles = glob(os.path.join(tempDir2, res_base + "*"))
assert len(resFiles) == pmap.n_calls
# Compare computed single-channel results to expected low-freq signal
for chNo in range(self.nChannels):
h5name = res_base + "{}.h5".format(chNo)
with h5py.File(os.path.join(tempDir2, h5name), "r") as h5f:
assert np.mean(np.abs(h5f[dset_name][()] - self.orig[:, chNo])) < self.tol
# Ensure log-file generation produces a non-empty log-file at the expected location
# Bonus: leave computing client alive and vet default SLURM settings
if not existingClient:
cluster_cleanup(pmap.client)
for handler in pmap.log.handlers:
if isinstance(handler, logging.FileHandler):
pmap.log.handlers.remove(handler)
with ParallelMap(lowpass_simple,
sigName,
range(self.nChannels),
logfile=True,
stop_client=False,
setup_interactive=False) as pmap:
pmap.compute()
outDirs.append(pmap.kwargv["outDir"][0])
logFileList = [handler.baseFilename for handler in pmap.log.handlers if isinstance(handler, logging.FileHandler)]
assert len(logFileList) == 1
logFile = logFileList[0]
assert os.path.dirname(os.path.realpath(__file__)) in logFile
with open(logFile, "r") as fl:
assert len(fl.readlines()) > 1
# Ensure client has not been killed; perform post-hoc check of default SLURM settings
assert dd.get_client()
client = dd.get_client()
if useSLURM and not existingClient:
assert pmap.n_calls == pmap.n_jobs
assert len(client.cluster.workers) == pmap.n_jobs
partition = client.cluster.job_header.split("-p ")[1].split("\n")[0]
assert "8GB" in partition
memory = np.unique([w["memory_limit"] for w in client.cluster.scheduler_info["workers"].values()])
assert memory.size == 1
assert round(memory[0] / 1000**3) == [int(s) for s in partition if s.isdigit()][0]
# Same, but use custom log-file
for handler in pmap.log.handlers:
if isinstance(handler, logging.FileHandler):
pmap.log.handlers.remove(handler)
customLog = os.path.join(tempDir, "acme_log.txt")
with ParallelMap(lowpass_simple,
sigName,
range(self.nChannels),
logfile=customLog,
verbose=True,
stop_client=True,
setup_interactive=False) as pmap:
pmap.compute()
outDirs.append(pmap.kwargv["outDir"][0])
assert os.path.isfile(customLog)
with open(customLog, "r") as fl:
assert len(fl.readlines()) > 1
# Ensure client has been stopped
with pytest.raises(ValueError):
dd.get_client()
# Underbook SLURM (more calls than jobs)
partition = "8GBXS"
n_jobs = int(self.nChannels / 2)
mem_per_job = "2GB"
with ParallelMap(lowpass_simple,
sigName,
range(self.nChannels),
partition=partition,
n_jobs=n_jobs,
mem_per_job=mem_per_job,
stop_client=False,
setup_interactive=False) as pmap:
pmap.compute()
outDirs.append(pmap.kwargv["outDir"][0])
# Post-hoc check of client to ensure custom settings were respected
client = pmap.client
assert pmap.n_calls == self.nChannels
if useSLURM:
assert pmap.n_jobs == n_jobs
assert len(client.cluster.workers) == pmap.n_jobs
actualPartition = client.cluster.job_header.split("-p ")[1].split("\n")[0]
assert actualPartition == partition
memory = np.unique([w["memory_limit"] for w in client.cluster.scheduler_info["workers"].values()])
assert memory.size == 1
assert round(memory[0] / 1000**3) == int(mem_per_job.replace("GB", ""))
# Let `cluster_cleanup` murder the custom setup and ensure it did its job
if not existingClient:
cluster_cleanup(pmap.client)
with pytest.raises(ValueError):
dd.get_client()
# Overbook SLURM (more jobs than calls)
partition = "8GBXS"
n_jobs = self.nChannels + 2
mem_per_job = "3000MB"
with ParallelMap(lowpass_simple,
sigName,
range(self.nChannels),
partition=partition,
n_jobs=n_jobs,
mem_per_job=mem_per_job,
stop_client=False,
setup_interactive=False) as pmap:
pmap.compute()
outDirs.append(pmap.kwargv["outDir"][0])
# Post-hoc check of client to ensure custom settings were respected
client = pmap.client
assert pmap.n_calls == self.nChannels
if useSLURM:
assert pmap.n_jobs == n_jobs
assert len(client.cluster.workers) == pmap.n_jobs
actualPartition = client.cluster.job_header.split("-p ")[1].split("\n")[0]
assert actualPartition == partition
memory = np.unique([w["memory_limit"] for w in client.cluster.scheduler_info["workers"].values()])
assert memory.size == 1
assert round(memory[0] / 1000**3) * 1000 == int(mem_per_job.replace("MB", ""))
if not existingClient:
cluster_cleanup(pmap.client)
# Close any open HDF5 files to not trigger any `OSError`s, close running clusters
# and clean up tmp dirs and created directories/log-files
sigData.file.close()
try:
os.unlink(logFile)
except PermissionError:
pass
shutil.rmtree(tempDir, ignore_errors=True)
shutil.rmtree(tempDir2, ignore_errors=True)
for folder in outDirs:
shutil.rmtree(folder, ignore_errors=True)
# Wait a second (literally) so that no new parallel jobs started by
# `test_existing_cluster` erroneously use existing HDF files
time.sleep(1.0)
# Test if pickling/emergency pickling and I/O in general works as intended
def test_pickling(self):
# Collected auto-generated output directories in list for later cleanup
outDirs = []
# Execute `pickle_func` w/regular HDF5 saving
with ParallelMap(pickle_func,
self.sig,
self.b,
self.a,
range(self.nChannels),
sabotage_hdf5=False,
n_inputs=self.nChannels,
setup_interactive=False) as pmap:
hdfResults = pmap.compute()
outDirs.append(pmap.kwargv["outDir"][0])
# Execute `pickle_func` w/pickling
with ParallelMap(pickle_func,
self.sig,
self.b,
self.a,
range(self.nChannels),
n_inputs=self.nChannels,
write_pickle=True,
setup_interactive=False) as pmap:
pklResults = pmap.compute()
outDirs.append(pmap.kwargv["outDir"][0])
# Ensure HDF5 and pickle match up
for chNo, h5name in enumerate(hdfResults):
with open(pklResults[chNo], "rb") as pkf:
pklRes = pickle.load(pkf)
with h5py.File(h5name, "r") as h5f:
assert np.array_equal(pklRes, h5f["result_0"][()])
# Test emergency pickling
with ParallelMap(pickle_func,
self.sig,
self.b,
self.a,
range(self.nChannels),
sabotage_hdf5=True,
n_inputs=self.nChannels,
setup_interactive=False) as pmap:
mixedResults = pmap.compute()
outDirs.append(pmap.kwargv["outDir"][0])
# Ensure non-compliant dicts were pickled, rest is in HDF5
for chNo, fname in enumerate(mixedResults):
if chNo % 2 == 0:
assert fname.endswith(".pickle")
with open(fname, "rb") as pkf:
assert np.array_equal(self.b, pickle.load(pkf)["b"])
else:
assert fname.endswith(".h5")
with h5py.File(fname, "r") as h5f:
with h5py.File(hdfResults[chNo], "r") as h5ref:
assert np.array_equal(h5f["result_0"][()], h5ref["result_0"][()])
# Test write breakdown (both for HDF5 saving and pickling)
pmap = ParallelMap(pickle_func,
self.sig,
self.b,
self.a,
range(self.nChannels),
sabotage_hdf5=True,
n_inputs=self.nChannels,
setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
pmap.kwargv["outDir"][0] = "/path/to/nowhere"
with pytest.raises(RuntimeError) as runerr:
pmap.compute()
assert "<ACMEdaemon> Parallel computation failed" in str(runerr.value)
pmap = ParallelMap(pickle_func,
self.sig,
self.b,
self.a,
range(self.nChannels),
sabotage_hdf5=True,
n_inputs=self.nChannels,
write_pickle=True,
setup_interactive=False)
outDirs.append(pmap.kwargv["outDir"][0])
pmap.kwargv["outDir"][0] = "/path/to/nowhere"
with pytest.raises(RuntimeError) as runerr:
pmap.compute()
assert "<ACMEdaemon> Parallel computation failed" in str(runerr.value)
# Clean up testing folder
for folder in outDirs:
shutil.rmtree(folder, ignore_errors=True)
# test if KeyboardInterrupts are handled correctly
@skip_in_win32
def test_cancel(self):
# Setup temp-directory layout for subprocess-scripts and prepare interpreters
tempDir = os.path.join(os.path.abspath(os.path.expanduser("~")), "acme_tmp")
os.makedirs(tempDir, exist_ok=True)
pshells = [os.path.join(os.path.split(sys.executable)[0], pyExec) for pyExec in ["python", "ipython"]]
# Prepare ad-hoc script for execution in new process
scriptName = os.path.join(tempDir, "dummy.py")
scriptContents = \
"from acme import ParallelMap\n" +\
"import time\n" +\
"def long_running(dummy):\n" +\
" time.sleep(10)\n" +\
" return\n" +\
"if __name__ == '__main__':\n" +\
" with ParallelMap(long_running, [None]*2, setup_interactive=False, write_worker_results=False) as pmap: \n" +\
" pmap.compute()\n" +\
" print('ALL DONE')\n"
with open(scriptName, "w") as f:
f.write(scriptContents)
# Execute the above script both in Python and iPython to ensure global functionality
for pshell in pshells:
# Launch new process in background (`stdbuf` prevents buffering of stdout)
proc = subprocess.Popen("stdbuf -o0 " + pshell + " " + scriptName,
shell=True, start_new_session=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0)
# Wait for ACME to start up (as soon as logging info is shown, `pmap.compute()` is running)
# However: don't wait indefinitely - if `pmap.compute` is not started within 30s, abort
logStr = "<ParallelMap> INFO: Log information available at"
buffer = bytearray()
timeout = 30
t0 = time.time()
for line in itertools.takewhile(lambda x: time.time() - t0 < timeout, iter(proc.stdout.readline, b"")):
buffer.extend(line)
if logStr in line.decode("utf8"):
break
assert logStr in buffer.decode("utf8")
# Wait a bit, then simulate CTRL+C in sub-process; make sure the above
# impromptu script did not run to completion *but* the created client was
# shut down with CTRL + C
time.sleep(2)
os.killpg(proc.pid, sys_signal.SIGINT)
time.sleep(1)
out = proc.stdout.read().decode()
assert "ALL DONE" not in out
assert "INFO: <cluster_cleanup> Successfully shut down" in out
# Almost identical script, this time use an externally started client
scriptName = os.path.join(tempDir, "dummy2.py")
scriptContents = \
"from acme import ParallelMap, esi_cluster_setup\n" +\
"import time\n" +\
"def long_running(dummy):\n" +\
" time.sleep(10)\n" +\
" return\n" +\
"if __name__ == '__main__':\n" +\
" client = esi_cluster_setup(partition='8GBDEV',n_jobs=1, interactive=False)\n" +\
" with ParallelMap(long_running, [None]*2, setup_interactive=False, write_worker_results=False) as pmap: \n" +\
" pmap.compute()\n" +\
" print('ALL DONE')\n"
with open(scriptName, "w") as f:
f.write(scriptContents)
# Test script functionality in both Python and iPython
for pshell in pshells:
proc = subprocess.Popen("stdbuf -o0 " + sys.executable + " " + scriptName,
shell=True, start_new_session=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0)
logStr = "<ParallelMap> INFO: Log information available at"
buffer = bytearray()
timeout = 30
t0 = time.time()
for line in itertools.takewhile(lambda x: time.time() - t0 < timeout, iter(proc.stdout.readline, b"")):
buffer.extend(line)
if logStr in line.decode("utf8"):
break
assert logStr in buffer.decode("utf8")
time.sleep(2)
os.killpg(proc.pid, sys_signal.SIGINT)
time.sleep(2)
out = proc.stdout.read().decode()
assert "ALL DONE" not in out
assert "<ParallelMap> INFO: <ACME> CTRL + C acknowledged, client and workers successfully killed" in out
# Ensure random exception does not immediately kill an active client
scriptName = os.path.join(tempDir, "dummy3.py")
scriptContents = \
"from acme import esi_cluster_setup\n" +\
"import time\n" +\
"if __name__ == '__main__':\n" +\
" esi_cluster_setup(partition='8GBDEV',n_jobs=1, interactive=False)\n" +\
" time.sleep(60)\n"
with open(scriptName, "w") as f:
f.write(scriptContents)
proc = subprocess.Popen("stdbuf -o0 " + sys.executable + " " + scriptName,
shell=True, start_new_session=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0)
# Give the client time to start up, then send a floating-point exception
# (equivalent to a `ZeroDivsionError` to the child process)
time.sleep(5)
assert proc.poll() is None
proc.send_signal(sys_signal.SIGFPE)
# Ensure the `ZeroDivsionError` did not kill the process. Then terminate it
# and confirm that the floating-exception was propagated correctly
assert proc.poll() is None
proc.terminate()
proc.wait()
assert proc.returncode in [-sys_signal.SIGFPE.value, -sys_signal.SIGTERM.value]
# Clean up tmp folder
shutil.rmtree(tempDir, ignore_errors=True)
# test esi-cluster-setup called separately before pmap
def test_existing_cluster(self):
# Test custom SLURM cluster setup
if useSLURM:
# Ensure invalid partition/memory specifications are caught
with pytest.raises(ValueError):
esi_cluster_setup(partition="invalid", interactive=False)
cluster_cleanup()
with pytest.raises(ValueError):
esi_cluster_setup(mem_per_job="invalidGB", interactive=False)
cluster_cleanup()
with pytest.raises(ValueError):
esi_cluster_setup(mem_per_job="-20MB", interactive=False)
cluster_cleanup()
# Over-allocation of memory should default to partition max
client = esi_cluster_setup(partition="8GBDEV", n_jobs=1, mem_per_job="9000MB", interactive=False)
memory = np.unique([w["memory_limit"] for w in client.cluster.scheduler_info["workers"].values()])
assert memory.size == 1
assert np.round(memory / 1000**3)[0] == 8
cluster_cleanup(client)
# Test if invalid extra args are caught
slurmOut = "/cs/home/{}/acme_out".format(getpass.getuser())
with pytest.raises(TypeError):
esi_cluster_setup(job_extra="--output={}".format(slurmOut), interactive=False)
cluster_cleanup()
with pytest.raises(ValueError):
esi_cluster_setup(job_extra=["output={}".format(slurmOut)], interactive=False)
cluster_cleanup()
with pytest.raises(ValueError):
esi_cluster_setup(job_extra=["--output=/path/to/nowhere"], interactive=False)
cluster_cleanup()
# Supply extra args to start client for actual tests
client = esi_cluster_setup(partition="8GBXS", job_extra=["--output={}".format(slurmOut)], interactive=False)
assert "--output={}".format(slurmOut) in client.cluster.job_header
else:
client = esi_cluster_setup(n_jobs=6, interactive=False)
# Re-run tests with pre-allocated client (except for `test_cancel`)
skipTests = ["test_existing_cluster", "test_cancel"]
all_tests = [attr for attr in self.__dir__()
if (inspect.ismethod(getattr(self, attr)) and attr not in skipTests)]
for test in all_tests:
getattr(self, test)()
client.close()
client.cluster.close()
if useSLURM:
shutil.rmtree(slurmOut, ignore_errors=True)
| [
"acme.esi_cluster_setup",
"scipy.signal.filtfilt",
"acme.cluster_cleanup",
"time.sleep",
"numpy.array",
"numpy.sin",
"getpass.getuser",
"acme.shared.is_slurm_node",
"subprocess.Popen",
"os.path.split",
"numpy.linspace",
"os.unlink",
"pytest.mark.skipif",
"os.path.expanduser",
"numpy.roun... | [((663, 739), 'pytest.mark.skipif', 'pytest.mark.skipif', (["(sys.platform == 'win32')"], {'reason': '"""Not running in Windows"""'}), "(sys.platform == 'win32', reason='Not running in Windows')\n", (681, 739), False, 'import pytest\n'), ((1951, 1966), 'acme.shared.is_slurm_node', 'is_slurm_node', ([], {}), '()\n', (1964, 1966), False, 'from acme.shared import is_slurm_node\n'), ((871, 886), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (878, 886), True, 'import numpy as np\n'), ((955, 971), 'numpy.zeros', 'np.zeros', (['(3, 1)'], {}), '((3, 1))\n', (963, 971), True, 'import numpy as np\n'), ((1220, 1262), 'scipy.signal.filtfilt', 'signal.filtfilt', (['b', 'a', 'channel'], {'padlen': '(200)'}), '(b, a, channel, padlen=200)\n', (1235, 1262), False, 'from scipy import signal\n'), ((1447, 1492), 'scipy.signal.filtfilt', 'signal.filtfilt', (['b', 'a', 'channel'], {'padlen': 'padlen'}), '(b, a, channel, padlen=padlen)\n', (1462, 1492), False, 'from scipy import signal\n'), ((1733, 1786), 'scipy.signal.filtfilt', 'signal.filtfilt', (['b', 'a', 'arr[:, channel_no]'], {'padlen': '(200)'}), '(b, a, arr[:, channel_no], padlen=200)\n', (1748, 1786), False, 'from scipy import signal\n'), ((2246, 2268), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'fs'], {}), '(-1, 1, fs)\n', (2257, 2268), True, 'import numpy as np\n'), ((2280, 2309), 'numpy.sin', 'np.sin', (['(2 * np.pi * fData * t)'], {}), '(2 * np.pi * fData * t)\n', (2286, 2309), True, 'import numpy as np\n'), ((2385, 2418), 'scipy.signal.butter', 'signal.butter', (['(8)', '(2 * cutoff / fs)'], {}), '(8, 2 * cutoff / fs)\n', (2398, 2418), False, 'from scipy import signal\n'), ((2666, 2692), 'numpy.tile', 'np.tile', (['sig', '(nTrials, 1)'], {}), '(sig, (nTrials, 1))\n', (2673, 2692), True, 'import numpy as np\n'), ((2796, 2823), 'numpy.tile', 'np.tile', (['orig', '(nTrials, 1)'], {}), '(orig, (nTrials, 1))\n', (2803, 2823), True, 'import numpy as np\n'), ((1064, 1086), 'h5py.File', 'h5py.File', (['h5name', '"""r"""'], {}), "(h5name, 'r')\n", (1073, 1086), False, 'import h5py\n'), ((1571, 1593), 'h5py.File', 'h5py.File', (['h5name', '"""w"""'], {}), "(h5name, 'w')\n", (1580, 1593), False, 'import h5py\n'), ((2327, 2357), 'numpy.sin', 'np.sin', (['(2 * np.pi * fNoise * t)'], {}), '(2 * np.pi * fNoise * t)\n', (2333, 2357), True, 'import numpy as np\n'), ((3167, 3233), 'acme.ParallelMap', 'ParallelMap', (['simple_func', '[2, 4, 6, 8]', '(4)'], {'setup_interactive': '(False)'}), '(simple_func, [2, 4, 6, 8], 4, setup_interactive=False)\n', (3178, 3233), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((3298, 3366), 'acme.ParallelMap', 'ParallelMap', (['simple_func', '[2, 4, 6, 8]'], {'y': '(4)', 'setup_interactive': '(False)'}), '(simple_func, [2, 4, 6, 8], y=4, setup_interactive=False)\n', (3309, 3366), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((3471, 3542), 'acme.ParallelMap', 'ParallelMap', (['simple_func', '(0)', '(4)'], {'z': '[3, 4, 5, 6]', 'setup_interactive': '(False)'}), '(simple_func, 0, 4, z=[3, 4, 5, 6], setup_interactive=False)\n', (3482, 3542), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((3607, 3694), 'acme.ParallelMap', 'ParallelMap', (['simple_func', '[2, 4, 6, 8]', '[2, 2]'], {'n_inputs': '(2)', 'setup_interactive': '(False)'}), '(simple_func, [2, 4, 6, 8], [2, 2], n_inputs=2,\n setup_interactive=False)\n', (3618, 3694), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((3804, 3893), 'acme.ParallelMap', 'ParallelMap', (['medium_func', '[2, 4, 6, 8]'], {'y': '[2, 2]', 'n_inputs': '(2)', 'setup_interactive': '(False)'}), '(medium_func, [2, 4, 6, 8], y=[2, 2], n_inputs=2,\n setup_interactive=False)\n', (3815, 3893), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((7262, 7279), 'acme.cluster_cleanup', 'cluster_cleanup', ([], {}), '()\n', (7277, 7279), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((7949, 7984), 'os.makedirs', 'os.makedirs', (['tempDir'], {'exist_ok': '(True)'}), '(tempDir, exist_ok=True)\n', (7960, 7984), False, 'import os\n'), ((8003, 8038), 'os.path.join', 'os.path.join', (['tempDir', '"""sigdata.h5"""'], {}), "(tempDir, 'sigdata.h5')\n", (8015, 8038), False, 'import os\n'), ((8058, 8094), 'os.path.join', 'os.path.join', (['tempDir', '"""origdata.h5"""'], {}), "(tempDir, 'origdata.h5')\n", (8070, 8094), False, 'import os\n'), ((10277, 10320), 'shutil.rmtree', 'shutil.rmtree', (['tempDir2'], {'ignore_errors': '(True)'}), '(tempDir2, ignore_errors=True)\n', (10290, 10320), False, 'import shutil\n'), ((10329, 10365), 'os.makedirs', 'os.makedirs', (['tempDir2'], {'exist_ok': '(True)'}), '(tempDir2, exist_ok=True)\n', (10340, 10365), False, 'import os\n'), ((12737, 12752), 'dask.distributed.get_client', 'dd.get_client', ([], {}), '()\n', (12750, 12752), True, 'import dask.distributed as dd\n'), ((12770, 12785), 'dask.distributed.get_client', 'dd.get_client', ([], {}), '()\n', (12783, 12785), True, 'import dask.distributed as dd\n'), ((13510, 13547), 'os.path.join', 'os.path.join', (['tempDir', '"""acme_log.txt"""'], {}), "(tempDir, 'acme_log.txt')\n", (13522, 13547), False, 'import os\n'), ((13947, 13972), 'os.path.isfile', 'os.path.isfile', (['customLog'], {}), '(customLog)\n', (13961, 13972), False, 'import os\n'), ((17215, 17257), 'shutil.rmtree', 'shutil.rmtree', (['tempDir'], {'ignore_errors': '(True)'}), '(tempDir, ignore_errors=True)\n', (17228, 17257), False, 'import shutil\n'), ((17266, 17309), 'shutil.rmtree', 'shutil.rmtree', (['tempDir2'], {'ignore_errors': '(True)'}), '(tempDir2, ignore_errors=True)\n', (17279, 17309), False, 'import shutil\n'), ((17549, 17564), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (17559, 17564), False, 'import time\n'), ((21840, 21875), 'os.makedirs', 'os.makedirs', (['tempDir'], {'exist_ok': '(True)'}), '(tempDir, exist_ok=True)\n', (21851, 21875), False, 'import os\n'), ((22070, 22103), 'os.path.join', 'os.path.join', (['tempDir', '"""dummy.py"""'], {}), "(tempDir, 'dummy.py')\n", (22082, 22103), False, 'import os\n'), ((24324, 24358), 'os.path.join', 'os.path.join', (['tempDir', '"""dummy2.py"""'], {}), "(tempDir, 'dummy2.py')\n", (24336, 24358), False, 'import os\n'), ((26213, 26247), 'os.path.join', 'os.path.join', (['tempDir', '"""dummy3.py"""'], {}), "(tempDir, 'dummy3.py')\n", (26225, 26247), False, 'import os\n'), ((26620, 26794), 'subprocess.Popen', 'subprocess.Popen', (["('stdbuf -o0 ' + sys.executable + ' ' + scriptName)"], {'shell': '(True)', 'start_new_session': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT', 'bufsize': '(0)'}), "('stdbuf -o0 ' + sys.executable + ' ' + scriptName, shell=\n True, start_new_session=True, stdout=subprocess.PIPE, stderr=subprocess\n .STDOUT, bufsize=0)\n", (26636, 26794), False, 'import subprocess\n'), ((27007, 27020), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (27017, 27020), False, 'import time\n'), ((27467, 27509), 'shutil.rmtree', 'shutil.rmtree', (['tempDir'], {'ignore_errors': '(True)'}), '(tempDir, ignore_errors=True)\n', (27480, 27509), False, 'import shutil\n'), ((4779, 4792), 'numpy.ones', 'np.ones', (['(3,)'], {}), '((3,))\n', (4786, 4792), True, 'import numpy as np\n'), ((5367, 5392), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5380, 5392), False, 'import pytest\n'), ((5416, 5468), 'acme.ParallelMap', 'ParallelMap', (['simple_func', '(4)'], {'setup_interactive': '(False)'}), '(simple_func, 4, setup_interactive=False)\n', (5427, 5468), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((5612, 5637), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5625, 5637), False, 'import pytest\n'), ((5661, 5726), 'acme.ParallelMap', 'ParallelMap', (['simple_func', '(4)', '(4)'], {'z': '(3)', 'w': '(4)', 'setup_interactive': '(False)'}), '(simple_func, 4, 4, z=3, w=4, setup_interactive=False)\n', (5672, 5726), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((5928, 5953), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5941, 5953), False, 'import pytest\n'), ((5977, 6048), 'acme.ParallelMap', 'ParallelMap', (['simple_func', '[2, 4, 6, 8]', '[2, 2]'], {'setup_interactive': '(False)'}), '(simple_func, [2, 4, 6, 8], [2, 2], setup_interactive=False)\n', (5988, 6048), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((6278, 6303), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (6291, 6303), False, 'import pytest\n'), ((6599, 6624), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (6612, 6624), False, 'import pytest\n'), ((6648, 6735), 'acme.ParallelMap', 'ParallelMap', (['simple_func', '[2, 4, 6, 8]', '[2, 2]'], {'n_inputs': '(3)', 'setup_interactive': '(False)'}), '(simple_func, [2, 4, 6, 8], [2, 2], n_inputs=3,\n setup_interactive=False)\n', (6659, 6735), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((6948, 6973), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (6961, 6973), False, 'import pytest\n'), ((7323, 7364), 'shutil.rmtree', 'shutil.rmtree', (['folder'], {'ignore_errors': '(True)'}), '(folder, ignore_errors=True)\n', (7336, 7364), False, 'import shutil\n'), ((7593, 7608), 'dask.distributed.get_client', 'dd.get_client', ([], {}), '()\n', (7606, 7608), True, 'import dask.distributed as dd\n'), ((8108, 8131), 'h5py.File', 'h5py.File', (['sigName', '"""w"""'], {}), "(sigName, 'w')\n", (8117, 8131), False, 'import h5py\n'), ((8296, 8320), 'h5py.File', 'h5py.File', (['origName', '"""w"""'], {}), "(origName, 'w')\n", (8305, 8320), False, 'import h5py\n'), ((8832, 8879), 'os.path.join', 'os.path.join', (["pmap.kwargv['outDir'][0]", 'outFile'], {}), "(pmap.kwargv['outDir'][0], outFile)\n", (8844, 8879), False, 'import os\n'), ((10481, 10504), 'h5py.File', 'h5py.File', (['sigName', '"""r"""'], {}), "(sigName, 'r')\n", (10490, 10504), False, 'import h5py\n'), ((10600, 10830), 'acme.ParallelMap', 'ParallelMap', (['lowpass_hard', 'sigData', 'self.b', 'self.a'], {'res_dir': 'tempDir2', 'res_base': 'res_base', 'dset_name': 'dset_name', 'padlen': '([200] * self.nChannels)', 'n_inputs': 'self.nChannels', 'write_worker_results': '(False)', 'setup_interactive': '(False)'}), '(lowpass_hard, sigData, self.b, self.a, res_dir=tempDir2,\n res_base=res_base, dset_name=dset_name, padlen=[200] * self.nChannels,\n n_inputs=self.nChannels, write_worker_results=False, setup_interactive=\n False)\n', (10611, 10830), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((11128, 11166), 'os.path.join', 'os.path.join', (['tempDir2', "(res_base + '*')"], {}), "(tempDir2, res_base + '*')\n", (11140, 11166), False, 'import os\n'), ((11764, 11792), 'acme.cluster_cleanup', 'cluster_cleanup', (['pmap.client'], {}), '(pmap.client)\n', (11779, 11792), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((14112, 14137), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (14125, 14137), False, 'import pytest\n'), ((14151, 14166), 'dask.distributed.get_client', 'dd.get_client', ([], {}), '()\n', (14164, 14166), True, 'import dask.distributed as dd\n'), ((15520, 15548), 'acme.cluster_cleanup', 'cluster_cleanup', (['pmap.client'], {}), '(pmap.client)\n', (15535, 15548), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((16899, 16927), 'acme.cluster_cleanup', 'cluster_cleanup', (['pmap.client'], {}), '(pmap.client)\n', (16914, 16927), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((17139, 17157), 'os.unlink', 'os.unlink', (['logFile'], {}), '(logFile)\n', (17148, 17157), False, 'import os\n'), ((17353, 17394), 'shutil.rmtree', 'shutil.rmtree', (['folder'], {'ignore_errors': '(True)'}), '(folder, ignore_errors=True)\n', (17366, 17394), False, 'import shutil\n'), ((20630, 20657), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (20643, 20657), False, 'import pytest\n'), ((21289, 21316), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (21302, 21316), False, 'import pytest\n'), ((21516, 21557), 'shutil.rmtree', 'shutil.rmtree', (['folder'], {'ignore_errors': '(True)'}), '(folder, ignore_errors=True)\n', (21529, 21557), False, 'import shutil\n'), ((22879, 23044), 'subprocess.Popen', 'subprocess.Popen', (["('stdbuf -o0 ' + pshell + ' ' + scriptName)"], {'shell': '(True)', 'start_new_session': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT', 'bufsize': '(0)'}), "('stdbuf -o0 ' + pshell + ' ' + scriptName, shell=True,\n start_new_session=True, stdout=subprocess.PIPE, stderr=subprocess.\n STDOUT, bufsize=0)\n", (22895, 23044), False, 'import subprocess\n'), ((23460, 23471), 'time.time', 'time.time', ([], {}), '()\n', (23469, 23471), False, 'import time\n'), ((23971, 23984), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (23981, 23984), False, 'import time\n'), ((23997, 24035), 'os.killpg', 'os.killpg', (['proc.pid', 'sys_signal.SIGINT'], {}), '(proc.pid, sys_signal.SIGINT)\n', (24006, 24035), False, 'import os\n'), ((24048, 24061), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (24058, 24061), False, 'import time\n'), ((25132, 25306), 'subprocess.Popen', 'subprocess.Popen', (["('stdbuf -o0 ' + sys.executable + ' ' + scriptName)"], {'shell': '(True)', 'start_new_session': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT', 'bufsize': '(0)'}), "('stdbuf -o0 ' + sys.executable + ' ' + scriptName, shell=\n True, start_new_session=True, stdout=subprocess.PIPE, stderr=subprocess\n .STDOUT, bufsize=0)\n", (25148, 25306), False, 'import subprocess\n'), ((25516, 25527), 'time.time', 'time.time', ([], {}), '()\n', (25525, 25527), False, 'import time\n'), ((25819, 25832), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (25829, 25832), False, 'import time\n'), ((25845, 25883), 'os.killpg', 'os.killpg', (['proc.pid', 'sys_signal.SIGINT'], {}), '(proc.pid, sys_signal.SIGINT)\n', (25854, 25883), False, 'import os\n'), ((25896, 25909), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (25906, 25909), False, 'import time\n'), ((27874, 27891), 'acme.cluster_cleanup', 'cluster_cleanup', ([], {}), '()\n', (27889, 27891), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((28026, 28043), 'acme.cluster_cleanup', 'cluster_cleanup', ([], {}), '()\n', (28041, 28043), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((28174, 28191), 'acme.cluster_cleanup', 'cluster_cleanup', ([], {}), '()\n', (28189, 28191), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((28286, 28378), 'acme.esi_cluster_setup', 'esi_cluster_setup', ([], {'partition': '"""8GBDEV"""', 'n_jobs': '(1)', 'mem_per_job': '"""9000MB"""', 'interactive': '(False)'}), "(partition='8GBDEV', n_jobs=1, mem_per_job='9000MB',\n interactive=False)\n", (28303, 28378), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((28588, 28611), 'acme.cluster_cleanup', 'cluster_cleanup', (['client'], {}), '(client)\n', (28603, 28611), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((28887, 28904), 'acme.cluster_cleanup', 'cluster_cleanup', ([], {}), '()\n', (28902, 28904), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((29056, 29073), 'acme.cluster_cleanup', 'cluster_cleanup', ([], {}), '()\n', (29071, 29073), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((29224, 29241), 'acme.cluster_cleanup', 'cluster_cleanup', ([], {}), '()\n', (29239, 29241), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((29544, 29590), 'acme.esi_cluster_setup', 'esi_cluster_setup', ([], {'n_jobs': '(6)', 'interactive': '(False)'}), '(n_jobs=6, interactive=False)\n', (29561, 29590), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((30025, 30068), 'shutil.rmtree', 'shutil.rmtree', (['slurmOut'], {'ignore_errors': '(True)'}), '(slurmOut, ignore_errors=True)\n', (30038, 30068), False, 'import shutil\n'), ((4160, 4174), 'numpy.zeros', 'np.zeros', (['(3,)'], {}), '((3,))\n', (4168, 4174), True, 'import numpy as np\n'), ((4304, 4320), 'numpy.zeros', 'np.zeros', (['(3, 1)'], {}), '((3, 1))\n', (4312, 4320), True, 'import numpy as np\n'), ((4501, 4514), 'numpy.ones', 'np.ones', (['(3,)'], {}), '((3,))\n', (4508, 4514), True, 'import numpy as np\n'), ((4650, 4665), 'numpy.ones', 'np.ones', (['(7, 1)'], {}), '((7, 1))\n', (4657, 4665), True, 'import numpy as np\n'), ((4799, 4814), 'numpy.ones', 'np.ones', (['(7, 1)'], {}), '((7, 1))\n', (4806, 4814), True, 'import numpy as np\n'), ((4952, 4968), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (4960, 4968), True, 'import numpy as np\n'), ((4972, 4987), 'numpy.ones', 'np.ones', (['(8, 1)'], {}), '((8, 1))\n', (4979, 4987), True, 'import numpy as np\n'), ((5137, 5152), 'numpy.ones', 'np.ones', (['(8, 1)'], {}), '((8, 1))\n', (5144, 5152), True, 'import numpy as np\n'), ((7811, 7834), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (7829, 7834), False, 'import os\n'), ((7922, 7939), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (7937, 7939), False, 'import getpass\n'), ((8975, 8994), 'os.path.isfile', 'os.path.isfile', (['fle'], {}), '(fle)\n', (8989, 8994), False, 'import os\n'), ((9163, 9185), 'h5py.File', 'h5py.File', (['h5name', '"""r"""'], {}), "(h5name, 'r')\n", (9172, 9185), False, 'import h5py\n'), ((9907, 9929), 'h5py.File', 'h5py.File', (['h5name', '"""r"""'], {}), "(h5name, 'r')\n", (9916, 9929), False, 'import h5py\n'), ((9961, 10012), 'numpy.array_equal', 'np.array_equal', (["h5f['result_0'][()]", 'resInMem[chNo]'], {}), "(h5f['result_0'][()], resInMem[chNo])\n", (9975, 10012), True, 'import numpy as np\n'), ((10112, 10135), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (10130, 10135), False, 'import os\n'), ((10250, 10267), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (10265, 10267), False, 'import getpass\n'), ((12506, 12532), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (12522, 12532), False, 'import os\n'), ((15566, 15591), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (15579, 15591), False, 'import pytest\n'), ((15609, 15624), 'dask.distributed.get_client', 'dd.get_client', ([], {}), '()\n', (15622, 15624), True, 'import dask.distributed as dd\n'), ((18908, 18924), 'pickle.load', 'pickle.load', (['pkf'], {}), '(pkf)\n', (18919, 18924), False, 'import pickle\n'), ((18942, 18964), 'h5py.File', 'h5py.File', (['h5name', '"""r"""'], {}), "(h5name, 'r')\n", (18951, 18964), False, 'import h5py\n'), ((18996, 19039), 'numpy.array_equal', 'np.array_equal', (['pklRes', "h5f['result_0'][()]"], {}), "(pklRes, h5f['result_0'][()])\n", (19010, 19039), True, 'import numpy as np\n'), ((21794, 21817), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (21812, 21817), False, 'import os\n'), ((27761, 27786), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (27774, 27786), False, 'import pytest\n'), ((27804, 27861), 'acme.esi_cluster_setup', 'esi_cluster_setup', ([], {'partition': '"""invalid"""', 'interactive': '(False)'}), "(partition='invalid', interactive=False)\n", (27821, 27861), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((27909, 27934), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (27922, 27934), False, 'import pytest\n'), ((27952, 28013), 'acme.esi_cluster_setup', 'esi_cluster_setup', ([], {'mem_per_job': '"""invalidGB"""', 'interactive': '(False)'}), "(mem_per_job='invalidGB', interactive=False)\n", (27969, 28013), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((28061, 28086), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (28074, 28086), False, 'import pytest\n'), ((28104, 28161), 'acme.esi_cluster_setup', 'esi_cluster_setup', ([], {'mem_per_job': '"""-20MB"""', 'interactive': '(False)'}), "(mem_per_job='-20MB', interactive=False)\n", (28121, 28161), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((28718, 28735), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (28733, 28735), False, 'import getpass\n'), ((28754, 28778), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (28767, 28778), False, 'import pytest\n'), ((28922, 28947), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (28935, 28947), False, 'import pytest\n'), ((29091, 29116), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (29104, 29116), False, 'import pytest\n'), ((29134, 29211), 'acme.esi_cluster_setup', 'esi_cluster_setup', ([], {'job_extra': "['--output=/path/to/nowhere']", 'interactive': '(False)'}), "(job_extra=['--output=/path/to/nowhere'], interactive=False)\n", (29151, 29211), False, 'from acme import ParallelMap, cluster_cleanup, esi_cluster_setup\n'), ((3994, 4009), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (4001, 4009), True, 'import numpy as np\n'), ((7044, 7059), 'numpy.ones', 'np.ones', (['(8, 1)'], {}), '((8, 1))\n', (7051, 7059), True, 'import numpy as np\n'), ((9707, 9750), 'numpy.abs', 'np.abs', (['(resInMem[chNo] - self.orig[:, chNo])'], {}), '(resInMem[chNo] - self.orig[:, chNo])\n', (9713, 9750), True, 'import numpy as np\n'), ((11415, 11445), 'os.path.join', 'os.path.join', (['tempDir2', 'h5name'], {}), '(tempDir2, h5name)\n', (11427, 11445), False, 'import os\n'), ((19910, 19931), 'h5py.File', 'h5py.File', (['fname', '"""r"""'], {}), "(fname, 'r')\n", (19919, 19931), False, 'import h5py\n'), ((21908, 21937), 'os.path.split', 'os.path.split', (['sys.executable'], {}), '(sys.executable)\n', (21921, 21937), False, 'import os\n'), ((28541, 28569), 'numpy.round', 'np.round', (['(memory / 1000 ** 3)'], {}), '(memory / 1000 ** 3)\n', (28549, 28569), True, 'import numpy as np\n'), ((4015, 4030), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (4022, 4030), True, 'import numpy as np\n'), ((6372, 6387), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (6379, 6387), True, 'import numpy as np\n'), ((9225, 9273), 'numpy.abs', 'np.abs', (["(h5f['result_0'][()] - self.orig[:, chNo])"], {}), "(h5f['result_0'][()] - self.orig[:, chNo])\n", (9231, 9273), True, 'import numpy as np\n'), ((11491, 11538), 'numpy.abs', 'np.abs', (['(h5f[dset_name][()] - self.orig[:, chNo])'], {}), '(h5f[dset_name][()] - self.orig[:, chNo])\n', (11497, 11538), True, 'import numpy as np\n'), ((19965, 19997), 'h5py.File', 'h5py.File', (['hdfResults[chNo]', '"""r"""'], {}), "(hdfResults[chNo], 'r')\n", (19974, 19997), False, 'import h5py\n'), ((20039, 20097), 'numpy.array_equal', 'np.array_equal', (["h5f['result_0'][()]", "h5ref['result_0'][()]"], {}), "(h5f['result_0'][()], h5ref['result_0'][()])\n", (20053, 20097), True, 'import numpy as np\n'), ((6392, 6407), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (6399, 6407), True, 'import numpy as np\n'), ((19803, 19819), 'pickle.load', 'pickle.load', (['pkf'], {}), '(pkf)\n', (19814, 19819), False, 'import pickle\n'), ((23526, 23537), 'time.time', 'time.time', ([], {}), '()\n', (23535, 23537), False, 'import time\n'), ((25582, 25593), 'time.time', 'time.time', ([], {}), '()\n', (25591, 25593), False, 'import time\n')] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the analysis front-end object."""
import unittest
from plaso.frontend import analysis_frontend
from plaso.storage import zip_file as storage_zip_file
from tests.frontend import test_lib
class AnalysisFrontendTests(test_lib.FrontendTestCase):
"""Tests for the analysis front-end object."""
def testOpenStorage(self):
"""Tests the OpenStorage function."""
test_front_end = analysis_frontend.AnalysisFrontend()
storage_file_path = self._GetTestFilePath([u'psort_test.proto.plaso'])
storage_file = test_front_end.OpenStorage(storage_file_path)
self.assertIsInstance(storage_file, storage_zip_file.StorageFile)
storage_file.Close()
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"plaso.frontend.analysis_frontend.AnalysisFrontend"
] | [((750, 765), 'unittest.main', 'unittest.main', ([], {}), '()\n', (763, 765), False, 'import unittest\n'), ((444, 480), 'plaso.frontend.analysis_frontend.AnalysisFrontend', 'analysis_frontend.AnalysisFrontend', ([], {}), '()\n', (478, 480), False, 'from plaso.frontend import analysis_frontend\n')] |
import numpy as np
from numpy import log
#Se define la función a integrar
def f(x):
return 1 / log(x)
#Implementación del método de Simpson
#Parámetros:
#f es la función a integrar
#a el límite inferior de la integral
#b el límite superior de la integral
#n el número de intervalos
def simpson (f, a, b ,n):
h = (b - a) / n
g = f(a) + f(b)
#Suma de áreas
for i in range (1, n // 2):
g = g + 2 * f(a + 2 * i * h)
for i in range (0, n // 2):
g = g + 4 * f(a + (2 * i + 1) * h)
return h * g / 3
def main():
li = simpson(f, 2, 3 ,16)
print("Li(3): ", li)
main()
| [
"numpy.log"
] | [((105, 111), 'numpy.log', 'log', (['x'], {}), '(x)\n', (108, 111), False, 'from numpy import log\n')] |
import argparse
import i18n
import logging
import os
import rdflib
import sys
from termcolor import colored
from timeit import default_timer as timer
__VERSION__ = '0.2.0'
__LOG__ = None
FORMATS = ['nt', 'n3', 'turtle', 'rdfa', 'xml', 'pretty-xml']
HEADER_SEP = '='
COLUMN_SEP = '|'
EMPTY_LINE = ''
COLUMN_SPEC = '{:%d}'
USE_COLOR = False
def startup(description_key, add_args, read_files=True, argv=None):
global __LOG__, USE_COLOR
configure_translation()
description = i18n.t(description_key)
parser = configure_argparse(description, read_files)
if callable(add_args):
parser = add_args(parser)
if argv is None:
command = parser.parse_args()
else:
command = parser.parse_args(argv)
USE_COLOR = command.use_color
process = parser.prog
__LOG__ = configure_logging(process, command.verbose)
__LOG__.info(i18n.t('rdftools.started', tool=process, name=description))
__LOG__.info(argv)
return (__LOG__, command)
def configure_translation(force_locale=None):
i18n.load_path.append(os.path.join(os.path.dirname(__file__), 'messages'))
if force_locale is not None:
i18n.set('locale', force_locale)
i18n.set('fallback', 'en')
def configure_argparse(description, read_files=True):
parser = argparse.ArgumentParser(description=description)
parser.add_argument('-v', '--verbose', default=0, action='count')
parser.add_argument('-b', '--base', action='store')
if read_files:
parser.add_argument('-i', '--input',
type=argparse.FileType('r'), nargs='*')
parser.add_argument('-r', '--read', action='store', choices=FORMATS)
parser.add_argument('-c', '--use-color', action='store_true')
return parser
def configure_logging(name, level):
global __LOG__
logging.basicConfig(format='%(asctime)-15s %(module)s.%(funcName)s:' +
'%(lineno)d [%(levelname)s] %(message)s')
logger = logging.getLogger(name)
if level > 2:
logger.setLevel(logging.INFO)
elif level > 1:
logger.setLevel(logging.DEBUG)
elif level > 0:
logger.setLevel(logging.WARN)
else:
logger.setLevel(logging.ERROR)
logger.info(i18n.t('rdftools.logging', level=logger.getEffectiveLevel()))
__LOG__ = logger
return logger
def read_into(input, format, graph, base=None):
start = end = 0
if format is None:
if input is None:
format = FORMATS[0]
else:
format = rdflib.util.guess_format(input.name)
if input is None:
__LOG__.info(i18n.t('rdftools.read_stdin', format=format))
start = timer()
graph.parse(source=sys.stdin.buffer, format=format, publicID=base)
end = timer()
else:
__LOG__.info(i18n.t('rdftools.read_file',
name=input.name, format=format))
start = timer()
graph.parse(source=input.name, format=format, publicID=base)
end = timer()
__LOG__.info(i18n.t('rdftools.read_complete',
len=len(graph), time=end - start))
return graph
def read(input, format, base=None):
graph = rdflib.Graph()
return read_into(input, format, graph, base)
def read_all(inputs, format, base=None):
graph = rdflib.Graph()
for input in inputs:
graph = read_into(input, format, graph, base)
return graph
def write(graph, output, format, base=None):
__LOG__.debug(i18n.t('rdftools.write', graph=graph, len=len(graph)))
start = end = 0
if format is None:
if output is None:
format = FORMATS[0]
else:
format = rdflib.util.guess_format(output.name)
if output is None:
__LOG__.info(i18n.t('rdftools.write_stdout', format=format))
start = timer()
data = graph.serialize(format=format, base=base)
end = timer()
try:
# This fails on Travis ONLY for Python 3.4
sys.stdout.buffer.write(data)
except AttributeError:
sys.stdout.write(data.decode('utf-8'))
else:
__LOG__.info(i18n.t('rdftools.write_file',
name=output.name, format=format))
start = timer()
graph.serialize(destination=output.name, format=format, base=base)
end = timer()
__LOG__.debug(i18n.t('rdftools.write_complete', time=(end - start)))
def get_terminal_width(default=80):
import shutil
return shutil.get_terminal_size((default, 20))[0]
def header(str):
return colored(str, attrs=['reverse']) if USE_COLOR else str
def line(str):
return colored(str, attrs=['dark']) if USE_COLOR else str
def comment(str):
return colored(str, attrs=['dark']) if USE_COLOR else str
def report(columns, rows, timer=0):
# TODO: Should also take this as a parameter? so "rdf query -c 80 -q ..."
width = get_terminal_width()
col_width = int((width - len(columns)) / len(columns))
col_string = COLUMN_SPEC % col_width
for column in columns:
print(header(col_string.format(column)), end=line(COLUMN_SEP))
print(EMPTY_LINE)
for column in columns:
print(line(HEADER_SEP * col_width), end=line(COLUMN_SEP))
print(EMPTY_LINE)
for row in rows:
for col in columns:
print(col_string.format(row[col]), end=line(COLUMN_SEP))
print(EMPTY_LINE)
if timer != 0:
print(comment(i18n.t('rdftools.report_timed',
len=len(rows), time=timer)))
else:
print(comment(i18n.t('rdftools.report_timed',
len=len(rows))))
| [
"logging.basicConfig",
"logging.getLogger",
"argparse.FileType",
"termcolor.colored",
"argparse.ArgumentParser",
"timeit.default_timer",
"shutil.get_terminal_size",
"rdflib.Graph",
"i18n.set",
"os.path.dirname",
"sys.stdout.buffer.write",
"rdflib.util.guess_format",
"i18n.t"
] | [((490, 513), 'i18n.t', 'i18n.t', (['description_key'], {}), '(description_key)\n', (496, 513), False, 'import i18n\n'), ((1196, 1222), 'i18n.set', 'i18n.set', (['"""fallback"""', '"""en"""'], {}), "('fallback', 'en')\n", (1204, 1222), False, 'import i18n\n'), ((1292, 1340), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'description'}), '(description=description)\n', (1315, 1340), False, 'import argparse\n'), ((1821, 1937), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': "('%(asctime)-15s %(module)s.%(funcName)s:' +\n '%(lineno)d [%(levelname)s] %(message)s')"}), "(format='%(asctime)-15s %(module)s.%(funcName)s:' +\n '%(lineno)d [%(levelname)s] %(message)s')\n", (1840, 1937), False, 'import logging\n'), ((1971, 1994), 'logging.getLogger', 'logging.getLogger', (['name'], {}), '(name)\n', (1988, 1994), False, 'import logging\n'), ((3165, 3179), 'rdflib.Graph', 'rdflib.Graph', ([], {}), '()\n', (3177, 3179), False, 'import rdflib\n'), ((3284, 3298), 'rdflib.Graph', 'rdflib.Graph', ([], {}), '()\n', (3296, 3298), False, 'import rdflib\n'), ((878, 936), 'i18n.t', 'i18n.t', (['"""rdftools.started"""'], {'tool': 'process', 'name': 'description'}), "('rdftools.started', tool=process, name=description)\n", (884, 936), False, 'import i18n\n'), ((1159, 1191), 'i18n.set', 'i18n.set', (['"""locale"""', 'force_locale'], {}), "('locale', force_locale)\n", (1167, 1191), False, 'import i18n\n'), ((2662, 2669), 'timeit.default_timer', 'timer', ([], {}), '()\n', (2667, 2669), True, 'from timeit import default_timer as timer\n'), ((2759, 2766), 'timeit.default_timer', 'timer', ([], {}), '()\n', (2764, 2766), True, 'from timeit import default_timer as timer\n'), ((2897, 2904), 'timeit.default_timer', 'timer', ([], {}), '()\n', (2902, 2904), True, 'from timeit import default_timer as timer\n'), ((2988, 2995), 'timeit.default_timer', 'timer', ([], {}), '()\n', (2993, 2995), True, 'from timeit import default_timer as timer\n'), ((3798, 3805), 'timeit.default_timer', 'timer', ([], {}), '()\n', (3803, 3805), True, 'from timeit import default_timer as timer\n'), ((3877, 3884), 'timeit.default_timer', 'timer', ([], {}), '()\n', (3882, 3884), True, 'from timeit import default_timer as timer\n'), ((4209, 4216), 'timeit.default_timer', 'timer', ([], {}), '()\n', (4214, 4216), True, 'from timeit import default_timer as timer\n'), ((4306, 4313), 'timeit.default_timer', 'timer', ([], {}), '()\n', (4311, 4313), True, 'from timeit import default_timer as timer\n'), ((4332, 4383), 'i18n.t', 'i18n.t', (['"""rdftools.write_complete"""'], {'time': '(end - start)'}), "('rdftools.write_complete', time=end - start)\n", (4338, 4383), False, 'import i18n\n'), ((4454, 4493), 'shutil.get_terminal_size', 'shutil.get_terminal_size', (['(default, 20)'], {}), '((default, 20))\n', (4478, 4493), False, 'import shutil\n'), ((4527, 4558), 'termcolor.colored', 'colored', (['str'], {'attrs': "['reverse']"}), "(str, attrs=['reverse'])\n", (4534, 4558), False, 'from termcolor import colored\n'), ((4609, 4637), 'termcolor.colored', 'colored', (['str'], {'attrs': "['dark']"}), "(str, attrs=['dark'])\n", (4616, 4637), False, 'from termcolor import colored\n'), ((4691, 4719), 'termcolor.colored', 'colored', (['str'], {'attrs': "['dark']"}), "(str, attrs=['dark'])\n", (4698, 4719), False, 'from termcolor import colored\n'), ((1078, 1103), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1093, 1103), False, 'import os\n'), ((2520, 2556), 'rdflib.util.guess_format', 'rdflib.util.guess_format', (['input.name'], {}), '(input.name)\n', (2544, 2556), False, 'import rdflib\n'), ((2600, 2644), 'i18n.t', 'i18n.t', (['"""rdftools.read_stdin"""'], {'format': 'format'}), "('rdftools.read_stdin', format=format)\n", (2606, 2644), False, 'import i18n\n'), ((2798, 2858), 'i18n.t', 'i18n.t', (['"""rdftools.read_file"""'], {'name': 'input.name', 'format': 'format'}), "('rdftools.read_file', name=input.name, format=format)\n", (2804, 2858), False, 'import i18n\n'), ((3652, 3689), 'rdflib.util.guess_format', 'rdflib.util.guess_format', (['output.name'], {}), '(output.name)\n', (3676, 3689), False, 'import rdflib\n'), ((3734, 3780), 'i18n.t', 'i18n.t', (['"""rdftools.write_stdout"""'], {'format': 'format'}), "('rdftools.write_stdout', format=format)\n", (3740, 3780), False, 'import i18n\n'), ((3965, 3994), 'sys.stdout.buffer.write', 'sys.stdout.buffer.write', (['data'], {}), '(data)\n', (3988, 3994), False, 'import sys\n'), ((4108, 4170), 'i18n.t', 'i18n.t', (['"""rdftools.write_file"""'], {'name': 'output.name', 'format': 'format'}), "('rdftools.write_file', name=output.name, format=format)\n", (4114, 4170), False, 'import i18n\n'), ((1564, 1586), 'argparse.FileType', 'argparse.FileType', (['"""r"""'], {}), "('r')\n", (1581, 1586), False, 'import argparse\n')] |
from loguru import logger
from scrapy.crawler import CrawlerProcess
from scrapy.utils.log import DEFAULT_LOGGING
from scrapy.utils.project import get_project_settings
from scrape_magic.spiders.gatherer_spider import GathererSpider
from scrape_magic.spiders.starcity_spider import StarcitySpider
settings = get_project_settings()
DEFAULT_LOGGING["loggers"] = dict(scrapy={"level": "INFO"}, twisted={"level": "ERROR"})
process = CrawlerProcess(settings, install_root_handler=False)
def update_items():
process.crawl(StarcitySpider)
process.crawl(GathererSpider)
try:
process.start(stop_after_crawl=False)
except RuntimeError as e:
logger.error(e)
| [
"loguru.logger.error",
"scrapy.crawler.CrawlerProcess",
"scrapy.utils.project.get_project_settings"
] | [((308, 330), 'scrapy.utils.project.get_project_settings', 'get_project_settings', ([], {}), '()\n', (328, 330), False, 'from scrapy.utils.project import get_project_settings\n'), ((429, 481), 'scrapy.crawler.CrawlerProcess', 'CrawlerProcess', (['settings'], {'install_root_handler': '(False)'}), '(settings, install_root_handler=False)\n', (443, 481), False, 'from scrapy.crawler import CrawlerProcess\n'), ((665, 680), 'loguru.logger.error', 'logger.error', (['e'], {}), '(e)\n', (677, 680), False, 'from loguru import logger\n')] |
from flask import (
Blueprint, request, jsonify, render_template, session, redirect, url_for
)
from app.models import User
bp = Blueprint('auth', __name__, url_prefix='/auth')
@bp.route('/login', methods=['GET','POST'])
def login():
if request.method == 'GET':
return render_template("login.html")
email_address = request.form['email_address']
password = request.form['password']
if request.method == 'POST':
email_address = request.form['email_address']
password = request.form['password']
"""
ADD POST LOGIN LOGIC HERE
"""
else:
error = "Incorrect login details"
return render_template("login.html", error=error)
@bp.route('/logout', methods=['GET'])
def logout():
session.pop('user')
return redirect(url_for('auth.login'))
@bp.route('/update_password', methods=['GET', 'POST'])
def update_password():
if request.method == 'GET':
token = request.args.get('token')
user_id = request.args.get('user_id')
#Check if token is valid
# if
return render_template('error_page.html', error=error)
User.update()
elif request.method == 'POST':
"""
ADD PASSWORD RESET LOGIC HERE
"""
return render_template('login.html', message=message)
| [
"flask.render_template",
"flask.request.args.get",
"flask.url_for",
"flask.session.pop",
"flask.Blueprint",
"app.models.User.update"
] | [((133, 180), 'flask.Blueprint', 'Blueprint', (['"""auth"""', '__name__'], {'url_prefix': '"""/auth"""'}), "('auth', __name__, url_prefix='/auth')\n", (142, 180), False, 'from flask import Blueprint, request, jsonify, render_template, session, redirect, url_for\n'), ((1264, 1283), 'flask.session.pop', 'session.pop', (['"""user"""'], {}), "('user')\n", (1275, 1283), False, 'from flask import Blueprint, request, jsonify, render_template, session, redirect, url_for\n'), ((1795, 1841), 'flask.render_template', 'render_template', (['"""login.html"""'], {'message': 'message'}), "('login.html', message=message)\n", (1810, 1841), False, 'from flask import Blueprint, request, jsonify, render_template, session, redirect, url_for\n'), ((768, 797), 'flask.render_template', 'render_template', (['"""login.html"""'], {}), "('login.html')\n", (783, 797), False, 'from flask import Blueprint, request, jsonify, render_template, session, redirect, url_for\n'), ((1163, 1205), 'flask.render_template', 'render_template', (['"""login.html"""'], {'error': 'error'}), "('login.html', error=error)\n", (1178, 1205), False, 'from flask import Blueprint, request, jsonify, render_template, session, redirect, url_for\n'), ((1305, 1326), 'flask.url_for', 'url_for', (['"""auth.login"""'], {}), "('auth.login')\n", (1312, 1326), False, 'from flask import Blueprint, request, jsonify, render_template, session, redirect, url_for\n'), ((1457, 1482), 'flask.request.args.get', 'request.args.get', (['"""token"""'], {}), "('token')\n", (1473, 1482), False, 'from flask import Blueprint, request, jsonify, render_template, session, redirect, url_for\n'), ((1501, 1528), 'flask.request.args.get', 'request.args.get', (['"""user_id"""'], {}), "('user_id')\n", (1517, 1528), False, 'from flask import Blueprint, request, jsonify, render_template, session, redirect, url_for\n'), ((1593, 1640), 'flask.render_template', 'render_template', (['"""error_page.html"""'], {'error': 'error'}), "('error_page.html', error=error)\n", (1608, 1640), False, 'from flask import Blueprint, request, jsonify, render_template, session, redirect, url_for\n'), ((1650, 1663), 'app.models.User.update', 'User.update', ([], {}), '()\n', (1661, 1663), False, 'from app.models import User\n')] |
import json
import pathlib
from src.extract_old_site.extract import run_extraction
from src.generate_new_site.generate import generate_site
if __name__ == "__main__":
script_root_dir = pathlib.Path(__file__).parent
config = None
with open((script_root_dir / "config.json")) as f:
config = json.load(f)
# Resolve any default config values
if config["extractionOutputDirPath"] == "Default":
config["extractionOutputDirPath"] = str(script_root_dir / "jsons")
if config["generationOutputDirPath"] == "Default":
config["generationOutputDirPath"] = str(script_root_dir / "newdig")
(script_root_dir / "newdig").mkdir(parents=True, exist_ok=True)
# Set up for generating the site
dig_dir = str((pathlib.Path(config["digParentDirPath"]) / "dig").as_posix())
input_dir = config["extractionOutputDirPath"]
output_dir = config["generationOutputDirPath"]
overwrite_out = config["overwriteExistingGeneratedFiles"]
copy_images = config["copyImages"]
copy_videos = config["copyVideos"]
copy_data = config["copyData"]
# Run extraction and site generation
if config['runExtraction']:
print("\n-----------------------------------\n"
"Extracting old site data.\n")
run_extraction(config)
else:
print("\n-----------------------------------\n"
"SKIPPING extracting old site data.\n")
if config['runGeneration']:
print("\n-----------------------------------\n"
"Generating new site files.\n")
generate_site(dig_dir, input_dir, output_dir, overwrite_out, copy_images, copy_videos, copy_data)
else:
print("\n-----------------------------------\n"
"SKIPPING generating new site files.\n")
# if config['runDigPro']:
# TODO
# pass
| [
"json.load",
"src.generate_new_site.generate.generate_site",
"src.extract_old_site.extract.run_extraction",
"pathlib.Path"
] | [((190, 212), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (202, 212), False, 'import pathlib\n'), ((311, 323), 'json.load', 'json.load', (['f'], {}), '(f)\n', (320, 323), False, 'import json\n'), ((1276, 1298), 'src.extract_old_site.extract.run_extraction', 'run_extraction', (['config'], {}), '(config)\n', (1290, 1298), False, 'from src.extract_old_site.extract import run_extraction\n'), ((1561, 1662), 'src.generate_new_site.generate.generate_site', 'generate_site', (['dig_dir', 'input_dir', 'output_dir', 'overwrite_out', 'copy_images', 'copy_videos', 'copy_data'], {}), '(dig_dir, input_dir, output_dir, overwrite_out, copy_images,\n copy_videos, copy_data)\n', (1574, 1662), False, 'from src.generate_new_site.generate import generate_site\n'), ((755, 795), 'pathlib.Path', 'pathlib.Path', (["config['digParentDirPath']"], {}), "(config['digParentDirPath'])\n", (767, 795), False, 'import pathlib\n')] |
"""Environments."""
import gin
from alpacka.envs import bin_packing
from alpacka.envs import cartpole
from alpacka.envs import gfootball
from alpacka.envs import octomaze
from alpacka.envs import sokoban
from alpacka.envs.base import *
from alpacka.envs.wrappers import *
# Configure envs in this module to ensure they're accessible via the
# alpacka.envs.* namespace.
def configure_env(env_class):
return gin.external_configurable(
env_class, module='alpacka.envs'
)
ActionNoiseSokoban = configure_env(sokoban.ActionNoiseSokoban) # pylint: disable=invalid-name
BinPacking = configure_env(bin_packing.BinPacking) # pylint: disable=invalid-name
CartPole = configure_env(cartpole.CartPole) # pylint: disable=invalid-name
GoogleFootball = configure_env(gfootball.GoogleFootball) # pylint: disable=invalid-name
Octomaze = configure_env(octomaze.Octomaze) # pylint: disable=invalid-name
Sokoban = configure_env(sokoban.Sokoban) # pylint: disable=invalid-name
| [
"gin.external_configurable"
] | [((414, 473), 'gin.external_configurable', 'gin.external_configurable', (['env_class'], {'module': '"""alpacka.envs"""'}), "(env_class, module='alpacka.envs')\n", (439, 473), False, 'import gin\n')] |
from typing import List, Tuple
import mlflow
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from interpret.glassbox import ExplainableBoostingClassifier, ExplainableBoostingRegressor
from ..OEA_model import OEAModelInterface, ModelType, ExplanationType
from ..modeling_utils import log_metrics
class mlflow_pyfunc_wrapper(mlflow.pyfunc.PythonModel):
"""
Wrapper class that allows us to use generic predictors in the mlflow pyfunc format.
Used to wrap predictor types that are not already in the mlflow.* setup.
In order to work with this class, needs to have generic: predict, fit, score, predict_proba functions
"""
def __init__(self, model):
"""
Initialized Wrapped python model
Parameters
----------
model: Python Object
A model that implements the predict, fit, score, and predict_proba functions
"""
self.model = model
def predict(self, *args):
"""
Use Predict function of wrapped model
Parameters
----------
*args :
Arguments needed for wrapped predict function
Returns
-------
predictions: pandas.DataFrame or numpy.ndarray
Predictions of wrapped model on passed arguments
"""
predictions = self.model.predict(*args)
return predictions
def fit(self, *args):
"""
Train/Fit Wrapped model on passed arguments
Parameters
----------
*args :
Arguments needed for wrapped fit(train) function
Returns
-------
Wrapped model after being fit on passed arguments
"""
return self.model.fit(*args)
def score(self, *args):
"""
Predicts and Scores the wrapped model on passed arguments
Parameters
----------
*args :
Arguments needed for wrapped score function
Returns
-------
score: Float
Resulting score of wrapped model score function. (Generally accuracy)
"""
score = self.model.score(*args)
return score
def predict_proba(self,*args):
"""
Generate prediction probabilities of the wrapped model on passed arguments
Parameters
----------
*args :
Arguments needed for wrapped prediction probability functin
Returns
-------
probabilities: pandas.DataFrame or numpy.ndarray
Predicted output probabilities
"""
probabilities = self.model.predict_proba(*args)
return probabilities
class wrapped_basic(OEAModelInterface):
def __init__(self, modelname):
"""
Initialize Basic Wrapped Pyfunc Model utilities (base class)
Parameters
----------
modelname: String
Name of the model for registration and saving purposes
"""
self.predictor = None
self.modelname = modelname
def load_split_data(self, X, Y, A, key, split=.4, stratify=None):
"""
Splits Data into training, validation, and test sets
Parameters
----------
X: pandas.DataFrame
Feature data
Y: pandas.DataFrame
Label data
A: pandas.DataFrame
Senstive Feature data (may or may not be overlap with X)
key: String or List[Strings]
Columns to identify as Keys for all three dataframes. Dropped at loading time.
split: Float
Percentage of data to exclude for testing set
stratify: pandas.DataFrame
Dataframe used to stratify split of data. I.e. if labels are provided, will ensure equal label distribution in train / test sets.
Returns
-------
X_train: pandas.DataFrame
Feature data for training set
X_val: pandas.DataFrame
Feature data for validation set
X_test: pandas.DataFrame
Feature data for test set
y_train: pandas.DataFrame
Label data for training set
y_val: pandas.DataFrame
Label data for validation set
y_test: pandas.DataFrame
Label data for test set
A_train: pandas.DataFrame
Senstive Feature data for training set
A_val: pandas.DataFrame
Senstive Feature data for validation set
A_test: pandas.DataFrame
Senstive Feature data for test set
classes: List[str]
List of classes for classification problem outcomes
"""
if not (A is None):
(
X_train,
X_val_test,
y_train,
y_val_test,
A_train,
A_val_test,
) = train_test_split(
X,
Y,
A,
test_size=split,
random_state=12345,
stratify=stratify,
)
(X_val, X_test, y_val, y_test, A_val, A_test) = train_test_split(
X_val_test, y_val_test, A_val_test, test_size=0.5, random_state=12345
)
else:
(X_train, X_val_test, y_train, y_val_test) = train_test_split(
X,
Y,
test_size=split,
random_state=12345,
stratify=stratify,
)
(X_val, X_test, y_val, y_test) = train_test_split(
X_val_test, y_val_test, test_size=0.5, random_state=12345
)
X_train = X_train.drop(key, axis='columns').reset_index(drop=True)
X_val = X_val.drop(key, axis='columns').reset_index(drop=True)
X_test = X_test.drop(key, axis='columns').reset_index(drop=True)
y_train = y_train.drop(key, axis='columns')
y_train = y_train[y_train.columns[:1]].reset_index(drop=True)
y_val = y_val.drop(key, axis='columns').reset_index(drop=True)
y_val = y_val[y_val.columns[:1]].reset_index(drop=True)
y_test = y_test.drop(key, axis='columns').reset_index(drop=True)
y_test = y_test[y_test.columns[:1]].reset_index(drop=True)
classes = None
self.X_train = X_train
self.X_val = X_val
self.X_test = X_test
self.y_train = y_train.values.reshape(-1)
self.y_val = y_val.values.reshape(-1)
self.y_test = y_test.values.reshape(-1)
self.classes = classes
if not(A is None):
A_train = A_train.drop(key, axis='columns').reset_index(drop=True)
A_val = A_val.drop(key, axis='columns').reset_index(drop=True)
A_test = A_test.drop(key, axis='columns').reset_index(drop=True)
self.A_train = A_train
self.A_val = A_val
self.A_test = A_test
else:
A_train = None
A_val = None
A_test = None
self.A_train = A_train
self.A_val = A_val
self.A_test = A_test
return (
X_train,
X_val,
X_test,
y_train,
y_val,
y_test,
A_train,
A_val,
A_test,
classes,
)
def infer(self, data):
"""
Infer using model
Parameters
----------
data: pandas.DataFrame OR numpy array
Feature data
Returns
-------
predictions: pandas.DataFrame OR numpy array
Results of running inference of the predictor
"""
return self.predictor.predict(data)
def train(self):
"""
Trains model based on data originally loaded using load_split_data. Logs training metrics.
Returns
-------
self.predictor: sklearn Predictor
Trained predictor model object
"""
X_train_val = pd.concat([self.X_train, self.X_val], axis=0)
y_train_val = np.concatenate([self.y_train, self.y_val], axis=0)
self.predictor.fit(X_train_val, y_train_val)
log_metrics(self, dataset="training_val")
return self.predictor
def test(self):
"""
Evaluates model on the test set originally loaded using load_split_data. Logs testing metrics and returns predictions on test set.
Returns
-------
preds: pandas.DataFrame OR numpy array
Results of running inference of the predictor
"""
preds = log_metrics(self, dataset="test")
return preds
def save_model(self, foldername):
"""
Save Wrapped Pyfunc Model to a Path
Parameters
----------
foldername: String
Name of intermediate folder to save model to using mlflow utilities.
"""
mlflow.pyfunc.save_model(foldername, python_model=self.predictor)
def register_model(self, foldername):
"""
Register Model to repository attached to mlflow instance
Parameters
----------
foldername: String
Path of folder to upload to model repository
"""
mlflow.pyfunc.log_model(foldername, python_model=self.predictor, registered_model_name=self.modelname)
def load_model(self, modelname, version):
"""
Load Model from a registered endpoint
Parameters
----------
modelname: String
name of model to load from remote repository
version: String
version of model to load from mllow model repository.
Returns
-------
self.predictor: Wrapped PyFunc Predictor
Returns the predictor loaded from the registered endpoint
"""
model_version_uri = "models:/{model_name}/{version}".format(model_name=modelname,version=version)
self.predictor = mlflow.pyfunc.load_model(model_version_uri)
return self.predictor
class classification_EBM(wrapped_basic):
"""
Model Class for EBM used for Binary CLassification. Inherits from base wrapped model class (OEA Interface Type)
Classification type with Eplainable Boosting Machine special explanation type
"""
model_type = ModelType.binary_classification
explanation_type = ExplanationType.ebm
def init_model(self, seed=5):
"""Initialize Model"""
self.predictor = mlflow_pyfunc_wrapper(ExplainableBoostingClassifier(random_state=seed))
class multi_classification_EBM(wrapped_basic):
"""
Model Class for EBM used for Multiclass CLassification. Inherits from base wrapped model class (OEA Interface Type)
Multiclass Classification type with Eplainable Boosting Machine special explanation type
"""
model_type = ModelType.multiclass_classification
explanation_type = ExplanationType.ebm
def init_model(self, seed=5):
"""Initialize Model"""
self.predictor = mlflow_pyfunc_wrapper(ExplainableBoostingClassifier(random_state=seed))
class regression_EBM(wrapped_basic):
"""
Model Class for EBM used for Regression. Inherits from base wrapped model class (OEA Interface Type)
Regression type with Eplainable Boosting Machine special explanation type
"""
model_type = ModelType.regression
explanation_type = ExplanationType.ebm
def init_model(self, seed=5):
"""Initialize Model"""
self.predictor = mlflow_pyfunc_wrapper(ExplainableBoostingRegressor(random_state=seed))
| [
"interpret.glassbox.ExplainableBoostingRegressor",
"sklearn.model_selection.train_test_split",
"interpret.glassbox.ExplainableBoostingClassifier",
"numpy.concatenate",
"pandas.concat",
"mlflow.pyfunc.load_model",
"mlflow.pyfunc.save_model",
"mlflow.pyfunc.log_model"
] | [((8051, 8096), 'pandas.concat', 'pd.concat', (['[self.X_train, self.X_val]'], {'axis': '(0)'}), '([self.X_train, self.X_val], axis=0)\n', (8060, 8096), True, 'import pandas as pd\n'), ((8119, 8169), 'numpy.concatenate', 'np.concatenate', (['[self.y_train, self.y_val]'], {'axis': '(0)'}), '([self.y_train, self.y_val], axis=0)\n', (8133, 8169), True, 'import numpy as np\n'), ((9003, 9068), 'mlflow.pyfunc.save_model', 'mlflow.pyfunc.save_model', (['foldername'], {'python_model': 'self.predictor'}), '(foldername, python_model=self.predictor)\n', (9027, 9068), False, 'import mlflow\n'), ((9341, 9447), 'mlflow.pyfunc.log_model', 'mlflow.pyfunc.log_model', (['foldername'], {'python_model': 'self.predictor', 'registered_model_name': 'self.modelname'}), '(foldername, python_model=self.predictor,\n registered_model_name=self.modelname)\n', (9364, 9447), False, 'import mlflow\n'), ((10056, 10099), 'mlflow.pyfunc.load_model', 'mlflow.pyfunc.load_model', (['model_version_uri'], {}), '(model_version_uri)\n', (10080, 10099), False, 'import mlflow\n'), ((4886, 4972), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y', 'A'], {'test_size': 'split', 'random_state': '(12345)', 'stratify': 'stratify'}), '(X, Y, A, test_size=split, random_state=12345, stratify=\n stratify)\n', (4902, 4972), False, 'from sklearn.model_selection import train_test_split\n'), ((5140, 5231), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X_val_test', 'y_val_test', 'A_val_test'], {'test_size': '(0.5)', 'random_state': '(12345)'}), '(X_val_test, y_val_test, A_val_test, test_size=0.5,\n random_state=12345)\n', (5156, 5231), False, 'from sklearn.model_selection import train_test_split\n'), ((5330, 5408), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': 'split', 'random_state': '(12345)', 'stratify': 'stratify'}), '(X, Y, test_size=split, random_state=12345, stratify=stratify)\n', (5346, 5408), False, 'from sklearn.model_selection import train_test_split\n'), ((5550, 5625), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X_val_test', 'y_val_test'], {'test_size': '(0.5)', 'random_state': '(12345)'}), '(X_val_test, y_val_test, test_size=0.5, random_state=12345)\n', (5566, 5625), False, 'from sklearn.model_selection import train_test_split\n'), ((10593, 10641), 'interpret.glassbox.ExplainableBoostingClassifier', 'ExplainableBoostingClassifier', ([], {'random_state': 'seed'}), '(random_state=seed)\n', (10622, 10641), False, 'from interpret.glassbox import ExplainableBoostingClassifier, ExplainableBoostingRegressor\n'), ((11130, 11178), 'interpret.glassbox.ExplainableBoostingClassifier', 'ExplainableBoostingClassifier', ([], {'random_state': 'seed'}), '(random_state=seed)\n', (11159, 11178), False, 'from interpret.glassbox import ExplainableBoostingClassifier, ExplainableBoostingRegressor\n'), ((11612, 11659), 'interpret.glassbox.ExplainableBoostingRegressor', 'ExplainableBoostingRegressor', ([], {'random_state': 'seed'}), '(random_state=seed)\n', (11640, 11659), False, 'from interpret.glassbox import ExplainableBoostingClassifier, ExplainableBoostingRegressor\n')] |
import os
import sys
from optparse import make_option
from django.core.management import BaseCommand, call_command
from django.conf import settings
def rel(*x):
return os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--generators-dir',
action='store',
dest='generators_dir',
type='string',
default=0,
help='Specify directory where to look for generators'),
)
def handle(self, *app_labels, **options):
settings.TEMPLATE_CONTEXT_PROCESSORS += ('staging.contexts.data_generator_enabled',)
settings.TEMPLATE_DIRS += (rel('..', '..', 'templates'),)
settings.MIDDLEWARE_CLASSES += ('staging.middlewares.GeneratorPagesMiddleware',)
settings.GENERATORS_DIRS = [rel('..', '..', 'generators')]
if os.environ.get('GENERATORS_DIR'):
settings.GENERATORS_DIRS.append(os.environ.get('GENERATORS_DIR'))
if options.get('generators_dir'):
settings.GENERATORS_DIRS.append(options.get('generators_dir'))
for directory in settings.GENERATORS_DIRS:
if not os.path.isdir(directory):
print('%s generators directory does not exist' % directory)
call_command('runserver')
| [
"django.core.management.call_command",
"os.environ.get",
"os.path.dirname",
"os.path.isdir",
"optparse.make_option"
] | [((911, 943), 'os.environ.get', 'os.environ.get', (['"""GENERATORS_DIR"""'], {}), "('GENERATORS_DIR')\n", (925, 943), False, 'import os\n'), ((1320, 1345), 'django.core.management.call_command', 'call_command', (['"""runserver"""'], {}), "('runserver')\n", (1332, 1345), False, 'from django.core.management import BaseCommand, call_command\n'), ((203, 228), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (218, 228), False, 'import os\n'), ((319, 480), 'optparse.make_option', 'make_option', (['"""--generators-dir"""'], {'action': '"""store"""', 'dest': '"""generators_dir"""', 'type': '"""string"""', 'default': '(0)', 'help': '"""Specify directory where to look for generators"""'}), "('--generators-dir', action='store', dest='generators_dir', type\n ='string', default=0, help='Specify directory where to look for generators'\n )\n", (330, 480), False, 'from optparse import make_option\n'), ((989, 1021), 'os.environ.get', 'os.environ.get', (['"""GENERATORS_DIR"""'], {}), "('GENERATORS_DIR')\n", (1003, 1021), False, 'import os\n'), ((1210, 1234), 'os.path.isdir', 'os.path.isdir', (['directory'], {}), '(directory)\n', (1223, 1234), False, 'import os\n')] |
"""Add contact_details to House
Revision ID: 1<PASSWORD>7
Revises: <PASSWORD>
Create Date: 2018-08-08 10:58:44.869939
"""
# revision identifiers, used by Alembic.
revision = '1<PASSWORD>'
down_revision = '<PASSWORD>'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('house', sa.Column('contact_details', sa.Text(), nullable=True))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('house', 'contact_details')
### end Alembic commands ###
| [
"sqlalchemy.Text",
"alembic.op.drop_column"
] | [((552, 594), 'alembic.op.drop_column', 'op.drop_column', (['"""house"""', '"""contact_details"""'], {}), "('house', 'contact_details')\n", (566, 594), False, 'from alembic import op\n'), ((405, 414), 'sqlalchemy.Text', 'sa.Text', ([], {}), '()\n', (412, 414), True, 'import sqlalchemy as sa\n')] |
from random import randint
def longname():
return ''.join(chr(randint(0,143859)) for i in range(10000)).encode('utf-8','ignore').decode()
| [
"random.randint"
] | [((67, 85), 'random.randint', 'randint', (['(0)', '(143859)'], {}), '(0, 143859)\n', (74, 85), False, 'from random import randint\n')] |
"""
This module contains utility functions used in the example scripts. They are
implemented separately because they use scipy and numpy and we want to remove
external dependencies from within the core library.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from math import sqrt
from scipy.stats import sem
from scipy.stats import t
from scipy import linalg
import numpy as np
from concept_formation.utils import mean
def moving_average(a, n=3):
"""A function for computing the moving average, so that we can smooth out the
curves on a graph.
"""
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
def lowess(x, y, f=1./3., iter=3, confidence=0.95):
"""
Performs Lowess smoothing
Code adapted from: https://gist.github.com/agramfort/850437
lowess(x, y, f=2./3., iter=3) -> yest
Lowess smoother: Robust locally weighted regression.
The lowess function fits a nonparametric regression curve to a scatterplot.
The arrays x and y contain an equal number of elements; each pair
(x[i], y[i]) defines a data point in the scatterplot. The function returns
the estimated (smooth) values of y.
The smoothing span is given by f. A larger value for f will result in a
smoother curve. The number of robustifying iterations is given by iter. The
function will run faster with a smaller number of iterations.
.. todo:: double check that the confidence bounds are correct
"""
n = len(x)
r = int(np.ceil(f*n))
h = [np.sort(np.abs(x - x[i]))[r] for i in range(n)]
w = np.clip(np.abs((x[:, None] - x[None, :]) / h), 0.0, 1.0)
w = (1 - w**3)**3
yest = np.zeros(n)
delta = np.ones(n)
for iteration in range(iter):
for i in range(n):
weights = delta * w[:, i]
b = np.array([np.sum(weights*y), np.sum(weights*y*x)])
A = np.array([[np.sum(weights), np.sum(weights*x)],
[np.sum(weights*x), np.sum(weights*x*x)]])
beta = linalg.solve(A, b)
yest[i] = beta[0] + beta[1]*x[i]
residuals = y - yest
s = np.median(np.abs(residuals))
delta = np.clip(residuals / (6.0 * s), -1, 1)
delta = (1 - delta**2)**2
h = np.zeros(n)
for x_idx, x_val in enumerate(x):
r2 = np.array([v*v for i, v in enumerate(residuals) if x[i] == x_val])
n = len(r2)
se = sqrt(mean(r2)) / sqrt(len(r2))
h[x_idx] = se * t._ppf((1+confidence)/2., n-1)
return yest, yest-h, yest+h
def avg_lines(x, y, confidence=0.95):
n = len(x)
mean = np.zeros(n)
lower = np.zeros(n)
upper = np.zeros(n)
for x_idx, x_val in enumerate(x):
ys = np.array([v for i, v in enumerate(y) if x[i] == x_val])
m, l, u = mean_confidence_interval(ys)
mean[x_idx] = m
lower[x_idx] = l
upper[x_idx] = u
return mean, lower, upper
def mean_confidence_interval(data, confidence=0.95):
"""
Given a list or vector of data, this returns the mean, lower, and upper
confidence intervals to the level of confidence specified (default = 95%
confidence interval).
"""
a = 1.0*np.array(data)
n = len(a)
m, se = np.mean(a), sem(a)
h = se * t._ppf((1+confidence)/2., n-1)
return m, m-h, m+h
| [
"numpy.clip",
"numpy.abs",
"numpy.ceil",
"numpy.mean",
"scipy.stats.t._ppf",
"numpy.ones",
"scipy.linalg.solve",
"numpy.array",
"numpy.zeros",
"concept_formation.utils.mean",
"numpy.sum",
"scipy.stats.sem",
"numpy.cumsum"
] | [((703, 728), 'numpy.cumsum', 'np.cumsum', (['a'], {'dtype': 'float'}), '(a, dtype=float)\n', (712, 728), True, 'import numpy as np\n'), ((1840, 1851), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1848, 1851), True, 'import numpy as np\n'), ((1865, 1875), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (1872, 1875), True, 'import numpy as np\n'), ((2441, 2452), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (2449, 2452), True, 'import numpy as np\n'), ((2800, 2811), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (2808, 2811), True, 'import numpy as np\n'), ((2825, 2836), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (2833, 2836), True, 'import numpy as np\n'), ((2850, 2861), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (2858, 2861), True, 'import numpy as np\n'), ((1667, 1681), 'numpy.ceil', 'np.ceil', (['(f * n)'], {}), '(f * n)\n', (1674, 1681), True, 'import numpy as np\n'), ((1756, 1793), 'numpy.abs', 'np.abs', (['((x[:, None] - x[None, :]) / h)'], {}), '((x[:, None] - x[None, :]) / h)\n', (1762, 1793), True, 'import numpy as np\n'), ((2357, 2394), 'numpy.clip', 'np.clip', (['(residuals / (6.0 * s))', '(-1)', '(1)'], {}), '(residuals / (6.0 * s), -1, 1)\n', (2364, 2394), True, 'import numpy as np\n'), ((3402, 3416), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (3410, 3416), True, 'import numpy as np\n'), ((3446, 3456), 'numpy.mean', 'np.mean', (['a'], {}), '(a)\n', (3453, 3456), True, 'import numpy as np\n'), ((3458, 3464), 'scipy.stats.sem', 'sem', (['a'], {}), '(a)\n', (3461, 3464), False, 'from scipy.stats import sem\n'), ((3479, 3516), 'scipy.stats.t._ppf', 't._ppf', (['((1 + confidence) / 2.0)', '(n - 1)'], {}), '((1 + confidence) / 2.0, n - 1)\n', (3485, 3516), False, 'from scipy.stats import t\n'), ((2201, 2219), 'scipy.linalg.solve', 'linalg.solve', (['A', 'b'], {}), '(A, b)\n', (2213, 2219), False, 'from scipy import linalg\n'), ((2321, 2338), 'numpy.abs', 'np.abs', (['residuals'], {}), '(residuals)\n', (2327, 2338), True, 'import numpy as np\n'), ((2663, 2700), 'scipy.stats.t._ppf', 't._ppf', (['((1 + confidence) / 2.0)', '(n - 1)'], {}), '((1 + confidence) / 2.0, n - 1)\n', (2669, 2700), False, 'from scipy.stats import t\n'), ((1699, 1715), 'numpy.abs', 'np.abs', (['(x - x[i])'], {}), '(x - x[i])\n', (1705, 1715), True, 'import numpy as np\n'), ((2612, 2620), 'concept_formation.utils.mean', 'mean', (['r2'], {}), '(r2)\n', (2616, 2620), False, 'from concept_formation.utils import mean\n'), ((2005, 2024), 'numpy.sum', 'np.sum', (['(weights * y)'], {}), '(weights * y)\n', (2011, 2024), True, 'import numpy as np\n'), ((2024, 2047), 'numpy.sum', 'np.sum', (['(weights * y * x)'], {}), '(weights * y * x)\n', (2030, 2047), True, 'import numpy as np\n'), ((2074, 2089), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (2080, 2089), True, 'import numpy as np\n'), ((2091, 2110), 'numpy.sum', 'np.sum', (['(weights * x)'], {}), '(weights * x)\n', (2097, 2110), True, 'import numpy as np\n'), ((2139, 2158), 'numpy.sum', 'np.sum', (['(weights * x)'], {}), '(weights * x)\n', (2145, 2158), True, 'import numpy as np\n'), ((2158, 2181), 'numpy.sum', 'np.sum', (['(weights * x * x)'], {}), '(weights * x * x)\n', (2164, 2181), True, 'import numpy as np\n')] |
from aiohttp import web
from avio.app_builder import AppBuilder
from avio.default_handlers import InfoHandler
def test_create_app():
app = AppBuilder().build_app()
assert isinstance(app, web.Application)
def test_app_config():
builder = AppBuilder({'app_key': 'value'})
app = builder.build_app({'update_key': 'value'})
config = app['config']
assert 'value' == config['app_key']
assert 'value' == config['update_key']
assert 'logging' in config
assert 'host' in config
assert 'port' in config
assert 'ioloop_type' in config
def test_app_routes():
builder = AppBuilder()
app = builder.build_app()
assert 'info' in app.router.named_resources()
assert 'error' in app.router.named_resources()
def test_additional_routes():
class MyAppBuilder(AppBuilder):
def prepare_app(self, app: web.Application, config: dict = None):
app.router.add_view('/_info2', InfoHandler, name='info2')
builder = MyAppBuilder()
app_ = builder.build_app()
assert 'info2' in app_.router.named_resources()
| [
"avio.app_builder.AppBuilder"
] | [((254, 286), 'avio.app_builder.AppBuilder', 'AppBuilder', (["{'app_key': 'value'}"], {}), "({'app_key': 'value'})\n", (264, 286), False, 'from avio.app_builder import AppBuilder\n'), ((611, 623), 'avio.app_builder.AppBuilder', 'AppBuilder', ([], {}), '()\n', (621, 623), False, 'from avio.app_builder import AppBuilder\n'), ((146, 158), 'avio.app_builder.AppBuilder', 'AppBuilder', ([], {}), '()\n', (156, 158), False, 'from avio.app_builder import AppBuilder\n')] |
# -*- coding: utf-8 -*-
# Copyright 2022 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the PostgreSQL account analysis task."""
import os
import unittest
from turbinia import config
from turbinia.workers.analysis import postgresql_acct
from turbinia.workers.workers_test import TestTurbiniaTaskBase
class PostgresAcctAnalysisTaskTest(TestTurbiniaTaskBase):
"""Tests for PostgresAcctAnalysisTask Task."""
TEST_DATA_DIR = None
EXPECTED_CREDENTIALS = {'<KEY>': 'postgres'}
POSTGRES_REPORT = """#### **PostgreSQL analysis found 1 weak password(s)**
* **1 weak password(s) found:**
* User 'postgres' with password 'password'"""
def setUp(self):
super(PostgresAcctAnalysisTaskTest, self).setUp()
self.setResults(mock_run=False)
filedir = os.path.dirname(os.path.realpath(__file__))
self.TEST_DATA_DIR = os.path.join(filedir, '..', '..', '..', 'test_data')
self.evidence.local_path = self.TEST_DATA_DIR
def test_extract_data_dir(self):
"""Tests the _extract_data_dir method."""
config.LoadConfig()
task = postgresql_acct.PostgresAccountAnalysisTask()
# pylint: disable=protected-access
data_dirs = task._extract_data_dir(self.TEST_DATA_DIR, self.result)
self.assertEqual(len(data_dirs), 1)
self.assertEqual(data_dirs, ['test_data'])
def test_extract_creds(self):
"""Tests the _extract_creds method."""
config.LoadConfig()
task = postgresql_acct.PostgresAccountAnalysisTask()
# pylint: disable=protected-access
hashes = task._extract_creds(['/database'], self.evidence)
self.assertDictEqual(hashes, self.EXPECTED_CREDENTIALS)
def test_analyse_postgres_creds(self):
"""Tests the _analyse_postegres_creds method."""
config.LoadConfig()
task = postgresql_acct.PostgresAccountAnalysisTask()
(report, priority, summary) = task._analyse_postgres_creds(
self.EXPECTED_CREDENTIALS)
self.assertEqual(report, self.POSTGRES_REPORT)
self.assertEqual(priority, 10)
self.assertEqual(summary, 'PostgreSQL analysis found 1 weak password(s)') | [
"turbinia.workers.analysis.postgresql_acct.PostgresAccountAnalysisTask",
"os.path.realpath",
"os.path.join",
"turbinia.config.LoadConfig"
] | [((1361, 1413), 'os.path.join', 'os.path.join', (['filedir', '""".."""', '""".."""', '""".."""', '"""test_data"""'], {}), "(filedir, '..', '..', '..', 'test_data')\n", (1373, 1413), False, 'import os\n'), ((1550, 1569), 'turbinia.config.LoadConfig', 'config.LoadConfig', ([], {}), '()\n', (1567, 1569), False, 'from turbinia import config\n'), ((1581, 1626), 'turbinia.workers.analysis.postgresql_acct.PostgresAccountAnalysisTask', 'postgresql_acct.PostgresAccountAnalysisTask', ([], {}), '()\n', (1624, 1626), False, 'from turbinia.workers.analysis import postgresql_acct\n'), ((1906, 1925), 'turbinia.config.LoadConfig', 'config.LoadConfig', ([], {}), '()\n', (1923, 1925), False, 'from turbinia import config\n'), ((1937, 1982), 'turbinia.workers.analysis.postgresql_acct.PostgresAccountAnalysisTask', 'postgresql_acct.PostgresAccountAnalysisTask', ([], {}), '()\n', (1980, 1982), False, 'from turbinia.workers.analysis import postgresql_acct\n'), ((2245, 2264), 'turbinia.config.LoadConfig', 'config.LoadConfig', ([], {}), '()\n', (2262, 2264), False, 'from turbinia import config\n'), ((2276, 2321), 'turbinia.workers.analysis.postgresql_acct.PostgresAccountAnalysisTask', 'postgresql_acct.PostgresAccountAnalysisTask', ([], {}), '()\n', (2319, 2321), False, 'from turbinia.workers.analysis import postgresql_acct\n'), ((1308, 1334), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (1324, 1334), False, 'import os\n')] |
#!/usr/bin/env python
from collections import defaultdict
import gzip
import os
import pandas as pd
import sys
import pdb
def collectDataForMatchesToPMProteins(annotated_PM_proteins, blast_directory):
pORF_to_PM_protein_matches = defaultdict(set)
blast_file_columns = ["query", "subject", "perc_ident", "align_len", "num_mismatches", "num_gaps", \
"query_start", "query_end", "subject_start", "subject_end", "E_value", "bit_score"]
ip = gzip.open(annotated_PM_proteins, 'rb')
header = ip.readline()
for line in ip:
uniprot_id, aa_seq, tm_segments = line.strip().split("\t")
print >> sys.stderr, "\rINFO: processing Blast results for %s" % uniprot_id,
tm_segments_positions = []
for tm_segment in tm_segments.split(','):
start, stop = tm_segment.split('-')
tm_segments_positions.append( set(range(int(start),int(stop)+1)) )
blast_file = "%s/%s.blastp.bz2" % (blast_directory, uniprot_id)
assert(os.path.exists(blast_file))
min_TM_match_len = 15
blast_df = pd.read_csv(blast_file, sep="\t", header=None, skiprows=5, names=blast_file_columns, compression="bz2", skipfooter=1)
for tup in blast_df.itertuples(index=False):
match_positions = set(range(int(tup[6]), int(tup[7]+1)))
if (any(map(lambda x: len(match_positions & x) >= min_TM_match_len, tm_segments_positions))):
pORF_to_PM_protein_matches[tup[1]].add(uniprot_id)
ip.close()
print >> sys.stderr, "INFO: done\n"
return pORF_to_PM_protein_matches
def writeOutput(pORF_to_PM_protein_matches, output_tsv):
print >> sys.stderr, "INFO: writing output to %s" % output_tsv
op = gzip.open(output_tsv, 'wb')
op.write("pORF_ID\tPM_PROTEIN_ID\tGPI_PROTEIN_ID\n")
for pORF_ID, PM_protein_IDs in pORF_to_PM_protein_matches.items():
for protein_ID in PM_protein_IDs:
op.write("%s\t%s\t-\n" % (pORF_ID, protein_ID))
op.close()
if (__name__ == "__main__"):
annotated_PM_proteins, blast_directory, output_tsv = sys.argv[1:]
# Record which regions of each HMPAS protein aligned to which pORFs
pORF_to_PM_protein_matches = collectDataForMatchesToPMProteins(annotated_PM_proteins, blast_directory)
writeOutput(pORF_to_PM_protein_matches, output_tsv)
sys.exit(0)
| [
"os.path.exists",
"pandas.read_csv",
"gzip.open",
"collections.defaultdict",
"sys.exit"
] | [((243, 259), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (254, 259), False, 'from collections import defaultdict\n'), ((486, 524), 'gzip.open', 'gzip.open', (['annotated_PM_proteins', '"""rb"""'], {}), "(annotated_PM_proteins, 'rb')\n", (495, 524), False, 'import gzip\n'), ((1744, 1771), 'gzip.open', 'gzip.open', (['output_tsv', '"""wb"""'], {}), "(output_tsv, 'wb')\n", (1753, 1771), False, 'import gzip\n'), ((2360, 2371), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (2368, 2371), False, 'import sys\n'), ((1024, 1050), 'os.path.exists', 'os.path.exists', (['blast_file'], {}), '(blast_file)\n', (1038, 1050), False, 'import os\n'), ((1102, 1224), 'pandas.read_csv', 'pd.read_csv', (['blast_file'], {'sep': '"""\t"""', 'header': 'None', 'skiprows': '(5)', 'names': 'blast_file_columns', 'compression': '"""bz2"""', 'skipfooter': '(1)'}), "(blast_file, sep='\\t', header=None, skiprows=5, names=\n blast_file_columns, compression='bz2', skipfooter=1)\n", (1113, 1224), True, 'import pandas as pd\n')] |
# -*- coding: UTF-8 -*-
import numpy as np
from numpy.testing import assert_array_almost_equal
from spectral_clustering.spectral_embedding_ import spectral_embedding
def assert_first_col_equal(maps):
constant_vec = [1] * maps.shape[0]
assert_array_almost_equal(maps[:, 0] / maps[0, 0], constant_vec)
def test_spectral_embedding():
"""
根据spectral embedding的定义,第一列的数据是恒等的
"""
adjacency = np.array([
[0., 0.8, 0.9, 0.],
[0.8, 0., 0., 0.],
[0.9, 0., 0., 1.],
[0., 0., 1., 0.]])
maps = spectral_embedding(
adjacency, n_components=2, drop_first=False, eigen_solver="arpack")
assert_first_col_equal(maps)
maps_1 = spectral_embedding(
adjacency, n_components=2, drop_first=False, eigen_solver="lobpcg")
assert_first_col_equal(maps_1)
| [
"spectral_clustering.spectral_embedding_.spectral_embedding",
"numpy.array",
"numpy.testing.assert_array_almost_equal"
] | [((245, 309), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['(maps[:, 0] / maps[0, 0])', 'constant_vec'], {}), '(maps[:, 0] / maps[0, 0], constant_vec)\n', (270, 309), False, 'from numpy.testing import assert_array_almost_equal\n'), ((414, 516), 'numpy.array', 'np.array', (['[[0.0, 0.8, 0.9, 0.0], [0.8, 0.0, 0.0, 0.0], [0.9, 0.0, 0.0, 1.0], [0.0, \n 0.0, 1.0, 0.0]]'], {}), '([[0.0, 0.8, 0.9, 0.0], [0.8, 0.0, 0.0, 0.0], [0.9, 0.0, 0.0, 1.0],\n [0.0, 0.0, 1.0, 0.0]])\n', (422, 516), True, 'import numpy as np\n'), ((545, 635), 'spectral_clustering.spectral_embedding_.spectral_embedding', 'spectral_embedding', (['adjacency'], {'n_components': '(2)', 'drop_first': '(False)', 'eigen_solver': '"""arpack"""'}), "(adjacency, n_components=2, drop_first=False,\n eigen_solver='arpack')\n", (563, 635), False, 'from spectral_clustering.spectral_embedding_ import spectral_embedding\n'), ((687, 777), 'spectral_clustering.spectral_embedding_.spectral_embedding', 'spectral_embedding', (['adjacency'], {'n_components': '(2)', 'drop_first': '(False)', 'eigen_solver': '"""lobpcg"""'}), "(adjacency, n_components=2, drop_first=False,\n eigen_solver='lobpcg')\n", (705, 777), False, 'from spectral_clustering.spectral_embedding_ import spectral_embedding\n')] |
from setuptools import setup, find_packages
def readme():
with open('README.md') as f:
return f.read()
setup(
name='pyschemavalidator',
version='1.0.4',
description='Decorator for endpoint inputs on APIs and a dictionary/JSON validator.',
long_description=readme(),
long_description_content_type="text/markdown",
url='https://github.com/albarsil/pyschemavalidator',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9'
],
keywords=['api', 'flask', 'graphql', 'json', 'validation', 'schema', 'dictionary', 'graphql'],
packages=find_packages(exclude=['tests.*', 'tests']),
install_requires=[],
test_suite='tests.test_suite'
)
| [
"setuptools.find_packages"
] | [((903, 946), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests.*', 'tests']"}), "(exclude=['tests.*', 'tests'])\n", (916, 946), False, 'from setuptools import setup, find_packages\n')] |
"""
Specification for what parameters are used at what location within
the Cascade.
"""
from os import linesep
from types import SimpleNamespace
import networkx as nx
from cascade.core import getLoggers
from cascade.core.parameters import ParameterProperty, _ParameterHierarchy
from cascade.input_data import InputDataError
from cascade.input_data.configuration.builder import policies_from_settings
from cascade.input_data.configuration.sex import SEX_ID_TO_NAME, SEX_NAME_TO_ID
from cascade.input_data.db.locations import location_id_from_start_and_finish
from cascade.runner.application_config import application_config
from cascade.runner.job_graph import RecipeIdentifier
CODELOG, MATHLOG = getLoggers(__name__)
class EstimationParameters:
def __init__(self, settings, policies, children,
parent_location_id, grandparent_location_id, sexes, number_of_fixed_effect_samples,
model_options):
self.parent_location_id = parent_location_id
self.sexes = sexes
self.data_access = ParameterProperty()
"""These decide which data to get."""
self.run = ParameterProperty()
"""These affect how the program runs but not its results."""
self.grandparent_location_id = grandparent_location_id
"""Can be null at top of drill, even when not global location."""
self.model_options = model_options
self.children = children
self.settings = settings
self.policies = policies
self.number_of_fixed_effect_samples = number_of_fixed_effect_samples
def make_model_options(locations, parent_location_id, ev_settings):
bound_random = get_bound_random_this_location(locations, parent_location_id, ev_settings)
model_options = _ParameterHierarchy(**dict(
bound_random=bound_random,
))
return model_options
def get_bound_random_this_location(locations, parent_location_id, ev_settings):
# Set the bounds throughout the location hierarchy.
# hasattr is right here because any unset ancestor makes the parent unset.
# and one of the child forms can have an unset location or value.
location_tree = locations.copy()
if hasattr(ev_settings, "re_bound_location"):
add_bound_random_to_location_properties(ev_settings.re_bound_location, location_tree)
else:
CODELOG.debug("No re_bound_location in settings.")
# Get the global value, if it exists.
if not ev_settings.model.is_field_unset("bound_random"):
bound_random = ev_settings.model.bound_random
else:
bound_random = None
CODELOG.debug(f"Setting bound_random's default to {bound_random}")
# Search up the location hierarchy to see if an ancestor has a value.
this_and_ancestors = nx.ancestors(location_tree, parent_location_id) | {parent_location_id}
to_top = list(nx.topological_sort(nx.subgraph(location_tree, this_and_ancestors)))
to_top.reverse()
for check_bounds in to_top:
if "bound_random" in location_tree.node[check_bounds]:
CODELOG.debug(f"Found bound random in location {check_bounds}")
bound_random = location_tree.node[check_bounds]["bound_random"]
break
return bound_random
def add_bound_random_to_location_properties(re_bound_location, locations):
for bounds_form in re_bound_location:
if not bounds_form.is_field_unset("value"):
value = bounds_form.value
else:
value = None # This turns off bound random option.
if not bounds_form.is_field_unset("location"):
CODELOG.debug(f"setting {bounds_form.location} to {value}")
locations.node[bounds_form.location]["bound_random"] = value
else:
CODELOG.debug(f"setting root to {value}")
locations.node[locations.graph["root"]]["bound_random"] = value
def recipe_graph_from_settings(locations, settings, args):
"""
This defines the full set of recipes that are the model.
These may be a subset of all locations,
and we may execute a subset of these.
Args:
locations (nx.DiGraph): A graph of locations in a hierarchy.
settings (Configuration): The EpiViz-AT Form (in form.py)
args (Namespace|SimpleNamespace): Parsed arguments.
Returns:
nx.DiGraph: Each node is a RecipeIdentifier. Edges denote dependency
on a previous transform. The graph has a key called "root" that
tells you the first node.
"""
if not settings.model.is_field_unset("drill") and settings.model.drill == "drill":
recipe_graph = drill_recipe_graph(locations, settings, args)
else:
recipe_graph = global_recipe_graph(locations, settings, args)
for recipe_identifier in recipe_graph.nodes:
local_settings = location_specific_settings(locations, settings, args, recipe_identifier)
recipe_graph.nodes[recipe_identifier]["local_settings"] = local_settings
if len(recipe_graph) < application_config()["NonModel"].getint("small-graph-nodes"):
debug_lines = [str(node) for node in nx.topological_sort(recipe_graph)]
debug_str = f"{linesep}\t".join(debug_lines)
CODELOG.debug(f"Recipes in order{linesep}\t{debug_str}")
return recipe_graph
def drill_recipe_graph(locations, settings, args):
if not settings.model.is_field_unset("drill_location_start"):
drill_start = settings.model.drill_location_start
else:
drill_start = None
if not settings.model.is_field_unset("drill_location_end"):
drill_end = settings.model.drill_location_end
else:
raise InputDataError(f"Set to drill but drill location end not set")
try:
drill = location_id_from_start_and_finish(locations, drill_start, drill_end)
except ValueError as ve:
raise InputDataError(f"Location parameter is wrong in settings.") from ve
MATHLOG.info(f"drill nodes {', '.join(str(d) for d in drill)}")
drill = list(drill)
drill_sex = SEX_ID_TO_NAME[settings.model.drill_sex]
setup_task = [RecipeIdentifier(0, "bundle_setup", drill_sex)]
recipes = setup_task + [
RecipeIdentifier(drill_location, "estimate_location", drill_sex)
for drill_location in drill
]
recipe_pairs = list(zip(recipes[:-1], recipes[1:]))
recipe_graph = nx.DiGraph(root=recipes[0])
recipe_graph.add_nodes_from(recipes)
recipe_graph.add_edges_from(recipe_pairs)
return recipe_graph
def global_recipe_graph(locations, settings, args):
"""
Constructs the graph of recipes.
Args:
locations (nx.DiGraph): Root node in the data, and each node
has a level.
settings: The global settings object.
args (Namespace|SimpleNamespace): Command-line arguments.
Returns:
nx.DiGraph: Each node is a RecipeIdentifier.
"""
assert "root" in locations.graph
if settings.model.split_sex == "most_detailed":
split_sex = max([locations.nodes[nl]["level"] for nl in locations.nodes])
else:
split_sex = int(settings.model.split_sex)
global_node = RecipeIdentifier(locations.graph["root"], "estimate_location", "both")
recipe_graph = nx.DiGraph(root=global_node)
# Start with bundle setup
bundle_setup = RecipeIdentifier(0, "bundle_setup", "both")
recipe_graph.graph["root"] = bundle_setup
recipe_graph.add_edge(bundle_setup, global_node)
global_recipe_graph_add_estimations(locations, recipe_graph, split_sex)
return recipe_graph
def global_recipe_graph_add_estimations(locations, recipe_graph, split_sex):
"""There are estimations for every location and for both sexes below
the level where we split sex. This modifies the recipe graph in place."""
# Follow location hierarchy, splitting into male and female below a level.
for start, finish in locations.edges:
if "level" not in locations.nodes[finish]:
raise RuntimeError(
"Expect location graph nodes to have a level property")
finish_level = locations.nodes[finish]["level"]
if finish_level == split_sex:
for finish_sex in ["male", "female"]:
recipe_graph.add_edge(
RecipeIdentifier(start, "estimate_location", "both"),
RecipeIdentifier(finish, "estimate_location", finish_sex),
)
elif finish_level > split_sex:
for same_sex in ["male", "female"]:
recipe_graph.add_edge(
RecipeIdentifier(start, "estimate_location", same_sex),
RecipeIdentifier(finish, "estimate_location", same_sex),
)
else:
recipe_graph.add_edge(
RecipeIdentifier(start, "estimate_location", "both"),
RecipeIdentifier(finish, "estimate_location", "both"),
)
def location_specific_settings(locations, settings, args, recipe_id):
"""
This takes a modeler's description of how the model should be set up,
as described in settings and command-line arguments, and translates
it into what choices apply to this particular recipe. Modelers discuss
plans in terms of what rules apply to which level of the Cascade,
so this works in those terms, not in terms of individual tasks
within a recipe.
Adds ``settings.model.parent_location_id``,
``settings.model.grandparent_location_id``,
and ``settings.model.children``.
There is a grandparent location only if there is a grandparent recipe,
so a drill starting halfway will not have a grandparent location.
There are child locations for the last task though.
Args:
locations (nx.DiGraph): Location hierarchy
settings: Settings from EpiViz-AT
args (Namespace|SimpleNamespace): Command-line arguments
recipe_id (RecipeIdentifier): Identifies what happens at
this location.
Returns:
Settings for this job.
"""
parent_location_id = recipe_id.location_id
if parent_location_id != 0:
predecessors = list(locations.predecessors(parent_location_id))
successors = list(sorted(locations.successors(parent_location_id)))
model_options = make_model_options(locations, parent_location_id, settings)
else:
predecessors = None
successors = None
model_options = None
if predecessors:
grandparent_location_id = predecessors[0]
else:
grandparent_location_id = None
if settings.model.is_field_unset("drill_sex"):
# An unset drill sex gets all data.
sexes = list(SEX_ID_TO_NAME.keys())
else:
# Setting to male or female pulls in "both."
sexes = [settings.model.drill_sex, SEX_NAME_TO_ID["both"]]
policies = policies_from_settings(settings)
if args.num_samples:
sample_cnt = args.num_samples
else:
sample_cnt = policies["number_of_fixed_effect_samples"]
local_settings = EstimationParameters(
settings=settings,
policies=SimpleNamespace(**policies),
children=successors,
parent_location_id=parent_location_id,
grandparent_location_id=grandparent_location_id,
# This is a list of [1], [3], [1,3], [2,3], [1,2,3], not [1,2].
sexes=sexes,
number_of_fixed_effect_samples=sample_cnt,
model_options=model_options,
)
local_settings.data_access = _ParameterHierarchy(**dict(
gbd_round_id=policies["gbd_round_id"],
decomp_step=policies["decomp_step"],
modelable_entity_id=settings.model.modelable_entity_id,
model_version_id=settings.model.model_version_id,
settings_file=args.settings_file,
bundle_file=args.bundle_file,
bundle_id=settings.model.bundle_id,
bundle_study_covariates_file=args.bundle_study_covariates_file,
tier=2 if args.skip_cache else 3,
age_group_set_id=policies["age_group_set_id"],
with_hiv=policies["with_hiv"],
cod_version=settings.csmr_cod_output_version_id,
location_set_version_id=settings.location_set_version_id,
add_csmr_cause=settings.model.add_csmr_cause,
))
local_settings.run = _ParameterHierarchy(**dict(
no_upload=args.no_upload,
db_only=args.db_only,
))
return local_settings
| [
"networkx.topological_sort",
"types.SimpleNamespace",
"networkx.DiGraph",
"cascade.input_data.InputDataError",
"cascade.runner.job_graph.RecipeIdentifier",
"cascade.input_data.configuration.sex.SEX_ID_TO_NAME.keys",
"networkx.subgraph",
"cascade.core.getLoggers",
"cascade.core.parameters.ParameterPr... | [((699, 719), 'cascade.core.getLoggers', 'getLoggers', (['__name__'], {}), '(__name__)\n', (709, 719), False, 'from cascade.core import getLoggers\n'), ((6327, 6354), 'networkx.DiGraph', 'nx.DiGraph', ([], {'root': 'recipes[0]'}), '(root=recipes[0])\n', (6337, 6354), True, 'import networkx as nx\n'), ((7106, 7176), 'cascade.runner.job_graph.RecipeIdentifier', 'RecipeIdentifier', (["locations.graph['root']", '"""estimate_location"""', '"""both"""'], {}), "(locations.graph['root'], 'estimate_location', 'both')\n", (7122, 7176), False, 'from cascade.runner.job_graph import RecipeIdentifier\n'), ((7196, 7224), 'networkx.DiGraph', 'nx.DiGraph', ([], {'root': 'global_node'}), '(root=global_node)\n', (7206, 7224), True, 'import networkx as nx\n'), ((7274, 7317), 'cascade.runner.job_graph.RecipeIdentifier', 'RecipeIdentifier', (['(0)', '"""bundle_setup"""', '"""both"""'], {}), "(0, 'bundle_setup', 'both')\n", (7290, 7317), False, 'from cascade.runner.job_graph import RecipeIdentifier\n'), ((10799, 10831), 'cascade.input_data.configuration.builder.policies_from_settings', 'policies_from_settings', (['settings'], {}), '(settings)\n', (10821, 10831), False, 'from cascade.input_data.configuration.builder import policies_from_settings\n'), ((1045, 1064), 'cascade.core.parameters.ParameterProperty', 'ParameterProperty', ([], {}), '()\n', (1062, 1064), False, 'from cascade.core.parameters import ParameterProperty, _ParameterHierarchy\n'), ((1131, 1150), 'cascade.core.parameters.ParameterProperty', 'ParameterProperty', ([], {}), '()\n', (1148, 1150), False, 'from cascade.core.parameters import ParameterProperty, _ParameterHierarchy\n'), ((2764, 2811), 'networkx.ancestors', 'nx.ancestors', (['location_tree', 'parent_location_id'], {}), '(location_tree, parent_location_id)\n', (2776, 2811), True, 'import networkx as nx\n'), ((5625, 5687), 'cascade.input_data.InputDataError', 'InputDataError', (['f"""Set to drill but drill location end not set"""'], {}), "(f'Set to drill but drill location end not set')\n", (5639, 5687), False, 'from cascade.input_data import InputDataError\n'), ((5713, 5781), 'cascade.input_data.db.locations.location_id_from_start_and_finish', 'location_id_from_start_and_finish', (['locations', 'drill_start', 'drill_end'], {}), '(locations, drill_start, drill_end)\n', (5746, 5781), False, 'from cascade.input_data.db.locations import location_id_from_start_and_finish\n'), ((6060, 6106), 'cascade.runner.job_graph.RecipeIdentifier', 'RecipeIdentifier', (['(0)', '"""bundle_setup"""', 'drill_sex'], {}), "(0, 'bundle_setup', drill_sex)\n", (6076, 6106), False, 'from cascade.runner.job_graph import RecipeIdentifier\n'), ((2873, 2919), 'networkx.subgraph', 'nx.subgraph', (['location_tree', 'this_and_ancestors'], {}), '(location_tree, this_and_ancestors)\n', (2884, 2919), True, 'import networkx as nx\n'), ((5825, 5884), 'cascade.input_data.InputDataError', 'InputDataError', (['f"""Location parameter is wrong in settings."""'], {}), "(f'Location parameter is wrong in settings.')\n", (5839, 5884), False, 'from cascade.input_data import InputDataError\n'), ((6145, 6209), 'cascade.runner.job_graph.RecipeIdentifier', 'RecipeIdentifier', (['drill_location', '"""estimate_location"""', 'drill_sex'], {}), "(drill_location, 'estimate_location', drill_sex)\n", (6161, 6209), False, 'from cascade.runner.job_graph import RecipeIdentifier\n'), ((10630, 10651), 'cascade.input_data.configuration.sex.SEX_ID_TO_NAME.keys', 'SEX_ID_TO_NAME.keys', ([], {}), '()\n', (10649, 10651), False, 'from cascade.input_data.configuration.sex import SEX_ID_TO_NAME, SEX_NAME_TO_ID\n'), ((11057, 11084), 'types.SimpleNamespace', 'SimpleNamespace', ([], {}), '(**policies)\n', (11072, 11084), False, 'from types import SimpleNamespace\n'), ((5091, 5124), 'networkx.topological_sort', 'nx.topological_sort', (['recipe_graph'], {}), '(recipe_graph)\n', (5110, 5124), True, 'import networkx as nx\n'), ((4984, 5004), 'cascade.runner.application_config.application_config', 'application_config', ([], {}), '()\n', (5002, 5004), False, 'from cascade.runner.application_config import application_config\n'), ((8228, 8280), 'cascade.runner.job_graph.RecipeIdentifier', 'RecipeIdentifier', (['start', '"""estimate_location"""', '"""both"""'], {}), "(start, 'estimate_location', 'both')\n", (8244, 8280), False, 'from cascade.runner.job_graph import RecipeIdentifier\n'), ((8302, 8359), 'cascade.runner.job_graph.RecipeIdentifier', 'RecipeIdentifier', (['finish', '"""estimate_location"""', 'finish_sex'], {}), "(finish, 'estimate_location', finish_sex)\n", (8318, 8359), False, 'from cascade.runner.job_graph import RecipeIdentifier\n'), ((8741, 8793), 'cascade.runner.job_graph.RecipeIdentifier', 'RecipeIdentifier', (['start', '"""estimate_location"""', '"""both"""'], {}), "(start, 'estimate_location', 'both')\n", (8757, 8793), False, 'from cascade.runner.job_graph import RecipeIdentifier\n'), ((8811, 8864), 'cascade.runner.job_graph.RecipeIdentifier', 'RecipeIdentifier', (['finish', '"""estimate_location"""', '"""both"""'], {}), "(finish, 'estimate_location', 'both')\n", (8827, 8864), False, 'from cascade.runner.job_graph import RecipeIdentifier\n'), ((8525, 8579), 'cascade.runner.job_graph.RecipeIdentifier', 'RecipeIdentifier', (['start', '"""estimate_location"""', 'same_sex'], {}), "(start, 'estimate_location', same_sex)\n", (8541, 8579), False, 'from cascade.runner.job_graph import RecipeIdentifier\n'), ((8601, 8656), 'cascade.runner.job_graph.RecipeIdentifier', 'RecipeIdentifier', (['finish', '"""estimate_location"""', 'same_sex'], {}), "(finish, 'estimate_location', same_sex)\n", (8617, 8656), False, 'from cascade.runner.job_graph import RecipeIdentifier\n')] |