code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
#------------------------------------------------------------------------------ # File: GeoTiff.pm # # Description: Read GeoTiff meta information # # Revisions: 02/23/2004 - P. Harvey Created # 02/25/2004 - PH Added new codes from libgeotiff-1.2.1 # 02/01/2007 - PH Added new codes from libgeotiff-1.2.3 # 01/22/2014 - PH Added new code from libgeotiff-1.4.0 # 01/19/2015 - PH Added ChartTIFF tags # # References: 1) ftp://ftp.remotesensing.org/geotiff/libgeotiff/libgeotiff-1.1.4.tar.gz # 2) http://www.charttiff.com/whitepapers.shtml #------------------------------------------------------------------------------ package Image::ExifTool::GeoTiff; use strict; use vars qw($VERSION); use Image::ExifTool qw(:DataAccess :Utils); $VERSION = '1.11'; # format codes for geoTiff directory entries my %geoTiffFormat = ( 0 => 'int16u', 0x87b0 => 'double', 0x87b1 => 'string', ); my %epsg_units = ( 9001 => 'Linear Meter', 9002 => 'Linear Foot', 9003 => 'Linear Foot US Survey', 9004 => 'Linear Foot Modified American', 9005 => 'Linear Foot Clarke', 9006 => 'Linear Foot Indian', 9007 => 'Linear Link', 9008 => 'Linear Link Benoit', 9009 => 'Linear Link Sears', 9010 => 'Linear Chain Benoit', 9011 => 'Linear Chain Sears', 9012 => 'Linear Yard Sears', 9013 => 'Linear Yard Indian', 9014 => 'Linear Fathom', 9015 => 'Linear Mile International Nautical', 9101 => 'Angular Radian', 9102 => 'Angular Degree', 9103 => 'Angular Arc Minute', 9104 => 'Angular Arc Second', 9105 => 'Angular Grad', 9106 => 'Angular Gon', 9107 => 'Angular DMS', 9108 => 'Angular DMS Hemisphere', 32767 => 'User Defined', ); my %epsg_vertcs = ( 0 => 'Undefined', 5001 => 'Airy 1830 ellipsoid', 5002 => 'Airy Modified 1849 ellipsoid', 5003 => 'ANS ellipsoid', 5004 => 'Bessel 1841 ellipsoid', 5005 => 'Bessel Modified ellipsoid', 5006 => 'Bessel Namibia ellipsoid', 5007 => 'Clarke 1858 ellipsoid', 5008 => 'Clarke 1866 ellipsoid', 5010 => 'Clarke 1880 Benoit ellipsoid', 5011 => 'Clarke 1880 IGN ellipsoid', 5012 => 'Clarke 1880 RGS ellipsoid', 5013 => 'Clarke 1880 Arc ellipsoid', 5014 => 'Clarke 1880 SGA 1922 ellipsoid', 5015 => 'Everest 1830 1937 Adjustment ellipsoid', 5016 => 'Everest 1830 1967 Definition ellipsoid', 5017 => 'Everest 1830 1975 Definition ellipsoid', 5018 => 'Everest 1830 Modified ellipsoid', 5019 => 'GRS 1980 ellipsoid', 5020 => 'Helmert 1906 ellipsoid', 5021 => 'INS ellipsoid', 5022 => 'International 1924 ellipsoid', 5023 => 'International 1967 ellipsoid', 5024 => 'Krassowsky 1940 ellipsoid', 5025 => 'NWL 9D ellipsoid', 5026 => 'NWL 10D ellipsoid', 5027 => 'Plessis 1817 ellipsoid', 5028 => 'Struve 1860 ellipsoid', 5029 => 'War Office ellipsoid', 5030 => 'WGS 84 ellipsoid', 5031 => 'GEM 10C ellipsoid', 5032 => 'OSU86F ellipsoid', 5033 => 'OSU91A ellipsoid', 5101 => 'Newlyn', 5102 => 'North American Vertical Datum 1929', 5103 => 'North American Vertical Datum 1988', 5104 => 'Yellow Sea 1956', 5105 => 'Baltic Sea', 5106 => 'Caspian Sea', 32767 => 'User Defined', ); %Image::ExifTool::GeoTiff::Main = ( GROUPS => { 2 => 'Location' }, 1 => { # this isn't a real GeoTiff key, but put it here # so it will appear in tag lists since we generate it below Name => 'GeoTiffVersion', }, 1024 => { Name => 'GTModelType', PrintConv => { 1 => 'Projected', 2 => 'Geographic', 3 => 'Geocentric', 32767 => 'User Defined', }, }, 1025 => { Name => 'GTRasterType', PrintConv => { 1 => 'Pixel Is Area', 2 => 'Pixel Is Point', 32767 => 'User Defined', }, }, 1026 => 'GTCitation', 2048 => { Name => 'GeographicType', PrintConv => { # epsg_gcs 4001 => 'Airy 1830', 4002 => 'Airy Modified 1849', 4003 => 'Australian National Spheroid', 4004 => 'Bessel 1841', 4005 => 'Bessel Modified', 4006 => 'Bessel Namibia', 4007 => 'Clarke 1858', 4008 => 'Clarke 1866', 4009 => 'Clarke 1866 Michigan', 4010 => 'Clarke 1880 Benoit', 4011 => 'Clarke 1880 IGN', 4012 => 'Clarke 1880 RGS', 4013 => 'Clarke 1880 Arc', 4014 => 'Clarke 1880 SGA 1922', 4015 => 'Everest 1830 1937 Adjustment', 4016 => 'Everest 1830 1967 Definition', 4017 => 'Everest 1830 1975 Definition', 4018 => 'Everest 1830 Modified', 4019 => 'GRS 1980', 4020 => 'Helmert 1906', 4021 => 'Indonesian National Spheroid', 4022 => 'International 1924', 4023 => 'International 1967', 4024 => 'Krassowsky 1940', 4025 => 'NWL9D', 4026 => 'NWL10D', 4027 => 'Plessis 1817', 4028 => 'Struve 1860', 4029 => 'War Office', 4030 => 'WGS84', 4031 => 'GEM10C', 4032 => 'OSU86F', 4033 => 'OSU91A', 4034 => 'Clarke 1880', 4035 => 'Sphere', 4120 => 'Greek', 4121 => 'GGRS87', 4123 => 'KKJ', 4124 => 'RT90', 4133 => 'EST92', 4815 => 'Greek Athens', 4201 => 'Adindan', 4202 => 'AGD66', 4203 => 'AGD84', 4204 => 'Ain el Abd', 4205 => 'Afgooye', 4206 => 'Agadez', 4207 => 'Lisbon', 4208 => 'Aratu', 4209 => 'Arc 1950', 4210 => 'Arc 1960', 4211 => 'Batavia', 4212 => 'Barbados', 4213 => 'Beduaram', 4214 => 'Beijing 1954', 4215 => 'Belge 1950', 4216 => 'Bermuda 1957', 4217 => 'Bern 1898', 4218 => 'Bogota', 4219 => 'Bukit Rimpah', 4220 => 'Camacupa', 4221 => 'Campo Inchauspe', 4222 => 'Cape', 4223 => 'Carthage', 4224 => 'Chua', 4225 => 'Corrego Alegre', 4226 => 'Cote d Ivoire', 4227 => 'Deir ez Zor', 4228 => 'Douala', 4229 => 'Egypt 1907', 4230 => 'ED50', 4231 => 'ED87', 4232 => 'Fahud', 4233 => 'Gandajika 1970', 4234 => 'Garoua', 4235 => 'Guyane Francaise', 4236 => 'Hu Tzu Shan', 4237 => 'HD72', 4238 => 'ID74', 4239 => 'Indian 1954', 4240 => 'Indian 1975', 4241 => 'Jamaica 1875', 4242 => 'JAD69', 4243 => 'Kalianpur', 4244 => 'Kandawala', 4245 => 'Kertau', 4246 => 'KOC', 4247 => 'La Canoa', 4248 => 'PSAD56', 4249 => 'Lake', 4250 => 'Leigon', 4251 => 'Liberia 1964', 4252 => 'Lome', 4253 => 'Luzon 1911', 4254 => 'Hito XVIII 1963', 4255 => 'Herat North', 4256 => 'Mahe 1971', 4257 => 'Makassar', 4258 => 'EUREF89', 4259 => 'Malongo 1987', 4260 => 'Manoca', 4261 => 'Merchich', 4262 => 'Massawa', 4263 => 'Minna', 4264 => 'Mhast', 4265 => 'Monte Mario', 4266 => 'M poraloko', 4267 => 'NAD27', 4268 => 'NAD Michigan', 4269 => 'NAD83', 4270 => 'Nahrwan 1967', 4271 => 'Naparima 1972', 4272 => 'GD49', 4273 => 'NGO 1948', 4274 => '73', 4275 => 'NTF', 4276 => 'NSWC 9Z 2', 4277 => 'OSGB 1936', 4278 => 'OSGB70', 4279 => 'OS SN80', 4280 => 'Padang', 4281 => 'Palestine 1923', 4282 => 'Pointe Noire', 4283 => 'GDA94', 4284 => 'Pulkovo 1942', 4285 => 'Qatar', 4286 => 'Qatar 1948', 4287 => 'Qornoq', 4288 => 'Loma Quintana', 4289 => 'Amersfoort', 4290 => 'RT38', 4291 => 'SAD69', 4292 => 'Sapper Hill 1943', 4293 => 'Schwarzeck', 4294 => 'Segora', 4295 => 'Serindung', 4296 => 'Sudan', 4297 => 'Tananarive', 4298 => 'Timbalai 1948', 4299 => 'TM65', 4300 => 'TM75', 4301 => 'Tokyo', 4302 => 'Trinidad 1903', 4303 => 'TC 1948', 4304 => 'Voirol 1875', 4305 => 'Voirol Unifie', 4306 => 'Bern 1938', 4307 => 'Nord Sahara 1959', 4308 => 'Stockholm 1938', 4309 => 'Yacare', 4310 => 'Yoff', 4311 => 'Zanderij', 4312 => 'MGI', 4313 => 'Belge 1972', 4314 => 'DHDN', 4315 => 'Conakry 1905', 4317 => 'Dealul Piscului 1970', 4322 => 'WGS 72', 4324 => 'WGS 72BE', 4326 => 'WGS 84', 4801 => 'Bern 1898 Bern', 4802 => 'Bogota Bogota', 4803 => 'Lisbon Lisbon', 4804 => 'Makassar Jakarta', 4805 => 'MGI Ferro', 4806 => 'Monte Mario Rome', 4807 => 'NTF Paris', 4808 => 'Padang Jakarta', 4809 => 'Belge 1950 Brussels', 4810 => 'Tananarive Paris', 4811 => 'Voirol 1875 Paris', 4812 => 'Voirol Unifie Paris', 4813 => 'Batavia Jakarta', 4901 => 'ATF Paris', 4902 => 'NDG Paris', 32767 => 'User Defined', }, }, 2049 => 'GeogCitation', 2050 => { Name => 'GeogGeodeticDatum', PrintConv => { # epsg_datum, 6001 => 'Airy 1830', 6002 => 'Airy Modified 1849', 6003 => 'Australian National Spheroid', 6004 => 'Bessel 1841', 6005 => 'Bessel Modified', 6006 => 'Bessel Namibia', 6007 => 'Clarke 1858', 6008 => 'Clarke 1866', 6009 => 'Clarke 1866 Michigan', 6010 => 'Clarke 1880 Benoit', 6011 => 'Clarke 1880 IGN', 6012 => 'Clarke 1880 RGS', 6013 => 'Clarke 1880 Arc', 6014 => 'Clarke 1880 SGA 1922', 6015 => 'Everest 1830 1937 Adjustment', 6016 => 'Everest 1830 1967 Definition', 6017 => 'Everest 1830 1975 Definition', 6018 => 'Everest 1830 Modified', 6019 => 'GRS 1980', 6020 => 'Helmert 1906', 6021 => 'Indonesian National Spheroid', 6022 => 'International 1924', 6023 => 'International 1967', 6024 => 'Krassowsky 1960', 6025 => 'NWL9D', 6026 => 'NWL10D', 6027 => 'Plessis 1817', 6028 => 'Struve 1860', 6029 => 'War Office', 6030 => 'WGS84', 6031 => 'GEM10C', 6032 => 'OSU86F', 6033 => 'OSU91A', 6034 => 'Clarke 1880', 6035 => 'Sphere', 6201 => 'Adindan', 6202 => 'Australian Geodetic Datum 1966', 6203 => 'Australian Geodetic Datum 1984', 6204 => 'Ain el Abd 1970', 6205 => 'Afgooye', 6206 => 'Agadez', 6207 => 'Lisbon', 6208 => 'Aratu', 6209 => 'Arc 1950', 6210 => 'Arc 1960', 6211 => 'Batavia', 6212 => 'Barbados', 6213 => 'Beduaram', 6214 => 'Beijing 1954', 6215 => 'Reseau National Belge 1950', 6216 => 'Bermuda 1957', 6217 => 'Bern 1898', 6218 => 'Bogota', 6219 => 'Bukit Rimpah', 6220 => 'Camacupa', 6221 => 'Campo Inchauspe', 6222 => 'Cape', 6223 => 'Carthage', 6224 => 'Chua', 6225 => 'Corrego Alegre', 6226 => 'Cote d Ivoire', 6227 => 'Deir ez Zor', 6228 => 'Douala', 6229 => 'Egypt 1907', 6230 => 'European Datum 1950', 6231 => 'European Datum 1987', 6232 => 'Fahud', 6233 => 'Gandajika 1970', 6234 => 'Garoua', 6235 => 'Guyane Francaise', 6236 => 'Hu Tzu Shan', 6237 => 'Hungarian Datum 1972', 6238 => 'Indonesian Datum 1974', 6239 => 'Indian 1954', 6240 => 'Indian 1975', 6241 => 'Jamaica 1875', 6242 => 'Jamaica 1969', 6243 => 'Kalianpur', 6244 => 'Kandawala', 6245 => 'Kertau', 6246 => 'Kuwait Oil Company', 6247 => 'La Canoa', 6248 => 'Provisional S American Datum 1956', 6249 => 'Lake', 6250 => 'Leigon', 6251 => 'Liberia 1964', 6252 => 'Lome', 6253 => 'Luzon 1911', 6254 => 'Hito XVIII 1963', 6255 => 'Herat North', 6256 => 'Mahe 1971', 6257 => 'Makassar', 6258 => 'European Reference System 1989', 6259 => 'Malongo 1987', 6260 => 'Manoca', 6261 => 'Merchich', 6262 => 'Massawa', 6263 => 'Minna', 6264 => 'Mhast', 6265 => 'Monte Mario', 6266 => 'M poraloko', 6267 => 'North American Datum 1927', 6268 => 'NAD Michigan', 6269 => 'North American Datum 1983', 6270 => 'Nahrwan 1967', 6271 => 'Naparima 1972', 6272 => 'New Zealand Geodetic Datum 1949', 6273 => 'NGO 1948', 6274 => 'Datum 73', 6275 => 'Nouvelle Triangulation Francaise', 6276 => 'NSWC 9Z 2', 6277 => 'OSGB 1936', 6278 => 'OSGB 1970 SN', 6279 => 'OS SN 1980', 6280 => 'Padang 1884', 6281 => 'Palestine 1923', 6282 => 'Pointe Noire', 6283 => 'Geocentric Datum of Australia 1994', 6284 => 'Pulkovo 1942', 6285 => 'Qatar', 6286 => 'Qatar 1948', 6287 => 'Qornoq', 6288 => 'Loma Quintana', 6289 => 'Amersfoort', 6290 => 'RT38', 6291 => 'South American Datum 1969', 6292 => 'Sapper Hill 1943', 6293 => 'Schwarzeck', 6294 => 'Segora', 6295 => 'Serindung', 6296 => 'Sudan', 6297 => 'Tananarive 1925', 6298 => 'Timbalai 1948', 6299 => 'TM65', 6300 => 'TM75', 6301 => 'Tokyo', 6302 => 'Trinidad 1903', 6303 => 'Trucial Coast 1948', 6304 => 'Voirol 1875', 6305 => 'Voirol Unifie 1960', 6306 => 'Bern 1938', 6307 => 'Nord Sahara 1959', 6308 => 'Stockholm 1938', 6309 => 'Yacare', 6310 => 'Yoff', 6311 => 'Zanderij', 6312 => 'Militar Geographische Institut', 6313 => 'Reseau National Belge 1972', 6314 => 'Deutsche Hauptdreiecksnetz', 6315 => 'Conakry 1905', 6317 => 'Dealul Piscului 1970', 6322 => 'WGS72', 6324 => 'WGS72 Transit Broadcast Ephemeris', 6326 => 'WGS84', 6901 => 'Ancienne Triangulation Francaise', 6902 => 'Nord de Guerre', 32767 => 'User Defined', }, }, 2051 => { Name => 'GeogPrimeMeridian', PrintConv => { # epsg_pm 8901 => 'Greenwich', 8902 => 'Lisbon', 8903 => 'Paris', 8904 => 'Bogota', 8905 => 'Madrid', 8906 => 'Rome', 8907 => 'Bern', 8908 => 'Jakarta', 8909 => 'Ferro', 8910 => 'Brussels', 8911 => 'Stockholm', 32767 => 'User Defined', }, }, 2052 => { Name => 'GeogLinearUnits', SeparateTable => 'Units', PrintConv => \%epsg_units, }, 2053 => 'GeogLinearUnitSize', 2054 => { Name => 'GeogAngularUnits', SeparateTable => 'Units', PrintConv => \%epsg_units, }, 2055 => 'GeogAngularUnitSize', 2056 => { Name => 'GeogEllipsoid', PrintConv => { # epsg_ellipse 7001 => 'Airy 1830', 7002 => 'Airy Modified 1849', 7003 => 'Australian National Spheroid', 7004 => 'Bessel 1841', 7005 => 'Bessel Modified', 7006 => 'Bessel Namibia', 7007 => 'Clarke 1858', 7008 => 'Clarke 1866', 7009 => 'Clarke 1866 Michigan', 7010 => 'Clarke 1880 Benoit', 7011 => 'Clarke 1880 IGN', 7012 => 'Clarke 1880 RGS', 7013 => 'Clarke 1880 Arc', 7014 => 'Clarke 1880 SGA 1922', 7015 => 'Everest 1830 1937 Adjustment', 7016 => 'Everest 1830 1967 Definition', 7017 => 'Everest 1830 1975 Definition', 7018 => 'Everest 1830 Modified', 7019 => 'GRS 1980', 7020 => 'Helmert 1906', 7021 => 'Indonesian National Spheroid', 7022 => 'International 1924', 7023 => 'International 1967', 7024 => 'Krassowsky 1940', 7025 => 'NWL 9D', 7026 => 'NWL 10D', 7027 => 'Plessis 1817', 7028 => 'Struve 1860', 7029 => 'War Office', 7030 => 'WGS 84', 7031 => 'GEM 10C', 7032 => 'OSU86F', 7033 => 'OSU91A', 7034 => 'Clarke 1880', 7035 => 'Sphere', 32767 => 'User Defined', }, }, 2057 => 'GeogSemiMajorAxis', 2058 => 'GeogSemiMinorAxis', 2059 => 'GeogInvFlattening', 2060 => { Name => 'GeogAzimuthUnits', SeparateTable => 'Units', PrintConv => \%epsg_units, }, 2061 => 'GeogPrimeMeridianLong', 2062 => 'GeogToWGS84', 3072 => { Name => 'ProjectedCSType', PrintConv => { # epsg_pcs 2100 => 'GGRS87 Greek Grid', 2176 => 'ETRS89 Poland CS2000 zone 5', 2177 => 'ETRS89 Poland CS2000 zone 6', 2177 => 'ETRS89 Poland CS2000 zone 7', 2178 => 'ETRS89 Poland CS2000 zone 8', 2180 => 'ETRS89 Poland CS92', 2204 => 'NAD27 Tennessee', 2205 => 'NAD83 Kentucky North', 2391 => 'KKJ Finland zone 1', 2392 => 'KKJ Finland zone 2', 2393 => 'KKJ Finland zone 3', 2394 => 'KKJ Finland zone 4', 2400 => 'RT90 2 5 gon W', 2600 => 'Lietuvos Koordinoei Sistema 1994', 3053 => 'Hjorsey 1955 Lambert', 3057 => 'ISN93 Lambert 1993', 3300 => 'Estonian Coordinate System of 1992', 20137 => 'Adindan UTM zone 37N', 20138 => 'Adindan UTM zone 38N', 20248 => 'AGD66 AMG zone 48', 20249 => 'AGD66 AMG zone 49', 20250 => 'AGD66 AMG zone 50', 20251 => 'AGD66 AMG zone 51', 20252 => 'AGD66 AMG zone 52', 20253 => 'AGD66 AMG zone 53', 20254 => 'AGD66 AMG zone 54', 20255 => 'AGD66 AMG zone 55', 20256 => 'AGD66 AMG zone 56', 20257 => 'AGD66 AMG zone 57', 20258 => 'AGD66 AMG zone 58', 20348 => 'AGD84 AMG zone 48', 20349 => 'AGD84 AMG zone 49', 20350 => 'AGD84 AMG zone 50', 20351 => 'AGD84 AMG zone 51', 20352 => 'AGD84 AMG zone 52', 20353 => 'AGD84 AMG zone 53', 20354 => 'AGD84 AMG zone 54', 20355 => 'AGD84 AMG zone 55', 20356 => 'AGD84 AMG zone 56', 20357 => 'AGD84 AMG zone 57', 20358 => 'AGD84 AMG zone 58', 20437 => 'Ain el Abd UTM zone 37N', 20438 => 'Ain el Abd UTM zone 38N', 20439 => 'Ain el Abd UTM zone 39N', 20499 => 'Ain el Abd Bahrain Grid', 20538 => 'Afgooye UTM zone 38N', 20539 => 'Afgooye UTM zone 39N', 20700 => 'Lisbon Portugese Grid', 20822 => 'Aratu UTM zone 22S', 20823 => 'Aratu UTM zone 23S', 20824 => 'Aratu UTM zone 24S', 20973 => 'Arc 1950 Lo13', 20975 => 'Arc 1950 Lo15', 20977 => 'Arc 1950 Lo17', 20979 => 'Arc 1950 Lo19', 20981 => 'Arc 1950 Lo21', 20983 => 'Arc 1950 Lo23', 20985 => 'Arc 1950 Lo25', 20987 => 'Arc 1950 Lo27', 20989 => 'Arc 1950 Lo29', 20991 => 'Arc 1950 Lo31', 20993 => 'Arc 1950 Lo33', 20995 => 'Arc 1950 Lo35', 21100 => 'Batavia NEIEZ', 21148 => 'Batavia UTM zone 48S', 21149 => 'Batavia UTM zone 49S', 21150 => 'Batavia UTM zone 50S', 21413 => 'Beijing Gauss zone 13', 21414 => 'Beijing Gauss zone 14', 21415 => 'Beijing Gauss zone 15', 21416 => 'Beijing Gauss zone 16', 21417 => 'Beijing Gauss zone 17', 21418 => 'Beijing Gauss zone 18', 21419 => 'Beijing Gauss zone 19', 21420 => 'Beijing Gauss zone 20', 21421 => 'Beijing Gauss zone 21', 21422 => 'Beijing Gauss zone 22', 21423 => 'Beijing Gauss zone 23', 21473 => 'Beijing Gauss 13N', 21474 => 'Beijing Gauss 14N', 21475 => 'Beijing Gauss 15N', 21476 => 'Beijing Gauss 16N', 21477 => 'Beijing Gauss 17N', 21478 => 'Beijing Gauss 18N', 21479 => 'Beijing Gauss 19N', 21480 => 'Beijing Gauss 20N', 21481 => 'Beijing Gauss 21N', 21482 => 'Beijing Gauss 22N', 21483 => 'Beijing Gauss 23N', 21500 => 'Belge Lambert 50', 21790 => 'Bern 1898 Swiss Old', 21817 => 'Bogota UTM zone 17N', 21818 => 'Bogota UTM zone 18N', 21891 => 'Bogota Colombia 3W', 21892 => 'Bogota Colombia Bogota', 21893 => 'Bogota Colombia 3E', 21894 => 'Bogota Colombia 6E', 22032 => 'Camacupa UTM 32S', 22033 => 'Camacupa UTM 33S', 22191 => 'C Inchauspe Argentina 1', 22192 => 'C Inchauspe Argentina 2', 22193 => 'C Inchauspe Argentina 3', 22194 => 'C Inchauspe Argentina 4', 22195 => 'C Inchauspe Argentina 5', 22196 => 'C Inchauspe Argentina 6', 22197 => 'C Inchauspe Argentina 7', 22332 => 'Carthage UTM zone 32N', 22391 => 'Carthage Nord Tunisie', 22392 => 'Carthage Sud Tunisie', 22523 => 'Corrego Alegre UTM 23S', 22524 => 'Corrego Alegre UTM 24S', 22832 => 'Douala UTM zone 32N', 22992 => 'Egypt 1907 Red Belt', 22993 => 'Egypt 1907 Purple Belt', 22994 => 'Egypt 1907 Ext Purple', 23028 => 'ED50 UTM zone 28N', 23029 => 'ED50 UTM zone 29N', 23030 => 'ED50 UTM zone 30N', 23031 => 'ED50 UTM zone 31N', 23032 => 'ED50 UTM zone 32N', 23033 => 'ED50 UTM zone 33N', 23034 => 'ED50 UTM zone 34N', 23035 => 'ED50 UTM zone 35N', 23036 => 'ED50 UTM zone 36N', 23037 => 'ED50 UTM zone 37N', 23038 => 'ED50 UTM zone 38N', 23239 => 'Fahud UTM zone 39N', 23240 => 'Fahud UTM zone 40N', 23433 => 'Garoua UTM zone 33N', 23700 => 'HD72 EOV', 23846 => 'ID74 UTM zone 46N', 23847 => 'ID74 UTM zone 47N', 23848 => 'ID74 UTM zone 48N', 23849 => 'ID74 UTM zone 49N', 23850 => 'ID74 UTM zone 50N', 23851 => 'ID74 UTM zone 51N', 23852 => 'ID74 UTM zone 52N', 23853 => 'ID74 UTM zone 53N', 23886 => 'ID74 UTM zone 46S', 23887 => 'ID74 UTM zone 47S', 23888 => 'ID74 UTM zone 48S', 23889 => 'ID74 UTM zone 49S', 23890 => 'ID74 UTM zone 50S', 23891 => 'ID74 UTM zone 51S', 23892 => 'ID74 UTM zone 52S', 23893 => 'ID74 UTM zone 53S', 23894 => 'ID74 UTM zone 54S', 23947 => 'Indian 1954 UTM 47N', 23948 => 'Indian 1954 UTM 48N', 24047 => 'Indian 1975 UTM 47N', 24048 => 'Indian 1975 UTM 48N', 24100 => 'Jamaica 1875 Old Grid', 24200 => 'JAD69 Jamaica Grid', 24370 => 'Kalianpur India 0', 24371 => 'Kalianpur India I', 24372 => 'Kalianpur India IIa', 24373 => 'Kalianpur India IIIa', 24374 => 'Kalianpur India IVa', 24382 => 'Kalianpur India IIb', 24383 => 'Kalianpur India IIIb', 24384 => 'Kalianpur India IVb', 24500 => 'Kertau Singapore Grid', 24547 => 'Kertau UTM zone 47N', 24548 => 'Kertau UTM zone 48N', 24720 => 'La Canoa UTM zone 20N', 24721 => 'La Canoa UTM zone 21N', 24818 => 'PSAD56 UTM zone 18N', 24819 => 'PSAD56 UTM zone 19N', 24820 => 'PSAD56 UTM zone 20N', 24821 => 'PSAD56 UTM zone 21N', 24877 => 'PSAD56 UTM zone 17S', 24878 => 'PSAD56 UTM zone 18S', 24879 => 'PSAD56 UTM zone 19S', 24880 => 'PSAD56 UTM zone 20S', 24891 => 'PSAD56 Peru west zone', 24892 => 'PSAD56 Peru central', 24893 => 'PSAD56 Peru east zone', 25000 => 'Leigon Ghana Grid', 25231 => 'Lome UTM zone 31N', 25391 => 'Luzon Philippines I', 25392 => 'Luzon Philippines II', 25393 => 'Luzon Philippines III', 25394 => 'Luzon Philippines IV', 25395 => 'Luzon Philippines V', 25700 => 'Makassar NEIEZ', 25932 => 'Malongo 1987 UTM 32S', 26191 => 'Merchich Nord Maroc', 26192 => 'Merchich Sud Maroc', 26193 => 'Merchich Sahara', 26237 => 'Massawa UTM zone 37N', 26331 => 'Minna UTM zone 31N', 26332 => 'Minna UTM zone 32N', 26391 => 'Minna Nigeria West', 26392 => 'Minna Nigeria Mid Belt', 26393 => 'Minna Nigeria East', 26432 => 'Mhast UTM zone 32S', 26591 => 'Monte Mario Italy 1', 26592 => 'Monte Mario Italy 2', 26632 => 'M poraloko UTM 32N', 26692 => 'M poraloko UTM 32S', 26703 => 'NAD27 UTM zone 3N', 26704 => 'NAD27 UTM zone 4N', 26705 => 'NAD27 UTM zone 5N', 26706 => 'NAD27 UTM zone 6N', 26707 => 'NAD27 UTM zone 7N', 26708 => 'NAD27 UTM zone 8N', 26709 => 'NAD27 UTM zone 9N', 26710 => 'NAD27 UTM zone 10N', 26711 => 'NAD27 UTM zone 11N', 26712 => 'NAD27 UTM zone 12N', 26713 => 'NAD27 UTM zone 13N', 26714 => 'NAD27 UTM zone 14N', 26715 => 'NAD27 UTM zone 15N', 26716 => 'NAD27 UTM zone 16N', 26717 => 'NAD27 UTM zone 17N', 26718 => 'NAD27 UTM zone 18N', 26719 => 'NAD27 UTM zone 19N', 26720 => 'NAD27 UTM zone 20N', 26721 => 'NAD27 UTM zone 21N', 26722 => 'NAD27 UTM zone 22N', 26729 => 'NAD27 Alabama East', 26730 => 'NAD27 Alabama West', 26731 => 'NAD27 Alaska zone 1', 26732 => 'NAD27 Alaska zone 2', 26733 => 'NAD27 Alaska zone 3', 26734 => 'NAD27 Alaska zone 4', 26735 => 'NAD27 Alaska zone 5', 26736 => 'NAD27 Alaska zone 6', 26737 => 'NAD27 Alaska zone 7', 26738 => 'NAD27 Alaska zone 8', 26739 => 'NAD27 Alaska zone 9', 26740 => 'NAD27 Alaska zone 10', 26741 => 'NAD27 California I', 26742 => 'NAD27 California II', 26743 => 'NAD27 California III', 26744 => 'NAD27 California IV', 26745 => 'NAD27 California V', 26746 => 'NAD27 California VI', 26747 => 'NAD27 California VII', 26748 => 'NAD27 Arizona East', 26749 => 'NAD27 Arizona Central', 26750 => 'NAD27 Arizona West', 26751 => 'NAD27 Arkansas North', 26752 => 'NAD27 Arkansas South', 26753 => 'NAD27 Colorado North', 26754 => 'NAD27 Colorado Central', 26755 => 'NAD27 Colorado South', 26756 => 'NAD27 Connecticut', 26757 => 'NAD27 Delaware', 26758 => 'NAD27 Florida East', 26759 => 'NAD27 Florida West', 26760 => 'NAD27 Florida North', 26761 => 'NAD27 Hawaii zone 1', 26762 => 'NAD27 Hawaii zone 2', 26763 => 'NAD27 Hawaii zone 3', 26764 => 'NAD27 Hawaii zone 4', 26765 => 'NAD27 Hawaii zone 5', 26766 => 'NAD27 Georgia East', 26767 => 'NAD27 Georgia West', 26768 => 'NAD27 Idaho East', 26769 => 'NAD27 Idaho Central', 26770 => 'NAD27 Idaho West', 26771 => 'NAD27 Illinois East', 26772 => 'NAD27 Illinois West', 26773 => 'NAD27 Indiana East', 26774 => 'NAD27 BLM 14N feet', 26774 => 'NAD27 Indiana West', 26775 => 'NAD27 BLM 15N feet', 26775 => 'NAD27 Iowa North', 26776 => 'NAD27 BLM 16N feet', 26776 => 'NAD27 Iowa South', 26777 => 'NAD27 BLM 17N feet', 26777 => 'NAD27 Kansas North', 26778 => 'NAD27 Kansas South', 26779 => 'NAD27 Kentucky North', 26780 => 'NAD27 Kentucky South', 26781 => 'NAD27 Louisiana North', 26782 => 'NAD27 Louisiana South', 26783 => 'NAD27 Maine East', 26784 => 'NAD27 Maine West', 26785 => 'NAD27 Maryland', 26786 => 'NAD27 Massachusetts', 26787 => 'NAD27 Massachusetts Is', 26788 => 'NAD27 Michigan North', 26789 => 'NAD27 Michigan Central', 26790 => 'NAD27 Michigan South', 26791 => 'NAD27 Minnesota North', 26792 => 'NAD27 Minnesota Cent', 26793 => 'NAD27 Minnesota South', 26794 => 'NAD27 Mississippi East', 26795 => 'NAD27 Mississippi West', 26796 => 'NAD27 Missouri East', 26797 => 'NAD27 Missouri Central', 26798 => 'NAD27 Missouri West', 26801 => 'NAD Michigan Michigan East', 26802 => 'NAD Michigan Michigan Old Central', 26803 => 'NAD Michigan Michigan West', 26903 => 'NAD83 UTM zone 3N', 26904 => 'NAD83 UTM zone 4N', 26905 => 'NAD83 UTM zone 5N', 26906 => 'NAD83 UTM zone 6N', 26907 => 'NAD83 UTM zone 7N', 26908 => 'NAD83 UTM zone 8N', 26909 => 'NAD83 UTM zone 9N', 26910 => 'NAD83 UTM zone 10N', 26911 => 'NAD83 UTM zone 11N', 26912 => 'NAD83 UTM zone 12N', 26913 => 'NAD83 UTM zone 13N', 26914 => 'NAD83 UTM zone 14N', 26915 => 'NAD83 UTM zone 15N', 26916 => 'NAD83 UTM zone 16N', 26917 => 'NAD83 UTM zone 17N', 26918 => 'NAD83 UTM zone 18N', 26919 => 'NAD83 UTM zone 19N', 26920 => 'NAD83 UTM zone 20N', 26921 => 'NAD83 UTM zone 21N', 26922 => 'NAD83 UTM zone 22N', 26923 => 'NAD83 UTM zone 23N', 26929 => 'NAD83 Alabama East', 26930 => 'NAD83 Alabama West', 26931 => 'NAD83 Alaska zone 1', 26932 => 'NAD83 Alaska zone 2', 26933 => 'NAD83 Alaska zone 3', 26934 => 'NAD83 Alaska zone 4', 26935 => 'NAD83 Alaska zone 5', 26936 => 'NAD83 Alaska zone 6', 26937 => 'NAD83 Alaska zone 7', 26938 => 'NAD83 Alaska zone 8', 26939 => 'NAD83 Alaska zone 9', 26940 => 'NAD83 Alaska zone 10', 26941 => 'NAD83 California 1', 26942 => 'NAD83 California 2', 26943 => 'NAD83 California 3', 26944 => 'NAD83 California 4', 26945 => 'NAD83 California 5', 26946 => 'NAD83 California 6', 26948 => 'NAD83 Arizona East', 26949 => 'NAD83 Arizona Central', 26950 => 'NAD83 Arizona West', 26951 => 'NAD83 Arkansas North', 26952 => 'NAD83 Arkansas South', 26953 => 'NAD83 Colorado North', 26954 => 'NAD83 Colorado Central', 26955 => 'NAD83 Colorado South', 26956 => 'NAD83 Connecticut', 26957 => 'NAD83 Delaware', 26958 => 'NAD83 Florida East', 26959 => 'NAD83 Florida West', 26960 => 'NAD83 Florida North', 26961 => 'NAD83 Hawaii zone 1', 26962 => 'NAD83 Hawaii zone 2', 26963 => 'NAD83 Hawaii zone 3', 26964 => 'NAD83 Hawaii zone 4', 26965 => 'NAD83 Hawaii zone 5', 26966 => 'NAD83 Georgia East', 26967 => 'NAD83 Georgia West', 26968 => 'NAD83 Idaho East', 26969 => 'NAD83 Idaho Central', 26970 => 'NAD83 Idaho West', 26971 => 'NAD83 Illinois East', 26972 => 'NAD83 Illinois West', 26973 => 'NAD83 Indiana East', 26974 => 'NAD83 Indiana West', 26975 => 'NAD83 Iowa North', 26976 => 'NAD83 Iowa South', 26977 => 'NAD83 Kansas North', 26978 => 'NAD83 Kansas South', 26979 => 'NAD83 Kentucky North', 26980 => 'NAD83 Kentucky South', 26981 => 'NAD83 Louisiana North', 26982 => 'NAD83 Louisiana South', 26983 => 'NAD83 Maine East', 26984 => 'NAD83 Maine West', 26985 => 'NAD83 Maryland', 26986 => 'NAD83 Massachusetts', 26987 => 'NAD83 Massachusetts Is', 26988 => 'NAD83 Michigan North', 26989 => 'NAD83 Michigan Central', 26990 => 'NAD83 Michigan South', 26991 => 'NAD83 Minnesota North', 26992 => 'NAD83 Minnesota Cent', 26993 => 'NAD83 Minnesota South', 26994 => 'NAD83 Mississippi East', 26995 => 'NAD83 Mississippi West', 26996 => 'NAD83 Missouri East', 26997 => 'NAD83 Missouri Central', 26998 => 'NAD83 Missouri West', 27038 => 'Nahrwan 1967 UTM 38N', 27039 => 'Nahrwan 1967 UTM 39N', 27040 => 'Nahrwan 1967 UTM 40N', 27120 => 'Naparima UTM 20N', 27200 => 'GD49 NZ Map Grid', 27291 => 'GD49 North Island Grid', 27292 => 'GD49 South Island Grid', 27429 => 'Datum 73 UTM zone 29N', 27500 => 'ATF Nord de Guerre', 27581 => 'NTF France I', 27582 => 'NTF France II', 27583 => 'NTF France III', 27591 => 'NTF Nord France', 27592 => 'NTF Centre France', 27593 => 'NTF Sud France', 27700 => 'British National Grid', 28232 => 'Point Noire UTM 32S', 28348 => 'GDA94 MGA zone 48', 28349 => 'GDA94 MGA zone 49', 28350 => 'GDA94 MGA zone 50', 28351 => 'GDA94 MGA zone 51', 28352 => 'GDA94 MGA zone 52', 28353 => 'GDA94 MGA zone 53', 28354 => 'GDA94 MGA zone 54', 28355 => 'GDA94 MGA zone 55', 28356 => 'GDA94 MGA zone 56', 28357 => 'GDA94 MGA zone 57', 28358 => 'GDA94 MGA zone 58', 28404 => 'Pulkovo Gauss zone 4', 28405 => 'Pulkovo Gauss zone 5', 28406 => 'Pulkovo Gauss zone 6', 28407 => 'Pulkovo Gauss zone 7', 28408 => 'Pulkovo Gauss zone 8', 28409 => 'Pulkovo Gauss zone 9', 28410 => 'Pulkovo Gauss zone 10', 28411 => 'Pulkovo Gauss zone 11', 28412 => 'Pulkovo Gauss zone 12', 28413 => 'Pulkovo Gauss zone 13', 28414 => 'Pulkovo Gauss zone 14', 28415 => 'Pulkovo Gauss zone 15', 28416 => 'Pulkovo Gauss zone 16', 28417 => 'Pulkovo Gauss zone 17', 28418 => 'Pulkovo Gauss zone 18', 28419 => 'Pulkovo Gauss zone 19', 28420 => 'Pulkovo Gauss zone 20', 28421 => 'Pulkovo Gauss zone 21', 28422 => 'Pulkovo Gauss zone 22', 28423 => 'Pulkovo Gauss zone 23', 28424 => 'Pulkovo Gauss zone 24', 28425 => 'Pulkovo Gauss zone 25', 28426 => 'Pulkovo Gauss zone 26', 28427 => 'Pulkovo Gauss zone 27', 28428 => 'Pulkovo Gauss zone 28', 28429 => 'Pulkovo Gauss zone 29', 28430 => 'Pulkovo Gauss zone 30', 28431 => 'Pulkovo Gauss zone 31', 28432 => 'Pulkovo Gauss zone 32', 28464 => 'Pulkovo Gauss 4N', 28465 => 'Pulkovo Gauss 5N', 28466 => 'Pulkovo Gauss 6N', 28467 => 'Pulkovo Gauss 7N', 28468 => 'Pulkovo Gauss 8N', 28469 => 'Pulkovo Gauss 9N', 28470 => 'Pulkovo Gauss 10N', 28471 => 'Pulkovo Gauss 11N', 28472 => 'Pulkovo Gauss 12N', 28473 => 'Pulkovo Gauss 13N', 28474 => 'Pulkovo Gauss 14N', 28475 => 'Pulkovo Gauss 15N', 28476 => 'Pulkovo Gauss 16N', 28477 => 'Pulkovo Gauss 17N', 28478 => 'Pulkovo Gauss 18N', 28479 => 'Pulkovo Gauss 19N', 28480 => 'Pulkovo Gauss 20N', 28481 => 'Pulkovo Gauss 21N', 28482 => 'Pulkovo Gauss 22N', 28483 => 'Pulkovo Gauss 23N', 28484 => 'Pulkovo Gauss 24N', 28485 => 'Pulkovo Gauss 25N', 28486 => 'Pulkovo Gauss 26N', 28487 => 'Pulkovo Gauss 27N', 28488 => 'Pulkovo Gauss 28N', 28489 => 'Pulkovo Gauss 29N', 28490 => 'Pulkovo Gauss 30N', 28491 => 'Pulkovo Gauss 31N', 28492 => 'Pulkovo Gauss 32N', 28600 => 'Qatar National Grid', 28991 => 'RD Netherlands Old', 28992 => 'RD Netherlands New', 29118 => 'SAD69 UTM zone 18N', 29119 => 'SAD69 UTM zone 19N', 29120 => 'SAD69 UTM zone 20N', 29121 => 'SAD69 UTM zone 21N', 29122 => 'SAD69 UTM zone 22N', 29177 => 'SAD69 UTM zone 17S', 29178 => 'SAD69 UTM zone 18S', 29179 => 'SAD69 UTM zone 19S', 29180 => 'SAD69 UTM zone 20S', 29181 => 'SAD69 UTM zone 21S', 29182 => 'SAD69 UTM zone 22S', 29183 => 'SAD69 UTM zone 23S', 29184 => 'SAD69 UTM zone 24S', 29185 => 'SAD69 UTM zone 25S', 29220 => 'Sapper Hill UTM 20S', 29221 => 'Sapper Hill UTM 21S', 29333 => 'Schwarzeck UTM 33S', 29635 => 'Sudan UTM zone 35N', 29636 => 'Sudan UTM zone 36N', 29700 => 'Tananarive Laborde', 29738 => 'Tananarive UTM 38S', 29739 => 'Tananarive UTM 39S', 29800 => 'Timbalai 1948 Borneo', 29849 => 'Timbalai 1948 UTM 49N', 29850 => 'Timbalai 1948 UTM 50N', 29900 => 'TM65 Irish Nat Grid', 30200 => 'Trinidad 1903 Trinidad', 30339 => 'TC 1948 UTM zone 39N', 30340 => 'TC 1948 UTM zone 40N', 30491 => 'Voirol N Algerie ancien', 30492 => 'Voirol S Algerie ancien', 30591 => 'Voirol Unifie N Algerie', 30592 => 'Voirol Unifie S Algerie', 30600 => 'Bern 1938 Swiss New', 30729 => 'Nord Sahara UTM 29N', 30730 => 'Nord Sahara UTM 30N', 30731 => 'Nord Sahara UTM 31N', 30732 => 'Nord Sahara UTM 32N', 31028 => 'Yoff UTM zone 28N', 31121 => 'Zanderij UTM zone 21N', 31291 => 'MGI Austria West', 31292 => 'MGI Austria Central', 31293 => 'MGI Austria East', 31300 => 'Belge Lambert 72', 31491 => 'DHDN Germany zone 1', 31492 => 'DHDN Germany zone 2', 31493 => 'DHDN Germany zone 3', 31494 => 'DHDN Germany zone 4', 31495 => 'DHDN Germany zone 5', 31700 => 'Dealul Piscului 1970 Stereo 70', 32001 => 'NAD27 Montana North', 32002 => 'NAD27 Montana Central', 32003 => 'NAD27 Montana South', 32005 => 'NAD27 Nebraska North', 32006 => 'NAD27 Nebraska South', 32007 => 'NAD27 Nevada East', 32008 => 'NAD27 Nevada Central', 32009 => 'NAD27 Nevada West', 32010 => 'NAD27 New Hampshire', 32011 => 'NAD27 New Jersey', 32012 => 'NAD27 New Mexico East', 32013 => 'NAD27 New Mexico Cent', 32014 => 'NAD27 New Mexico West', 32015 => 'NAD27 New York East', 32016 => 'NAD27 New York Central', 32017 => 'NAD27 New York West', 32018 => 'NAD27 New York Long Is', 32019 => 'NAD27 North Carolina', 32020 => 'NAD27 North Dakota N', 32021 => 'NAD27 North Dakota S', 32022 => 'NAD27 Ohio North', 32023 => 'NAD27 Ohio South', 32024 => 'NAD27 Oklahoma North', 32025 => 'NAD27 Oklahoma South', 32026 => 'NAD27 Oregon North', 32027 => 'NAD27 Oregon South', 32028 => 'NAD27 Pennsylvania N', 32029 => 'NAD27 Pennsylvania S', 32030 => 'NAD27 Rhode Island', 32031 => 'NAD27 South Carolina N', 32033 => 'NAD27 South Carolina S', 32034 => 'NAD27 South Dakota N', 32035 => 'NAD27 South Dakota S', 32036 => 'NAD27 Tennessee', 32037 => 'NAD27 Texas North', 32038 => 'NAD27 Texas North Cen', 32039 => 'NAD27 Texas Central', 32040 => 'NAD27 Texas South Cen', 32041 => 'NAD27 Texas South', 32042 => 'NAD27 Utah North', 32043 => 'NAD27 Utah Central', 32044 => 'NAD27 Utah South', 32045 => 'NAD27 Vermont', 32046 => 'NAD27 Virginia North', 32047 => 'NAD27 Virginia South', 32048 => 'NAD27 Washington North', 32049 => 'NAD27 Washington South', 32050 => 'NAD27 West Virginia N', 32051 => 'NAD27 West Virginia S', 32052 => 'NAD27 Wisconsin North', 32053 => 'NAD27 Wisconsin Cen', 32054 => 'NAD27 Wisconsin South', 32055 => 'NAD27 Wyoming East', 32056 => 'NAD27 Wyoming E Cen', 32057 => 'NAD27 Wyoming W Cen', 32058 => 'NAD27 Wyoming West', 32059 => 'NAD27 Puerto Rico', 32060 => 'NAD27 St Croix', 32100 => 'NAD83 Montana', 32104 => 'NAD83 Nebraska', 32107 => 'NAD83 Nevada East', 32108 => 'NAD83 Nevada Central', 32109 => 'NAD83 Nevada West', 32110 => 'NAD83 New Hampshire', 32111 => 'NAD83 New Jersey', 32112 => 'NAD83 New Mexico East', 32113 => 'NAD83 New Mexico Cent', 32114 => 'NAD83 New Mexico West', 32115 => 'NAD83 New York East', 32116 => 'NAD83 New York Central', 32117 => 'NAD83 New York West', 32118 => 'NAD83 New York Long Is', 32119 => 'NAD83 North Carolina', 32120 => 'NAD83 North Dakota N', 32121 => 'NAD83 North Dakota S', 32122 => 'NAD83 Ohio North', 32123 => 'NAD83 Ohio South', 32124 => 'NAD83 Oklahoma North', 32125 => 'NAD83 Oklahoma South', 32126 => 'NAD83 Oregon North', 32127 => 'NAD83 Oregon South', 32128 => 'NAD83 Pennsylvania N', 32129 => 'NAD83 Pennsylvania S', 32130 => 'NAD83 Rhode Island', 32133 => 'NAD83 South Carolina', 32134 => 'NAD83 South Dakota N', 32135 => 'NAD83 South Dakota S', 32136 => 'NAD83 Tennessee', 32137 => 'NAD83 Texas North', 32138 => 'NAD83 Texas North Cen', 32139 => 'NAD83 Texas Central', 32140 => 'NAD83 Texas South Cen', 32141 => 'NAD83 Texas South', 32142 => 'NAD83 Utah North', 32143 => 'NAD83 Utah Central', 32144 => 'NAD83 Utah South', 32145 => 'NAD83 Vermont', 32146 => 'NAD83 Virginia North', 32147 => 'NAD83 Virginia South', 32148 => 'NAD83 Washington North', 32149 => 'NAD83 Washington South', 32150 => 'NAD83 West Virginia N', 32151 => 'NAD83 West Virginia S', 32152 => 'NAD83 Wisconsin North', 32153 => 'NAD83 Wisconsin Cen', 32154 => 'NAD83 Wisconsin South', 32155 => 'NAD83 Wyoming East', 32156 => 'NAD83 Wyoming E Cen', 32157 => 'NAD83 Wyoming W Cen', 32158 => 'NAD83 Wyoming West', 32161 => 'NAD83 Puerto Rico Virgin Is', 32201 => 'WGS72 UTM zone 1N', 32202 => 'WGS72 UTM zone 2N', 32203 => 'WGS72 UTM zone 3N', 32204 => 'WGS72 UTM zone 4N', 32205 => 'WGS72 UTM zone 5N', 32206 => 'WGS72 UTM zone 6N', 32207 => 'WGS72 UTM zone 7N', 32208 => 'WGS72 UTM zone 8N', 32209 => 'WGS72 UTM zone 9N', 32210 => 'WGS72 UTM zone 10N', 32211 => 'WGS72 UTM zone 11N', 32212 => 'WGS72 UTM zone 12N', 32213 => 'WGS72 UTM zone 13N', 32214 => 'WGS72 UTM zone 14N', 32215 => 'WGS72 UTM zone 15N', 32216 => 'WGS72 UTM zone 16N', 32217 => 'WGS72 UTM zone 17N', 32218 => 'WGS72 UTM zone 18N', 32219 => 'WGS72 UTM zone 19N', 32220 => 'WGS72 UTM zone 20N', 32221 => 'WGS72 UTM zone 21N', 32222 => 'WGS72 UTM zone 22N', 32223 => 'WGS72 UTM zone 23N', 32224 => 'WGS72 UTM zone 24N', 32225 => 'WGS72 UTM zone 25N', 32226 => 'WGS72 UTM zone 26N', 32227 => 'WGS72 UTM zone 27N', 32228 => 'WGS72 UTM zone 28N', 32229 => 'WGS72 UTM zone 29N', 32230 => 'WGS72 UTM zone 30N', 32231 => 'WGS72 UTM zone 31N', 32232 => 'WGS72 UTM zone 32N', 32233 => 'WGS72 UTM zone 33N', 32234 => 'WGS72 UTM zone 34N', 32235 => 'WGS72 UTM zone 35N', 32236 => 'WGS72 UTM zone 36N', 32237 => 'WGS72 UTM zone 37N', 32238 => 'WGS72 UTM zone 38N', 32239 => 'WGS72 UTM zone 39N', 32240 => 'WGS72 UTM zone 40N', 32241 => 'WGS72 UTM zone 41N', 32242 => 'WGS72 UTM zone 42N', 32243 => 'WGS72 UTM zone 43N', 32244 => 'WGS72 UTM zone 44N', 32245 => 'WGS72 UTM zone 45N', 32246 => 'WGS72 UTM zone 46N', 32247 => 'WGS72 UTM zone 47N', 32248 => 'WGS72 UTM zone 48N', 32249 => 'WGS72 UTM zone 49N', 32250 => 'WGS72 UTM zone 50N', 32251 => 'WGS72 UTM zone 51N', 32252 => 'WGS72 UTM zone 52N', 32253 => 'WGS72 UTM zone 53N', 32254 => 'WGS72 UTM zone 54N', 32255 => 'WGS72 UTM zone 55N', 32256 => 'WGS72 UTM zone 56N', 32257 => 'WGS72 UTM zone 57N', 32258 => 'WGS72 UTM zone 58N', 32259 => 'WGS72 UTM zone 59N', 32260 => 'WGS72 UTM zone 60N', 32301 => 'WGS72 UTM zone 1S', 32302 => 'WGS72 UTM zone 2S', 32303 => 'WGS72 UTM zone 3S', 32304 => 'WGS72 UTM zone 4S', 32305 => 'WGS72 UTM zone 5S', 32306 => 'WGS72 UTM zone 6S', 32307 => 'WGS72 UTM zone 7S', 32308 => 'WGS72 UTM zone 8S', 32309 => 'WGS72 UTM zone 9S', 32310 => 'WGS72 UTM zone 10S', 32311 => 'WGS72 UTM zone 11S', 32312 => 'WGS72 UTM zone 12S', 32313 => 'WGS72 UTM zone 13S', 32314 => 'WGS72 UTM zone 14S', 32315 => 'WGS72 UTM zone 15S', 32316 => 'WGS72 UTM zone 16S', 32317 => 'WGS72 UTM zone 17S', 32318 => 'WGS72 UTM zone 18S', 32319 => 'WGS72 UTM zone 19S', 32320 => 'WGS72 UTM zone 20S', 32321 => 'WGS72 UTM zone 21S', 32322 => 'WGS72 UTM zone 22S', 32323 => 'WGS72 UTM zone 23S', 32324 => 'WGS72 UTM zone 24S', 32325 => 'WGS72 UTM zone 25S', 32326 => 'WGS72 UTM zone 26S', 32327 => 'WGS72 UTM zone 27S', 32328 => 'WGS72 UTM zone 28S', 32329 => 'WGS72 UTM zone 29S', 32330 => 'WGS72 UTM zone 30S', 32331 => 'WGS72 UTM zone 31S', 32332 => 'WGS72 UTM zone 32S', 32333 => 'WGS72 UTM zone 33S', 32334 => 'WGS72 UTM zone 34S', 32335 => 'WGS72 UTM zone 35S', 32336 => 'WGS72 UTM zone 36S', 32337 => 'WGS72 UTM zone 37S', 32338 => 'WGS72 UTM zone 38S', 32339 => 'WGS72 UTM zone 39S', 32340 => 'WGS72 UTM zone 40S', 32341 => 'WGS72 UTM zone 41S', 32342 => 'WGS72 UTM zone 42S', 32343 => 'WGS72 UTM zone 43S', 32344 => 'WGS72 UTM zone 44S', 32345 => 'WGS72 UTM zone 45S', 32346 => 'WGS72 UTM zone 46S', 32347 => 'WGS72 UTM zone 47S', 32348 => 'WGS72 UTM zone 48S', 32349 => 'WGS72 UTM zone 49S', 32350 => 'WGS72 UTM zone 50S', 32351 => 'WGS72 UTM zone 51S', 32352 => 'WGS72 UTM zone 52S', 32353 => 'WGS72 UTM zone 53S', 32354 => 'WGS72 UTM zone 54S', 32355 => 'WGS72 UTM zone 55S', 32356 => 'WGS72 UTM zone 56S', 32357 => 'WGS72 UTM zone 57S', 32358 => 'WGS72 UTM zone 58S', 32359 => 'WGS72 UTM zone 59S', 32360 => 'WGS72 UTM zone 60S', 32401 => 'WGS72BE UTM zone 1N', 32402 => 'WGS72BE UTM zone 2N', 32403 => 'WGS72BE UTM zone 3N', 32404 => 'WGS72BE UTM zone 4N', 32405 => 'WGS72BE UTM zone 5N', 32406 => 'WGS72BE UTM zone 6N', 32407 => 'WGS72BE UTM zone 7N', 32408 => 'WGS72BE UTM zone 8N', 32409 => 'WGS72BE UTM zone 9N', 32410 => 'WGS72BE UTM zone 10N', 32411 => 'WGS72BE UTM zone 11N', 32412 => 'WGS72BE UTM zone 12N', 32413 => 'WGS72BE UTM zone 13N', 32414 => 'WGS72BE UTM zone 14N', 32415 => 'WGS72BE UTM zone 15N', 32416 => 'WGS72BE UTM zone 16N', 32417 => 'WGS72BE UTM zone 17N', 32418 => 'WGS72BE UTM zone 18N', 32419 => 'WGS72BE UTM zone 19N', 32420 => 'WGS72BE UTM zone 20N', 32421 => 'WGS72BE UTM zone 21N', 32422 => 'WGS72BE UTM zone 22N', 32423 => 'WGS72BE UTM zone 23N', 32424 => 'WGS72BE UTM zone 24N', 32425 => 'WGS72BE UTM zone 25N', 32426 => 'WGS72BE UTM zone 26N', 32427 => 'WGS72BE UTM zone 27N', 32428 => 'WGS72BE UTM zone 28N', 32429 => 'WGS72BE UTM zone 29N', 32430 => 'WGS72BE UTM zone 30N', 32431 => 'WGS72BE UTM zone 31N', 32432 => 'WGS72BE UTM zone 32N', 32433 => 'WGS72BE UTM zone 33N', 32434 => 'WGS72BE UTM zone 34N', 32435 => 'WGS72BE UTM zone 35N', 32436 => 'WGS72BE UTM zone 36N', 32437 => 'WGS72BE UTM zone 37N', 32438 => 'WGS72BE UTM zone 38N', 32439 => 'WGS72BE UTM zone 39N', 32440 => 'WGS72BE UTM zone 40N', 32441 => 'WGS72BE UTM zone 41N', 32442 => 'WGS72BE UTM zone 42N', 32443 => 'WGS72BE UTM zone 43N', 32444 => 'WGS72BE UTM zone 44N', 32445 => 'WGS72BE UTM zone 45N', 32446 => 'WGS72BE UTM zone 46N', 32447 => 'WGS72BE UTM zone 47N', 32448 => 'WGS72BE UTM zone 48N', 32449 => 'WGS72BE UTM zone 49N', 32450 => 'WGS72BE UTM zone 50N', 32451 => 'WGS72BE UTM zone 51N', 32452 => 'WGS72BE UTM zone 52N', 32453 => 'WGS72BE UTM zone 53N', 32454 => 'WGS72BE UTM zone 54N', 32455 => 'WGS72BE UTM zone 55N', 32456 => 'WGS72BE UTM zone 56N', 32457 => 'WGS72BE UTM zone 57N', 32458 => 'WGS72BE UTM zone 58N', 32459 => 'WGS72BE UTM zone 59N', 32460 => 'WGS72BE UTM zone 60N', 32501 => 'WGS72BE UTM zone 1S', 32502 => 'WGS72BE UTM zone 2S', 32503 => 'WGS72BE UTM zone 3S', 32504 => 'WGS72BE UTM zone 4S', 32505 => 'WGS72BE UTM zone 5S', 32506 => 'WGS72BE UTM zone 6S', 32507 => 'WGS72BE UTM zone 7S', 32508 => 'WGS72BE UTM zone 8S', 32509 => 'WGS72BE UTM zone 9S', 32510 => 'WGS72BE UTM zone 10S', 32511 => 'WGS72BE UTM zone 11S', 32512 => 'WGS72BE UTM zone 12S', 32513 => 'WGS72BE UTM zone 13S', 32514 => 'WGS72BE UTM zone 14S', 32515 => 'WGS72BE UTM zone 15S', 32516 => 'WGS72BE UTM zone 16S', 32517 => 'WGS72BE UTM zone 17S', 32518 => 'WGS72BE UTM zone 18S', 32519 => 'WGS72BE UTM zone 19S', 32520 => 'WGS72BE UTM zone 20S', 32521 => 'WGS72BE UTM zone 21S', 32522 => 'WGS72BE UTM zone 22S', 32523 => 'WGS72BE UTM zone 23S', 32524 => 'WGS72BE UTM zone 24S', 32525 => 'WGS72BE UTM zone 25S', 32526 => 'WGS72BE UTM zone 26S', 32527 => 'WGS72BE UTM zone 27S', 32528 => 'WGS72BE UTM zone 28S', 32529 => 'WGS72BE UTM zone 29S', 32530 => 'WGS72BE UTM zone 30S', 32531 => 'WGS72BE UTM zone 31S', 32532 => 'WGS72BE UTM zone 32S', 32533 => 'WGS72BE UTM zone 33S', 32534 => 'WGS72BE UTM zone 34S', 32535 => 'WGS72BE UTM zone 35S', 32536 => 'WGS72BE UTM zone 36S', 32537 => 'WGS72BE UTM zone 37S', 32538 => 'WGS72BE UTM zone 38S', 32539 => 'WGS72BE UTM zone 39S', 32540 => 'WGS72BE UTM zone 40S', 32541 => 'WGS72BE UTM zone 41S', 32542 => 'WGS72BE UTM zone 42S', 32543 => 'WGS72BE UTM zone 43S', 32544 => 'WGS72BE UTM zone 44S', 32545 => 'WGS72BE UTM zone 45S', 32546 => 'WGS72BE UTM zone 46S', 32547 => 'WGS72BE UTM zone 47S', 32548 => 'WGS72BE UTM zone 48S', 32549 => 'WGS72BE UTM zone 49S', 32550 => 'WGS72BE UTM zone 50S', 32551 => 'WGS72BE UTM zone 51S', 32552 => 'WGS72BE UTM zone 52S', 32553 => 'WGS72BE UTM zone 53S', 32554 => 'WGS72BE UTM zone 54S', 32555 => 'WGS72BE UTM zone 55S', 32556 => 'WGS72BE UTM zone 56S', 32557 => 'WGS72BE UTM zone 57S', 32558 => 'WGS72BE UTM zone 58S', 32559 => 'WGS72BE UTM zone 59S', 32560 => 'WGS72BE UTM zone 60S', 32601 => 'WGS84 UTM zone 1N', 32602 => 'WGS84 UTM zone 2N', 32603 => 'WGS84 UTM zone 3N', 32604 => 'WGS84 UTM zone 4N', 32605 => 'WGS84 UTM zone 5N', 32606 => 'WGS84 UTM zone 6N', 32607 => 'WGS84 UTM zone 7N', 32608 => 'WGS84 UTM zone 8N', 32609 => 'WGS84 UTM zone 9N', 32610 => 'WGS84 UTM zone 10N', 32611 => 'WGS84 UTM zone 11N', 32612 => 'WGS84 UTM zone 12N', 32613 => 'WGS84 UTM zone 13N', 32614 => 'WGS84 UTM zone 14N', 32615 => 'WGS84 UTM zone 15N', 32616 => 'WGS84 UTM zone 16N', 32617 => 'WGS84 UTM zone 17N', 32618 => 'WGS84 UTM zone 18N', 32619 => 'WGS84 UTM zone 19N', 32620 => 'WGS84 UTM zone 20N', 32621 => 'WGS84 UTM zone 21N', 32622 => 'WGS84 UTM zone 22N', 32623 => 'WGS84 UTM zone 23N', 32624 => 'WGS84 UTM zone 24N', 32625 => 'WGS84 UTM zone 25N', 32626 => 'WGS84 UTM zone 26N', 32627 => 'WGS84 UTM zone 27N', 32628 => 'WGS84 UTM zone 28N', 32629 => 'WGS84 UTM zone 29N', 32630 => 'WGS84 UTM zone 30N', 32631 => 'WGS84 UTM zone 31N', 32632 => 'WGS84 UTM zone 32N', 32633 => 'WGS84 UTM zone 33N', 32634 => 'WGS84 UTM zone 34N', 32635 => 'WGS84 UTM zone 35N', 32636 => 'WGS84 UTM zone 36N', 32637 => 'WGS84 UTM zone 37N', 32638 => 'WGS84 UTM zone 38N', 32639 => 'WGS84 UTM zone 39N', 32640 => 'WGS84 UTM zone 40N', 32641 => 'WGS84 UTM zone 41N', 32642 => 'WGS84 UTM zone 42N', 32643 => 'WGS84 UTM zone 43N', 32644 => 'WGS84 UTM zone 44N', 32645 => 'WGS84 UTM zone 45N', 32646 => 'WGS84 UTM zone 46N', 32647 => 'WGS84 UTM zone 47N', 32648 => 'WGS84 UTM zone 48N', 32649 => 'WGS84 UTM zone 49N', 32650 => 'WGS84 UTM zone 50N', 32651 => 'WGS84 UTM zone 51N', 32652 => 'WGS84 UTM zone 52N', 32653 => 'WGS84 UTM zone 53N', 32654 => 'WGS84 UTM zone 54N', 32655 => 'WGS84 UTM zone 55N', 32656 => 'WGS84 UTM zone 56N', 32657 => 'WGS84 UTM zone 57N', 32658 => 'WGS84 UTM zone 58N', 32659 => 'WGS84 UTM zone 59N', 32660 => 'WGS84 UTM zone 60N', 32701 => 'WGS84 UTM zone 1S', 32702 => 'WGS84 UTM zone 2S', 32703 => 'WGS84 UTM zone 3S', 32704 => 'WGS84 UTM zone 4S', 32705 => 'WGS84 UTM zone 5S', 32706 => 'WGS84 UTM zone 6S', 32707 => 'WGS84 UTM zone 7S', 32708 => 'WGS84 UTM zone 8S', 32709 => 'WGS84 UTM zone 9S', 32710 => 'WGS84 UTM zone 10S', 32711 => 'WGS84 UTM zone 11S', 32712 => 'WGS84 UTM zone 12S', 32713 => 'WGS84 UTM zone 13S', 32714 => 'WGS84 UTM zone 14S', 32715 => 'WGS84 UTM zone 15S', 32716 => 'WGS84 UTM zone 16S', 32717 => 'WGS84 UTM zone 17S', 32718 => 'WGS84 UTM zone 18S', 32719 => 'WGS84 UTM zone 19S', 32720 => 'WGS84 UTM zone 20S', 32721 => 'WGS84 UTM zone 21S', 32722 => 'WGS84 UTM zone 22S', 32723 => 'WGS84 UTM zone 23S', 32724 => 'WGS84 UTM zone 24S', 32725 => 'WGS84 UTM zone 25S', 32726 => 'WGS84 UTM zone 26S', 32727 => 'WGS84 UTM zone 27S', 32728 => 'WGS84 UTM zone 28S', 32729 => 'WGS84 UTM zone 29S', 32730 => 'WGS84 UTM zone 30S', 32731 => 'WGS84 UTM zone 31S', 32732 => 'WGS84 UTM zone 32S', 32733 => 'WGS84 UTM zone 33S', 32734 => 'WGS84 UTM zone 34S', 32735 => 'WGS84 UTM zone 35S', 32736 => 'WGS84 UTM zone 36S', 32737 => 'WGS84 UTM zone 37S', 32738 => 'WGS84 UTM zone 38S', 32739 => 'WGS84 UTM zone 39S', 32740 => 'WGS84 UTM zone 40S', 32741 => 'WGS84 UTM zone 41S', 32742 => 'WGS84 UTM zone 42S', 32743 => 'WGS84 UTM zone 43S', 32744 => 'WGS84 UTM zone 44S', 32745 => 'WGS84 UTM zone 45S', 32746 => 'WGS84 UTM zone 46S', 32747 => 'WGS84 UTM zone 47S', 32748 => 'WGS84 UTM zone 48S', 32749 => 'WGS84 UTM zone 49S', 32750 => 'WGS84 UTM zone 50S', 32751 => 'WGS84 UTM zone 51S', 32752 => 'WGS84 UTM zone 52S', 32753 => 'WGS84 UTM zone 53S', 32754 => 'WGS84 UTM zone 54S', 32755 => 'WGS84 UTM zone 55S', 32756 => 'WGS84 UTM zone 56S', 32757 => 'WGS84 UTM zone 57S', 32758 => 'WGS84 UTM zone 58S', 32759 => 'WGS84 UTM zone 59S', 32760 => 'WGS84 UTM zone 60S', 32767 => 'User Defined', }, }, 3073 => 'PCSCitation', 3074 => { Name => 'Projection', PrintConv => { # epsg_proj 10101 => 'Alabama CS27 East', 10102 => 'Alabama CS27 West', 10131 => 'Alabama CS83 East', 10132 => 'Alabama CS83 West', 10201 => 'Arizona Coordinate System east', 10202 => 'Arizona Coordinate System Central', 10203 => 'Arizona Coordinate System west', 10231 => 'Arizona CS83 east', 10232 => 'Arizona CS83 Central', 10233 => 'Arizona CS83 west', 10301 => 'Arkansas CS27 North', 10302 => 'Arkansas CS27 South', 10331 => 'Arkansas CS83 North', 10332 => 'Arkansas CS83 South', 10401 => 'California CS27 I', 10402 => 'California CS27 II', 10403 => 'California CS27 III', 10404 => 'California CS27 IV', 10405 => 'California CS27 V', 10406 => 'California CS27 VI', 10407 => 'California CS27 VII', 10431 => 'California CS83 1', 10432 => 'California CS83 2', 10433 => 'California CS83 3', 10434 => 'California CS83 4', 10435 => 'California CS83 5', 10436 => 'California CS83 6', 10501 => 'Colorado CS27 North', 10502 => 'Colorado CS27 Central', 10503 => 'Colorado CS27 South', 10531 => 'Colorado CS83 North', 10532 => 'Colorado CS83 Central', 10533 => 'Colorado CS83 South', 10600 => 'Connecticut CS27', 10630 => 'Connecticut CS83', 10700 => 'Delaware CS27', 10730 => 'Delaware CS83', 10901 => 'Florida CS27 East', 10902 => 'Florida CS27 West', 10903 => 'Florida CS27 North', 10931 => 'Florida CS83 East', 10932 => 'Florida CS83 West', 10933 => 'Florida CS83 North', 11001 => 'Georgia CS27 East', 11002 => 'Georgia CS27 West', 11031 => 'Georgia CS83 East', 11032 => 'Georgia CS83 West', 11101 => 'Idaho CS27 East', 11102 => 'Idaho CS27 Central', 11103 => 'Idaho CS27 West', 11131 => 'Idaho CS83 East', 11132 => 'Idaho CS83 Central', 11133 => 'Idaho CS83 West', 11201 => 'Illinois CS27 East', 11202 => 'Illinois CS27 West', 11231 => 'Illinois CS83 East', 11232 => 'Illinois CS83 West', 11301 => 'Indiana CS27 East', 11302 => 'Indiana CS27 West', 11331 => 'Indiana CS83 East', 11332 => 'Indiana CS83 West', 11401 => 'Iowa CS27 North', 11402 => 'Iowa CS27 South', 11431 => 'Iowa CS83 North', 11432 => 'Iowa CS83 South', 11501 => 'Kansas CS27 North', 11502 => 'Kansas CS27 South', 11531 => 'Kansas CS83 North', 11532 => 'Kansas CS83 South', 11601 => 'Kentucky CS27 North', 11602 => 'Kentucky CS27 South', 11631 => 'Kentucky CS83 North', 11632 => 'Kentucky CS83 South', 11701 => 'Louisiana CS27 North', 11702 => 'Louisiana CS27 South', 11731 => 'Louisiana CS83 North', 11732 => 'Louisiana CS83 South', 11801 => 'Maine CS27 East', 11802 => 'Maine CS27 West', 11831 => 'Maine CS83 East', 11832 => 'Maine CS83 West', 11900 => 'Maryland CS27', 11930 => 'Maryland CS83', 12001 => 'Massachusetts CS27 Mainland', 12002 => 'Massachusetts CS27 Island', 12031 => 'Massachusetts CS83 Mainland', 12032 => 'Massachusetts CS83 Island', 12101 => 'Michigan State Plane East', 12102 => 'Michigan State Plane Old Central', 12103 => 'Michigan State Plane West', 12111 => 'Michigan CS27 North', 12112 => 'Michigan CS27 Central', 12113 => 'Michigan CS27 South', 12141 => 'Michigan CS83 North', 12142 => 'Michigan CS83 Central', 12143 => 'Michigan CS83 South', 12201 => 'Minnesota CS27 North', 12202 => 'Minnesota CS27 Central', 12203 => 'Minnesota CS27 South', 12231 => 'Minnesota CS83 North', 12232 => 'Minnesota CS83 Central', 12233 => 'Minnesota CS83 South', 12301 => 'Mississippi CS27 East', 12302 => 'Mississippi CS27 West', 12331 => 'Mississippi CS83 East', 12332 => 'Mississippi CS83 West', 12401 => 'Missouri CS27 East', 12402 => 'Missouri CS27 Central', 12403 => 'Missouri CS27 West', 12431 => 'Missouri CS83 East', 12432 => 'Missouri CS83 Central', 12433 => 'Missouri CS83 West', 12501 => 'Montana CS27 North', 12502 => 'Montana CS27 Central', 12503 => 'Montana CS27 South', 12530 => 'Montana CS83', 12601 => 'Nebraska CS27 North', 12602 => 'Nebraska CS27 South', 12630 => 'Nebraska CS83', 12701 => 'Nevada CS27 East', 12702 => 'Nevada CS27 Central', 12703 => 'Nevada CS27 West', 12731 => 'Nevada CS83 East', 12732 => 'Nevada CS83 Central', 12733 => 'Nevada CS83 West', 12800 => 'New Hampshire CS27', 12830 => 'New Hampshire CS83', 12900 => 'New Jersey CS27', 12930 => 'New Jersey CS83', 13001 => 'New Mexico CS27 East', 13002 => 'New Mexico CS27 Central', 13003 => 'New Mexico CS27 West', 13031 => 'New Mexico CS83 East', 13032 => 'New Mexico CS83 Central', 13033 => 'New Mexico CS83 West', 13101 => 'New York CS27 East', 13102 => 'New York CS27 Central', 13103 => 'New York CS27 West', 13104 => 'New York CS27 Long Island', 13131 => 'New York CS83 East', 13132 => 'New York CS83 Central', 13133 => 'New York CS83 West', 13134 => 'New York CS83 Long Island', 13200 => 'North Carolina CS27', 13230 => 'North Carolina CS83', 13301 => 'North Dakota CS27 North', 13302 => 'North Dakota CS27 South', 13331 => 'North Dakota CS83 North', 13332 => 'North Dakota CS83 South', 13401 => 'Ohio CS27 North', 13402 => 'Ohio CS27 South', 13431 => 'Ohio CS83 North', 13432 => 'Ohio CS83 South', 13501 => 'Oklahoma CS27 North', 13502 => 'Oklahoma CS27 South', 13531 => 'Oklahoma CS83 North', 13532 => 'Oklahoma CS83 South', 13601 => 'Oregon CS27 North', 13602 => 'Oregon CS27 South', 13631 => 'Oregon CS83 North', 13632 => 'Oregon CS83 South', 13701 => 'Pennsylvania CS27 North', 13702 => 'Pennsylvania CS27 South', 13731 => 'Pennsylvania CS83 North', 13732 => 'Pennsylvania CS83 South', 13800 => 'Rhode Island CS27', 13830 => 'Rhode Island CS83', 13901 => 'South Carolina CS27 North', 13902 => 'South Carolina CS27 South', 13930 => 'South Carolina CS83', 14001 => 'South Dakota CS27 North', 14002 => 'South Dakota CS27 South', 14031 => 'South Dakota CS83 North', 14032 => 'South Dakota CS83 South', 14100 => 'Tennessee CS27', 14130 => 'Tennessee CS83', 14201 => 'Texas CS27 North', 14202 => 'Texas CS27 North Central', 14203 => 'Texas CS27 Central', 14204 => 'Texas CS27 South Central', 14205 => 'Texas CS27 South', 14231 => 'Texas CS83 North', 14232 => 'Texas CS83 North Central', 14233 => 'Texas CS83 Central', 14234 => 'Texas CS83 South Central', 14235 => 'Texas CS83 South', 14301 => 'Utah CS27 North', 14302 => 'Utah CS27 Central', 14303 => 'Utah CS27 South', 14331 => 'Utah CS83 North', 14332 => 'Utah CS83 Central', 14333 => 'Utah CS83 South', 14400 => 'Vermont CS27', 14430 => 'Vermont CS83', 14501 => 'Virginia CS27 North', 14502 => 'Virginia CS27 South', 14531 => 'Virginia CS83 North', 14532 => 'Virginia CS83 South', 14601 => 'Washington CS27 North', 14602 => 'Washington CS27 South', 14631 => 'Washington CS83 North', 14632 => 'Washington CS83 South', 14701 => 'West Virginia CS27 North', 14702 => 'West Virginia CS27 South', 14731 => 'West Virginia CS83 North', 14732 => 'West Virginia CS83 South', 14801 => 'Wisconsin CS27 North', 14802 => 'Wisconsin CS27 Central', 14803 => 'Wisconsin CS27 South', 14831 => 'Wisconsin CS83 North', 14832 => 'Wisconsin CS83 Central', 14833 => 'Wisconsin CS83 South', 14901 => 'Wyoming CS27 East', 14902 => 'Wyoming CS27 East Central', 14903 => 'Wyoming CS27 West Central', 14904 => 'Wyoming CS27 West', 14931 => 'Wyoming CS83 East', 14932 => 'Wyoming CS83 East Central', 14933 => 'Wyoming CS83 West Central', 14934 => 'Wyoming CS83 West', 15001 => 'Alaska CS27 1', 15002 => 'Alaska CS27 2', 15003 => 'Alaska CS27 3', 15004 => 'Alaska CS27 4', 15005 => 'Alaska CS27 5', 15006 => 'Alaska CS27 6', 15007 => 'Alaska CS27 7', 15008 => 'Alaska CS27 8', 15009 => 'Alaska CS27 9', 15010 => 'Alaska CS27 10', 15031 => 'Alaska CS83 1', 15032 => 'Alaska CS83 2', 15033 => 'Alaska CS83 3', 15034 => 'Alaska CS83 4', 15035 => 'Alaska CS83 5', 15036 => 'Alaska CS83 6', 15037 => 'Alaska CS83 7', 15038 => 'Alaska CS83 8', 15039 => 'Alaska CS83 9', 15040 => 'Alaska CS83 10', 15101 => 'Hawaii CS27 1', 15102 => 'Hawaii CS27 2', 15103 => 'Hawaii CS27 3', 15104 => 'Hawaii CS27 4', 15105 => 'Hawaii CS27 5', 15131 => 'Hawaii CS83 1', 15132 => 'Hawaii CS83 2', 15133 => 'Hawaii CS83 3', 15134 => 'Hawaii CS83 4', 15135 => 'Hawaii CS83 5', 15201 => 'Puerto Rico CS27', 15202 => 'St Croix', 15230 => 'Puerto Rico Virgin Is', 15302 => 'Kentucky CS27', 15303 => 'Kentucky CS83 North', 15914 => 'BLM 14N feet', 15915 => 'BLM 15N feet', 15916 => 'BLM 16N feet', 15917 => 'BLM 17N feet', 16001 => 'UTM zone 1N', 16002 => 'UTM zone 2N', 16003 => 'UTM zone 3N', 16004 => 'UTM zone 4N', 16005 => 'UTM zone 5N', 16006 => 'UTM zone 6N', 16007 => 'UTM zone 7N', 16008 => 'UTM zone 8N', 16009 => 'UTM zone 9N', 16010 => 'UTM zone 10N', 16011 => 'UTM zone 11N', 16012 => 'UTM zone 12N', 16013 => 'UTM zone 13N', 16014 => 'UTM zone 14N', 16015 => 'UTM zone 15N', 16016 => 'UTM zone 16N', 16017 => 'UTM zone 17N', 16018 => 'UTM zone 18N', 16019 => 'UTM zone 19N', 16020 => 'UTM zone 20N', 16021 => 'UTM zone 21N', 16022 => 'UTM zone 22N', 16023 => 'UTM zone 23N', 16024 => 'UTM zone 24N', 16025 => 'UTM zone 25N', 16026 => 'UTM zone 26N', 16027 => 'UTM zone 27N', 16028 => 'UTM zone 28N', 16029 => 'UTM zone 29N', 16030 => 'UTM zone 30N', 16031 => 'UTM zone 31N', 16032 => 'UTM zone 32N', 16033 => 'UTM zone 33N', 16034 => 'UTM zone 34N', 16035 => 'UTM zone 35N', 16036 => 'UTM zone 36N', 16037 => 'UTM zone 37N', 16038 => 'UTM zone 38N', 16039 => 'UTM zone 39N', 16040 => 'UTM zone 40N', 16041 => 'UTM zone 41N', 16042 => 'UTM zone 42N', 16043 => 'UTM zone 43N', 16044 => 'UTM zone 44N', 16045 => 'UTM zone 45N', 16046 => 'UTM zone 46N', 16047 => 'UTM zone 47N', 16048 => 'UTM zone 48N', 16049 => 'UTM zone 49N', 16050 => 'UTM zone 50N', 16051 => 'UTM zone 51N', 16052 => 'UTM zone 52N', 16053 => 'UTM zone 53N', 16054 => 'UTM zone 54N', 16055 => 'UTM zone 55N', 16056 => 'UTM zone 56N', 16057 => 'UTM zone 57N', 16058 => 'UTM zone 58N', 16059 => 'UTM zone 59N', 16060 => 'UTM zone 60N', 16101 => 'UTM zone 1S', 16102 => 'UTM zone 2S', 16103 => 'UTM zone 3S', 16104 => 'UTM zone 4S', 16105 => 'UTM zone 5S', 16106 => 'UTM zone 6S', 16107 => 'UTM zone 7S', 16108 => 'UTM zone 8S', 16109 => 'UTM zone 9S', 16110 => 'UTM zone 10S', 16111 => 'UTM zone 11S', 16112 => 'UTM zone 12S', 16113 => 'UTM zone 13S', 16114 => 'UTM zone 14S', 16115 => 'UTM zone 15S', 16116 => 'UTM zone 16S', 16117 => 'UTM zone 17S', 16118 => 'UTM zone 18S', 16119 => 'UTM zone 19S', 16120 => 'UTM zone 20S', 16121 => 'UTM zone 21S', 16122 => 'UTM zone 22S', 16123 => 'UTM zone 23S', 16124 => 'UTM zone 24S', 16125 => 'UTM zone 25S', 16126 => 'UTM zone 26S', 16127 => 'UTM zone 27S', 16128 => 'UTM zone 28S', 16129 => 'UTM zone 29S', 16130 => 'UTM zone 30S', 16131 => 'UTM zone 31S', 16132 => 'UTM zone 32S', 16133 => 'UTM zone 33S', 16134 => 'UTM zone 34S', 16135 => 'UTM zone 35S', 16136 => 'UTM zone 36S', 16137 => 'UTM zone 37S', 16138 => 'UTM zone 38S', 16139 => 'UTM zone 39S', 16140 => 'UTM zone 40S', 16141 => 'UTM zone 41S', 16142 => 'UTM zone 42S', 16143 => 'UTM zone 43S', 16144 => 'UTM zone 44S', 16145 => 'UTM zone 45S', 16146 => 'UTM zone 46S', 16147 => 'UTM zone 47S', 16148 => 'UTM zone 48S', 16149 => 'UTM zone 49S', 16150 => 'UTM zone 50S', 16151 => 'UTM zone 51S', 16152 => 'UTM zone 52S', 16153 => 'UTM zone 53S', 16154 => 'UTM zone 54S', 16155 => 'UTM zone 55S', 16156 => 'UTM zone 56S', 16157 => 'UTM zone 57S', 16158 => 'UTM zone 58S', 16159 => 'UTM zone 59S', 16160 => 'UTM zone 60S', 16200 => 'Gauss Kruger zone 0', 16201 => 'Gauss Kruger zone 1', 16202 => 'Gauss Kruger zone 2', 16203 => 'Gauss Kruger zone 3', 16204 => 'Gauss Kruger zone 4', 16205 => 'Gauss Kruger zone 5', 17348 => 'Map Grid of Australia 48', 17349 => 'Map Grid of Australia 49', 17350 => 'Map Grid of Australia 50', 17351 => 'Map Grid of Australia 51', 17352 => 'Map Grid of Australia 52', 17353 => 'Map Grid of Australia 53', 17354 => 'Map Grid of Australia 54', 17355 => 'Map Grid of Australia 55', 17356 => 'Map Grid of Australia 56', 17357 => 'Map Grid of Australia 57', 17358 => 'Map Grid of Australia 58', 17448 => 'Australian Map Grid 48', 17449 => 'Australian Map Grid 49', 17450 => 'Australian Map Grid 50', 17451 => 'Australian Map Grid 51', 17452 => 'Australian Map Grid 52', 17453 => 'Australian Map Grid 53', 17454 => 'Australian Map Grid 54', 17455 => 'Australian Map Grid 55', 17456 => 'Australian Map Grid 56', 17457 => 'Australian Map Grid 57', 17458 => 'Australian Map Grid 58', 18031 => 'Argentina 1', 18032 => 'Argentina 2', 18033 => 'Argentina 3', 18034 => 'Argentina 4', 18035 => 'Argentina 5', 18036 => 'Argentina 6', 18037 => 'Argentina 7', 18051 => 'Colombia 3W', 18052 => 'Colombia Bogota', 18053 => 'Colombia 3E', 18054 => 'Colombia 6E', 18072 => 'Egypt Red Belt', 18073 => 'Egypt Purple Belt', 18074 => 'Extended Purple Belt', 18141 => 'New Zealand North Island Nat Grid', 18142 => 'New Zealand South Island Nat Grid', 19900 => 'Bahrain Grid', 19905 => 'Netherlands E Indies Equatorial', 19912 => 'RSO Borneo', 19926 => 'Stereo 70', 32767 => 'User Defined', }, }, 3075 => { Name => 'ProjCoordTrans', PrintConv => { # geo_ctrans 1 => 'Transverse Mercator', 2 => 'Transverse Mercator Modified Alaska', 3 => 'Oblique Mercator', 4 => 'Oblique Mercator Laborde', 5 => 'Oblique Mercator Rosenmund', 6 => 'Oblique Mercator Spherical', # not advisable 7 => 'Mercator', 8 => 'Lambert Conf Conic 2SP', 9 => 'Lambert Conf Conic 1SP', 10 => 'Lambert Azim Equal Area', 11 => 'Albers Equal Area', 12 => 'Azimuthal Equidistant', 13 => 'Equidistant Conic', 14 => 'Stereographic', 15 => 'Polar Stereographic', 16 => 'Oblique Stereographic', # not advisable 17 => 'Equirectangular', 18 => 'Cassini Soldner', 19 => 'Gnomonic', 20 => 'Miller Cylindrical', 21 => 'Orthographic', 22 => 'Polyconic', 23 => 'Robinson', 24 => 'Sinusoidal', 25 => 'VanDerGrinten', 26 => 'New Zealand Map Grid', 27 => 'Transverse Mercator South Orientated', 28 => 'Cylindrical Equal Area', 32767 => 'User Defined', }, }, 3076 => { Name => 'ProjLinearUnits', SeparateTable => 'Units', PrintConv => \%epsg_units, }, 3077 => 'ProjLinearUnitSize', 3078 => 'ProjStdParallel1', 3079 => 'ProjStdParallel2', 3080 => 'ProjNatOriginLong', 3081 => 'ProjNatOriginLat', 3082 => 'ProjFalseEasting', 3083 => 'ProjFalseNorthing', 3084 => 'ProjFalseOriginLong', 3085 => 'ProjFalseOriginLat', 3086 => 'ProjFalseOriginEasting', 3087 => 'ProjFalseOriginNorthing', 3088 => 'ProjCenterLong', 3089 => 'ProjCenterLat', 3090 => 'ProjCenterEasting', 3091 => 'ProjCenterNorthing', 3092 => 'ProjScaleAtNatOrigin', 3093 => 'ProjScaleAtCenter', 3094 => 'ProjAzimuthAngle', 3095 => 'ProjStraightVertPoleLong', 3096 => 'ProjRectifiedGridAngle', 4096 => { Name => 'VerticalCSType', SeparateTable => 'VerticalCS', PrintConv => \%epsg_vertcs, }, 4097 => 'VerticalCitation', 4098 => { Name => 'VerticalDatum', SeparateTable => 'VerticalCS', PrintConv => \%epsg_vertcs, }, 4099 => { Name => 'VerticalUnits', SeparateTable => 'Units', PrintConv => \%epsg_units, }, # # ChartTiff extensions (ref 2) # 47001 => { Name => 'ChartFormat', PrintConv => { 47500 => 'General', 47501 => 'Coastal', 47502 => 'Harbor', 47503 => 'SailingInternational', 47504 => 'SmallCraft Route', 47505 => 'SmallCraftArea', 47506 => 'SmallCraftFolio', 47507 => 'Topographic', 47508 => 'Recreation', 47509 => 'Index', 47510 => 'Inset', }, }, 47002 => 'ChartSource', 47003 => 'ChartSourceEdition', 47004 => 'ChartSourceDate', 47005 => 'ChartCorrDate', 47006 => 'ChartCountryOrigin', 47007 => 'ChartRasterEdition', 47008 => { Name => 'ChartSoundingDatum', PrintConv => { 47600 => 'Equatorial Spring Low Water', 47601 => 'Indian Spring Low Water', 47602 => 'Lowest Astronomical Tide', 47603 => 'Lowest Low Water', 47604 => 'Lowest Normal Low Water', 47605 => 'Mean Higher High Water', 47606 => 'Mean High Water', 47607 => 'Mean High Water Springs', 47608 => 'Mean Lower Low Water', 47609 => 'Mean Lower Low Water Springs', 47610 => 'Mean Low Water', 47611 => 'Mean Sea Level', 47612 => 'Tropic Higher High Water', 47613 => 'Tropic Lower Low Water', }, }, 47009 => { Name => 'ChartDepthUnits', SeparateTable => 'Units', PrintConv => \%epsg_units, }, 47010 => 'ChartMagVar', 47011 => 'ChartMagVarYear', 47012 => 'ChartMagVarAnnChange', 47013 => 'ChartWGSNSShift', 47015 => 'InsetNWPixelX', 47016 => 'InsetNWPixelY', 47017 => 'ChartContourInterval', ); #------------------------------------------------------------------------------ # Inputs: 0) ExifTool object ref # Notes: byte order must be set before calling this routine sub ProcessGeoTiff($) { my $et = shift; my $dirData = $et->GetValue('GeoTiffDirectory', 'ValueConv') or return; # avoid re-processing if another EXIF directory is found $$et{DidGeoTiff} and $$et{DidGeoTiff} eq $dirData and return; $$et{DidGeoTiff} = $dirData; my $doubleData = $et->GetValue('GeoTiffDoubleParams', 'ValueConv'); my $asciiData = $et->GetValue('GeoTiffAsciiParams', 'ValueConv'); my $verbose = $et->Options('Verbose'); if (length($$dirData) >= 8 and length($$dirData) >= 8 * (Get16u($dirData,6) + 1)) { my $version = Get16u($dirData,0); my $revision = Get16u($dirData,2); my $minorRev = Get16u($dirData,4); my $numEntries = Get16u($dirData,6); if ($verbose) { $$et{INDENT} .= '| '; $et->VerboseDir('GeoTiff',$numEntries); } # generate version number tag (not a real GeoTiff tag) my $tagTable = GetTagTable("Image::ExifTool::GeoTiff::Main"); my $tagInfo = $et->GetTagInfo($tagTable, 1); $tagInfo and $et->FoundTag($tagInfo,"$version.$revision.$minorRev"); my $i; for ($i=0; $i<$numEntries; ++$i) { my $pt = 8 * ($i + 1); my $tag = Get16u($dirData, $pt); $tagInfo = $et->GetTagInfo($tagTable, $tag) or next; my $loc = Get16u($dirData, $pt+2); my $count = Get16u($dirData, $pt+4); my $offset = Get16u($dirData, $pt+6); my $format = $geoTiffFormat{$loc}; my ($val, $dataPt); if ($format eq 'double') { # in the double parms if (not $doubleData or length($$doubleData) < 8*($offset+$count)) { $et->Warn("Missing double data for $$tagInfo{Name}"); next; } $dataPt = $doubleData; $offset *= 8; $val = Image::ExifTool::ReadValue($dataPt, $offset, $format, $count, length($$doubleData)-$offset); } elsif ($format eq 'string') { # in the ASCII parms if (not $asciiData or length($$asciiData) < $offset+$count) { $et->Warn("Missing string data for $$tagInfo{Name}"); next; } $dataPt = $asciiData; $val = substr($$dataPt, $offset, $count); $val =~ s/(\0|\|)$//; # remove trailing terminator (NULL or '|') } elsif ($format eq 'int16u') { # use the offset as the value $dataPt = $dirData; $val = $offset; $offset = $pt+6; } else { $et->Warn("Unknown GeoTiff location: $loc"); next; } $verbose and $et->VerboseInfo($tag, $tagInfo, 'Table' => $tagTable, 'Index' => $i, 'Value' => $val, 'DataPt' => $dataPt, 'Start' => $offset, 'Format' => $format, 'Count' => $count, 'Size' => $count * Image::ExifTool::FormatSize($format), ); $et->FoundTag($tagInfo, $val); } if ($verbose) { $$et{INDENT} =~ s/..$//; } } else { $et->Warn('Bad GeoTIFF directory'); } # extract block tags only if requested unless ($$et{OPTIONS}{RequestAll}) { $et->DeleteTag('GeoTiffDirectory') unless $$et{REQ_TAG_LOOKUP}{geotiffdirectory}; $et->DeleteTag('GeoTiffDoubleParams') unless $$et{REQ_TAG_LOOKUP}{geotiffdoubleparams}; $et->DeleteTag('GeoTiffAsciiParams') unless $$et{REQ_TAG_LOOKUP}{geotiffasciiparams}; } } 1; #end __END__ =head1 NAME Image::ExifTool::GeoTiff - Read GeoTiff meta information =head1 SYNOPSIS This module is loaded automatically by Image::ExifTool when required. =head1 DESCRIPTION This module contains definitions required by Image::ExifTool to interpret GeoTiff meta information. GeoTiff information is used in images to specify exact geometric mappings used to transform the image to real world coordinates. =head1 AUTHOR Copyright 2003-2015, Phil Harvey (phil at owl.phy.queensu.ca) This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 REFERENCES =over 4 =item ftp://ftp.remotesensing.org/geotiff/libgeotiff/libgeotiff-1.1.4.tar.gz =item http://www.charttiff.com/whitepapers.shtml =back =head1 SEE ALSO L<Image::ExifTool::TagNames/GeoTiff Tags>, L<Image::ExifTool(3pm)|Image::ExifTool> =cut
mudasobwa/exifice
vendor/Image-ExifTool-10.02/lib/Image/ExifTool/GeoTiff.pm
Perl
mit
89,369
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by mktables from the Unicode # database, Version 6.1.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 0F72 0F7A 0F7D 0F80 END
Dokaponteam/ITF_Project
xampp/perl/lib/unicore/lib/Ccc/CCC130.pl
Perl
mit
435
# cluster-software-lib.pl # common functions for installing packages across a cluster # XXX refresh all packages after installing BEGIN { push(@INC, ".."); }; use WebminCore; &init_config(); &foreign_require("servers", "servers-lib.pl"); &foreign_require("software", "software-lib.pl"); $parallel_max = 20; %access = &get_module_acl(); # list_software_hosts() # Returns a list of all hosts whose software is being managed by this module sub list_software_hosts { local @rv; local %smap = map { $_->{'id'}, $_ } &list_servers(); local $hdir = "$module_config_directory/hosts"; opendir(DIR, $hdir); foreach $h (readdir(DIR)) { next if ($h =~ /\.host$/ || $h eq '.' || $h eq '..'); local %host = ( 'id', $h ); next if (!$smap{$h}); # underlying server was deleted opendir(PDIR, "$hdir/$h") || next; foreach $p (readdir(PDIR)) { next if ($p eq "." || $p eq ".."); local %pkg; &read_file("$hdir/$h/$p", \%pkg); push(@{$host{'packages'}}, \%pkg); } closedir(PDIR); &read_file("$hdir/$h.host", \%host); push(@rv, \%host); } closedir(DIR); return @rv; } # save_software_host(&host) # Add or update a managed host with it's package list sub save_software_host { local $hdir = "$module_config_directory/hosts"; mkdir($hdir, 0700); if (-d "$hdir/$_[0]->{'id'}") { opendir(DIR, "$hdir/$_[0]->{'id'}"); foreach $f (readdir(DIR)) { unlink("$hdir/$_[0]->{'id'}/$f"); } closedir(DIR); } else { mkdir("$hdir/$_[0]->{'id'}", 0700); } foreach $p (@{$_[0]->{'packages'}}) { local $pname = $p->{'name'}; $pname =~ s/\//_/g; &write_file("$hdir/$_[0]->{'id'}/$pname", $p); } local %h = %{$_[0]}; delete($h{'packages'}); &write_file("$hdir/$_[0]->{'id'}.host", \%h); } # delete_software_host(&host) sub delete_software_host { &unlink_file("$module_config_directory/hosts/$_[0]->{'id'}.host"); &unlink_file("$module_config_directory/hosts/$_[0]->{'id'}"); } # list_servers() # Returns a list of all servers from the webmin servers module that can be # managed, plus this server sub list_servers { local @servers = &servers::list_servers_sorted(); return ( &servers::this_server(), grep { $_->{'user'} } @servers ); } # host_to_server(&host|id) sub host_to_server { local $id = ref($_[0]) ? $_[0]->{'id'} : $_[0]; local ($serv) = grep { $_->{'id'} eq $id } &list_servers(); return $serv; } # server_name(&server) sub server_name { return $_[0]->{'desc'} || $_[0]->{'realhost'} || $_[0]->{'host'}; } # get_heiropen(hostid) # Returns an array of open categories sub get_heiropen { open(HEIROPEN, "$module_config_directory/heiropen.$_[0]"); local @heiropen = <HEIROPEN>; chop(@heiropen); close(HEIROPEN); return @heiropen; } # save_heiropen(&heir, hostid) sub save_heiropen { &open_tempfile(HEIR, ">$module_config_directory/heiropen.$_[1]"); foreach $h (@{$_[0]}) { &print_tempfile(HEIR, $h,"\n"); } &close_tempfile(HEIR); } # create_on_input(desc, [no-donthave], [no-have]) sub create_on_input { local @hosts = &list_software_hosts(); local @servers = &list_servers(); local @opts; push(@opts, [ -1, $text{'edit_all'} ]); push(@opts, [ -2, $text{'edit_donthave'} ]) if (!$_[1]); push(@opts, [ -3, $text{'edit_have'} ]) if (!$_[2]); local @groups = &servers::list_all_groups(\@servers); local $h; foreach $h (@hosts) { local ($s) = grep { $_->{'id'} == $h->{'id'} } @servers; if ($s) { push(@opts, [ $s->{'id'}, $s->{'desc'} || $s->{'realhost'} || $s->{'host'} ]); $gothost{$s->{'host'}}++; } } local $g; foreach $g (@groups) { local ($found, $m); foreach $m (@{$g->{'members'}}) { ($found++, last) if ($gothost{$m}); } push(@opts, [ "group_$g->{'name'}", &text('edit_group', $g->{'name'}) ]) if ($found); } local $sel = &ui_select("server", undef, \@opts); if ($_[0]) { print &ui_table_row($_[0], $sel); } else { print $sel; } } # create_on_parse(prefix, &already, name) sub create_on_parse { local @hosts = &list_software_hosts(); local @servers = &list_servers(); if ($in{'server'} == -2) { # Install on hosts that don't have it local %already = map { $_->{'id'}, 1 } @{$_[1]}; @hosts = grep { !$already{$_->{'id'}} } @hosts; print "<b>",&text($_[0].'3', $_[2]),"</b><p>\n"; } elsif ($in{'server'} == -3) { # Install on hosts that do have it local %already = map { $_->{'id'}, 1 } @{$_[1]}; @hosts = grep { $already{$_->{'id'}} } @hosts; print "<b>",&text($_[0].'6', $_[2]),"</b><p>\n"; } elsif ($in{'server'} =~ /^group_(.*)/) { # Install on members of some group local ($group) = grep { $_->{'name'} eq $1 } &servers::list_all_groups(\@servers); @hosts = grep { local $hid = $_->{'id'}; local ($s) = grep { $_->{'id'} == $hid } @servers; &indexof($s->{'host'}, @{$group->{'members'}}) >= 0 } @hosts; print "<b>",&text($_[0].'4', $_[2], $group->{'name'}), "</b><p>\n"; } elsif ($in{'server'} != -1) { # Just install on one host @hosts = grep { $_->{'id'} == $in{'server'} } @hosts; local ($s) = grep { $_->{'id'} == $hosts[0]->{'id'} } @servers; print "<b>",&text($_[0].'5', $_[2], &server_name($s)),"</b><p>\n"; } else { # Installing on every host print "<b>",&text($_[0], join(" ", @names)),"</b><p>\n"; } return @hosts; } # Setup error handler for down hosts sub add_error { $add_error_msg = join("", @_); } # add_managed_host(&server) # Adds a new system to this module for management, and returns a status code # (0 or 1) and error or information message sub add_managed_host { local ($s) = @_; &remote_error_setup(\&add_error); # Get the packages for each host local %sconfig = &foreign_config("software"); $add_error_msg = undef; local $host = { 'id' => $s->{'id'} }; local $soft = &remote_foreign_check($s->{'host'}, "software"); if ($add_error_msg) { return (0, $add_error_msg); } if (!$soft) { return (0, &text('add_echeck', $s->{'host'})); } &remote_foreign_require($s->{'host'}, "software", "software-lib.pl"); local $rconfig = &remote_foreign_config($s->{'host'}, "software"); #if ($rconfig->{'package_system'} ne $sconfig{'package_system'}) { # return (0, &text('add_esystem', $s->{'host'})); # } $host->{'package_system'} = $rconfig->{'package_system'}; local $gconfig = &remote_foreign_config($s->{'host'}, undef); foreach $g ('os_type', 'os_version', 'real_os_type', 'real_os_version') { $host->{$g} = $gconfig->{$g}; } local $n = &remote_foreign_call($s->{'host'}, "software", "list_packages"); local $packages = &remote_eval($s->{'host'}, "software", "\\%packages"); for(my $i=0; $i<$n; $i++) { push(@{$host->{'packages'}}, { 'name' => $packages->{$i,'name'}, 'class' => $packages->{$i,'class'}, 'desc' => $packages->{$i,'desc'}, 'version' => $packages->{$i,'version'}, 'nouninstall' => $packages->{$i,'nouninstall'}, 'nolist' => $packages->{$i,'nolist'}, }); } &save_software_host($host); return (1, &text('add_ok', &server_name($s), $n)); } # refresh_packages(&hosts) # Update the local cache with actual installed packages. Returns an array # of either an error messages or two arrays of added and removed packages. sub refresh_packages { local ($hosts) = @_; local @servers = &list_servers(); # Setup error handler for down hosts sub ref_error { $ref_error_msg = join("", @_); } &remote_error_setup(\&ref_error); local $p = 0; foreach my $h (@$hosts) { local ($s) = grep { $_->{'id'} == $h->{'id'} } @servers; local ($rh = "READ$p", $wh = "WRITE$p"); pipe($rh, $wh); if (!fork()) { close($rh); if ($s) { # Refresh the list &remote_foreign_require($s->{'host'}, "software", "software-lib.pl"); if ($ref_error_msg) { # Host is down .. print $wh &serialise_variable($ref_error_msg); exit; } local $gconfig = &remote_foreign_config($s->{'host'}, undef); foreach $g ('os_type', 'os_version', 'real_os_type', 'real_os_version') { $h->{$g} = $gconfig->{$g}; } local @old = map { $_->{'name'} } @{$h->{'packages'}}; undef($h->{'packages'}); local $n = &remote_foreign_call($s->{'host'}, "software", "list_packages"); local $packages = &remote_eval($s->{'host'}, "software", "\\%packages"); local @added; for($i=0; $i<$n; $i++) { next if (!$packages->{$i,'name'}); push(@{$h->{'packages'}}, { 'name' => $packages->{$i,'name'}, 'class' => $packages->{$i,'class'}, 'desc' => $packages->{$i,'desc'}, 'version' => $packages->{$i,'version'}, 'nouninstall' => $packages->{$i,'nouninstall'}, 'nolist' => $packages->{$i,'nolist'}, }); $idx = &indexof($packages->{$i,'name'}, @old); if ($idx < 0) { push(@added, $packages->{$i,'name'}); } else { splice(@old, $idx, 1); } } &save_software_host($h); $rv = [ \@added, \@old ]; } else { # remove from managed list &delete_software_host($h); $rv = undef; } print $wh &serialise_variable($rv); close($wh); exit; } close($wh); $p++; } # Read back results $p = 0; local @results; foreach my $h (@hosts) { local ($s) = grep { $_->{'id'} == $h->{'id'} } @servers; local $rh = "READ$p"; local $line = <$rh>; local $rv = &unserialise_variable($line); close($rh); push(@results, $rv); $p++; } return @results; } # same_package_system(&host) # Returns 1 if some host is using the same package system as this master sub same_package_system { local ($host) = @_; return !$host->{'package_system'} || $host->{'package_system'} eq $software::config{'package_system'}; } 1;
HasClass0/webmin
cluster-software/cluster-software-lib.pl
Perl
bsd-3-clause
9,740
############################################################################ # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. package TestDriver; ########################################################################### # Class: TestDriver # A base class for TestDrivers. # use TestDriverFactory; use TestReport; use File::Path; use Parallel::ForkManager; use FileHandle; use File::Copy; use File::Basename; my $passedStr = 'passed'; my $failedStr = 'failed'; my $abortedStr = 'aborted'; my $skippedStr = 'skipped'; my $dependStr = 'failed_dependency'; # A constant to be used as a key in hash: my $keyGlobalSetupConditionalDone = 'globalSetupConditionaldone'; ################################################################################ # Sub: appendToLength # static mathod to make a string not shorter than N characters in length: # appends spaces unlit the desired length achieved. # # Paramaters: # str - the string # len - the min deired length # # Returns: the modified string # sub appendToLength($$) { my ($str, $len) = @_; while (length($str) < $len) { $str .= " "; } return $str; } ############################################################################## # Sub: printResults # Static function, can be used by test_harness.pl # Print the results so far, given the testStatuses hash. # # Paramaters: # testStatuses - reference to hash of test status results. # log - reference to file handle to print results to. # prefix - A title to prefix to the results # # Returns: # None. # sub printResults { my ($testStatuses, $log, $prefix, $confFile, $groupName) = @_; my ($pass, $fail, $abort, $depend, $skipped) = (0, 0, 0, 0, 0); foreach (keys(%$testStatuses)) { ($testStatuses->{$_} eq $passedStr) && $pass++; ($testStatuses->{$_} eq $failedStr) && $fail++; ($testStatuses->{$_} eq $abortedStr) && $abort++; ($testStatuses->{$_} eq $dependStr) && $depend++; ($testStatuses->{$_} eq $skippedStr) && $skipped++; } my $context = ""; if (defined($confFile) && (length(confFile) > 0)) { $context = " [$confFile-$groupName]"; } # XXX why comma is added there? my $msg = appendToLength($prefix . ",", 18) . " PASSED: " . appendToLength($pass,4) . " FAILED: " . appendToLength($fail,4) . " SKIPPED: " . appendToLength($skipped,4) . " ABORTED: " . appendToLength($abort,4) . " FAILED DEPENDENCY: " . appendToLength($depend,4) . $context; print $log "$msg\n"; print "$msg\n"; } ############################################################################## # Puts all the k-v pairs from sourceHash to the targetHash. # Returns: void # parameters: # 1: targetHash, # 2: sourceHash. sub putAll($$) { my ($targetHash, $sourceHash) = @_; while (my ($key, $value) = each(%$sourceHash)) { $targetHash->{ $key } = $value; } } ############################################################################## # appends one file to another. # parameters: # 1: sourceFileName, # 2: targetFileName. # Returns: void sub appendFile($$) { my ($source, $target) = @_; dbg("Appending file [" . Cwd::realpath($source) . "] >> [" . Cwd::realpath($target) . "]\n"); $sourceHandle = FileHandle->new("<$source"); if (! defined $sourceHandle) { die "Cannot open source file [$source]."; } $targetHandle = FileHandle->new(">>$target"); if (defined $targetHandle) { copy($sourceHandle, $targetHandle); $targetHandle->close(); $sourceHandle->close(); } else { die "cannot open target file [$target]."; } } ############################################################################## # Diagnostic sub to print a hash contents # Paramaters: # 1: the hash reference; # Returns: void sub dbgDumpHash($;$) { if ($ENV{'E2E_DEBUG'} eq 'true') { my ($myhash, $msg) = @_; print "Dump of hash $msg:\n"; while (my ($key, $value) = each(%$myhash)) { print " [$key] = [$value]\n"; } } } ############################################################################## # Diagnostic sub to print a debug output. # This is useful when debugging the harness perl scripts. # Paramaters: # 1*: object(s) to be printed, typically one string; # Returns: void sub dbg(@) { if ($ENV{'E2E_DEBUG'} eq 'true') { print @_; } } ############################################################################## # Sub: printGroupResultsXml # Print the results for the group using junit xml schema using values from the testStatuses hash. # # Paramaters: # $report - the report object to use to generate the report # $groupName - the name of the group to report totals for # $testStatuses - the hash containing the results for the tests run so far # $totalDuration- The total time it took to run the group of tests # # Returns: # None. # sub printGroupResultsXml { my ( $report, $groupName, $testStatuses, $totalDuration) = @_; $totalDuration=0 if ( !$totalDuration ); my ($pass, $fail, $abort, $depend) = (0, 0, 0, 0); foreach my $key (keys(%$testStatuses)) { if ( $key =~ /^$groupName/ ){ ($testStatuses->{$key} eq $passedStr) && $pass++; ($testStatuses->{$key} eq $failedStr) && $fail++; ($testStatuses->{$key} eq $abortedStr) && $abort++; ($testStatuses->{$key} eq $dependStr) && $depend++; } } my $total= $pass + $fail + $abort; $report->totals( $groupName, $total, $fail, $abort, $totalDuration ); } ############################################################################## # Sub: new # Constructor, should only be called by TestDriverFactory. # # Paramaters: # None # # Returns: # None. sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; bless($self, $class); $self->{'wrong_execution_mode'} = "_xyz_wrong_execution_mode_zyx_"; return $self; } ############################################################################## # Sub: globalSetup # Set up before any tests from the group are run. This gives each individual driver a chance to do # setup. This function will only be called once, before all the tests are # run. A driver need not implement it. It is a virtual function. # # This method invoked unconditionally (always), even if there are no test to run in the group. See # also #globalSetupConditional() description. # # Paramaters: # globalHash - Top level hash from config file (does not have any group # or test information in it). # log - log file handle # # Returns: # None # sub globalSetup { } ############################################################################## # Sub: globalSetupConditional # Set up before any tests from the test config file (in sequential mode) or test group (in parallel mode) are run. # Executes after #globalSetup(). Executes *only* if there is at least one test to run. Introduced for performance # optimization in parallel execution mode. # It is a virtual function. Subclasses may override it. # # Paramaters: # globalHash - Top level hash from config file (does not have any group # or test information in it). # log - log file handle # # Returns: # None # sub globalSetupConditional { } ############################################################################### # Sub: globalCleanup # Clean up after all tests have run. This gives each individual driver a chance to do # cleanup. This function will only be called once, after all the tests are # run. A driver need not implement it. It is a virtual function. # This method invoked unconditionally, even if no test in the group was executed. # See #globalCleanupConditional() method description. # # Paramaters: # globalHash - Top level hash from config file (does not have any group # or test information in it). # log - log file handle # # Returns: # None sub globalCleanup { } ############################################################################### # Sub: globalCleanupConditional # Clean up after all tests have run, before #globalCleanup(). Invoked iff #globalSetupConditional() # was previously invoked gor this config file (sequential mode) or test group (parallel mode). # It is a virtual function. Subclasses may override it. # # Paramaters: # globalHash - Top level hash from config file (does not have any group # or test information in it). # log - log file handle # # Returns: # None sub globalCleanupConditional() { } ############################################################################### # Sub: runTest # Run a test. This is a pure virtual function. # # Parameters: # testcmd - reference to hash with meta tags and command to run tests. # Interpretation of the tags and the command are up to the subclass. # log - reference to a stream pointer for the logs # # Returns: # @returns reference to hash. Contents of hash are defined by the subclass. # sub runTest { die "$0 INFO : This is a virtual function!"; } ############################################################################### # Sub: generateBenchmark # Generate benchmark results. This is a pure virtual function. # # Parameters: # benchmarkcmd - reference to hash with meta tags and command to # generate benchmark. Interpretation of the tags and the command are up to # log - reference to a stream pointer for the logs # the subclass. # # Returns: # @returns reference to hash. Contents of hash are defined by the subclass. # sub generateBenchmark { die "$0 INFO: This is a virtual function!"; } ############################################################################### # Sub: compare # Compare the results of the test run with the generated benchmark results. # This is a pure virtual function. # # Parameters: # benchmarkcmd - reference to hash with meta tags and command to # testResult - reference to hash returned by runTest. # benchmarkResult - reference to hash returned by generateBenchmark. # log - reference to a stream pointer for the logs # testHash - reference to hash with meta tags and commands # # Returns: # @returns reference true if results are the same, false otherwise. "the # same" is defined by the subclass. # sub compare { die "$0 INFO: This is a virtual function!"; } ############################################################################### # Sub: recordResults # Record results of the test run. The required fields are filled in by the # test harness. This call gives an individual driver a chance to fill in # additional fields of cmd, cmd_id, expected_results, and actual_results. # this function does not have to be implemened. # This is a virtual function. # # Parameters: # status - status of test passing, true or false # testResult - reference to hash returned by runTest. # benchmarkResult - reference to hash returned by generateBenchmark. # dbinfo - reference to hash that will be used to fill in db. # log - reference to hash that will be used to fill in db. # # Returns: # None # sub recordResults { } ############################################################################### # Sub: cleanup # Clean up after a test. This gives each individual driver a chance to do # cleanup. A driver need not implement it. It is a virtual function. # # Parameters: # status - status of test passing, true or false # testHash - reference to hash that was passed to runTest() and # generateBenchmark(). # testResult - reference to hash returned by runTest. # benchmarkResult - reference to hash returned by generateBenchmark. # log - reference to a stream pointer for the logs # # Returns: # None # sub cleanup { } ############################################################################### # Sub: run # Run all the tests in the configuration file. # # Parameters: # testsToRun - reference to array of test groups and ids to run # testsToMatch - reference to array of test groups and ids to match. # If a test group_num matches any of these regular expressions it will be run. # cfg - reference to contents of cfg file # log - reference to a stream pointer for the logs # dbh - reference database connection # testStatuses- reference to hash of test statuses # confFile - config file name # startat - test to start at. # logname - name of the xml log for reporting results # # Returns: # @returns nothing # failed. # sub run { my ($self, $testsToRun, $testsToMatch, $cfg, $log, $dbh, $testStatuses, $confFile, $startat, $logname, $resources ) = @_; my $subName = (caller(0))[3]; my $msg=""; # Rather than make each driver handle our multi-level cfg, we'll flatten # the hashes into one for it. my %globalHash; my $runAll = ((scalar(@$testsToRun) == 0) && (scalar(@$testsToMatch) == 0)); # Read the global keys foreach (keys(%$cfg)) { next if $_ eq 'groups'; $globalHash{$_} = $cfg->{$_}; } my $report=0; my $properties= new Properties(0, $globalHash{'propertiesFile'}); my $fileForkFactor = int($ENV{'FORK_FACTOR_FILE'}); my $groupForkFactor = int($ENV{'FORK_FACTOR_GROUP'}); # NB: this is to distinguish the sequential mode from parallel one: my $productForkFactor = $fileForkFactor * $groupForkFactor; my $pm; if ($groupForkFactor > 1) { print $log "Group fork factor: $groupForkFactor\n"; # Create the fork manager: $pm = new Parallel::ForkManager($groupForkFactor); # this is a callback method that will run in the main process on each job subprocess completion: $pm -> run_on_finish ( sub { my ($pid, $exit_code, $identification, $exit_signal, $core_dump, $data_structure_reference) = @_; # see what the child sent us, if anything if (defined($data_structure_reference)) { dbg("Group subprocess [$identification] finished, pid=${pid}, sent back: [$data_structure_reference].\n"); dbgDumpHash($data_structure_reference, "The hash passed in in the run_on_finish callback:"); putAll($testStatuses, $data_structure_reference); dbgDumpHash($testStatuses, "The statuses after merge in the run_on_finish callback:"); } else { print "ERROR: Group subprocess [$identification] did not send back anything. Exit code = $exit_code\n"; } my $subLogAgain = "$logname-$identification"; appendFile($subLogAgain,$logname); } ); } else { # Do the global setup: $self->globalSetup(\%globalHash, $log); } my $localStartAt = $startat; foreach my $group (@{$cfg->{'groups'}}) { my $groupName = $group->{'name'}; my $subLog; my $subLogName; if ($groupForkFactor > 1) { # use group name as the Job id: my $jobId = $groupName; $subLogName = "$logname-$jobId"; open $subLog, ">$subLogName" or die "FATAL ERROR $0 at ".__LINE__." : Can't open $subLogName, $!\n"; dbg("**** Logging to [$subLogName].\n"); # PARALLEL SECTION START: =============================================================================== $pm->start($jobId) and next; dbg("Started test group job \"$jobId\"\n"); dbg("Doing setup for test group [$groupName]...\n"); # Set the group-specific ID: # NB: note that '$globalHash' here is an object cloned for this subprocess. # So, there is no concurrency issue in using '$globalHash' there: $globalHash{'job-id'} = $globalHash{'job-id'} . "-" . $jobId; # Do the global setup which is specific for *this group*: $self->globalSetup(\%globalHash, $subLog); } else { $subLog = $log; $subLogName = $logname; } # Run the group of tests. # NB: the processing of $localStartAt parameter happens only if the groupForkFactor < 1. my $sawStart = $self -> runTestGroup($groupName, $subLog, $confFile, \%globalHash, $group, $runAll, $testsToRun, $testsToMatch, $localStartAt, $testStatuses, $productForkFactor, $resources); if ((defined $localStartAt) && $sawStart) { undef $localStartAt; } if ($groupForkFactor > 1) { # do the clanups that are specific for *this group*. dbg("Doing cleanup for test group [$groupName]...\n"); # NB: invoke it in such way to emphasize the fact that this method is not virtual: globalCleanupConditionalIf($self, \%globalHash, $subLog); $self->globalCleanup(\%globalHash, $subLog); dbg("Finishing test group [$groupName].\n"); dbgDumpHash($testStatuses, "The satatuses hash at the fork section end"); # NB: send the "testStatuses" hash object reference (which is local to this subprocess) to the parent process: $subLog -> close(); # TODO: may also consider the #runTestGroup block exit status and use it there. $pm -> finish(0, $testStatuses); # PARALLEL SECTION END. =============================================================================== } } # foreach $group if ($groupForkFactor > 1) { $pm->wait_all_children; } else { # Do the global cleanups: # NB: invoke it in such way to emphasize the fact that this method is not virtual: globalCleanupConditionalIf($self, \%globalHash, $log); $self->globalCleanup(\%globalHash, $log); } } # Servce method to conditionally perform the virtual #globalCleanupConditional(). # NB: This sub should be "final" in Java terms, # subclasses should not override it. sub globalCleanupConditionalIf() { my ($self, $globalHash, $log) = @_; if (defined($globalHash->{$keyGlobalSetupConditionalDone})) { $self -> globalCleanupConditional($globalHash, $log); } } ################################################################################ # Separated sub to run a test group. # Parameters: (same named values from #run(...) sub with the same meaning). # Returns: 'true' if the test defined by '$startat' was found, and 'false' otherwise. # (If the '$startat' is null, always returns true.) sub runTestGroup() { my ($self, $groupName, $subLog, $confFile, $globalHash, $group, $runAll, $testsToRun, $testsToMatch, $startat, $testStatuses, $productForkFactor, $resources) = @_; my $subName = (caller(0))[3]; print $subLog "INFO $subName at ".__LINE__.": Running TEST GROUP(".$groupName.")\n"; my $sawstart = !(defined $startat); my %groupHash = %$globalHash; $groupHash{'group'} = $groupName; # Read the group keys foreach (keys(%$group)) { next if $_ eq 'tests'; $groupHash{$_} = $group->{$_}; } my $groupDuration=0; my $duration=0; # Run each test in the group: foreach my $test (@{$group->{'tests'}}) { # Check if we're supposed to run this one or not. if (!$runAll) { # check if we are supposed to run this test or not. my $foundIt = 0; foreach (@$testsToRun) { if (/^$groupHash{'group'}(_[0-9]+)?$/) { if (not defined $1) { # In this case it's just the group name, so we'll # run every test in the group $foundIt = 1; last; } else { # maybe, it at least matches the group my $num = "_" . $test->{'num'}; if ($num eq $1) { $foundIt = 1; last; } } } } foreach (@$testsToMatch) { my $protoName = $groupHash{'group'} . "_" . $test->{'num'}; if ($protoName =~ /$_/) { if (not defined $1) { # In this case it's just the group name, so we'll # run every test in the group $foundIt = 1; last; } else { # maybe, it at least matches the group my $num = "_" . $test->{'num'}; if ($num eq $1) { $foundIt = 1; last; } } } } next unless $foundIt; } # This is a test, so run it. my %testHash = %groupHash; my $tmpTestHash = \%testHash; foreach (keys(%$test)) { $testHash{$_} = $test->{$_}; } my $testName = $testHash{'group'} . "_" . $testHash{'num'}; dbg("################### Executing test [$testName]...\n"); # if ( $groupExecuted{ $group->{'name'} }== 0 ){ # $groupExecuted{ $group->{'name'} }=1; # # my $xmlDir= $globalHash{'localxmlpathbase'}."/run".$globalHash->{'UID'}; # mkpath( [ $xmlDir ] , 1, 0777) if ( ! -e $xmlDir ); # # my $filename = $group->{'name'}.".xml"; # $report = new TestReport ( $properties, "$xmlDir/$filename" ); # $report->purge(); # } # Check that ignore isn't set for this file, group, or test if (defined $testHash{'ignore'}) { print $subLog "Ignoring test $testName, ignore message: " . $testHash{'ignore'} . "\n"; next; } # Have we not reached the starting point yet? if (!$sawstart) { if ($testName eq $startat) { $sawstart = 1; } else { next; } } # Check that this test doesn't depend on an earlier test or tests # that failed. Don't abort if that test wasn't run, just assume the # user knew what they were doing and set it up right. my $skipThisOne = 0; foreach (keys(%testHash)) { if (/^depends_on/ && defined($testStatuses->{$testHash{$_}}) && $testStatuses->{$testHash{$_}} ne $passedStr) { print $subLog "Skipping test $testName, it depended on " . "$testHash{$_} which returned a status of " . "$testStatuses->{$testHash{$_}}\n"; $testStatuses->{$testName} = $dependStr; $skipThisOne = 1; last; } } if ($skipThisOne) { if ($productForkFactor > 1) { printResults($testStatuses, $subLog, "Results so far", basename($confFile), $groupName); } else { printResults($testStatuses, $subLog, "Results so far"); } next; } print $subLog "\n******************************************************\n"; print $subLog "\nTEST: $confFile::$testName\n"; print $subLog "******************************************************\n"; print $subLog "Beginning test $testName at " . time . "\n"; # At this point we're going to run the test for sure. # So, do the preparation for that, if not yet done: if (!defined($globalHash->{$keyGlobalSetupConditionalDone})) { $self -> globalSetupConditional($globalHash, $subLog); # this preparation should be done only *once* per each $globalHash instance, # so, set special flag to prevent #globalSetupConditional from being executed again: $globalHash->{$keyGlobalSetupConditionalDone} = 'true'; } my %dbinfo = ( 'testrun_id' => $testHash{'trid'}, 'test_type' => $testHash{'driver'}, #'test_file' => $testHash{'file'}, 'test_file' => $confFile, 'test_group' => $testHash{'group'}, 'test_num' => $testHash{'num'}, ); my $beginTime = time; my $endTime = 0; my ($testResult, $benchmarkResult); eval { $testResult = $self->runTest(\%testHash, $subLog, $resources); $endTime = time; $benchmarkResult = $self->generateBenchmark(\%testHash, $subLog); my $result = $self->compare($testResult, $benchmarkResult, $subLog, \%testHash, $resources); $msg = "INFO: $subName() at ".__LINE__.":Test $testName"; if ($result eq $self->{'wrong_execution_mode'}) { $msg .= " SKIPPED"; $testStatuses->{$testName} = $skippedStr; } elsif ($result) { $msg .= " SUCCEEDED"; $testStatuses->{$testName} = $passedStr; } else { $msg .= " FAILED"; $testStatuses->{$testName} = $failedStr; } $msg= "$msg at " . time . "\n"; #print $msg; print $subLog $msg; $duration = $endTime - $beginTime; $dbinfo{'duration'} = $duration; $self->recordResults($result, $testResult , $benchmarkResult, \%dbinfo, $subLog); }; if ($@) { $msg= "ERROR $subName at : ".__LINE__." Failed to run test $testName <$@>\n"; #print $msg; print $subLog $msg; $testStatuses->{$testName} = $abortedStr; $dbinfo{'duration'} = $duration; } eval { $dbinfo{'status'} = $testStatuses->{$testName}; if($dbh) { $dbh->insertTestCase(\%dbinfo); } }; if ($@) { chomp $@; warn "Failed to insert test case info, error <$@>\n"; } $self->cleanup($testStatuses->{$testName}, \%testHash, $testResult, $benchmarkResult, $subLog); #$report->testcase( $group->{'name'}, $testName, $duration, $msg, $testStatuses->{$testName}, $testResult ) if ( $report ); $report->testcase( $group->{'name'}, $testName, $duration, $msg, $testStatuses->{$testName} ) if ( $report ); $groupDuration = $groupDuration + $duration; if ($productForkFactor > 1) { printResults( $testStatuses, $subLog, "Results so far", basename($confFile), $groupName ); } else { printResults( $testStatuses, $subLog, "Results so far" ); } } # for each test if ( $report ) { $report->systemOut( $subLogName, $group->{'name'}); printGroupResultsXml( $report, $group->{'name'}, $testStatuses, $groupDuration ); } $report = 0; return $sawstart; } # TODO These should be removed sub tmpIPCRun(){ my $self = shift; my $subName = (caller(0))[3]; my $runningSubName= shift; my $refCmd = shift; my @cmd = @$refCmd; my $log = shift; my $msg = shift; print $log "$0::$subName INFO Running ( @cmd )\n"; my $result= `@cmd`; if ( $@ ) { my $msg= "$0::$subName FATAL Failed to run from $runningSubName $msg < $@ >\n$result\n"; print $log $msg; die "$msg"; } return $?; } sub tmpIPCRunSplitStdoe { my $self = shift; my $subName = (caller(0))[3]; my $runningSubName= shift; my $refCmd = shift; my @cmd = @$refCmd; my $dir = shift; my $log = shift; my $msg = shift; my $die = shift; my $failed = 0; my $outfilename = $dir."out.tmp"; my $errfilename = $dir."err.tmp"; print $log "$0::$subName INFO Running from $runningSubName ( @cmd 1>$outfilename 2>$errfilename )\n"; #make sure files are writeable open( TMP, ">$outfilename" ) || die "$0::$subName FATAL: Cannot open $outfilename for writing\n"; close( TMP ); open( TMP, ">$errfilename" ) || die "$0::$subName FATAL: Cannot open $errfilename for writing\n"; close( TMP ); #RUN CMD my $msg; print $log `@cmd 1>$outfilename 2>$errfilename`; my $failed=0; if ( $@ ) { $msg= "$0::$subName FATAL < $@ >\n"; $failed++; } #READ FILES my $stdout=""; my $stderr="";; open( TMP, "$outfilename" ) || die "$0::$subName FATAL: Cannot open $outfilename for reading\n"; while ( <TMP> ){ $stdout .= $_; } close( TMP ); open( TMP, "$errfilename" ) || die "$0::$subName FATAL: Cannot open $errfilename for reading\n"; while ( <TMP> ){ $stderr .= $_; } close( TMP ); #DIE IF Test Failed, otherwise return stdout and stderr if ( $failed ){ $msg = "$0::$subName FATAL: Faied from $runningSubName \nSTDOUT:".$result{'stdout'}."\nSTDERR:".$result{'stderr'}."\n" if ( $failed ); print $log "$msg"; die $msg if ( $die != "1" ); #die by default return ( -1, $stdout, $stderr ); } return ( $?, $stdout, $stderr); } sub tmpIPCRunJoinStdoe { my $self = shift; my $subName = (caller(0))[3]; my $runningSubName= shift; my $refCmd = shift; my @cmd = @$refCmd; my $outfilename= shift; my $log = shift; my $msg = shift; my $die = shift; #make sure files are writeable open( TMP, ">$outfilename" ) || die "$0::$subName FATAL: Cannot open $outfilename for writing\n"; close( TMP ); #RUN CMD my $msg; my $failed=0; print $log "$0::$subName INFO Running ( @cmd 2>&1$outfilename 2>/dev/null )\n"; print $log `@cmd 2>&1 > $outfilename 2>/dev/null`; if ( $@ ) { $failed++; $msg= "$0::$subName FATAL < $@ >\n"; } #READ FILES my $stdoe=""; open( TMP, "$outfilename" ) || die "$0::$subName FATAL: Cannot open $outfilename for reading\n"; while ( <TMP> ){ $stdoe .= $_; } close( TMP ); if ( $failed ){ print $log "$msg"; die $msg if ( $die != "1" ); #die by default return ( -1 ); } return ( $? ); } 1;
hxquangnhat/PIG-ROLLUP-MRCUBE
test/e2e/harness/TestDriver.pm
Perl
apache-2.0
30,130
use strict; use utf8; package Dorq::op::mod; use base 'Dorq::op::binary'; -1;
kainwinterheart/dorq-dsl
Dorq/op/mod.pm
Perl
mit
82
#!/usr/bin/perl use v5.10; use strict; use warnings; use Bio::DB::Query::GenBank; use Bio::DB::GenBank; use Bio::SeqIO; use Bio::Seq; use Bio::Tools::Run::StandAloneBlast; use Bio::SearchIO; use Bio::Annotation::Collection; # Search accession number and return isolation source and/or host my $gb = new Bio::DB::GenBank; my $acc_num = ""; # Read in file with accession number on seperate lines print "ACC NUM\tDates\tHost\tIsolation Source\tNote\tDescription\n"; while(<>) { chomp; my $acc_num = $_; my $seqio = $gb->get_Stream_by_acc(["$acc_num"]); while (my $seq = $seqio->next_seq) { print $seq->display_id, "\t"; print $seq->get_dates, "\t"; for my $feat_obj($seq->get_SeqFeatures) { print $feat_obj->get_tag_values("host") if ($feat_obj->has_tag("host")); } print "\t"; for my $feat_obj($seq->get_SeqFeatures) { print $feat_obj->get_tag_values("isolation_source") if ($feat_obj->has_tag("isolation_source")); } print "\t"; for my $feat_obj($seq->get_SeqFeatures) { print $feat_obj->get_tag_values("note") if ($feat_obj->has_tag("note")); } print "\t"; print $seq->desc, "\n"; } # Attempt to get Title #my $seq_obj = $seqio->next_seq; #my $anno_collection = $seqio->annotation; #for my $key( $anno_collection->get_all_annotation_keys) { # my @annotations = $anno_collection->get_Annotations($key); # for my $value (@annotations) { # if ($value->tagname eq "reference") { # print $value->title(), "\n"; # } # } #} }
bobthacker/NCBI-MetadataMiner
gbhostisonote.pl
Perl
mit
1,641
package Book ; use parent 'Lilyperl' ; use Paper ; use Header ; use Score ; use MusicDefinitions ; use Includes ; use Scalar::Util 'blessed'; my $isa = sub {blessed $_[0] and $_[0]->isa($_[1])}; use parent 'Clone'; # # Allow two forms of constructor in terms of the scores parameter: # an array of scores # a single score # sub new { my $class = shift; my $self = shift ; my @scores ; unless( ref($self) eq 'HASH' ) { $self = { name => $self, version => $self, includes => shift, page => shift, header => shift, scores => shift, transposed => shift, musicDefinitions => shift, instruments => shift, parts => shift } ; } if ( blessed $self->{scores} ) { if ( $self->{scores}->isa('Staff') ) { @scores = ( $self->{scores} ) ; $self->{scores} = \@scores ; } } unless ( $self->{musicDefinitions} ) { $self->{musicDefinitions} = MusicDefinitions->new() ; } return bless $self, $class; } sub name { my ( $self, $value ) = @_; $self->{name} = $value if defined $value ; return $self->{name}; } sub version { my ( $self, $value ) = @_; $self->{version} = $value if defined $value ; return '\version "' . $self->{version} . '"'; } sub includes { my ( $self, $value ) = @_; $self->{includes} = $value if defined $value ; return $self->{includes}; } sub pushIncludes { my ( $self, @files ) = @_; return $self->{includes} unless @files ; return $self->includes()->pushFiles( @files ) ; } sub page { my ( $self, $value ) = @_; $self->{page} = $value if defined $value ; return $self->{page}; } sub header { my ( $self, $value ) = @_; $self->{header} = $value if defined $value ; return $self->{header}; } sub scores { my ( $self, $value ) = @_; $self->{scores} = $value if defined $value ; return $self->{scores}; } sub getScores { my ( $self, @scoreNames ) = @_; my $scoreName ; my $scoresRef = $self->scores() ; my @scores = @$scoresRef ; my @selectedScores ; foreach $scoreName ( @scoreNames ) { foreach $score ( @scores ) { if ( $score->name() eq $scoreName ) { push( @selectedScores, $score ) ; } } } return @selectedScores; } sub pushScores { my ( $self, @newScores ) = shift ; my $scoresRef = $self->scores() ; my @scores = @$scoresRef ; my $score ; foreach $score ( @newScores ) { push( @scores, $score ) ; } $self->{scores} = \@scores ; return $self->{scores}; } sub transposed { my ( $self, $value ) = @_; $self->{transposed} = $value if defined $value ; return $self->{transposed}; } # # @param {String} filename The file where the functions will be saved (does not create the file). # @param {Array} List of lilypond lines to include between each section of a score, which defaults to a double bar line. # @returns {Array} Populaltes the musicDefinitions->()functions() property returns these function definitions. # sub createConstructorFunctions { my ( $self, $filename, @betweenSections ) = @_ ; $self->musicDefinitions()->functionsFilename( $filename ) ; $self->musicDefinitions()->functionsInclude( Includes->new($filename) ) ; (@betweenSections) = ( @betweenSections ) ? (@betweenSections) : ( '\bar "||"' ) ; my $score ; my $scoresRef = $self->scores() ; my @scores = @$scoresRef ; foreach $score (@scores) { $self->musicDefinitions()->pushFunction( $score->createConstructorFunction(@betweenSections) ) } return $self->musicDefinitions()->functions() ; } sub musicDefinitions { my ( $self, $value ) = shift ; $self->{musicDefinitions} = $value if defined $value ; return $self->{musicDefinitions} ; } # # Creates a file for each staff group # Files are located in specified directory, named by staff group name + .ly # Sets the musicDefinitions->staffGroupIncludes() to this set of files, and return this list ref. # Each file contain the book's lilypond version and global includes, plus the music and chord definitions for that staff group. # sub writeMusicDefinitionsFiles { my ( $self, $musicDir ) = @_ ; my $staffGroup ; my $staffGroupsRef = $self->getStaffGroups() ; my @staffGroups = @$staffGroupsRef ; my $staffGroupName ; my $filename ; my $fh ; my $score ; my $scoresRef = $self->scores() ; my @scores = @$scoresRef ; my @lilypond ; foreach $staffGroup (@staffGroups) { $staffGroupName = $staffGroup->name() ; $filename = 'music/' . $staffGroupName . '.ly' ; open( $fh, '>', $filename ) or die "Could not open music definitions file '$filename': " . $! ; print "$filename\n" ; (@lilypond) = ( "%%%%% Music definitions for staff group $staffGroupName for " . $self->name() . " %%%%%", $self->version(), $self->includes()->render(), $self->musicDefinitions()->functionsInclude()->render(), '' ) ; foreach $score (@scores) { push( @lilypond, $score->createMusicDefinitions($staffGroupName) ) ; push( @lilypond, $score->createChordDefinitions($staffGroupName) ) ; } print $fh join("\n", @lilypond) ; close $fh ; $self->musicDefinitions()->pushStaffGroupIncludes( "../$filename" ) ; } return $self->musicDefinitions()->staffGroupIncludes() ; } # # If a score name is specified, return the staff groups for that score. # Otherwise, return the staff groups for the first score. # sub getStaffGroups { my $self = shift ; my $scoreName = shift ; my $scoresRef = $self->scores() ; my @scores = @$scoresRef ; unless ( $scoreName ) { $scoreName = $scores[0]->name() ; } my @theseScores = $self->getScores($scoreName) ; my $thisScore = $theseScores[0] ; return $thisScore->staffGroups() ; } # # Not currently used, but possibly helpful. # sub sequenceMeasureNumbers { my $self = shift ; my $score ; my $scoresRef = $self->scores() ; my @scores = $scoresRef ; my $lastBarNumber = 0 ; foreach $score (@scores) { $score->startingBarNumber( $lastBarNumber + 1 ) ; $lastBarNumber += $score->howManyMeasures() ; } return $lastBarNumber ; } # # Returns a list of instruments. # If no score name is specified, returns the list of instruments from the first score in the book. # If a score name is specified, returns the list of instruments from the first score in the book with the specified score name. # If no score has the specified name, returns undef. # sub instruments { my $self = shift ; my $scoreName = shift ; my $score ; my $scoresRef = $self->scores() ; my @scores = @$scoresRef ; foreach $score (@scores) { unless ( $scoreName ) { return $score->instruments() ; } if ( $scoreName eq $score->name() ) { return $score->instruments() ; } } return undef ; } # # Returns an set of updated books with only one instrument per book. # If there are multiple staves with the same instrument name, all those are included in the same book. # sub parts { my $self = shift ; my (@instruments) = $self->instruments() ; my @parts ; foreach $instrument (@instruments) { push( @parts, $self->part( $instrument->name() ) ); } return $self->parts( \@parts ) ; } # # Returns an version of the book without all instruments expect the specified instrument. # If there are multiple staves with the same instrument name, all those are included. # sub part { my $self = shift ; my $instrumentName = shift ; my $score ; my $scoresRef = $self->scores() ; my @scores = @$scoresRef ; my $partScore ; my $staffGroupsRef ; my @staffGroups ; my $staffGroup ; my $instrument ; my @partScores ; my $part = $self->clone() ; foreach $score (@scores) { my $partScore = $score->clone() ; $staffGroupsRef = $partScore->staffGroups() ; @staffGroups = @$staffGroupsRef ; my @partStaffGroups ; foreach $staffGroup (@staffGroups) { my @instruments ; my $partStaffGroup = $staffGroup->clone() ; $instrument = $partStaffGroup->instrument( $instrumentName ) ; if ( $instrument ) { push( @instruments, $instrument ) ; } if ( @instruments ) { $partStaffGroup->instruments( \@instruments ) ; push( @partStaffGroups, $partStaffGroup ) ; } } $partScore->staffGroups( \@partStaffGroups ) ; push( @partScores, $partScore ) ; } $part->scores( \@partScores ) ; return $part ; } sub render { my $self = shift ; my $margin = shift ; my $indent = $margin . ' ' ; my @lilypond = ( "book {" ) ; if ( $self->page() ) { push( @lilypond, $indent . '\paper {', $self->page()->space()->render($indent), $indent . '}' ) ; } if ( $self->header() ) { push( @lilypond, $indent . '\header {', $self->header()->render($indent), "$indent}" ) ; } my $score ; my $scoresRef = $self->scores() ; my @scores = @$scoresRef ; foreach $score ( @scores ) { push( @lilypond, $score->render( $indent, $self->transposed() ) ) ; } push( @lilypond, '}' ) ; return @lilypond ; } 1 ;
flaminghakama/lilyperl
Book.pm
Perl
mit
9,941
/************************************************************************* name: domain_medical.pl description: Medical domain file *************************************************************************/ :- module( domain_medical, [ plan/2, issue/2, sort_restr/1, isa/2, postcond/2, depends/2, incompatible/2 ] ). :- discontiguous output_form/2, input_form/2, plan/2, postcond/2. :- use_module( library(lists), [ member/2, select/3, append/3 ] ). :- ensure_loaded( library( semsort_medical ) ). /*---------------------------------------------------------------------- Dialogue plans plan( ?ActionOrIssue, ?Plan ) ----------------------------------------------------------------------*/ plan( top, [ forget_all, findout( set( [ issue(X^disease(X)), issue(X1^info(X1) ) ] ) ) ] ). postcond( top, [] ). plan( X1^disease(X1), [ % try to get a best question from db dev_query( medical, X2^bestq(X2) ), % if there is a best question, try to find out the answer if_then( bestq(Q), [ findout(Q), % clean up forget( bestq(Q) ) ] ), % check if db can determine a disease dev_query( medical, X3^disease(X3)), % if successful, GoDiS will answer disease issue % if not, clean up if_then( fail(X5^disease(X5),_), forget(fail(X5^disease(X5),_) ) ), % enable accommodation, since findout is embedded in "if_then" bind( X4^symptom(X4) ), bind( X7^medicalHistory(X7) ) ] ). plan( confirmed_by_interview, [ %findout(X^disease(X)), %V2 % try to get a best question from db dev_query( medical, X2^bestq(X2) ), % if there is a best question, try to find out the answer if_then( bestq(Q), [ findout(Q), % clean up forget( bestq(Q) ) ] ), % check if db can determine a disease dev_query( medical, confirmed_by_interview ), % if successful, GoDiS will answer disease issue % if not, clean up if_then( fail(confirmed_by_interview), forget( fail(confirmed_by_interview ) ) ), % if there are no more questions, the result was not confirmed if_then( fail(X1^bestq(X1)), assume( not(confirmed_by_interview) ) ), % enable accommodation, since findout is embedded in "if_then" bind( X4^symptom(X4) ), bind( X7^medicalHistory(X7) ) ] ). plan( confirmed_by_tests,%positive_diagnosis, % [ % try to get a best labtest from db dev_query( medical, X9^best_labtest(X9) ), % if there is a best labtest, get nurse to perform test if_then( best_labtest(T), % T is y/n question [ % tell the user that test is pending report( take_test(T), pending ), % assume that test-result issue is now shared % assume_issue( X1^test_result(X1) ), assume_issue( test_result(T) ), % activate nurse-device to take the test dev_do( medical, take_test(T) ), % get results of test % dev_query( medical, X6^test_result(X6) ), dev_query( medical, test_result(T) ), % clean up forget( status(T, pending ) ), forget( best_labtest(T) ) ] ), % chec if db can determine a positive (or negative) diagnosis dev_query( medical, confirmed_by_tests ), % returns p_d, not(p_d) or fail(p_d) % if successful, GoDiS will answer positive_diagnosis issue % if not, clean up (and start again) if_then( fail( confirmed_by_tests ), forget( fail(confirmed_by_tests) ) ), if_then( fail(X2^best_labtest(X2)), assume( not(confirmed_by_test) ) ) ] ). % binds X^info_disease(X), but does not ask if X^disease(X) resolved plan( X^info(X), [ findout( X1^info_disease(X1) ), if_then_else( disease(D), assume(info(D)), if_then( info_disease(D), assume(info(D)) ) ) ]). % binds X^info_disease(X), but does not ask if X^disease(X) resolved plan( X^treatment(X), [ findout( X1^info_disease(X1) ), if_then_else( disease(D), assume(treatment(D)), if_then( info_disease(D), assume(treatment(D)) ) ) ]). plan( up, [] ). /*-------------------------------------------------------------- Conceptual knowledge ----------------------------------------------------------------------*/ % sortal restrictions; determine relevance and resolvement sort_restr( disease( X ) ) :- sem_sort( X, disease ). sort_restr( bestq( X ) ) :- of_type( X, question ). sort_restr( symptom( X ) ) :- sem_sort( X, symptom ). sort_restr( info( X ) ) :- sem_sort( X, disease ). sort_restr( medicalHistory( X ) ) :- sem_sort( X, medicalHistory ). sort_restr( test_result( X ) ) :- sem_sort( X, test ). sort_restr( info( X ) ) :- sem_sort( X, disease ). sort_restr( info_disease( X ) ) :- sem_sort( X, disease ). sort_restr( treatment( X ) ) :- sem_sort( X, disease ). % GENERAL STUFF % 0-place predicates sort_restr( Pred0 ) :- Pred0 =.. [_]. % negation sort_restr( not P ) :- sort_restr( P ). % action sort_restr( action( X ) ) :- sem_sort( X, action ). sort_restr( action( respond(Q) ) ) :- sort_restr( issue(Q) ). % issue sort_restr( issue(Q) ):- plan( Q, _ ), \+ sort_restr( action( Q ) ). sort_restr( issue(Q) ):- plan( _, Plan ), member( findout(Q), Plan ), \+ sort_restr( action( Q ) ). % metaissue sort_restr( und(_DP*P) ):- sort_restr(P). % sloppy, but allows "no" as answer to clarification alt-q % could be replaced by general rule saying that not(set([p1, ..., ])) is sortally correct, % menaing the same as (not P1 and not p2 and...) sort_restr( not und(_DP*set(_))). % valid parameter same as sortal restrictions % so everything that's understood is accepted valid_parameter( Prop ):- sort_restr( Prop ). default_question(dummy). depends( dummy, dummy ). % never two diseases at once incompatible(disease(D1), disease(D2)) :- D1 \= D2.
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/SIRIDUS/UGOT-D31/godis-apps/domain-medical/domain_medical.pl
Perl
mit
5,700
# This file is auto-generated by the Perl DateTime Suite time zone # code generator (0.07) This code generator comes with the # DateTime::TimeZone module distribution in the tools/ directory # # Generated from /tmp/BU3Xn7v6Kb/northamerica. Olson data version 2015g # # Do not edit this file directly. # package DateTime::TimeZone::America::Inuvik; $DateTime::TimeZone::America::Inuvik::VERSION = '1.94'; use strict; use Class::Singleton 1.03; use DateTime::TimeZone; use DateTime::TimeZone::OlsonDB; @DateTime::TimeZone::America::Inuvik::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' ); my $spans = [ [ DateTime::TimeZone::NEG_INFINITY, # utc_start 61599225600, # utc_end 1953-01-01 00:00:00 (Thu) DateTime::TimeZone::NEG_INFINITY, # local_start 61599225600, # local_end 1953-01-01 00:00:00 (Thu) 0, 0, 'zzz', ], [ 61599225600, # utc_start 1953-01-01 00:00:00 (Thu) 61987795200, # utc_end 1965-04-25 08:00:00 (Sun) 61599196800, # local_start 1952-12-31 16:00:00 (Wed) 61987766400, # local_end 1965-04-25 00:00:00 (Sun) -28800, 0, 'PST', ], [ 61987795200, # utc_start 1965-04-25 08:00:00 (Sun) 62004124800, # utc_end 1965-10-31 08:00:00 (Sun) 61987773600, # local_start 1965-04-25 02:00:00 (Sun) 62004103200, # local_end 1965-10-31 02:00:00 (Sun) -21600, 1, 'PDDT', ], [ 62004124800, # utc_start 1965-10-31 08:00:00 (Sun) 62429911200, # utc_end 1979-04-29 10:00:00 (Sun) 62004096000, # local_start 1965-10-31 00:00:00 (Sun) 62429882400, # local_end 1979-04-29 02:00:00 (Sun) -28800, 0, 'PST', ], [ 62429911200, # utc_start 1979-04-29 10:00:00 (Sun) 62451241200, # utc_end 1980-01-01 07:00:00 (Tue) 62429886000, # local_start 1979-04-29 03:00:00 (Sun) 62451216000, # local_end 1980-01-01 00:00:00 (Tue) -25200, 0, 'MST', ], [ 62451241200, # utc_start 1980-01-01 07:00:00 (Tue) 62461357200, # utc_end 1980-04-27 09:00:00 (Sun) 62451216000, # local_start 1980-01-01 00:00:00 (Tue) 62461332000, # local_end 1980-04-27 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62461357200, # utc_start 1980-04-27 09:00:00 (Sun) 62477078400, # utc_end 1980-10-26 08:00:00 (Sun) 62461335600, # local_start 1980-04-27 03:00:00 (Sun) 62477056800, # local_end 1980-10-26 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62477078400, # utc_start 1980-10-26 08:00:00 (Sun) 62492806800, # utc_end 1981-04-26 09:00:00 (Sun) 62477053200, # local_start 1980-10-26 01:00:00 (Sun) 62492781600, # local_end 1981-04-26 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62492806800, # utc_start 1981-04-26 09:00:00 (Sun) 62508528000, # utc_end 1981-10-25 08:00:00 (Sun) 62492785200, # local_start 1981-04-26 03:00:00 (Sun) 62508506400, # local_end 1981-10-25 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62508528000, # utc_start 1981-10-25 08:00:00 (Sun) 62524256400, # utc_end 1982-04-25 09:00:00 (Sun) 62508502800, # local_start 1981-10-25 01:00:00 (Sun) 62524231200, # local_end 1982-04-25 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62524256400, # utc_start 1982-04-25 09:00:00 (Sun) 62540582400, # utc_end 1982-10-31 08:00:00 (Sun) 62524234800, # local_start 1982-04-25 03:00:00 (Sun) 62540560800, # local_end 1982-10-31 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62540582400, # utc_start 1982-10-31 08:00:00 (Sun) 62555706000, # utc_end 1983-04-24 09:00:00 (Sun) 62540557200, # local_start 1982-10-31 01:00:00 (Sun) 62555680800, # local_end 1983-04-24 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62555706000, # utc_start 1983-04-24 09:00:00 (Sun) 62572032000, # utc_end 1983-10-30 08:00:00 (Sun) 62555684400, # local_start 1983-04-24 03:00:00 (Sun) 62572010400, # local_end 1983-10-30 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62572032000, # utc_start 1983-10-30 08:00:00 (Sun) 62587760400, # utc_end 1984-04-29 09:00:00 (Sun) 62572006800, # local_start 1983-10-30 01:00:00 (Sun) 62587735200, # local_end 1984-04-29 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62587760400, # utc_start 1984-04-29 09:00:00 (Sun) 62603481600, # utc_end 1984-10-28 08:00:00 (Sun) 62587738800, # local_start 1984-04-29 03:00:00 (Sun) 62603460000, # local_end 1984-10-28 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62603481600, # utc_start 1984-10-28 08:00:00 (Sun) 62619210000, # utc_end 1985-04-28 09:00:00 (Sun) 62603456400, # local_start 1984-10-28 01:00:00 (Sun) 62619184800, # local_end 1985-04-28 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62619210000, # utc_start 1985-04-28 09:00:00 (Sun) 62634931200, # utc_end 1985-10-27 08:00:00 (Sun) 62619188400, # local_start 1985-04-28 03:00:00 (Sun) 62634909600, # local_end 1985-10-27 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62634931200, # utc_start 1985-10-27 08:00:00 (Sun) 62650659600, # utc_end 1986-04-27 09:00:00 (Sun) 62634906000, # local_start 1985-10-27 01:00:00 (Sun) 62650634400, # local_end 1986-04-27 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62650659600, # utc_start 1986-04-27 09:00:00 (Sun) 62666380800, # utc_end 1986-10-26 08:00:00 (Sun) 62650638000, # local_start 1986-04-27 03:00:00 (Sun) 62666359200, # local_end 1986-10-26 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62666380800, # utc_start 1986-10-26 08:00:00 (Sun) 62680294800, # utc_end 1987-04-05 09:00:00 (Sun) 62666355600, # local_start 1986-10-26 01:00:00 (Sun) 62680269600, # local_end 1987-04-05 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62680294800, # utc_start 1987-04-05 09:00:00 (Sun) 62697830400, # utc_end 1987-10-25 08:00:00 (Sun) 62680273200, # local_start 1987-04-05 03:00:00 (Sun) 62697808800, # local_end 1987-10-25 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62697830400, # utc_start 1987-10-25 08:00:00 (Sun) 62711744400, # utc_end 1988-04-03 09:00:00 (Sun) 62697805200, # local_start 1987-10-25 01:00:00 (Sun) 62711719200, # local_end 1988-04-03 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62711744400, # utc_start 1988-04-03 09:00:00 (Sun) 62729884800, # utc_end 1988-10-30 08:00:00 (Sun) 62711722800, # local_start 1988-04-03 03:00:00 (Sun) 62729863200, # local_end 1988-10-30 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62729884800, # utc_start 1988-10-30 08:00:00 (Sun) 62743194000, # utc_end 1989-04-02 09:00:00 (Sun) 62729859600, # local_start 1988-10-30 01:00:00 (Sun) 62743168800, # local_end 1989-04-02 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62743194000, # utc_start 1989-04-02 09:00:00 (Sun) 62761334400, # utc_end 1989-10-29 08:00:00 (Sun) 62743172400, # local_start 1989-04-02 03:00:00 (Sun) 62761312800, # local_end 1989-10-29 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62761334400, # utc_start 1989-10-29 08:00:00 (Sun) 62774643600, # utc_end 1990-04-01 09:00:00 (Sun) 62761309200, # local_start 1989-10-29 01:00:00 (Sun) 62774618400, # local_end 1990-04-01 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62774643600, # utc_start 1990-04-01 09:00:00 (Sun) 62792784000, # utc_end 1990-10-28 08:00:00 (Sun) 62774622000, # local_start 1990-04-01 03:00:00 (Sun) 62792762400, # local_end 1990-10-28 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62792784000, # utc_start 1990-10-28 08:00:00 (Sun) 62806698000, # utc_end 1991-04-07 09:00:00 (Sun) 62792758800, # local_start 1990-10-28 01:00:00 (Sun) 62806672800, # local_end 1991-04-07 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62806698000, # utc_start 1991-04-07 09:00:00 (Sun) 62824233600, # utc_end 1991-10-27 08:00:00 (Sun) 62806676400, # local_start 1991-04-07 03:00:00 (Sun) 62824212000, # local_end 1991-10-27 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62824233600, # utc_start 1991-10-27 08:00:00 (Sun) 62838147600, # utc_end 1992-04-05 09:00:00 (Sun) 62824208400, # local_start 1991-10-27 01:00:00 (Sun) 62838122400, # local_end 1992-04-05 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62838147600, # utc_start 1992-04-05 09:00:00 (Sun) 62855683200, # utc_end 1992-10-25 08:00:00 (Sun) 62838126000, # local_start 1992-04-05 03:00:00 (Sun) 62855661600, # local_end 1992-10-25 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62855683200, # utc_start 1992-10-25 08:00:00 (Sun) 62869597200, # utc_end 1993-04-04 09:00:00 (Sun) 62855658000, # local_start 1992-10-25 01:00:00 (Sun) 62869572000, # local_end 1993-04-04 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62869597200, # utc_start 1993-04-04 09:00:00 (Sun) 62887737600, # utc_end 1993-10-31 08:00:00 (Sun) 62869575600, # local_start 1993-04-04 03:00:00 (Sun) 62887716000, # local_end 1993-10-31 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62887737600, # utc_start 1993-10-31 08:00:00 (Sun) 62901046800, # utc_end 1994-04-03 09:00:00 (Sun) 62887712400, # local_start 1993-10-31 01:00:00 (Sun) 62901021600, # local_end 1994-04-03 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62901046800, # utc_start 1994-04-03 09:00:00 (Sun) 62919187200, # utc_end 1994-10-30 08:00:00 (Sun) 62901025200, # local_start 1994-04-03 03:00:00 (Sun) 62919165600, # local_end 1994-10-30 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62919187200, # utc_start 1994-10-30 08:00:00 (Sun) 62932496400, # utc_end 1995-04-02 09:00:00 (Sun) 62919162000, # local_start 1994-10-30 01:00:00 (Sun) 62932471200, # local_end 1995-04-02 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62932496400, # utc_start 1995-04-02 09:00:00 (Sun) 62950636800, # utc_end 1995-10-29 08:00:00 (Sun) 62932474800, # local_start 1995-04-02 03:00:00 (Sun) 62950615200, # local_end 1995-10-29 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62950636800, # utc_start 1995-10-29 08:00:00 (Sun) 62964550800, # utc_end 1996-04-07 09:00:00 (Sun) 62950611600, # local_start 1995-10-29 01:00:00 (Sun) 62964525600, # local_end 1996-04-07 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62964550800, # utc_start 1996-04-07 09:00:00 (Sun) 62982086400, # utc_end 1996-10-27 08:00:00 (Sun) 62964529200, # local_start 1996-04-07 03:00:00 (Sun) 62982064800, # local_end 1996-10-27 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 62982086400, # utc_start 1996-10-27 08:00:00 (Sun) 62996000400, # utc_end 1997-04-06 09:00:00 (Sun) 62982061200, # local_start 1996-10-27 01:00:00 (Sun) 62995975200, # local_end 1997-04-06 02:00:00 (Sun) -25200, 0, 'MST', ], [ 62996000400, # utc_start 1997-04-06 09:00:00 (Sun) 63013536000, # utc_end 1997-10-26 08:00:00 (Sun) 62995978800, # local_start 1997-04-06 03:00:00 (Sun) 63013514400, # local_end 1997-10-26 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63013536000, # utc_start 1997-10-26 08:00:00 (Sun) 63027450000, # utc_end 1998-04-05 09:00:00 (Sun) 63013510800, # local_start 1997-10-26 01:00:00 (Sun) 63027424800, # local_end 1998-04-05 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63027450000, # utc_start 1998-04-05 09:00:00 (Sun) 63044985600, # utc_end 1998-10-25 08:00:00 (Sun) 63027428400, # local_start 1998-04-05 03:00:00 (Sun) 63044964000, # local_end 1998-10-25 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63044985600, # utc_start 1998-10-25 08:00:00 (Sun) 63058899600, # utc_end 1999-04-04 09:00:00 (Sun) 63044960400, # local_start 1998-10-25 01:00:00 (Sun) 63058874400, # local_end 1999-04-04 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63058899600, # utc_start 1999-04-04 09:00:00 (Sun) 63077040000, # utc_end 1999-10-31 08:00:00 (Sun) 63058878000, # local_start 1999-04-04 03:00:00 (Sun) 63077018400, # local_end 1999-10-31 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63077040000, # utc_start 1999-10-31 08:00:00 (Sun) 63090349200, # utc_end 2000-04-02 09:00:00 (Sun) 63077014800, # local_start 1999-10-31 01:00:00 (Sun) 63090324000, # local_end 2000-04-02 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63090349200, # utc_start 2000-04-02 09:00:00 (Sun) 63108489600, # utc_end 2000-10-29 08:00:00 (Sun) 63090327600, # local_start 2000-04-02 03:00:00 (Sun) 63108468000, # local_end 2000-10-29 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63108489600, # utc_start 2000-10-29 08:00:00 (Sun) 63121798800, # utc_end 2001-04-01 09:00:00 (Sun) 63108464400, # local_start 2000-10-29 01:00:00 (Sun) 63121773600, # local_end 2001-04-01 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63121798800, # utc_start 2001-04-01 09:00:00 (Sun) 63139939200, # utc_end 2001-10-28 08:00:00 (Sun) 63121777200, # local_start 2001-04-01 03:00:00 (Sun) 63139917600, # local_end 2001-10-28 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63139939200, # utc_start 2001-10-28 08:00:00 (Sun) 63153853200, # utc_end 2002-04-07 09:00:00 (Sun) 63139914000, # local_start 2001-10-28 01:00:00 (Sun) 63153828000, # local_end 2002-04-07 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63153853200, # utc_start 2002-04-07 09:00:00 (Sun) 63171388800, # utc_end 2002-10-27 08:00:00 (Sun) 63153831600, # local_start 2002-04-07 03:00:00 (Sun) 63171367200, # local_end 2002-10-27 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63171388800, # utc_start 2002-10-27 08:00:00 (Sun) 63185302800, # utc_end 2003-04-06 09:00:00 (Sun) 63171363600, # local_start 2002-10-27 01:00:00 (Sun) 63185277600, # local_end 2003-04-06 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63185302800, # utc_start 2003-04-06 09:00:00 (Sun) 63202838400, # utc_end 2003-10-26 08:00:00 (Sun) 63185281200, # local_start 2003-04-06 03:00:00 (Sun) 63202816800, # local_end 2003-10-26 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63202838400, # utc_start 2003-10-26 08:00:00 (Sun) 63216752400, # utc_end 2004-04-04 09:00:00 (Sun) 63202813200, # local_start 2003-10-26 01:00:00 (Sun) 63216727200, # local_end 2004-04-04 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63216752400, # utc_start 2004-04-04 09:00:00 (Sun) 63234892800, # utc_end 2004-10-31 08:00:00 (Sun) 63216730800, # local_start 2004-04-04 03:00:00 (Sun) 63234871200, # local_end 2004-10-31 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63234892800, # utc_start 2004-10-31 08:00:00 (Sun) 63248202000, # utc_end 2005-04-03 09:00:00 (Sun) 63234867600, # local_start 2004-10-31 01:00:00 (Sun) 63248176800, # local_end 2005-04-03 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63248202000, # utc_start 2005-04-03 09:00:00 (Sun) 63266342400, # utc_end 2005-10-30 08:00:00 (Sun) 63248180400, # local_start 2005-04-03 03:00:00 (Sun) 63266320800, # local_end 2005-10-30 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63266342400, # utc_start 2005-10-30 08:00:00 (Sun) 63279651600, # utc_end 2006-04-02 09:00:00 (Sun) 63266317200, # local_start 2005-10-30 01:00:00 (Sun) 63279626400, # local_end 2006-04-02 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63279651600, # utc_start 2006-04-02 09:00:00 (Sun) 63297792000, # utc_end 2006-10-29 08:00:00 (Sun) 63279630000, # local_start 2006-04-02 03:00:00 (Sun) 63297770400, # local_end 2006-10-29 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63297792000, # utc_start 2006-10-29 08:00:00 (Sun) 63309286800, # utc_end 2007-03-11 09:00:00 (Sun) 63297766800, # local_start 2006-10-29 01:00:00 (Sun) 63309261600, # local_end 2007-03-11 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63309286800, # utc_start 2007-03-11 09:00:00 (Sun) 63329846400, # utc_end 2007-11-04 08:00:00 (Sun) 63309265200, # local_start 2007-03-11 03:00:00 (Sun) 63329824800, # local_end 2007-11-04 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63329846400, # utc_start 2007-11-04 08:00:00 (Sun) 63340736400, # utc_end 2008-03-09 09:00:00 (Sun) 63329821200, # local_start 2007-11-04 01:00:00 (Sun) 63340711200, # local_end 2008-03-09 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63340736400, # utc_start 2008-03-09 09:00:00 (Sun) 63361296000, # utc_end 2008-11-02 08:00:00 (Sun) 63340714800, # local_start 2008-03-09 03:00:00 (Sun) 63361274400, # local_end 2008-11-02 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63361296000, # utc_start 2008-11-02 08:00:00 (Sun) 63372186000, # utc_end 2009-03-08 09:00:00 (Sun) 63361270800, # local_start 2008-11-02 01:00:00 (Sun) 63372160800, # local_end 2009-03-08 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63372186000, # utc_start 2009-03-08 09:00:00 (Sun) 63392745600, # utc_end 2009-11-01 08:00:00 (Sun) 63372164400, # local_start 2009-03-08 03:00:00 (Sun) 63392724000, # local_end 2009-11-01 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63392745600, # utc_start 2009-11-01 08:00:00 (Sun) 63404240400, # utc_end 2010-03-14 09:00:00 (Sun) 63392720400, # local_start 2009-11-01 01:00:00 (Sun) 63404215200, # local_end 2010-03-14 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63404240400, # utc_start 2010-03-14 09:00:00 (Sun) 63424800000, # utc_end 2010-11-07 08:00:00 (Sun) 63404218800, # local_start 2010-03-14 03:00:00 (Sun) 63424778400, # local_end 2010-11-07 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63424800000, # utc_start 2010-11-07 08:00:00 (Sun) 63435690000, # utc_end 2011-03-13 09:00:00 (Sun) 63424774800, # local_start 2010-11-07 01:00:00 (Sun) 63435664800, # local_end 2011-03-13 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63435690000, # utc_start 2011-03-13 09:00:00 (Sun) 63456249600, # utc_end 2011-11-06 08:00:00 (Sun) 63435668400, # local_start 2011-03-13 03:00:00 (Sun) 63456228000, # local_end 2011-11-06 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63456249600, # utc_start 2011-11-06 08:00:00 (Sun) 63467139600, # utc_end 2012-03-11 09:00:00 (Sun) 63456224400, # local_start 2011-11-06 01:00:00 (Sun) 63467114400, # local_end 2012-03-11 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63467139600, # utc_start 2012-03-11 09:00:00 (Sun) 63487699200, # utc_end 2012-11-04 08:00:00 (Sun) 63467118000, # local_start 2012-03-11 03:00:00 (Sun) 63487677600, # local_end 2012-11-04 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63487699200, # utc_start 2012-11-04 08:00:00 (Sun) 63498589200, # utc_end 2013-03-10 09:00:00 (Sun) 63487674000, # local_start 2012-11-04 01:00:00 (Sun) 63498564000, # local_end 2013-03-10 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63498589200, # utc_start 2013-03-10 09:00:00 (Sun) 63519148800, # utc_end 2013-11-03 08:00:00 (Sun) 63498567600, # local_start 2013-03-10 03:00:00 (Sun) 63519127200, # local_end 2013-11-03 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63519148800, # utc_start 2013-11-03 08:00:00 (Sun) 63530038800, # utc_end 2014-03-09 09:00:00 (Sun) 63519123600, # local_start 2013-11-03 01:00:00 (Sun) 63530013600, # local_end 2014-03-09 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63530038800, # utc_start 2014-03-09 09:00:00 (Sun) 63550598400, # utc_end 2014-11-02 08:00:00 (Sun) 63530017200, # local_start 2014-03-09 03:00:00 (Sun) 63550576800, # local_end 2014-11-02 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63550598400, # utc_start 2014-11-02 08:00:00 (Sun) 63561488400, # utc_end 2015-03-08 09:00:00 (Sun) 63550573200, # local_start 2014-11-02 01:00:00 (Sun) 63561463200, # local_end 2015-03-08 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63561488400, # utc_start 2015-03-08 09:00:00 (Sun) 63582048000, # utc_end 2015-11-01 08:00:00 (Sun) 63561466800, # local_start 2015-03-08 03:00:00 (Sun) 63582026400, # local_end 2015-11-01 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63582048000, # utc_start 2015-11-01 08:00:00 (Sun) 63593542800, # utc_end 2016-03-13 09:00:00 (Sun) 63582022800, # local_start 2015-11-01 01:00:00 (Sun) 63593517600, # local_end 2016-03-13 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63593542800, # utc_start 2016-03-13 09:00:00 (Sun) 63614102400, # utc_end 2016-11-06 08:00:00 (Sun) 63593521200, # local_start 2016-03-13 03:00:00 (Sun) 63614080800, # local_end 2016-11-06 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63614102400, # utc_start 2016-11-06 08:00:00 (Sun) 63624992400, # utc_end 2017-03-12 09:00:00 (Sun) 63614077200, # local_start 2016-11-06 01:00:00 (Sun) 63624967200, # local_end 2017-03-12 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63624992400, # utc_start 2017-03-12 09:00:00 (Sun) 63645552000, # utc_end 2017-11-05 08:00:00 (Sun) 63624970800, # local_start 2017-03-12 03:00:00 (Sun) 63645530400, # local_end 2017-11-05 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63645552000, # utc_start 2017-11-05 08:00:00 (Sun) 63656442000, # utc_end 2018-03-11 09:00:00 (Sun) 63645526800, # local_start 2017-11-05 01:00:00 (Sun) 63656416800, # local_end 2018-03-11 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63656442000, # utc_start 2018-03-11 09:00:00 (Sun) 63677001600, # utc_end 2018-11-04 08:00:00 (Sun) 63656420400, # local_start 2018-03-11 03:00:00 (Sun) 63676980000, # local_end 2018-11-04 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63677001600, # utc_start 2018-11-04 08:00:00 (Sun) 63687891600, # utc_end 2019-03-10 09:00:00 (Sun) 63676976400, # local_start 2018-11-04 01:00:00 (Sun) 63687866400, # local_end 2019-03-10 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63687891600, # utc_start 2019-03-10 09:00:00 (Sun) 63708451200, # utc_end 2019-11-03 08:00:00 (Sun) 63687870000, # local_start 2019-03-10 03:00:00 (Sun) 63708429600, # local_end 2019-11-03 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63708451200, # utc_start 2019-11-03 08:00:00 (Sun) 63719341200, # utc_end 2020-03-08 09:00:00 (Sun) 63708426000, # local_start 2019-11-03 01:00:00 (Sun) 63719316000, # local_end 2020-03-08 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63719341200, # utc_start 2020-03-08 09:00:00 (Sun) 63739900800, # utc_end 2020-11-01 08:00:00 (Sun) 63719319600, # local_start 2020-03-08 03:00:00 (Sun) 63739879200, # local_end 2020-11-01 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63739900800, # utc_start 2020-11-01 08:00:00 (Sun) 63751395600, # utc_end 2021-03-14 09:00:00 (Sun) 63739875600, # local_start 2020-11-01 01:00:00 (Sun) 63751370400, # local_end 2021-03-14 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63751395600, # utc_start 2021-03-14 09:00:00 (Sun) 63771955200, # utc_end 2021-11-07 08:00:00 (Sun) 63751374000, # local_start 2021-03-14 03:00:00 (Sun) 63771933600, # local_end 2021-11-07 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63771955200, # utc_start 2021-11-07 08:00:00 (Sun) 63782845200, # utc_end 2022-03-13 09:00:00 (Sun) 63771930000, # local_start 2021-11-07 01:00:00 (Sun) 63782820000, # local_end 2022-03-13 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63782845200, # utc_start 2022-03-13 09:00:00 (Sun) 63803404800, # utc_end 2022-11-06 08:00:00 (Sun) 63782823600, # local_start 2022-03-13 03:00:00 (Sun) 63803383200, # local_end 2022-11-06 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63803404800, # utc_start 2022-11-06 08:00:00 (Sun) 63814294800, # utc_end 2023-03-12 09:00:00 (Sun) 63803379600, # local_start 2022-11-06 01:00:00 (Sun) 63814269600, # local_end 2023-03-12 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63814294800, # utc_start 2023-03-12 09:00:00 (Sun) 63834854400, # utc_end 2023-11-05 08:00:00 (Sun) 63814273200, # local_start 2023-03-12 03:00:00 (Sun) 63834832800, # local_end 2023-11-05 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63834854400, # utc_start 2023-11-05 08:00:00 (Sun) 63845744400, # utc_end 2024-03-10 09:00:00 (Sun) 63834829200, # local_start 2023-11-05 01:00:00 (Sun) 63845719200, # local_end 2024-03-10 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63845744400, # utc_start 2024-03-10 09:00:00 (Sun) 63866304000, # utc_end 2024-11-03 08:00:00 (Sun) 63845722800, # local_start 2024-03-10 03:00:00 (Sun) 63866282400, # local_end 2024-11-03 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63866304000, # utc_start 2024-11-03 08:00:00 (Sun) 63877194000, # utc_end 2025-03-09 09:00:00 (Sun) 63866278800, # local_start 2024-11-03 01:00:00 (Sun) 63877168800, # local_end 2025-03-09 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63877194000, # utc_start 2025-03-09 09:00:00 (Sun) 63897753600, # utc_end 2025-11-02 08:00:00 (Sun) 63877172400, # local_start 2025-03-09 03:00:00 (Sun) 63897732000, # local_end 2025-11-02 02:00:00 (Sun) -21600, 1, 'MDT', ], [ 63897753600, # utc_start 2025-11-02 08:00:00 (Sun) 63908643600, # utc_end 2026-03-08 09:00:00 (Sun) 63897728400, # local_start 2025-11-02 01:00:00 (Sun) 63908618400, # local_end 2026-03-08 02:00:00 (Sun) -25200, 0, 'MST', ], [ 63908643600, # utc_start 2026-03-08 09:00:00 (Sun) 63929203200, # utc_end 2026-11-01 08:00:00 (Sun) 63908622000, # local_start 2026-03-08 03:00:00 (Sun) 63929181600, # local_end 2026-11-01 02:00:00 (Sun) -21600, 1, 'MDT', ], ]; sub olson_version {'2015g'} sub has_dst_changes {48} sub _max_year {2025} sub _new_instance { return shift->_init( @_, spans => $spans ); } sub _last_offset { -25200 } my $last_observance = bless( { 'format' => 'M%sT', 'gmtoff' => '-7:00', 'local_start_datetime' => bless( { 'formatter' => undef, 'local_rd_days' => 722815, 'local_rd_secs' => 0, 'offset_modifier' => 0, 'rd_nanosecs' => 0, 'tz' => bless( { 'name' => 'floating', 'offset' => 0 }, 'DateTime::TimeZone::Floating' ), 'utc_rd_days' => 722815, 'utc_rd_secs' => 0, 'utc_year' => 1981 }, 'DateTime' ), 'offset_from_std' => 0, 'offset_from_utc' => -25200, 'until' => [], 'utc_start_datetime' => bless( { 'formatter' => undef, 'local_rd_days' => 722815, 'local_rd_secs' => 25200, 'offset_modifier' => 0, 'rd_nanosecs' => 0, 'tz' => bless( { 'name' => 'floating', 'offset' => 0 }, 'DateTime::TimeZone::Floating' ), 'utc_rd_days' => 722815, 'utc_rd_secs' => 25200, 'utc_year' => 1981 }, 'DateTime' ) }, 'DateTime::TimeZone::OlsonDB::Observance' ) ; sub _last_observance { $last_observance } my $rules = [ bless( { 'at' => '2:00', 'from' => '2007', 'in' => 'Nov', 'letter' => 'S', 'name' => 'Canada', 'offset_from_std' => 0, 'on' => 'Sun>=1', 'save' => '0', 'to' => 'max', 'type' => undef }, 'DateTime::TimeZone::OlsonDB::Rule' ), bless( { 'at' => '2:00', 'from' => '2007', 'in' => 'Mar', 'letter' => 'D', 'name' => 'Canada', 'offset_from_std' => 3600, 'on' => 'Sun>=8', 'save' => '1:00', 'to' => 'max', 'type' => undef }, 'DateTime::TimeZone::OlsonDB::Rule' ) ] ; sub _rules { $rules } 1;
rosiro/wasarabi
local/lib/perl5/DateTime/TimeZone/America/Inuvik.pm
Perl
mit
26,819
#!/usr/bin/perl use lib "/astro/grads/arh5361/code/perl"; use MyCols; $description="Makes an IRAF script used to run PHOT at the V-band centroids of the LAEs"; @names=("file list","aper int","aper max","aper min!0"); MyCols::PrintArgs(\@ARGV,\@names,$description,1,"processphot.pl"); $options=$ARGV[scalar(@ARGV)-1]; $options=MyCols::SetOpts($options,"processphot.pl"); $file = shift(@ARGV); $apint = shift(@ARGV); $apmax0 = shift(@ARGV); $apmin = shift(@ARGV); if ($apmin==0) { $apmin=$apint; } $lA=ReadFile($file); if (defined($$options{'inp'})) { $lQ=ReadFile("$$options{'inp'}"); } system("rm $$options{'o'}"); $k=0; foreach (@$lA) { ($pref,$dum,$dum,$fluxtot,$ra,$dec)=split; $pref=~s/\_bs//; $pref=~s/\.fits//; open(C,">$pref.apphot"); if (defined($$options{'inp'})) { ($dum,$apmax)=split(" ",$$lQ[$k]); } else { $apmax=$apmax0; } $lB=ReadFile("$pref.r$apmax"); $line=$$lB[scalar(@$lB)-1]; $line2=$$lB[scalar(@$lB)-4]; ($dum,$dum,$dum,$fluxmax,$magmax,$magmaxerr)=split(" ",$line); # print "$fluxmax\n"; ($dum,$dum,$dx,$dy,$ex,$ey)=split(" ",$line2); $halfflux=$fluxmax/2; $check=0; $fluxold=0; for ($aper=$apmin;$aper<=$apmax0;$aper+=$apint) { $lB=ReadFile("$pref.r$aper"); $line=$$lB[scalar(@$lB)-1]; ($dum,$dum,$dum,$flux,$mag,$magerr)=split(" ",$line); if (!$check && $flux>$halfflux) { $check=1; $halfrad=$aper-$apint+$apint/($flux-$fluxold)*($halfflux-$fluxold); } $halfrad=0 if ($fluxmax<=0); $fluxold=$flux; print C "$aper $flux $mag $magerr\n"; # print C "phot $pref coords=$pref.coo sigma=0.024 apertur=$apsky output=$pref.r$aper\n"; system("rm $pref.r$aper") if (!$$options{'v'}); } close(C); # $halfrad=0 if ($ra==0); if (defined($$options{'inp'})) { system("echo $pref $halfrad $magmax $magmaxerr $ra $dec $dx $dy $ex $ey >> $$options{'o'}"); } else { system("echo $pref $halfrad $mag $magerr $ra $dec $dx $dy $ex $ey >> $$options{'o'}"); } # system("interp_splint -f $pref.apphot 2 1 $halfflux | printcol 'substr(\$1,0,-7)' 2 'substr(\$1,0,0).$mag' 'substr(\$1,0,0).$magerr' >> $$options{'o'}"); # print("interp_splint -f $pref.apphot 2 1 $halfflux | printcol 'substr(\$1,0,-7)' 2 'substr($1,0,0).$mag' 'substr($1,0,0).$magerr' >> $$options{'o'}\n"); $k++; } MyCols::Finish();
astronomeralex/morphology-software
processphot.pl
Perl
mit
2,418
/************************************************************************* File: cnfFOL.pl Copyright (C) 2004 Patrick Blackburn & Johan Bos This file is part of BB1, version 1.2 (August 2005). BB1 is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. BB1 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with BB1; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ :- module(cnfFOL,[info/0, prefix/0, infix/0, nnf/2, cnf/2, cnfTestSuite/0]). :- use_module(comsemPredicates,[infix/0, prefix/0, appendLists/3, basicFormula/1, newFunctionCounter/1, substitute/4, compose/3, removeDuplicates/2]). :- use_module(cnfTestSuite,[formulaClause/2]). /*======================================================================== Main Predicate ========================================================================*/ cnf(Formula,SetCNF):- nnf(Formula,NNF), skolemise(NNF,Skolemised,[]), cnf([[Skolemised]],[],CNF), setCnf(CNF,SetCNF). /*======================================================================== Running the Test Suite ========================================================================*/ cnfTestSuite:- formulaClause(Formula,Cnf), format('~nInput formula: ~p',[Formula]), format('~nKnown cnf: ~p',[Cnf]), cnf(Formula,CNF), format('~nComputed cnf: ~p~n',[CNF]), fail. cnfTestSuite. /*======================================================================== Convert to Negated Normal Form ========================================================================*/ nnf(not(all(X,F)),some(X,N)):- nnf(not(F),N). nnf(all(X,F),all(X,N)):- nnf(F,N). nnf(not(some(X,F)),all(X,N)):- nnf(not(F),N). nnf(some(X,F),some(X,N)):- nnf(F,N). nnf(not(and(F1,F2)),or(N1,N2)):- nnf(not(F1),N1), nnf(not(F2),N2). nnf(and(F1,F2),and(N1,N2)):- nnf(F1,N1), nnf(F2,N2). nnf(not(or(F1,F2)),and(N1,N2)):- nnf(not(F1),N1), nnf(not(F2),N2). nnf(or(F1,F2),or(N1,N2)):- nnf(F1,N1), nnf(F2,N2). nnf(not(imp(F1,F2)),and(N1,N2)):- nnf(F1,N1), nnf(not(F2),N2). nnf(imp(F1,F2),or(N1,N2)):- nnf(not(F1),N1), nnf(F2,N2). nnf(not(not(F1)),N1):- nnf(F1,N1). nnf(F1,F1):- literal(F1). /*======================================================================== Literals ========================================================================*/ literal(not(F)):- basicFormula(F). literal(F):- basicFormula(F). /*======================================================================== Convert From Negative Normal Form to Conjunctive Normal Form ========================================================================*/ cnf([],_,[]). cnf([[]|Tcon],Lit,[Lit|NewTcon]):- !, cnf(Tcon,[],NewTcon). cnf([[and(F1,F2)|Tdis]|Tcon],Lits,Output):- !, appendLists(Tdis,Lits,Full), cnf([[F1|Full],[F2|Full]|Tcon],[],Output). cnf([[or(F1,F2)|Tdis]|Tcon],Lits,Output):- !, cnf([[F1,F2|Tdis]|Tcon],Lits,Output). cnf([[Lit|Tdis]|Tcon],Lits,Output):- cnf([Tdis|Tcon],[Lit|Lits],Output). /*======================================================================== Remove Duplicates and Sort ========================================================================*/ setCnf(Cnf1,Cnf2):- setCnf(Cnf1,[],Cnf2). setCnf([],Cnf1,Cnf2):- removeDuplicates(Cnf1,Cnf2). setCnf([X1|L1],L2,L3):- removeDuplicates(X1,X2), sort(X2,X3), setCnf(L1,[X3|L2],L3). /*======================================================================== Skolemise ========================================================================*/ skolemise(all(X,F),N,Vars):- skolemise(F,N,[X|Vars]). skolemise(some(X,F1),N,Vars):- skolemFunction(Vars,SkolemTerm), substitute(SkolemTerm,X,F1,F2), skolemise(F2,N,Vars). skolemise(and(F1,F2),and(N1,N2),Vars):- skolemise(F1,N1,Vars), skolemise(F2,N2,Vars). skolemise(or(F1,F2),or(N1,N2),Vars):- skolemise(F1,N1,Vars), skolemise(F2,N2,Vars). skolemise(F,F,_):- literal(F). /*======================================================================== VarList is a list of free variables, and SkolemTerm is a previously unused Skolem function symbol fun(N) applied to those free variables. ========================================================================*/ skolemFunction(VarList,SkolemTerm):- newFunctionCounter(N), compose(SkolemTerm,fun,[N|VarList]). /*======================================================================== Info ========================================================================*/ info:- format('~n> ------------------------------------------------------------------- <',[]), format('~n> cnfFOL.pl, by Patrick Blackburn and Johan Bos <',[]), format('~n> <',[]), format('~n> ?- cnf(Formula,CNF). - converts formula in conjunctive normal form <',[]), format('~n> ?- nnf(Formula,CNF). - converts formula in negative normal form <',[]), format('~n> ?- cnfTestSuite. - runs the test suite for CNF conversion <',[]), format('~n> ?- infix. - switches to infix display mode <',[]), format('~n> ?- prefix. - switches to prefix display mode <',[]), format('~n> ?- info. - show this information <',[]), format('~n> ------------------------------------------------------------------- <',[]), format('~n~n',[]). /*======================================================================== Display info at start ========================================================================*/ :- info.
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/CURT/bb1/cnfFOL.pl
Perl
mit
6,529
# Copyright 2020, Google LLC # # 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. package Google::Ads::GoogleAds::V10::Services::ConversionAdjustmentUploadService::ConversionAdjustment; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { adjustmentDateTime => $args->{adjustmentDateTime}, adjustmentType => $args->{adjustmentType}, conversionAction => $args->{conversionAction}, gclidDateTimePair => $args->{gclidDateTimePair}, orderId => $args->{orderId}, restatementValue => $args->{restatementValue}, userAgent => $args->{userAgent}, userIdentifiers => $args->{userIdentifiers}}; # Delete the unassigned fields in this object for a more concise JSON payload remove_unassigned_fields($self, $args); bless $self, $class; return $self; } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V10/Services/ConversionAdjustmentUploadService/ConversionAdjustment.pm
Perl
apache-2.0
1,440
package Google::Ads::AdWords::v201809::UserListLogicalRule; use strict; use warnings; __PACKAGE__->_set_element_form_qualified(1); sub get_xmlns { 'https://adwords.google.com/api/adwords/rm/v201809' }; our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %operator_of :ATTR(:get<operator>); my %ruleOperands_of :ATTR(:get<ruleOperands>); __PACKAGE__->_factory( [ qw( operator ruleOperands ) ], { 'operator' => \%operator_of, 'ruleOperands' => \%ruleOperands_of, }, { 'operator' => 'Google::Ads::AdWords::v201809::UserListLogicalRule::Operator', 'ruleOperands' => 'Google::Ads::AdWords::v201809::LogicalUserListOperand', }, { 'operator' => 'operator', 'ruleOperands' => 'ruleOperands', } ); } # end BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201809::UserListLogicalRule =head1 DESCRIPTION Perl data type class for the XML Schema defined complexType UserListLogicalRule from the namespace https://adwords.google.com/api/adwords/rm/v201809. A user list logical rule. A rule has a logical operator (and/or/not) and a list of operands that can be user lists or user interests. =head2 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * operator =item * ruleOperands =back =head1 METHODS =head2 new Constructor. The following data structure may be passed to new(): =head1 AUTHOR Generated by SOAP::WSDL =cut
googleads/googleads-perl-lib
lib/Google/Ads/AdWords/v201809/UserListLogicalRule.pm
Perl
apache-2.0
1,712
# # Copyright 2021 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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. # package apps::java::awa::jmx::plugin; use strict; use warnings; use base qw(centreon::plugins::script_custom); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '0.1'; %{$self->{modes}} = ( 'agent' => 'apps::java::awa::jmx::mode::agent', 'list-agents' => 'apps::java::awa::jmx::mode::listagents', 'list-queues' => 'apps::java::awa::jmx::mode::listqueues', 'list-servers' => 'apps::java::awa::jmx::mode::listservers', 'queue' => 'apps::java::awa::jmx::mode::queue', 'server' => 'apps::java::awa::jmx::mode::server', ); $self->{custom_modes}{jolokia} = 'centreon::common::protocols::jmx::custom::jolokia'; return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check Automic Workload Automation (Awa) in JMX. Need Jolokia agent. =cut
Tpo76/centreon-plugins
apps/java/awa/jmx/plugin.pm
Perl
apache-2.0
1,713
###########################################$ # Copyright 2008-2010 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://aws.amazon.com/apache2.0 # # or in the "license" file accompanying this file. This file 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. ###########################################$ # __ _ _ ___ # ( )( \/\/ )/ __) # /__\ \ / \__ \ # (_)(_) \/\/ (___/ # # Amazon EC2 Perl Library # API Version: 2010-06-15 # Generated: Wed Jul 21 13:37:54 PDT 2010 # package Amazon::EC2::Model::CreateVpcResult; use base qw (Amazon::EC2::Model); # # Amazon::EC2::Model::CreateVpcResult # # Properties: # # # Vpc: Amazon::EC2::Model::Vpc # # # sub new { my ($class, $data) = @_; my $self = {}; $self->{_fields} = { Vpc => {FieldValue => undef, FieldType => "Amazon::EC2::Model::Vpc"}, }; bless ($self, $class); if (defined $data) { $self->_fromHashRef($data); } return $self; } sub getVpc { return shift->{_fields}->{Vpc}->{FieldValue}; } sub setVpc { my ($self, $value) = @_; $self->{_fields}->{Vpc}->{FieldValue} = $value; } sub withVpc { my ($self, $value) = @_; $self->setVpc($value); return $self; } sub isSetVpc { return defined (shift->{_fields}->{Vpc}->{FieldValue}); } 1;
electric-cloud/EC-EC2
src/main/resources/project/lib/Amazon/EC2/Model/CreateVpcResult.pm
Perl
apache-2.0
1,845
# # Copyright 2021 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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. # package database::informix::sql::mode::checkpoints; use base qw(centreon::plugins::mode); use strict; use warnings; use centreon::plugins::misc; sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { "warning-cp:s" => { name => 'warning_cp', }, "critical-cp:s" => { name => 'critical_cp', }, "warning-flush:s" => { name => 'warning_flush', }, "critical-flush:s" => { name => 'critical_flush', }, "warning-crit:s" => { name => 'warning_crit', }, "critical-crit:s" => { name => 'critical_crit', }, "warning-block:s" => { name => 'warning_block', }, "critical-block:s" => { name => 'critical_block', }, "filter-trigger:s" => { name => 'filter_trigger', }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); if (($self->{perfdata}->threshold_validate(label => 'warning-cp', value => $self->{option_results}->{warning_cp})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning-cp threshold '" . $self->{option_results}->{warning_cp} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical-cp', value => $self->{option_results}->{critical_cp})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical-cp threshold '" . $self->{option_results}->{critical_cp} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'warning-flush', value => $self->{option_results}->{warning_flush})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning-flush threshold '" . $self->{option_results}->{warning_flush} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical-flush', value => $self->{option_results}->{critical_flush})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical-flush threshold '" . $self->{option_results}->{critical_flush} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'warning-crit', value => $self->{option_results}->{warning_crit})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning-crit threshold '" . $self->{option_results}->{warning_crit} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical-crit', value => $self->{option_results}->{critical_crit})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical-crit threshold '" . $self->{option_results}->{critical_crit} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'warning-block', value => $self->{option_results}->{warning_block})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning-block threshold '" . $self->{option_results}->{warning_block} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical-block', value => $self->{option_results}->{critical_block})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical-block threshold '" . $self->{option_results}->{critical_block} . "'."); $self->{output}->option_exit(); } } sub run { my ($self, %options) = @_; # $options{sql} = sqlmode object $self->{sql} = $options{sql}; $self->{sql}->connect(); $self->{sql}->query(query => q{ SELECT intvl, caller, cp_time, block_time, flush_time, crit_time FROM syscheckpoint }); $self->{output}->output_add(severity => 'OK', short_msg => "All checkpoint times are ok."); my $count = 0; while ((my $row = $self->{sql}->fetchrow_hashref())) { my $id = $row->{intvl}; my $name = centreon::plugins::misc::trim($row->{caller}); my ($cp_time, $block_time, $flush_time, $crit_time) = ($row->{cp_time}, $row->{block_time}, $row->{flush_time}, $row->{crit_time}); next if (defined($self->{option_results}->{filter_trigger}) && $name !~ /$self->{option_results}->{filter_trigger}/); $count++; my $exit1 = $self->{perfdata}->threshold_check(value => $cp_time, threshold => [ { label => 'critical-cp', 'exit_litteral' => 'critical' }, { label => 'warning-cp', exit_litteral => 'warning' } ]); my $exit2 = $self->{perfdata}->threshold_check(value => $block_time, threshold => [ { label => 'critical-block', 'exit_litteral' => 'critical' }, { label => 'warning-block', exit_litteral => 'warning' } ]); my $exit3 = $self->{perfdata}->threshold_check(value => $flush_time, threshold => [ { label => 'critical-flush', 'exit_litteral' => 'critical' }, { label => 'warning-flush', exit_litteral => 'warning' } ]); my $exit4 = $self->{perfdata}->threshold_check(value => $crit_time, threshold => [ { label => 'critical-crit', 'exit_litteral' => 'critical' }, { label => 'warning-crit', exit_litteral => 'warning' } ]); my $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2, $exit3, $exit4 ]); $self->{output}->output_add(long_msg => sprintf("Checkpoint %s %s : Total Time %.4f, Block Time %.4f, Flush Time %.4f, Ckpt Time %.4f", $name, $id, $cp_time, $block_time, $flush_time, $crit_time) ); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Checkpoint %s %s : Total Time %.4f, Block Time %.4f, Flush Time %.4f, Ckpt Time %.4f", $name, $id, $cp_time, $block_time, $flush_time, $crit_time) ); } $self->{output}->perfdata_add(label => 'cp_' . $name . "_" . $id, value => sprintf("%.4f", $cp_time), warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_cp'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_cp'), min => 0); $self->{output}->perfdata_add(label => 'block_' . $name . "_" . $id, value => sprintf("%.4f", $block_time), warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_block'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_block'), min => 0); $self->{output}->perfdata_add(label => 'flush_' . $name . "_" . $id, value => sprintf("%.4f", $flush_time), warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_flush'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_flush'), min => 0); $self->{output}->perfdata_add(label => 'crit_' . $name . "_" . $id, value => sprintf("%.4f", $crit_time), warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_crit'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_crit'), min => 0); } if ($count == 0) { $self->{output}->output_add(severity => 'UNKNOWN', short_msg => "Cannot find checkpoints (maybe the --name filter option)."); } $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check Informix Checkpoints. 4 values: - cp_time: Total checkpoint duration from request time to checkpoint completion. - flush_time: Time taken to flush all the bufferpools. - crit_time: This is the amount of time it takes for all transactions to recognize a checkpoint has been requested. - block_time: Transaction blocking time. =over 8 =item B<--warning-cp> Threshold warning 'cp_time' in seconds. =item B<--critical-cp> Threshold critical 'cp_time' in seconds. =item B<--warning-flush> Threshold warning 'flush_time' in seconds. =item B<--critical-flush> Threshold critical 'flush_time' in seconds. =item B<--warning-crit> Threshold warning 'crit_time' in seconds. =item B<--critical-crit> Threshold critical 'crit_time' in seconds. =item B<--warning-block> Threshold warning 'block_time' in seconds. =item B<--critical-block> Threshold critical 'block_time' in seconds. =item B<--filter-trigger> Filter events that can trigger a checkpoint with a regexp. =back =cut
Tpo76/centreon-plugins
database/informix/sql/mode/checkpoints.pm
Perl
apache-2.0
10,278
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2021] EMBL-European Bioinformatics Institute 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. =cut =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut # Ensembl module for Bio::EnsEMBL::Variation::BaseStructuralVariation # # =head1 NAME Bio::EnsEMBL::Variation::Failable =head1 DESCRIPTION This object returns failed information. =cut use strict; use warnings; use Bio::EnsEMBL::Utils::Exception qw(throw warning); package Bio::EnsEMBL::Variation::Failable; =head2 failed_description Arg [1] : $failed_description (optional) The new value to set the failed_description attribute to. Should be a reference to a list of strings, alternatively a string can be passed. If multiple failed descriptions are specified, they should be separated with semi-colons. Example : $failed_str = $sv->failed_description(); Description: Get/Sets the failed description for this variant. The failed descriptions are lazy-loaded from the database. Returntype : String (semi-colon separated) Exceptions : Thrown on illegal argument. Caller : general Status : Stable =cut sub failed_description { my $self = shift; my $description = shift; # Update the description if necessary if (defined($description)) { # If the description is a string, split it by semi-colon and take the reference if (check_ref($description,'STRING')) { my @pcs = split(/;/,$description); $description = \@pcs; } # Throw an error if the description is not an arrayref assert_ref($description.'ARRAY'); # Update the cached failed_description $self->{'failed_description'} = $description; } # Else, fetch it from the db if it's not cached elsif (!defined($self->{'failed_description'})) { $self->{'failed_description'} = $self->get_all_failed_descriptions(); } # Return a semi-colon separated string of descriptions return join(";",@{$self->{'failed_description'}}); } =head2 get_all_failed_descriptions Example : if ($sv->is_failed()) { my $descriptions = $sv->get_all_failed_descriptions(); print "Structural variant " . $sv->variation_name() . " has been flagged as failed because '"; print join("' and '",@{$descriptions}) . "'\n"; } Description: Gets all failed descriptions associated with this Structural variant. Returntype : Listref of strings Exceptions : Thrown if an adaptor is not attached to this object. Caller : general Status : At risk =cut sub get_all_failed_descriptions { my $self = shift; # If the failed descriptions haven't been cached yet, load them from db unless (defined($self->{'failed_description'})) { # Check that this allele has an adaptor attached # unless () { # throw('An adaptor must be attached to the ' . ref($self) . ' object'); # } $self->{'failed_description'} = defined($self->adaptor()) ? $self->adaptor->get_all_failed_descriptions($self) : []; } return $self->{'failed_description'}; } =head2 is_failed Example : print "Structural variant '" . $sv->variation_name() . "' has " . ($sv->is_failed() ? "" : "not ") . "been flagged as failed\n"; Description: Gets the failed attribute for this structural variant. The failed attribute is lazy-loaded from the database. Returntype : int Exceptions : none Caller : general Status : At risk =cut sub is_failed { my $self = shift; return (length($self->failed_description()) > 0); } 1;
Ensembl/ensembl-variation
modules/Bio/EnsEMBL/Variation/Failable.pm
Perl
apache-2.0
4,583
############################################################################# # Define and check attributes for a Graph::Easy textual description. # ############################################################################# package Graph::Easy::Attributes; $VERSION = '0.32'; package Graph::Easy; use strict; use utf8; # for examples like "Fähre" # to make it easier to remember the attribute names: my $att_aliases = { 'auto-label' => 'autolabel', 'auto-link' => 'autolink', 'auto-title' => 'autotitle', 'arrow-style' => 'arrowstyle', 'arrow-shape' => 'arrowshape', 'border-color' => 'bordercolor', 'border-style' => 'borderstyle', 'border-width' => 'borderwidth', 'font-size' => 'fontsize', 'label-color' => 'labelcolor', 'label-pos' => 'labelpos', 'text-style' => 'textstyle', 'text-wrap' => 'textwrap', 'point-style' => 'pointstyle', 'point-shape' => 'pointshape', }; sub _att_aliases { $att_aliases; } ############################################################################# # color handling # The W3C/SVG/CSS color scheme my $color_names = { w3c => { inherit => 'inherit', aliceblue => '#f0f8ff', antiquewhite => '#faebd7', aquamarine => '#7fffd4', aqua => '#00ffff', azure => '#f0ffff', beige => '#f5f5dc', bisque => '#ffe4c4', black => '#000000', blanchedalmond => '#ffebcd', blue => '#0000ff', blueviolet => '#8a2be2', brown => '#a52a2a', burlywood => '#deb887', cadetblue => '#5f9ea0', chartreuse => '#7fff00', chocolate => '#d2691e', coral => '#ff7f50', cornflowerblue => '#6495ed', cornsilk => '#fff8dc', crimson => '#dc143c', cyan => '#00ffff', darkblue => '#00008b', darkcyan => '#008b8b', darkgoldenrod => '#b8860b', darkgray => '#a9a9a9', darkgreen => '#006400', darkgrey => '#a9a9a9', darkkhaki => '#bdb76b', darkmagenta => '#8b008b', darkolivegreen => '#556b2f', darkorange => '#ff8c00', darkorchid => '#9932cc', darkred => '#8b0000', darksalmon => '#e9967a', darkseagreen => '#8fbc8f', darkslateblue => '#483d8b', darkslategray => '#2f4f4f', darkslategrey => '#2f4f4f', darkturquoise => '#00ced1', darkviolet => '#9400d3', deeppink => '#ff1493', deepskyblue => '#00bfff', dimgray => '#696969', dodgerblue => '#1e90ff', firebrick => '#b22222', floralwhite => '#fffaf0', forestgreen => '#228b22', fuchsia => '#ff00ff', gainsboro => '#dcdcdc', ghostwhite => '#f8f8ff', goldenrod => '#daa520', gold => '#ffd700', gray => '#808080', green => '#008000', greenyellow => '#adff2f', grey => '#808080', honeydew => '#f0fff0', hotpink => '#ff69b4', indianred => '#cd5c5c', indigo => '#4b0082', ivory => '#fffff0', khaki => '#f0e68c', lavenderblush => '#fff0f5', lavender => '#e6e6fa', lawngreen => '#7cfc00', lemonchiffon => '#fffacd', lightblue => '#add8e6', lightcoral => '#f08080', lightcyan => '#e0ffff', lightgoldenrodyellow => '#fafad2', lightgray => '#d3d3d3', lightgreen => '#90ee90', lightgrey => '#d3d3d3', lightpink => '#ffb6c1', lightsalmon => '#ffa07a', lightseagreen => '#20b2aa', lightskyblue => '#87cefa', lightslategray => '#778899', lightslategrey => '#778899', lightsteelblue => '#b0c4de', lightyellow => '#ffffe0', limegreen => '#32cd32', lime => '#00ff00', linen => '#faf0e6', magenta => '#ff00ff', maroon => '#800000', mediumaquamarine => '#66cdaa', mediumblue => '#0000cd', mediumorchid => '#ba55d3', mediumpurple => '#9370db', mediumseagreen => '#3cb371', mediumslateblue => '#7b68ee', mediumspringgreen => '#00fa9a', mediumturquoise => '#48d1cc', mediumvioletred => '#c71585', midnightblue => '#191970', mintcream => '#f5fffa', mistyrose => '#ffe4e1', moccasin => '#ffe4b5', navajowhite => '#ffdead', navy => '#000080', oldlace => '#fdf5e6', olivedrab => '#6b8e23', olive => '#808000', orangered => '#ff4500', orange => '#ffa500', orchid => '#da70d6', palegoldenrod => '#eee8aa', palegreen => '#98fb98', paleturquoise => '#afeeee', palevioletred => '#db7093', papayawhip => '#ffefd5', peachpuff => '#ffdab9', peru => '#cd853f', pink => '#ffc0cb', plum => '#dda0dd', powderblue => '#b0e0e6', purple => '#800080', red => '#ff0000', rosybrown => '#bc8f8f', royalblue => '#4169e1', saddlebrown => '#8b4513', salmon => '#fa8072', sandybrown => '#f4a460', seagreen => '#2e8b57', seashell => '#fff5ee', sienna => '#a0522d', silver => '#c0c0c0', skyblue => '#87ceeb', slateblue => '#6a5acd', slategray => '#708090', slategrey => '#708090', snow => '#fffafa', springgreen => '#00ff7f', steelblue => '#4682b4', tan => '#d2b48c', teal => '#008080', thistle => '#d8bfd8', tomato => '#ff6347', turquoise => '#40e0d0', violet => '#ee82ee', wheat => '#f5deb3', white => '#ffffff', whitesmoke => '#f5f5f5', yellowgreen => '#9acd32', yellow => '#ffff00', }, x11 => { inherit => 'inherit', aliceblue => '#f0f8ff', antiquewhite => '#faebd7', antiquewhite1 => '#ffefdb', antiquewhite2 => '#eedfcc', antiquewhite3 => '#cdc0b0', antiquewhite4 => '#8b8378', aquamarine => '#7fffd4', aquamarine1 => '#7fffd4', aquamarine2 => '#76eec6', aquamarine3 => '#66cdaa', aquamarine4 => '#458b74', azure => '#f0ffff', azure1 => '#f0ffff', azure2 => '#e0eeee', azure3 => '#c1cdcd', azure4 => '#838b8b', beige => '#f5f5dc', bisque => '#ffe4c4', bisque1 => '#ffe4c4', bisque2 => '#eed5b7', bisque3 => '#cdb79e', bisque4 => '#8b7d6b', black => '#000000', blanchedalmond => '#ffebcd', blue => '#0000ff', blue1 => '#0000ff', blue2 => '#0000ee', blue3 => '#0000cd', blue4 => '#00008b', blueviolet => '#8a2be2', brown => '#a52a2a', brown1 => '#ff4040', brown2 => '#ee3b3b', brown3 => '#cd3333', brown4 => '#8b2323', burlywood => '#deb887', burlywood1 => '#ffd39b', burlywood2 => '#eec591', burlywood3 => '#cdaa7d', burlywood4 => '#8b7355', cadetblue => '#5f9ea0', cadetblue1 => '#98f5ff', cadetblue2 => '#8ee5ee', cadetblue3 => '#7ac5cd', cadetblue4 => '#53868b', chartreuse => '#7fff00', chartreuse1 => '#7fff00', chartreuse2 => '#76ee00', chartreuse3 => '#66cd00', chartreuse4 => '#458b00', chocolate => '#d2691e', chocolate1 => '#ff7f24', chocolate2 => '#ee7621', chocolate3 => '#cd661d', chocolate4 => '#8b4513', coral => '#ff7f50', coral1 => '#ff7256', coral2 => '#ee6a50', coral3 => '#cd5b45', coral4 => '#8b3e2f', cornflowerblue => '#6495ed', cornsilk => '#fff8dc', cornsilk1 => '#fff8dc', cornsilk2 => '#eee8cd', cornsilk3 => '#cdc8b1', cornsilk4 => '#8b8878', crimson => '#dc143c', cyan => '#00ffff', cyan1 => '#00ffff', cyan2 => '#00eeee', cyan3 => '#00cdcd', cyan4 => '#008b8b', darkgoldenrod => '#b8860b', darkgoldenrod1 => '#ffb90f', darkgoldenrod2 => '#eead0e', darkgoldenrod3 => '#cd950c', darkgoldenrod4 => '#8b6508', darkgreen => '#006400', darkkhaki => '#bdb76b', darkolivegreen => '#556b2f', darkolivegreen1 => '#caff70', darkolivegreen2 => '#bcee68', darkolivegreen3 => '#a2cd5a', darkolivegreen4 => '#6e8b3d', darkorange => '#ff8c00', darkorange1 => '#ff7f00', darkorange2 => '#ee7600', darkorange3 => '#cd6600', darkorange4 => '#8b4500', darkorchid => '#9932cc', darkorchid1 => '#bf3eff', darkorchid2 => '#b23aee', darkorchid3 => '#9a32cd', darkorchid4 => '#68228b', darksalmon => '#e9967a', darkseagreen => '#8fbc8f', darkseagreen1 => '#c1ffc1', darkseagreen2 => '#b4eeb4', darkseagreen3 => '#9bcd9b', darkseagreen4 => '#698b69', darkslateblue => '#483d8b', darkslategray => '#2f4f4f', darkslategray1 => '#97ffff', darkslategray2 => '#8deeee', darkslategray3 => '#79cdcd', darkslategray4 => '#528b8b', darkslategrey => '#2f4f4f', darkturquoise => '#00ced1', darkviolet => '#9400d3', deeppink => '#ff1493', deeppink1 => '#ff1493', deeppink2 => '#ee1289', deeppink3 => '#cd1076', deeppink4 => '#8b0a50', deepskyblue => '#00bfff', deepskyblue1 => '#00bfff', deepskyblue2 => '#00b2ee', deepskyblue3 => '#009acd', deepskyblue4 => '#00688b', dimgray => '#696969', dimgrey => '#696969', dodgerblue => '#1e90ff', dodgerblue1 => '#1e90ff', dodgerblue2 => '#1c86ee', dodgerblue3 => '#1874cd', dodgerblue4 => '#104e8b', firebrick => '#b22222', firebrick1 => '#ff3030', firebrick2 => '#ee2c2c', firebrick3 => '#cd2626', firebrick4 => '#8b1a1a', floralwhite => '#fffaf0', forestgreen => '#228b22', gainsboro => '#dcdcdc', ghostwhite => '#f8f8ff', gold => '#ffd700', gold1 => '#ffd700', gold2 => '#eec900', gold3 => '#cdad00', gold4 => '#8b7500', goldenrod => '#daa520', goldenrod1 => '#ffc125', goldenrod2 => '#eeb422', goldenrod3 => '#cd9b1d', goldenrod4 => '#8b6914', gray => '#c0c0c0', gray0 => '#000000', gray1 => '#030303', gray2 => '#050505', gray3 => '#080808', gray4 => '#0a0a0a', gray5 => '#0d0d0d', gray6 => '#0f0f0f', gray7 => '#121212', gray8 => '#141414', gray9 => '#171717', gray10 => '#1a1a1a', gray11 => '#1c1c1c', gray12 => '#1f1f1f', gray13 => '#212121', gray14 => '#242424', gray15 => '#262626', gray16 => '#292929', gray17 => '#2b2b2b', gray18 => '#2e2e2e', gray19 => '#303030', gray20 => '#333333', gray21 => '#363636', gray22 => '#383838', gray23 => '#3b3b3b', gray24 => '#3d3d3d', gray25 => '#404040', gray26 => '#424242', gray27 => '#454545', gray28 => '#474747', gray29 => '#4a4a4a', gray30 => '#4d4d4d', gray31 => '#4f4f4f', gray32 => '#525252', gray33 => '#545454', gray34 => '#575757', gray35 => '#595959', gray36 => '#5c5c5c', gray37 => '#5e5e5e', gray38 => '#616161', gray39 => '#636363', gray40 => '#666666', gray41 => '#696969', gray42 => '#6b6b6b', gray43 => '#6e6e6e', gray44 => '#707070', gray45 => '#737373', gray46 => '#757575', gray47 => '#787878', gray48 => '#7a7a7a', gray49 => '#7d7d7d', gray50 => '#7f7f7f', gray51 => '#828282', gray52 => '#858585', gray53 => '#878787', gray54 => '#8a8a8a', gray55 => '#8c8c8c', gray56 => '#8f8f8f', gray57 => '#919191', gray58 => '#949494', gray59 => '#969696', gray60 => '#999999', gray61 => '#9c9c9c', gray62 => '#9e9e9e', gray63 => '#a1a1a1', gray64 => '#a3a3a3', gray65 => '#a6a6a6', gray66 => '#a8a8a8', gray67 => '#ababab', gray68 => '#adadad', gray69 => '#b0b0b0', gray70 => '#b3b3b3', gray71 => '#b5b5b5', gray72 => '#b8b8b8', gray73 => '#bababa', gray74 => '#bdbdbd', gray75 => '#bfbfbf', gray76 => '#c2c2c2', gray77 => '#c4c4c4', gray78 => '#c7c7c7', gray79 => '#c9c9c9', gray80 => '#cccccc', gray81 => '#cfcfcf', gray82 => '#d1d1d1', gray83 => '#d4d4d4', gray84 => '#d6d6d6', gray85 => '#d9d9d9', gray86 => '#dbdbdb', gray87 => '#dedede', gray88 => '#e0e0e0', gray89 => '#e3e3e3', gray90 => '#e5e5e5', gray91 => '#e8e8e8', gray92 => '#ebebeb', gray93 => '#ededed', gray94 => '#f0f0f0', gray95 => '#f2f2f2', gray96 => '#f5f5f5', gray97 => '#f7f7f7', gray98 => '#fafafa', gray99 => '#fcfcfc', gray100 => '#ffffff', green => '#00ff00', green1 => '#00ff00', green2 => '#00ee00', green3 => '#00cd00', green4 => '#008b00', greenyellow => '#adff2f', grey => '#c0c0c0', grey0 => '#000000', grey1 => '#030303', grey2 => '#050505', grey3 => '#080808', grey4 => '#0a0a0a', grey5 => '#0d0d0d', grey6 => '#0f0f0f', grey7 => '#121212', grey8 => '#141414', grey9 => '#171717', grey10 => '#1a1a1a', grey11 => '#1c1c1c', grey12 => '#1f1f1f', grey13 => '#212121', grey14 => '#242424', grey15 => '#262626', grey16 => '#292929', grey17 => '#2b2b2b', grey18 => '#2e2e2e', grey19 => '#303030', grey20 => '#333333', grey21 => '#363636', grey22 => '#383838', grey23 => '#3b3b3b', grey24 => '#3d3d3d', grey25 => '#404040', grey26 => '#424242', grey27 => '#454545', grey28 => '#474747', grey29 => '#4a4a4a', grey30 => '#4d4d4d', grey31 => '#4f4f4f', grey32 => '#525252', grey33 => '#545454', grey34 => '#575757', grey35 => '#595959', grey36 => '#5c5c5c', grey37 => '#5e5e5e', grey38 => '#616161', grey39 => '#636363', grey40 => '#666666', grey41 => '#696969', grey42 => '#6b6b6b', grey43 => '#6e6e6e', grey44 => '#707070', grey45 => '#737373', grey46 => '#757575', grey47 => '#787878', grey48 => '#7a7a7a', grey49 => '#7d7d7d', grey50 => '#7f7f7f', grey51 => '#828282', grey52 => '#858585', grey53 => '#878787', grey54 => '#8a8a8a', grey55 => '#8c8c8c', grey56 => '#8f8f8f', grey57 => '#919191', grey58 => '#949494', grey59 => '#969696', grey60 => '#999999', grey61 => '#9c9c9c', grey62 => '#9e9e9e', grey63 => '#a1a1a1', grey64 => '#a3a3a3', grey65 => '#a6a6a6', grey66 => '#a8a8a8', grey67 => '#ababab', grey68 => '#adadad', grey69 => '#b0b0b0', grey70 => '#b3b3b3', grey71 => '#b5b5b5', grey72 => '#b8b8b8', grey73 => '#bababa', grey74 => '#bdbdbd', grey75 => '#bfbfbf', grey76 => '#c2c2c2', grey77 => '#c4c4c4', grey78 => '#c7c7c7', grey79 => '#c9c9c9', grey80 => '#cccccc', grey81 => '#cfcfcf', grey82 => '#d1d1d1', grey83 => '#d4d4d4', grey84 => '#d6d6d6', grey85 => '#d9d9d9', grey86 => '#dbdbdb', grey87 => '#dedede', grey88 => '#e0e0e0', grey89 => '#e3e3e3', grey90 => '#e5e5e5', grey91 => '#e8e8e8', grey92 => '#ebebeb', grey93 => '#ededed', grey94 => '#f0f0f0', grey95 => '#f2f2f2', grey96 => '#f5f5f5', grey97 => '#f7f7f7', grey98 => '#fafafa', grey99 => '#fcfcfc', grey100 => '#ffffff', honeydew => '#f0fff0', honeydew1 => '#f0fff0', honeydew2 => '#e0eee0', honeydew3 => '#c1cdc1', honeydew4 => '#838b83', hotpink => '#ff69b4', hotpink1 => '#ff6eb4', hotpink2 => '#ee6aa7', hotpink3 => '#cd6090', hotpink4 => '#8b3a62', indianred => '#cd5c5c', indianred1 => '#ff6a6a', indianred2 => '#ee6363', indianred3 => '#cd5555', indianred4 => '#8b3a3a', indigo => '#4b0082', ivory => '#fffff0', ivory1 => '#fffff0', ivory2 => '#eeeee0', ivory3 => '#cdcdc1', ivory4 => '#8b8b83', khaki => '#f0e68c', khaki1 => '#fff68f', khaki2 => '#eee685', khaki3 => '#cdc673', khaki4 => '#8b864e', lavender => '#e6e6fa', lavenderblush => '#fff0f5', lavenderblush1 => '#fff0f5', lavenderblush2 => '#eee0e5', lavenderblush3 => '#cdc1c5', lavenderblush4 => '#8b8386', lawngreen => '#7cfc00', lemonchiffon => '#fffacd', lemonchiffon1 => '#fffacd', lemonchiffon2 => '#eee9bf', lemonchiffon3 => '#cdc9a5', lemonchiffon4 => '#8b8970', lightblue => '#add8e6', lightblue1 => '#bfefff', lightblue2 => '#b2dfee', lightblue3 => '#9ac0cd', lightblue4 => '#68838b', lightcoral => '#f08080', lightcyan => '#e0ffff', lightcyan1 => '#e0ffff', lightcyan2 => '#d1eeee', lightcyan3 => '#b4cdcd', lightcyan4 => '#7a8b8b', lightgoldenrod => '#eedd82', lightgoldenrod1 => '#ffec8b', lightgoldenrod2 => '#eedc82', lightgoldenrod3 => '#cdbe70', lightgoldenrod4 => '#8b814c', lightgoldenrodyellow => '#fafad2', lightgray => '#d3d3d3', lightgrey => '#d3d3d3', lightpink => '#ffb6c1', lightpink1 => '#ffaeb9', lightpink2 => '#eea2ad', lightpink3 => '#cd8c95', lightpink4 => '#8b5f65', lightsalmon => '#ffa07a', lightsalmon1 => '#ffa07a', lightsalmon2 => '#ee9572', lightsalmon3 => '#cd8162', lightsalmon4 => '#8b5742', lightseagreen => '#20b2aa', lightskyblue => '#87cefa', lightskyblue1 => '#b0e2ff', lightskyblue2 => '#a4d3ee', lightskyblue3 => '#8db6cd', lightskyblue4 => '#607b8b', lightslateblue => '#8470ff', lightslategray => '#778899', lightslategrey => '#778899', lightsteelblue => '#b0c4de', lightsteelblue1 => '#cae1ff', lightsteelblue2 => '#bcd2ee', lightsteelblue3 => '#a2b5cd', lightsteelblue4 => '#6e7b8b', lightyellow => '#ffffe0', lightyellow1 => '#ffffe0', lightyellow2 => '#eeeed1', lightyellow3 => '#cdcdb4', lightyellow4 => '#8b8b7a', limegreen => '#32cd32', linen => '#faf0e6', magenta => '#ff00ff', magenta1 => '#ff00ff', magenta2 => '#ee00ee', magenta3 => '#cd00cd', magenta4 => '#8b008b', maroon => '#b03060', maroon1 => '#ff34b3', maroon2 => '#ee30a7', maroon3 => '#cd2990', maroon4 => '#8b1c62', mediumaquamarine => '#66cdaa', mediumblue => '#0000cd', mediumorchid => '#ba55d3', mediumorchid1 => '#e066ff', mediumorchid2 => '#d15fee', mediumorchid3 => '#b452cd', mediumorchid4 => '#7a378b', mediumpurple => '#9370db', mediumpurple1 => '#ab82ff', mediumpurple2 => '#9f79ee', mediumpurple3 => '#8968cd', mediumpurple4 => '#5d478b', mediumseagreen => '#3cb371', mediumslateblue => '#7b68ee', mediumspringgreen => '#00fa9a', mediumturquoise => '#48d1cc', mediumvioletred => '#c71585', midnightblue => '#191970', mintcream => '#f5fffa', mistyrose => '#ffe4e1', mistyrose1 => '#ffe4e1', mistyrose2 => '#eed5d2', mistyrose3 => '#cdb7b5', mistyrose4 => '#8b7d7b', moccasin => '#ffe4b5', navajowhite => '#ffdead', navajowhite1 => '#ffdead', navajowhite2 => '#eecfa1', navajowhite3 => '#cdb38b', navajowhite4 => '#8b795e', navy => '#000080', navyblue => '#000080', oldlace => '#fdf5e6', olivedrab => '#6b8e23', olivedrab1 => '#c0ff3e', olivedrab2 => '#b3ee3a', olivedrab3 => '#9acd32', olivedrab4 => '#698b22', orange => '#ffa500', orange1 => '#ffa500', orange2 => '#ee9a00', orange3 => '#cd8500', orange4 => '#8b5a00', orangered => '#ff4500', orangered1 => '#ff4500', orangered2 => '#ee4000', orangered3 => '#cd3700', orangered4 => '#8b2500', orchid => '#da70d6', orchid1 => '#ff83fa', orchid2 => '#ee7ae9', orchid3 => '#cd69c9', orchid4 => '#8b4789', palegoldenrod => '#eee8aa', palegreen => '#98fb98', palegreen1 => '#9aff9a', palegreen2 => '#90ee90', palegreen3 => '#7ccd7c', palegreen4 => '#548b54', paleturquoise => '#afeeee', paleturquoise1 => '#bbffff', paleturquoise2 => '#aeeeee', paleturquoise3 => '#96cdcd', paleturquoise4 => '#668b8b', palevioletred => '#db7093', palevioletred1 => '#ff82ab', palevioletred2 => '#ee799f', palevioletred3 => '#cd6889', palevioletred4 => '#8b475d', papayawhip => '#ffefd5', peachpuff => '#ffdab9', peachpuff1 => '#ffdab9', peachpuff2 => '#eecbad', peachpuff3 => '#cdaf95', peachpuff4 => '#8b7765', peru => '#cd853f', pink => '#ffc0cb', pink1 => '#ffb5c5', pink2 => '#eea9b8', pink3 => '#cd919e', pink4 => '#8b636c', plum => '#dda0dd', plum1 => '#ffbbff', plum2 => '#eeaeee', plum3 => '#cd96cd', plum4 => '#8b668b', powderblue => '#b0e0e6', purple => '#a020f0', purple1 => '#9b30ff', purple2 => '#912cee', purple3 => '#7d26cd', purple4 => '#551a8b', red => '#ff0000', red1 => '#ff0000', red2 => '#ee0000', red3 => '#cd0000', red4 => '#8b0000', rosybrown => '#bc8f8f', rosybrown1 => '#ffc1c1', rosybrown2 => '#eeb4b4', rosybrown3 => '#cd9b9b', rosybrown4 => '#8b6969', royalblue => '#4169e1', royalblue1 => '#4876ff', royalblue2 => '#436eee', royalblue3 => '#3a5fcd', royalblue4 => '#27408b', saddlebrown => '#8b4513', salmon => '#fa8072', salmon1 => '#ff8c69', salmon2 => '#ee8262', salmon3 => '#cd7054', salmon4 => '#8b4c39', sandybrown => '#f4a460', seagreen => '#2e8b57', seagreen1 => '#54ff9f', seagreen2 => '#4eee94', seagreen3 => '#43cd80', seagreen4 => '#2e8b57', seashell => '#fff5ee', seashell1 => '#fff5ee', seashell2 => '#eee5de', seashell3 => '#cdc5bf', seashell4 => '#8b8682', sienna => '#a0522d', sienna1 => '#ff8247', sienna2 => '#ee7942', sienna3 => '#cd6839', sienna4 => '#8b4726', skyblue => '#87ceeb', skyblue1 => '#87ceff', skyblue2 => '#7ec0ee', skyblue3 => '#6ca6cd', skyblue4 => '#4a708b', slateblue => '#6a5acd', slateblue1 => '#836fff', slateblue2 => '#7a67ee', slateblue3 => '#6959cd', slateblue4 => '#473c8b', slategray => '#708090', slategray1 => '#c6e2ff', slategray2 => '#b9d3ee', slategray3 => '#9fb6cd', slategray4 => '#6c7b8b', slategrey => '#708090', snow => '#fffafa', snow1 => '#fffafa', snow2 => '#eee9e9', snow3 => '#cdc9c9', snow4 => '#8b8989', springgreen => '#00ff7f', springgreen1 => '#00ff7f', springgreen2 => '#00ee76', springgreen3 => '#00cd66', springgreen4 => '#008b45', steelblue => '#4682b4', steelblue1 => '#63b8ff', steelblue2 => '#5cacee', steelblue3 => '#4f94cd', steelblue4 => '#36648b', tan => '#d2b48c', tan1 => '#ffa54f', tan2 => '#ee9a49', tan3 => '#cd853f', tan4 => '#8b5a2b', thistle => '#d8bfd8', thistle1 => '#ffe1ff', thistle2 => '#eed2ee', thistle3 => '#cdb5cd', thistle4 => '#8b7b8b', tomato => '#ff6347', tomato1 => '#ff6347', tomato2 => '#ee5c42', tomato3 => '#cd4f39', tomato4 => '#8b3626', transparent => '#fffffe', turquoise => '#40e0d0', turquoise1 => '#00f5ff', turquoise2 => '#00e5ee', turquoise3 => '#00c5cd', turquoise4 => '#00868b', violet => '#ee82ee', violetred => '#d02090', violetred1 => '#ff3e96', violetred2 => '#ee3a8c', violetred3 => '#cd3278', violetred4 => '#8b2252', wheat => '#f5deb3', wheat1 => '#ffe7ba', wheat2 => '#eed8ae', wheat3 => '#cdba96', wheat4 => '#8b7e66', white => '#ffffff', whitesmoke => '#f5f5f5', yellow => '#ffff00', yellow1 => '#ffff00', yellow2 => '#eeee00', yellow3 => '#cdcd00', yellow4 => '#8b8b00', yellowgreen => '#9acd32', # The following 12 colors exist here so that a "color: 3; colorscheme: accent3" # will not report an "unknown color 3" from the Parser. As a side-effect # you will not get an error for a plain "color: 3". 1 => '#a6cee3', 2 => '#1f78b4', 3 => '#b2df8a', 4 => '#33a02c', 5 => '#fb9a99', 6 => '#e31a1c', 7 => '#fdbf6f', 8 => '#ff7f00', 9 => '#cab2d6', 10 => '#6a3d9a', 11 => '#ffff99', 12 => '#b15928', }, # The following color specifications were developed by: # Cynthia Brewer (http://colorbrewer.org/) # See the LICENSE FILE for the full license that applies to them. accent3 => { 1 => '#7fc97f', 2 => '#beaed4', 3 => '#fdc086', }, accent4 => { 1 => '#7fc97f', 2 => '#beaed4', 3 => '#fdc086', 4 => '#ffff99', }, accent5 => { 1 => '#7fc97f', 2 => '#beaed4', 3 => '#fdc086', 4 => '#ffff99', 5 => '#386cb0', }, accent6 => { 1 => '#7fc97f', 2 => '#beaed4', 3 => '#fdc086', 4 => '#ffff99', 5 => '#386cb0', 6 => '#f0027f', }, accent7 => { 1 => '#7fc97f', 2 => '#beaed4', 3 => '#fdc086', 4 => '#ffff99', 5 => '#386cb0', 6 => '#f0027f', 7 => '#bf5b17', }, accent8 => { 1 => '#7fc97f', 2 => '#beaed4', 3 => '#fdc086', 4 => '#ffff99', 5 => '#386cb0', 6 => '#f0027f', 7 => '#bf5b17', 8 => '#666666', }, blues3 => { 1 => '#deebf7', 2 => '#9ecae1', 3 => '#3182bd', }, blues4 => { 1 => '#eff3ff', 2 => '#bdd7e7', 3 => '#6baed6', 4 => '#2171b5', }, blues5 => { 1 => '#eff3ff', 2 => '#bdd7e7', 3 => '#6baed6', 4 => '#3182bd', 5 => '#08519c', }, blues6 => { 1 => '#eff3ff', 2 => '#c6dbef', 3 => '#9ecae1', 4 => '#6baed6', 5 => '#3182bd', 6 => '#08519c', }, blues7 => { 1 => '#eff3ff', 2 => '#c6dbef', 3 => '#9ecae1', 4 => '#6baed6', 5 => '#4292c6', 6 => '#2171b5', 7 => '#084594', }, blues8 => { 1 => '#f7fbff', 2 => '#deebf7', 3 => '#c6dbef', 4 => '#9ecae1', 5 => '#6baed6', 6 => '#4292c6', 7 => '#2171b5', 8 => '#084594', }, blues9 => { 1 => '#f7fbff', 2 => '#deebf7', 3 => '#c6dbef', 4 => '#9ecae1', 5 => '#6baed6', 6 => '#4292c6', 7 => '#2171b5', 8 => '#08519c', 9 => '#08306b', }, brbg3 => { 1 => '#d8b365', 2 => '#f5f5f5', 3 => '#5ab4ac', }, brbg4 => { 1 => '#a6611a', 2 => '#dfc27d', 3 => '#80cdc1', 4 => '#018571', }, brbg5 => { 1 => '#a6611a', 2 => '#dfc27d', 3 => '#f5f5f5', 4 => '#80cdc1', 5 => '#018571', }, brbg6 => { 1 => '#8c510a', 2 => '#d8b365', 3 => '#f6e8c3', 4 => '#c7eae5', 5 => '#5ab4ac', 6 => '#01665e', }, brbg7 => { 1 => '#8c510a', 2 => '#d8b365', 3 => '#f6e8c3', 4 => '#f5f5f5', 5 => '#c7eae5', 6 => '#5ab4ac', 7 => '#01665e', }, brbg8 => { 1 => '#8c510a', 2 => '#bf812d', 3 => '#dfc27d', 4 => '#f6e8c3', 5 => '#c7eae5', 6 => '#80cdc1', 7 => '#35978f', 8 => '#01665e', }, brbg9 => { 1 => '#8c510a', 2 => '#bf812d', 3 => '#dfc27d', 4 => '#f6e8c3', 5 => '#f5f5f5', 6 => '#c7eae5', 7 => '#80cdc1', 8 => '#35978f', 9 => '#01665e', }, brbg10 => { 1 => '#543005', 2 => '#8c510a', 3 => '#bf812d', 4 => '#dfc27d', 5 => '#f6e8c3', 6 => '#c7eae5', 7 => '#80cdc1', 8 => '#35978f', 9 => '#01665e', 10 => '#003c30', }, brbg11 => { 1 => '#543005', 2 => '#8c510a', 3 => '#bf812d', 4 => '#dfc27d', 5 => '#f6e8c3', 6 => '#f5f5f5', 7 => '#c7eae5', 8 => '#80cdc1', 9 => '#35978f', 10 => '#01665e', 11 => '#003c30', }, bugn3 => { 1 => '#e5f5f9', 2 => '#99d8c9', 3 => '#2ca25f', }, bugn4 => { 1 => '#edf8fb', 2 => '#b2e2e2', 3 => '#66c2a4', 4 => '#238b45', }, bugn5 => { 1 => '#edf8fb', 2 => '#b2e2e2', 3 => '#66c2a4', 4 => '#2ca25f', 5 => '#006d2c', }, bugn6 => { 1 => '#edf8fb', 2 => '#ccece6', 3 => '#99d8c9', 4 => '#66c2a4', 5 => '#2ca25f', 6 => '#006d2c', }, bugn7 => { 1 => '#edf8fb', 2 => '#ccece6', 3 => '#99d8c9', 4 => '#66c2a4', 5 => '#41ae76', 6 => '#238b45', 7 => '#005824', }, bugn8 => { 1 => '#f7fcfd', 2 => '#e5f5f9', 3 => '#ccece6', 4 => '#99d8c9', 5 => '#66c2a4', 6 => '#41ae76', 7 => '#238b45', 8 => '#005824', }, bugn9 => { 1 => '#f7fcfd', 2 => '#e5f5f9', 3 => '#ccece6', 4 => '#99d8c9', 5 => '#66c2a4', 6 => '#41ae76', 7 => '#238b45', 8 => '#006d2c', 9 => '#00441b', }, bupu3 => { 1 => '#e0ecf4', 2 => '#9ebcda', 3 => '#8856a7', }, bupu4 => { 1 => '#edf8fb', 2 => '#b3cde3', 3 => '#8c96c6', 4 => '#88419d', }, bupu5 => { 1 => '#edf8fb', 2 => '#b3cde3', 3 => '#8c96c6', 4 => '#8856a7', 5 => '#810f7c', }, bupu6 => { 1 => '#edf8fb', 2 => '#bfd3e6', 3 => '#9ebcda', 4 => '#8c96c6', 5 => '#8856a7', 6 => '#810f7c', }, bupu7 => { 1 => '#edf8fb', 2 => '#bfd3e6', 3 => '#9ebcda', 4 => '#8c96c6', 5 => '#8c6bb1', 6 => '#88419d', 7 => '#6e016b', }, bupu8 => { 1 => '#f7fcfd', 2 => '#e0ecf4', 3 => '#bfd3e6', 4 => '#9ebcda', 5 => '#8c96c6', 6 => '#8c6bb1', 7 => '#88419d', 8 => '#6e016b', }, bupu9 => { 1 => '#f7fcfd', 2 => '#e0ecf4', 3 => '#bfd3e6', 4 => '#9ebcda', 5 => '#8c96c6', 6 => '#8c6bb1', 7 => '#88419d', 8 => '#810f7c', 9 => '#4d004b', }, dark23 => { 1 => '#1b9e77', 2 => '#d95f02', 3 => '#7570b3', }, dark24 => { 1 => '#1b9e77', 2 => '#d95f02', 3 => '#7570b3', 4 => '#e7298a', }, dark25 => { 1 => '#1b9e77', 2 => '#d95f02', 3 => '#7570b3', 4 => '#e7298a', 5 => '#66a61e', }, dark26 => { 1 => '#1b9e77', 2 => '#d95f02', 3 => '#7570b3', 4 => '#e7298a', 5 => '#66a61e', 6 => '#e6ab02', }, dark27 => { 1 => '#1b9e77', 2 => '#d95f02', 3 => '#7570b3', 4 => '#e7298a', 5 => '#66a61e', 6 => '#e6ab02', 7 => '#a6761d', }, dark28 => { 1 => '#1b9e77', 2 => '#d95f02', 3 => '#7570b3', 4 => '#e7298a', 5 => '#66a61e', 6 => '#e6ab02', 7 => '#a6761d', 8 => '#666666', }, gnbu3 => { 1 => '#e0f3db', 2 => '#a8ddb5', 3 => '#43a2ca', }, gnbu4 => { 1 => '#f0f9e8', 2 => '#bae4bc', 3 => '#7bccc4', 4 => '#2b8cbe', }, gnbu5 => { 1 => '#f0f9e8', 2 => '#bae4bc', 3 => '#7bccc4', 4 => '#43a2ca', 5 => '#0868ac', }, gnbu6 => { 1 => '#f0f9e8', 2 => '#ccebc5', 3 => '#a8ddb5', 4 => '#7bccc4', 5 => '#43a2ca', 6 => '#0868ac', }, gnbu7 => { 1 => '#f0f9e8', 2 => '#ccebc5', 3 => '#a8ddb5', 4 => '#7bccc4', 5 => '#4eb3d3', 6 => '#2b8cbe', 7 => '#08589e', }, gnbu8 => { 1 => '#f7fcf0', 2 => '#e0f3db', 3 => '#ccebc5', 4 => '#a8ddb5', 5 => '#7bccc4', 6 => '#4eb3d3', 7 => '#2b8cbe', 8 => '#08589e', }, gnbu9 => { 1 => '#f7fcf0', 2 => '#e0f3db', 3 => '#ccebc5', 4 => '#a8ddb5', 5 => '#7bccc4', 6 => '#4eb3d3', 7 => '#2b8cbe', 8 => '#0868ac', 9 => '#084081', }, greens3 => { 1 => '#e5f5e0', 2 => '#a1d99b', 3 => '#31a354', }, greens4 => { 1 => '#edf8e9', 2 => '#bae4b3', 3 => '#74c476', 4 => '#238b45', }, greens5 => { 1 => '#edf8e9', 2 => '#bae4b3', 3 => '#74c476', 4 => '#31a354', 5 => '#006d2c', }, greens6 => { 1 => '#edf8e9', 2 => '#c7e9c0', 3 => '#a1d99b', 4 => '#74c476', 5 => '#31a354', 6 => '#006d2c', }, greens7 => { 1 => '#edf8e9', 2 => '#c7e9c0', 3 => '#a1d99b', 4 => '#74c476', 5 => '#41ab5d', 6 => '#238b45', 7 => '#005a32', }, greens8 => { 1 => '#f7fcf5', 2 => '#e5f5e0', 3 => '#c7e9c0', 4 => '#a1d99b', 5 => '#74c476', 6 => '#41ab5d', 7 => '#238b45', 8 => '#005a32', }, greens9 => { 1 => '#f7fcf5', 2 => '#e5f5e0', 3 => '#c7e9c0', 4 => '#a1d99b', 5 => '#74c476', 6 => '#41ab5d', 7 => '#238b45', 8 => '#006d2c', 9 => '#00441b', }, greys3 => { 1 => '#f0f0f0', 2 => '#bdbdbd', 3 => '#636363', }, greys4 => { 1 => '#f7f7f7', 2 => '#cccccc', 3 => '#969696', 4 => '#525252', }, greys5 => { 1 => '#f7f7f7', 2 => '#cccccc', 3 => '#969696', 4 => '#636363', 5 => '#252525', }, greys6 => { 1 => '#f7f7f7', 2 => '#d9d9d9', 3 => '#bdbdbd', 4 => '#969696', 5 => '#636363', 6 => '#252525', }, greys7 => { 1 => '#f7f7f7', 2 => '#d9d9d9', 3 => '#bdbdbd', 4 => '#969696', 5 => '#737373', 6 => '#525252', 7 => '#252525', }, greys8 => { 1 => '#ffffff', 2 => '#f0f0f0', 3 => '#d9d9d9', 4 => '#bdbdbd', 5 => '#969696', 6 => '#737373', 7 => '#525252', 8 => '#252525', }, greys9 => { 1 => '#ffffff', 2 => '#f0f0f0', 3 => '#d9d9d9', 4 => '#bdbdbd', 5 => '#969696', 6 => '#737373', 7 => '#525252', 8 => '#252525', 9 => '#000000', }, oranges3 => { 1 => '#fee6ce', 2 => '#fdae6b', 3 => '#e6550d', }, oranges4 => { 1 => '#feedde', 2 => '#fdbe85', 3 => '#fd8d3c', 4 => '#d94701', }, oranges5 => { 1 => '#feedde', 2 => '#fdbe85', 3 => '#fd8d3c', 4 => '#e6550d', 5 => '#a63603', }, oranges6 => { 1 => '#feedde', 2 => '#fdd0a2', 3 => '#fdae6b', 4 => '#fd8d3c', 5 => '#e6550d', 6 => '#a63603', }, oranges7 => { 1 => '#feedde', 2 => '#fdd0a2', 3 => '#fdae6b', 4 => '#fd8d3c', 5 => '#f16913', 6 => '#d94801', 7 => '#8c2d04', }, oranges8 => { 1 => '#fff5eb', 2 => '#fee6ce', 3 => '#fdd0a2', 4 => '#fdae6b', 5 => '#fd8d3c', 6 => '#f16913', 7 => '#d94801', 8 => '#8c2d04', }, oranges9 => { 1 => '#fff5eb', 2 => '#fee6ce', 3 => '#fdd0a2', 4 => '#fdae6b', 5 => '#fd8d3c', 6 => '#f16913', 7 => '#d94801', 8 => '#a63603', 9 => '#7f2704', }, orrd3 => { 1 => '#fee8c8', 2 => '#fdbb84', 3 => '#e34a33', }, orrd4 => { 1 => '#fef0d9', 2 => '#fdcc8a', 3 => '#fc8d59', 4 => '#d7301f', }, orrd5 => { 1 => '#fef0d9', 2 => '#fdcc8a', 3 => '#fc8d59', 4 => '#e34a33', 5 => '#b30000', }, orrd6 => { 1 => '#fef0d9', 2 => '#fdd49e', 3 => '#fdbb84', 4 => '#fc8d59', 5 => '#e34a33', 6 => '#b30000', }, orrd7 => { 1 => '#fef0d9', 2 => '#fdd49e', 3 => '#fdbb84', 4 => '#fc8d59', 5 => '#ef6548', 6 => '#d7301f', 7 => '#990000', }, orrd8 => { 1 => '#fff7ec', 2 => '#fee8c8', 3 => '#fdd49e', 4 => '#fdbb84', 5 => '#fc8d59', 6 => '#ef6548', 7 => '#d7301f', 8 => '#990000', }, orrd9 => { 1 => '#fff7ec', 2 => '#fee8c8', 3 => '#fdd49e', 4 => '#fdbb84', 5 => '#fc8d59', 6 => '#ef6548', 7 => '#d7301f', 8 => '#b30000', 9 => '#7f0000', }, paired3 => { 1 => '#a6cee3', 2 => '#1f78b4', 3 => '#b2df8a', }, paired4 => { 1 => '#a6cee3', 2 => '#1f78b4', 3 => '#b2df8a', 4 => '#33a02c', }, paired5 => { 1 => '#a6cee3', 2 => '#1f78b4', 3 => '#b2df8a', 4 => '#33a02c', 5 => '#fb9a99', }, paired6 => { 1 => '#a6cee3', 2 => '#1f78b4', 3 => '#b2df8a', 4 => '#33a02c', 5 => '#fb9a99', 6 => '#e31a1c', }, paired7 => { 1 => '#a6cee3', 2 => '#1f78b4', 3 => '#b2df8a', 4 => '#33a02c', 5 => '#fb9a99', 6 => '#e31a1c', 7 => '#fdbf6f', }, paired8 => { 1 => '#a6cee3', 2 => '#1f78b4', 3 => '#b2df8a', 4 => '#33a02c', 5 => '#fb9a99', 6 => '#e31a1c', 7 => '#fdbf6f', 8 => '#ff7f00', }, paired9 => { 1 => '#a6cee3', 2 => '#1f78b4', 3 => '#b2df8a', 4 => '#33a02c', 5 => '#fb9a99', 6 => '#e31a1c', 7 => '#fdbf6f', 8 => '#ff7f00', 9 => '#cab2d6', }, paired10 => { 1 => '#a6cee3', 2 => '#1f78b4', 3 => '#b2df8a', 4 => '#33a02c', 5 => '#fb9a99', 6 => '#e31a1c', 7 => '#fdbf6f', 8 => '#ff7f00', 9 => '#cab2d6', 10 => '#6a3d9a', }, paired11 => { 1 => '#a6cee3', 2 => '#1f78b4', 3 => '#b2df8a', 4 => '#33a02c', 5 => '#fb9a99', 6 => '#e31a1c', 7 => '#fdbf6f', 8 => '#ff7f00', 9 => '#cab2d6', 10 => '#6a3d9a', 11 => '#ffff99', }, paired12 => { 1 => '#a6cee3', 2 => '#1f78b4', 3 => '#b2df8a', 4 => '#33a02c', 5 => '#fb9a99', 6 => '#e31a1c', 7 => '#fdbf6f', 8 => '#ff7f00', 9 => '#cab2d6', 10 => '#6a3d9a', 11 => '#ffff99', 12 => '#b15928', }, pastel13 => { 1 => '#fbb4ae', 2 => '#b3cde3', 3 => '#ccebc5', }, pastel14 => { 1 => '#fbb4ae', 2 => '#b3cde3', 3 => '#ccebc5', 4 => '#decbe4', }, pastel15 => { 1 => '#fbb4ae', 2 => '#b3cde3', 3 => '#ccebc5', 4 => '#decbe4', 5 => '#fed9a6', }, pastel16 => { 1 => '#fbb4ae', 2 => '#b3cde3', 3 => '#ccebc5', 4 => '#decbe4', 5 => '#fed9a6', 6 => '#ffffcc', }, pastel17 => { 1 => '#fbb4ae', 2 => '#b3cde3', 3 => '#ccebc5', 4 => '#decbe4', 5 => '#fed9a6', 6 => '#ffffcc', 7 => '#e5d8bd', }, pastel18 => { 1 => '#fbb4ae', 2 => '#b3cde3', 3 => '#ccebc5', 4 => '#decbe4', 5 => '#fed9a6', 6 => '#ffffcc', 7 => '#e5d8bd', 8 => '#fddaec', }, pastel19 => { 1 => '#fbb4ae', 2 => '#b3cde3', 3 => '#ccebc5', 4 => '#decbe4', 5 => '#fed9a6', 6 => '#ffffcc', 7 => '#e5d8bd', 8 => '#fddaec', 9 => '#f2f2f2', }, pastel23 => { 1 => '#b3e2cd', 2 => '#fdcdac', 3 => '#cbd5e8', }, pastel24 => { 1 => '#b3e2cd', 2 => '#fdcdac', 3 => '#cbd5e8', 4 => '#f4cae4', }, pastel25 => { 1 => '#b3e2cd', 2 => '#fdcdac', 3 => '#cbd5e8', 4 => '#f4cae4', 5 => '#e6f5c9', }, pastel26 => { 1 => '#b3e2cd', 2 => '#fdcdac', 3 => '#cbd5e8', 4 => '#f4cae4', 5 => '#e6f5c9', 6 => '#fff2ae', }, pastel27 => { 1 => '#b3e2cd', 2 => '#fdcdac', 3 => '#cbd5e8', 4 => '#f4cae4', 5 => '#e6f5c9', 6 => '#fff2ae', 7 => '#f1e2cc', }, pastel28 => { 1 => '#b3e2cd', 2 => '#fdcdac', 3 => '#cbd5e8', 4 => '#f4cae4', 5 => '#e6f5c9', 6 => '#fff2ae', 7 => '#f1e2cc', 8 => '#cccccc', }, piyg3 => { 1 => '#e9a3c9', 2 => '#f7f7f7', 3 => '#a1d76a', }, piyg4 => { 1 => '#d01c8b', 2 => '#f1b6da', 3 => '#b8e186', 4 => '#4dac26', }, piyg5 => { 1 => '#d01c8b', 2 => '#f1b6da', 3 => '#f7f7f7', 4 => '#b8e186', 5 => '#4dac26', }, piyg6 => { 1 => '#c51b7d', 2 => '#e9a3c9', 3 => '#fde0ef', 4 => '#e6f5d0', 5 => '#a1d76a', 6 => '#4d9221', }, piyg7 => { 1 => '#c51b7d', 2 => '#e9a3c9', 3 => '#fde0ef', 4 => '#f7f7f7', 5 => '#e6f5d0', 6 => '#a1d76a', 7 => '#4d9221', }, piyg8 => { 1 => '#c51b7d', 2 => '#de77ae', 3 => '#f1b6da', 4 => '#fde0ef', 5 => '#e6f5d0', 6 => '#b8e186', 7 => '#7fbc41', 8 => '#4d9221', }, piyg9 => { 1 => '#c51b7d', 2 => '#de77ae', 3 => '#f1b6da', 4 => '#fde0ef', 5 => '#f7f7f7', 6 => '#e6f5d0', 7 => '#b8e186', 8 => '#7fbc41', 9 => '#4d9221', }, piyg10 => { 1 => '#8e0152', 2 => '#c51b7d', 3 => '#de77ae', 4 => '#f1b6da', 5 => '#fde0ef', 6 => '#e6f5d0', 7 => '#b8e186', 8 => '#7fbc41', 9 => '#4d9221', 10 => '#276419', }, piyg11 => { 1 => '#8e0152', 2 => '#c51b7d', 3 => '#de77ae', 4 => '#f1b6da', 5 => '#fde0ef', 6 => '#f7f7f7', 7 => '#e6f5d0', 8 => '#b8e186', 9 => '#7fbc41', 10 => '#4d9221', 11 => '#276419', }, prgn3 => { 1 => '#af8dc3', 2 => '#f7f7f7', 3 => '#7fbf7b', }, prgn4 => { 1 => '#7b3294', 2 => '#c2a5cf', 3 => '#a6dba0', 4 => '#008837', }, prgn5 => { 1 => '#7b3294', 2 => '#c2a5cf', 3 => '#f7f7f7', 4 => '#a6dba0', 5 => '#008837', }, prgn6 => { 1 => '#762a83', 2 => '#af8dc3', 3 => '#e7d4e8', 4 => '#d9f0d3', 5 => '#7fbf7b', 6 => '#1b7837', }, prgn7 => { 1 => '#762a83', 2 => '#af8dc3', 3 => '#e7d4e8', 4 => '#f7f7f7', 5 => '#d9f0d3', 6 => '#7fbf7b', 7 => '#1b7837', }, prgn8 => { 1 => '#762a83', 2 => '#9970ab', 3 => '#c2a5cf', 4 => '#e7d4e8', 5 => '#d9f0d3', 6 => '#a6dba0', 7 => '#5aae61', 8 => '#1b7837', }, prgn9 => { 1 => '#762a83', 2 => '#9970ab', 3 => '#c2a5cf', 4 => '#e7d4e8', 5 => '#f7f7f7', 6 => '#d9f0d3', 7 => '#a6dba0', 8 => '#5aae61', 9 => '#1b7837', }, prgn10 => { 1 => '#40004b', 2 => '#762a83', 3 => '#9970ab', 4 => '#c2a5cf', 5 => '#e7d4e8', 6 => '#d9f0d3', 7 => '#a6dba0', 8 => '#5aae61', 9 => '#1b7837', 10 => '#00441b', }, prgn11 => { 1 => '#40004b', 2 => '#762a83', 3 => '#9970ab', 4 => '#c2a5cf', 5 => '#e7d4e8', 6 => '#f7f7f7', 7 => '#d9f0d3', 8 => '#a6dba0', 9 => '#5aae61', 10 => '#1b7837', 11 => '#00441b', }, pubu3 => { 1 => '#ece7f2', 2 => '#a6bddb', 3 => '#2b8cbe', }, pubu4 => { 1 => '#f1eef6', 2 => '#bdc9e1', 3 => '#74a9cf', 4 => '#0570b0', }, pubu5 => { 1 => '#f1eef6', 2 => '#bdc9e1', 3 => '#74a9cf', 4 => '#2b8cbe', 5 => '#045a8d', }, pubu6 => { 1 => '#f1eef6', 2 => '#d0d1e6', 3 => '#a6bddb', 4 => '#74a9cf', 5 => '#2b8cbe', 6 => '#045a8d', }, pubu7 => { 1 => '#f1eef6', 2 => '#d0d1e6', 3 => '#a6bddb', 4 => '#74a9cf', 5 => '#3690c0', 6 => '#0570b0', 7 => '#034e7b', }, pubu8 => { 1 => '#fff7fb', 2 => '#ece7f2', 3 => '#d0d1e6', 4 => '#a6bddb', 5 => '#74a9cf', 6 => '#3690c0', 7 => '#0570b0', 8 => '#034e7b', }, pubu9 => { 1 => '#fff7fb', 2 => '#ece7f2', 3 => '#d0d1e6', 4 => '#a6bddb', 5 => '#74a9cf', 6 => '#3690c0', 7 => '#0570b0', 8 => '#045a8d', 9 => '#023858', }, pubugn3 => { 1 => '#ece2f0', 2 => '#a6bddb', 3 => '#1c9099', }, pubugn4 => { 1 => '#f6eff7', 2 => '#bdc9e1', 3 => '#67a9cf', 4 => '#02818a', }, pubugn5 => { 1 => '#f6eff7', 2 => '#bdc9e1', 3 => '#67a9cf', 4 => '#1c9099', 5 => '#016c59', }, pubugn6 => { 1 => '#f6eff7', 2 => '#d0d1e6', 3 => '#a6bddb', 4 => '#67a9cf', 5 => '#1c9099', 6 => '#016c59', }, pubugn7 => { 1 => '#f6eff7', 2 => '#d0d1e6', 3 => '#a6bddb', 4 => '#67a9cf', 5 => '#3690c0', 6 => '#02818a', 7 => '#016450', }, pubugn8 => { 1 => '#fff7fb', 2 => '#ece2f0', 3 => '#d0d1e6', 4 => '#a6bddb', 5 => '#67a9cf', 6 => '#3690c0', 7 => '#02818a', 8 => '#016450', }, pubugn9 => { 1 => '#fff7fb', 2 => '#ece2f0', 3 => '#d0d1e6', 4 => '#a6bddb', 5 => '#67a9cf', 6 => '#3690c0', 7 => '#02818a', 8 => '#016c59', 9 => '#014636', }, puor3 => { 1 => '#f1a340', 2 => '#f7f7f7', 3 => '#998ec3', }, puor4 => { 1 => '#e66101', 2 => '#fdb863', 3 => '#b2abd2', 4 => '#5e3c99', }, puor5 => { 1 => '#e66101', 2 => '#fdb863', 3 => '#f7f7f7', 4 => '#b2abd2', 5 => '#5e3c99', }, puor6 => { 1 => '#b35806', 2 => '#f1a340', 3 => '#fee0b6', 4 => '#d8daeb', 5 => '#998ec3', 6 => '#542788', }, puor7 => { 1 => '#b35806', 2 => '#f1a340', 3 => '#fee0b6', 4 => '#f7f7f7', 5 => '#d8daeb', 6 => '#998ec3', 7 => '#542788', }, puor8 => { 1 => '#b35806', 2 => '#e08214', 3 => '#fdb863', 4 => '#fee0b6', 5 => '#d8daeb', 6 => '#b2abd2', 7 => '#8073ac', 8 => '#542788', }, puor9 => { 1 => '#b35806', 2 => '#e08214', 3 => '#fdb863', 4 => '#fee0b6', 5 => '#f7f7f7', 6 => '#d8daeb', 7 => '#b2abd2', 8 => '#8073ac', 9 => '#542788', }, purd3 => { 1 => '#e7e1ef', 2 => '#c994c7', 3 => '#dd1c77', }, purd4 => { 1 => '#f1eef6', 2 => '#d7b5d8', 3 => '#df65b0', 4 => '#ce1256', }, purd5 => { 1 => '#f1eef6', 2 => '#d7b5d8', 3 => '#df65b0', 4 => '#dd1c77', 5 => '#980043', }, purd6 => { 1 => '#f1eef6', 2 => '#d4b9da', 3 => '#c994c7', 4 => '#df65b0', 5 => '#dd1c77', 6 => '#980043', }, purd7 => { 1 => '#f1eef6', 2 => '#d4b9da', 3 => '#c994c7', 4 => '#df65b0', 5 => '#e7298a', 6 => '#ce1256', 7 => '#91003f', }, purd8 => { 1 => '#f7f4f9', 2 => '#e7e1ef', 3 => '#d4b9da', 4 => '#c994c7', 5 => '#df65b0', 6 => '#e7298a', 7 => '#ce1256', 8 => '#91003f', }, purd9 => { 1 => '#f7f4f9', 2 => '#e7e1ef', 3 => '#d4b9da', 4 => '#c994c7', 5 => '#df65b0', 6 => '#e7298a', 7 => '#ce1256', 8 => '#980043', 9 => '#67001f', }, puor10 => { 1 => '#7f3b08', 2 => '#b35806', 3 => '#e08214', 4 => '#fdb863', 5 => '#fee0b6', 6 => '#d8daeb', 7 => '#b2abd2', 8 => '#8073ac', 9 => '#542788', 10 => '#2d004b', }, puor11 => { 1 => '#7f3b08', 2 => '#b35806', 3 => '#e08214', 4 => '#fdb863', 5 => '#fee0b6', 6 => '#f7f7f7', 7 => '#d8daeb', 8 => '#b2abd2', 9 => '#8073ac', 10 => '#542788', 11 => '#2d004b', }, purples3 => { 1 => '#efedf5', 2 => '#bcbddc', 3 => '#756bb1', }, purples4 => { 1 => '#f2f0f7', 2 => '#cbc9e2', 3 => '#9e9ac8', 4 => '#6a51a3', }, purples5 => { 1 => '#f2f0f7', 2 => '#cbc9e2', 3 => '#9e9ac8', 4 => '#756bb1', 5 => '#54278f', }, purples6 => { 1 => '#f2f0f7', 2 => '#dadaeb', 3 => '#bcbddc', 4 => '#9e9ac8', 5 => '#756bb1', 6 => '#54278f', }, purples7 => { 1 => '#f2f0f7', 2 => '#dadaeb', 3 => '#bcbddc', 4 => '#9e9ac8', 5 => '#807dba', 6 => '#6a51a3', 7 => '#4a1486', }, purples8 => { 1 => '#fcfbfd', 2 => '#efedf5', 3 => '#dadaeb', 4 => '#bcbddc', 5 => '#9e9ac8', 6 => '#807dba', 7 => '#6a51a3', 8 => '#4a1486', }, purples9 => { 1 => '#fcfbfd', 2 => '#efedf5', 3 => '#dadaeb', 4 => '#bcbddc', 5 => '#9e9ac8', 6 => '#807dba', 7 => '#6a51a3', 8 => '#54278f', 9 => '#3f007d', }, rdbu10 => { 1 => '#67001f', 2 => '#b2182b', 3 => '#d6604d', 4 => '#f4a582', 5 => '#fddbc7', 6 => '#d1e5f0', 7 => '#92c5de', 8 => '#4393c3', 9 => '#2166ac', 10 => '#053061', }, rdbu11 => { 1 => '#67001f', 2 => '#b2182b', 3 => '#d6604d', 4 => '#f4a582', 5 => '#fddbc7', 6 => '#f7f7f7', 7 => '#d1e5f0', 8 => '#92c5de', 9 => '#4393c3', 10 => '#2166ac', 11 => '#053061', }, rdbu3 => { 1 => '#ef8a62', 2 => '#f7f7f7', 3 => '#67a9cf', }, rdbu4 => { 1 => '#ca0020', 2 => '#f4a582', 3 => '#92c5de', 4 => '#0571b0', }, rdbu5 => { 1 => '#ca0020', 2 => '#f4a582', 3 => '#f7f7f7', 4 => '#92c5de', 5 => '#0571b0', }, rdbu6 => { 1 => '#b2182b', 2 => '#ef8a62', 3 => '#fddbc7', 4 => '#d1e5f0', 5 => '#67a9cf', 6 => '#2166ac', }, rdbu7 => { 1 => '#b2182b', 2 => '#ef8a62', 3 => '#fddbc7', 4 => '#f7f7f7', 5 => '#d1e5f0', 6 => '#67a9cf', 7 => '#2166ac', }, rdbu8 => { 1 => '#b2182b', 2 => '#d6604d', 3 => '#f4a582', 4 => '#fddbc7', 5 => '#d1e5f0', 6 => '#92c5de', 7 => '#4393c3', 8 => '#2166ac', }, rdbu9 => { 1 => '#b2182b', 2 => '#d6604d', 3 => '#f4a582', 4 => '#fddbc7', 5 => '#f7f7f7', 6 => '#d1e5f0', 7 => '#92c5de', 8 => '#4393c3', 9 => '#2166ac', }, rdgy3 => { 1 => '#ef8a62', 2 => '#ffffff', 3 => '#999999', }, rdgy4 => { 1 => '#ca0020', 2 => '#f4a582', 3 => '#bababa', 4 => '#404040', }, rdgy5 => { 1 => '#ca0020', 2 => '#f4a582', 3 => '#ffffff', 4 => '#bababa', 5 => '#404040', }, rdgy6 => { 1 => '#b2182b', 2 => '#ef8a62', 3 => '#fddbc7', 4 => '#e0e0e0', 5 => '#999999', 6 => '#4d4d4d', }, rdgy7 => { 1 => '#b2182b', 2 => '#ef8a62', 3 => '#fddbc7', 4 => '#ffffff', 5 => '#e0e0e0', 6 => '#999999', 7 => '#4d4d4d', }, rdgy8 => { 1 => '#b2182b', 2 => '#d6604d', 3 => '#f4a582', 4 => '#fddbc7', 5 => '#e0e0e0', 6 => '#bababa', 7 => '#878787', 8 => '#4d4d4d', }, rdgy9 => { 1 => '#b2182b', 2 => '#d6604d', 3 => '#f4a582', 4 => '#fddbc7', 5 => '#ffffff', 6 => '#e0e0e0', 7 => '#bababa', 8 => '#878787', 9 => '#4d4d4d', }, rdpu3 => { 1 => '#fde0dd', 2 => '#fa9fb5', 3 => '#c51b8a', }, rdpu4 => { 1 => '#feebe2', 2 => '#fbb4b9', 3 => '#f768a1', 4 => '#ae017e', }, rdpu5 => { 1 => '#feebe2', 2 => '#fbb4b9', 3 => '#f768a1', 4 => '#c51b8a', 5 => '#7a0177', }, rdpu6 => { 1 => '#feebe2', 2 => '#fcc5c0', 3 => '#fa9fb5', 4 => '#f768a1', 5 => '#c51b8a', 6 => '#7a0177', }, rdpu7 => { 1 => '#feebe2', 2 => '#fcc5c0', 3 => '#fa9fb5', 4 => '#f768a1', 5 => '#dd3497', 6 => '#ae017e', 7 => '#7a0177', }, rdpu8 => { 1 => '#fff7f3', 2 => '#fde0dd', 3 => '#fcc5c0', 4 => '#fa9fb5', 5 => '#f768a1', 6 => '#dd3497', 7 => '#ae017e', 8 => '#7a0177', }, rdpu9 => { 1 => '#fff7f3', 2 => '#fde0dd', 3 => '#fcc5c0', 4 => '#fa9fb5', 5 => '#f768a1', 6 => '#dd3497', 7 => '#ae017e', 8 => '#7a0177', 9 => '#49006a', }, rdgy10 => { 1 => '#67001f', 2 => '#b2182b', 3 => '#d6604d', 4 => '#f4a582', 5 => '#fddbc7', 6 => '#e0e0e0', 7 => '#bababa', 8 => '#878787', 9 => '#4d4d4d', 10 => '#1a1a1a', }, rdgy11 => { 1 => '#67001f', 2 => '#b2182b', 3 => '#d6604d', 4 => '#f4a582', 5 => '#fddbc7', 6 => '#ffffff', 7 => '#e0e0e0', 8 => '#bababa', 9 => '#878787', 10 => '#4d4d4d', 11 => '#1a1a1a', }, rdylbu3 => { 1 => '#fc8d59', 2 => '#ffffbf', 3 => '#91bfdb', }, rdylbu4 => { 1 => '#d7191c', 2 => '#fdae61', 3 => '#abd9e9', 4 => '#2c7bb6', }, rdylbu5 => { 1 => '#d7191c', 2 => '#fdae61', 3 => '#ffffbf', 4 => '#abd9e9', 5 => '#2c7bb6', }, rdylbu6 => { 1 => '#d73027', 2 => '#fc8d59', 3 => '#fee090', 4 => '#e0f3f8', 5 => '#91bfdb', 6 => '#4575b4', }, rdylbu7 => { 1 => '#d73027', 2 => '#fc8d59', 3 => '#fee090', 4 => '#ffffbf', 5 => '#e0f3f8', 6 => '#91bfdb', 7 => '#4575b4', }, rdylbu8 => { 1 => '#d73027', 2 => '#f46d43', 3 => '#fdae61', 4 => '#fee090', 5 => '#e0f3f8', 6 => '#abd9e9', 7 => '#74add1', 8 => '#4575b4', }, rdylbu9 => { 1 => '#d73027', 2 => '#f46d43', 3 => '#fdae61', 4 => '#fee090', 5 => '#ffffbf', 6 => '#e0f3f8', 7 => '#abd9e9', 8 => '#74add1', 9 => '#4575b4', }, rdylbu10 => { 1 => '#a50026', 2 => '#d73027', 3 => '#f46d43', 4 => '#fdae61', 5 => '#fee090', 6 => '#e0f3f8', 7 => '#abd9e9', 8 => '#74add1', 9 => '#4575b4', 10 => '#313695', }, rdylbu11 => { 1 => '#a50026', 2 => '#d73027', 3 => '#f46d43', 4 => '#fdae61', 5 => '#fee090', 6 => '#ffffbf', 7 => '#e0f3f8', 8 => '#abd9e9', 9 => '#74add1', 10 => '#4575b4', 11 => '#313695', }, rdylgn3 => { 1 => '#fc8d59', 2 => '#ffffbf', 3 => '#91cf60', }, rdylgn4 => { 1 => '#d7191c', 2 => '#fdae61', 3 => '#a6d96a', 4 => '#1a9641', }, rdylgn5 => { 1 => '#d7191c', 2 => '#fdae61', 3 => '#ffffbf', 4 => '#a6d96a', 5 => '#1a9641', }, rdylgn6 => { 1 => '#d73027', 2 => '#fc8d59', 3 => '#fee08b', 4 => '#d9ef8b', 5 => '#91cf60', 6 => '#1a9850', }, rdylgn7 => { 1 => '#d73027', 2 => '#fc8d59', 3 => '#fee08b', 4 => '#ffffbf', 5 => '#d9ef8b', 6 => '#91cf60', 7 => '#1a9850', }, rdylgn8 => { 1 => '#d73027', 2 => '#f46d43', 3 => '#fdae61', 4 => '#fee08b', 5 => '#d9ef8b', 6 => '#a6d96a', 7 => '#66bd63', 8 => '#1a9850', }, rdylgn9 => { 1 => '#d73027', 2 => '#f46d43', 3 => '#fdae61', 4 => '#fee08b', 5 => '#ffffbf', 6 => '#d9ef8b', 7 => '#a6d96a', 8 => '#66bd63', 9 => '#1a9850', }, rdylgn10 => { 1 => '#a50026', 2 => '#d73027', 3 => '#f46d43', 4 => '#fdae61', 5 => '#fee08b', 6 => '#d9ef8b', 7 => '#a6d96a', 8 => '#66bd63', 9 => '#1a9850', 10 => '#006837', }, rdylgn11 => { 1 => '#a50026', 2 => '#d73027', 3 => '#f46d43', 4 => '#fdae61', 5 => '#fee08b', 6 => '#ffffbf', 7 => '#d9ef8b', 8 => '#a6d96a', 9 => '#66bd63', 10 => '#1a9850', 11 => '#006837', }, reds3 => { 1 => '#fee0d2', 2 => '#fc9272', 3 => '#de2d26', }, reds4 => { 1 => '#fee5d9', 2 => '#fcae91', 3 => '#fb6a4a', 4 => '#cb181d', }, reds5 => { 1 => '#fee5d9', 2 => '#fcae91', 3 => '#fb6a4a', 4 => '#de2d26', 5 => '#a50f15', }, reds6 => { 1 => '#fee5d9', 2 => '#fcbba1', 3 => '#fc9272', 4 => '#fb6a4a', 5 => '#de2d26', 6 => '#a50f15', }, reds7 => { 1 => '#fee5d9', 2 => '#fcbba1', 3 => '#fc9272', 4 => '#fb6a4a', 5 => '#ef3b2c', 6 => '#cb181d', 7 => '#99000d', }, reds8 => { 1 => '#fff5f0', 2 => '#fee0d2', 3 => '#fcbba1', 4 => '#fc9272', 5 => '#fb6a4a', 6 => '#ef3b2c', 7 => '#cb181d', 8 => '#99000d', }, reds9 => { 1 => '#fff5f0', 2 => '#fee0d2', 3 => '#fcbba1', 4 => '#fc9272', 5 => '#fb6a4a', 6 => '#ef3b2c', 7 => '#cb181d', 8 => '#a50f15', 9 => '#67000d', }, set13 => { 1 => '#e41a1c', 2 => '#377eb8', 3 => '#4daf4a', }, set14 => { 1 => '#e41a1c', 2 => '#377eb8', 3 => '#4daf4a', 4 => '#984ea3', }, set15 => { 1 => '#e41a1c', 2 => '#377eb8', 3 => '#4daf4a', 4 => '#984ea3', 5 => '#ff7f00', }, set16 => { 1 => '#e41a1c', 2 => '#377eb8', 3 => '#4daf4a', 4 => '#984ea3', 5 => '#ff7f00', 6 => '#ffff33', }, set17 => { 1 => '#e41a1c', 2 => '#377eb8', 3 => '#4daf4a', 4 => '#984ea3', 5 => '#ff7f00', 6 => '#ffff33', 7 => '#a65628', }, set18 => { 1 => '#e41a1c', 2 => '#377eb8', 3 => '#4daf4a', 4 => '#984ea3', 5 => '#ff7f00', 6 => '#ffff33', 7 => '#a65628', 8 => '#f781bf', }, set19 => { 1 => '#e41a1c', 2 => '#377eb8', 3 => '#4daf4a', 4 => '#984ea3', 5 => '#ff7f00', 6 => '#ffff33', 7 => '#a65628', 8 => '#f781bf', 9 => '#999999', }, set23 => { 1 => '#66c2a5', 2 => '#fc8d62', 3 => '#8da0cb', }, set24 => { 1 => '#66c2a5', 2 => '#fc8d62', 3 => '#8da0cb', 4 => '#e78ac3', }, set25 => { 1 => '#66c2a5', 2 => '#fc8d62', 3 => '#8da0cb', 4 => '#e78ac3', 5 => '#a6d854', }, set26 => { 1 => '#66c2a5', 2 => '#fc8d62', 3 => '#8da0cb', 4 => '#e78ac3', 5 => '#a6d854', 6 => '#ffd92f', }, set27 => { 1 => '#66c2a5', 2 => '#fc8d62', 3 => '#8da0cb', 4 => '#e78ac3', 5 => '#a6d854', 6 => '#ffd92f', 7 => '#e5c494', }, set28 => { 1 => '#66c2a5', 2 => '#fc8d62', 3 => '#8da0cb', 4 => '#e78ac3', 5 => '#a6d854', 6 => '#ffd92f', 7 => '#e5c494', 8 => '#b3b3b3', }, set33 => { 1 => '#8dd3c7', 2 => '#ffffb3', 3 => '#bebada', }, set34 => { 1 => '#8dd3c7', 2 => '#ffffb3', 3 => '#bebada', 4 => '#fb8072', }, set35 => { 1 => '#8dd3c7', 2 => '#ffffb3', 3 => '#bebada', 4 => '#fb8072', 5 => '#80b1d3', }, set36 => { 1 => '#8dd3c7', 2 => '#ffffb3', 3 => '#bebada', 4 => '#fb8072', 5 => '#80b1d3', 6 => '#fdb462', }, set37 => { 1 => '#8dd3c7', 2 => '#ffffb3', 3 => '#bebada', 4 => '#fb8072', 5 => '#80b1d3', 6 => '#fdb462', 7 => '#b3de69', }, set38 => { 1 => '#8dd3c7', 2 => '#ffffb3', 3 => '#bebada', 4 => '#fb8072', 5 => '#80b1d3', 6 => '#fdb462', 7 => '#b3de69', 8 => '#fccde5', }, set39 => { 1 => '#8dd3c7', 2 => '#ffffb3', 3 => '#bebada', 4 => '#fb8072', 5 => '#80b1d3', 6 => '#fdb462', 7 => '#b3de69', 8 => '#fccde5', 9 => '#d9d9d9', }, set310 => { 1 => '#8dd3c7', 2 => '#ffffb3', 3 => '#bebada', 4 => '#fb8072', 5 => '#80b1d3', 6 => '#fdb462', 7 => '#b3de69', 8 => '#fccde5', 9 => '#d9d9d9', 10 => '#bc80bd', }, set311 => { 1 => '#8dd3c7', 2 => '#ffffb3', 3 => '#bebada', 4 => '#fb8072', 5 => '#80b1d3', 6 => '#fdb462', 7 => '#b3de69', 8 => '#fccde5', 9 => '#d9d9d9', 10 => '#bc80bd', 11 => '#ccebc5', }, set312 => { 1 => '#8dd3c7', 2 => '#ffffb3', 3 => '#bebada', 4 => '#fb8072', 5 => '#80b1d3', 6 => '#fdb462', 7 => '#b3de69', 8 => '#fccde5', 9 => '#d9d9d9', 10 => '#bc80bd', 11 => '#ccebc5', 12 => '#ffed6f', }, spectral3 => { 1 => '#fc8d59', 2 => '#ffffbf', 3 => '#99d594', }, spectral4 => { 1 => '#d7191c', 2 => '#fdae61', 3 => '#abdda4', 4 => '#2b83ba', }, spectral5 => { 1 => '#d7191c', 2 => '#fdae61', 3 => '#ffffbf', 4 => '#abdda4', 5 => '#2b83ba', }, spectral6 => { 1 => '#d53e4f', 2 => '#fc8d59', 3 => '#fee08b', 4 => '#e6f598', 5 => '#99d594', 6 => '#3288bd', }, spectral7 => { 1 => '#d53e4f', 2 => '#fc8d59', 3 => '#fee08b', 4 => '#ffffbf', 5 => '#e6f598', 6 => '#99d594', 7 => '#3288bd', }, spectral8 => { 1 => '#d53e4f', 2 => '#f46d43', 3 => '#fdae61', 4 => '#fee08b', 5 => '#e6f598', 6 => '#abdda4', 7 => '#66c2a5', 8 => '#3288bd', }, spectral9 => { 1 => '#d53e4f', 2 => '#f46d43', 3 => '#fdae61', 4 => '#fee08b', 5 => '#ffffbf', 6 => '#e6f598', 7 => '#abdda4', 8 => '#66c2a5', 9 => '#3288bd', }, spectral10 => { 1 => '#9e0142', 2 => '#d53e4f', 3 => '#f46d43', 4 => '#fdae61', 5 => '#fee08b', 6 => '#e6f598', 7 => '#abdda4', 8 => '#66c2a5', 9 => '#3288bd', 10 => '#5e4fa2', }, spectral11 => { 1 => '#9e0142', 2 => '#d53e4f', 3 => '#f46d43', 4 => '#fdae61', 5 => '#fee08b', 6 => '#ffffbf', 7 => '#e6f598', 8 => '#abdda4', 9 => '#66c2a5', 10 => '#3288bd', 11 => '#5e4fa2', }, ylgn3 => { 1 => '#f7fcb9', 2 => '#addd8e', 3 => '#31a354', }, ylgn4 => { 1 => '#ffffcc', 2 => '#c2e699', 3 => '#78c679', 4 => '#238443', }, ylgn5 => { 1 => '#ffffcc', 2 => '#c2e699', 3 => '#78c679', 4 => '#31a354', 5 => '#006837', }, ylgn6 => { 1 => '#ffffcc', 2 => '#d9f0a3', 3 => '#addd8e', 4 => '#78c679', 5 => '#31a354', 6 => '#006837', }, ylgn7 => { 1 => '#ffffcc', 2 => '#d9f0a3', 3 => '#addd8e', 4 => '#78c679', 5 => '#41ab5d', 6 => '#238443', 7 => '#005a32', }, ylgn8 => { 1 => '#ffffe5', 2 => '#f7fcb9', 3 => '#d9f0a3', 4 => '#addd8e', 5 => '#78c679', 6 => '#41ab5d', 7 => '#238443', 8 => '#005a32', }, ylgn9 => { 1 => '#ffffe5', 2 => '#f7fcb9', 3 => '#d9f0a3', 4 => '#addd8e', 5 => '#78c679', 6 => '#41ab5d', 7 => '#238443', 8 => '#006837', 9 => '#004529', }, ylgnbu3 => { 1 => '#edf8b1', 2 => '#7fcdbb', 3 => '#2c7fb8', }, ylgnbu4 => { 1 => '#ffffcc', 2 => '#a1dab4', 3 => '#41b6c4', 4 => '#225ea8', }, ylgnbu5 => { 1 => '#ffffcc', 2 => '#a1dab4', 3 => '#41b6c4', 4 => '#2c7fb8', 5 => '#253494', }, ylgnbu6 => { 1 => '#ffffcc', 2 => '#c7e9b4', 3 => '#7fcdbb', 4 => '#41b6c4', 5 => '#2c7fb8', 6 => '#253494', }, ylgnbu7 => { 1 => '#ffffcc', 2 => '#c7e9b4', 3 => '#7fcdbb', 4 => '#41b6c4', 5 => '#1d91c0', 6 => '#225ea8', 7 => '#0c2c84', }, ylgnbu8 => { 1 => '#ffffd9', 2 => '#edf8b1', 3 => '#c7e9b4', 4 => '#7fcdbb', 5 => '#41b6c4', 6 => '#1d91c0', 7 => '#225ea8', 8 => '#0c2c84', }, ylgnbu9 => { 1 => '#ffffd9', 2 => '#edf8b1', 3 => '#c7e9b4', 4 => '#7fcdbb', 5 => '#41b6c4', 6 => '#1d91c0', 7 => '#225ea8', 8 => '#253494', 9 => '#081d58', }, ylorbr3 => { 1 => '#fff7bc', 2 => '#fec44f', 3 => '#d95f0e', }, ylorbr4 => { 1 => '#ffffd4', 2 => '#fed98e', 3 => '#fe9929', 4 => '#cc4c02', }, ylorbr5 => { 1 => '#ffffd4', 2 => '#fed98e', 3 => '#fe9929', 4 => '#d95f0e', 5 => '#993404', }, ylorbr6 => { 1 => '#ffffd4', 2 => '#fee391', 3 => '#fec44f', 4 => '#fe9929', 5 => '#d95f0e', 6 => '#993404', }, ylorbr7 => { 1 => '#ffffd4', 2 => '#fee391', 3 => '#fec44f', 4 => '#fe9929', 5 => '#ec7014', 6 => '#cc4c02', 7 => '#8c2d04', }, ylorbr8 => { 1 => '#ffffe5', 2 => '#fff7bc', 3 => '#fee391', 4 => '#fec44f', 5 => '#fe9929', 6 => '#ec7014', 7 => '#cc4c02', 8 => '#8c2d04', }, ylorbr9 => { 1 => '#ffffe5', 2 => '#fff7bc', 3 => '#fee391', 4 => '#fec44f', 5 => '#fe9929', 6 => '#ec7014', 7 => '#cc4c02', 8 => '#993404', 9 => '#662506', }, ylorrd3 => { 1 => '#ffeda0', 2 => '#feb24c', 3 => '#f03b20', }, ylorrd4 => { 1 => '#ffffb2', 2 => '#fecc5c', 3 => '#fd8d3c', 4 => '#e31a1c', }, ylorrd5 => { 1 => '#ffffb2', 2 => '#fecc5c', 3 => '#fd8d3c', 4 => '#f03b20', 5 => '#bd0026', }, ylorrd6 => { 1 => '#ffffb2', 2 => '#fed976', 3 => '#feb24c', 4 => '#fd8d3c', 5 => '#f03b20', 6 => '#bd0026', }, ylorrd7 => { 1 => '#ffffb2', 2 => '#fed976', 3 => '#feb24c', 4 => '#fd8d3c', 5 => '#fc4e2a', 6 => '#e31a1c', 7 => '#b10026', }, ylorrd8 => { 1 => '#ffffcc', 2 => '#ffeda0', 3 => '#fed976', 4 => '#feb24c', 5 => '#fd8d3c', 6 => '#fc4e2a', 7 => '#e31a1c', 8 => '#b10026', }, ylorrd9 => { 1 => '#ffffcc', 2 => '#ffeda0', 3 => '#fed976', 4 => '#feb24c', 5 => '#fd8d3c', 6 => '#fc4e2a', 7 => '#e31a1c', 8 => '#bd0026', 9 => '#800026', }, }; # reverse mapping value => name my $color_values = { }; my $all_color_names = { }; { # reverse mapping "#ff0000 => 'red'" # also build a list of all possible color names for my $n (keys %$color_names) { my $s = $color_names->{$n}; $color_values->{ $n } = {}; my $t = $color_values->{$n}; # sort the names on their length for my $c (sort { length($a) <=> length($b) || $a cmp $b } keys %$s) { # don't add "blue1" if it is already set as "blue" $t->{ $s->{$c} } = $c unless exists $t->{ $s->{$c} }; # mark as existing $all_color_names->{ $c } = undef; } } } our $qr_custom_attribute = qr/^x-([a-z_0-9]+-)*[a-z_0-9]+\z/; sub color_names { $color_names; } sub color_name { # return "red" for "#ff0000" my ($self,$color,$scheme) = @_; $scheme ||= 'w3c'; $color_values->{$scheme}->{$color} || $color; } sub color_value { # return "#ff0000" for "red" my ($self,$color,$scheme) = @_; $scheme ||= 'w3c'; # 'w3c/red' => 'w3c', 'red' $scheme = $1 if $color =~ s/^([a-z0-9])\///; $color_names->{$scheme}->{$color} || $color; } sub _color_scheme { # check that a given color scheme is valid my ($self, $scheme) = @_; return $scheme if $scheme eq 'inherit'; exists $color_names->{ $scheme } ? $scheme : undef; } sub _color { # Check that a given color name (like 'red'), or value (like '#ff0000') # or rgb(1,2,3) is valid. Used by valid_attribute(). # Note that for color names, the color scheme is not known here, so we # can only look if the color name is potentially possible. F.i. under # the Brewer scheme ylorrd9, '1' is a valid color name, while 'red' # would not. To resolve such conflicts, we will fallback to 'x11' # (the largest of the schemes) if the color name doesn't exist in # the current scheme. my ($self, $org_color) = @_; $org_color = lc($org_color); # color names are case insensitive $org_color =~ s/\s//g; # remove spaces to unify format my $color = $org_color; if ($color =~ s/^(w3c|[a-z]+\d{0,2})\///) { my $scheme = $1; return $org_color if exists $color_names->{$scheme}->{$color}; # if it didn't work, then fall back to x11 $scheme = 'x11'; return (exists $color_names->{$scheme}->{$color} ? $org_color : undef); } # scheme unknown, fall back to generic handling # red => red return $org_color if exists $all_color_names->{$color}; # #ff0000 => #ff0000, rgb(1,2,3) => rgb(1,2,3) defined $self->color_as_hex($color) ? $org_color : undef; } sub _hsv_to_rgb { # H=0..360, S=0..1.0, V=0..1.0 my ($h, $s, $v) = @_; my $e = 0.0001; if ($s < $e) { $v = abs(int(256 * $v)); $v = 255 if $v > 255; return ($v,$v,$v); } my ($r,$g,$b); $h *= 360; my $h1 = int($h / 60); my $f = $h / 60 - $h1; my $p = $v * (1 - $s); my $q = $v * (1 - ($s * $f)); my $t = $v * (1 - ($s * (1-$f))); if ($h1 == 0 || $h1 == 6) { $r = $v; $g = $t; $b = $p; } elsif ($h1 == 1) { $r = $q; $g = $v; $b = $p; } elsif ($h1 == 2) { $r = $p; $g = $v; $b = $t; } elsif ($h1 == 3) { $r = $p; $g = $q; $b = $v; } elsif ($h1 == 4) { $r = $t; $g = $p; $b = $v; } else { $r = $v; $g = $p; $b = $q; } # clamp values to 0.255 $r = abs(int($r*256)); $g = abs(int($g*256)); $b = abs(int($b*256)); $r = 255 if $r > 255; $g = 255 if $g > 255; $b = 255 if $b > 255; ($r,$g,$b); } sub _hsl_to_rgb { # H=0..360, S=0..100, L=0..100 my ($h, $s, $l) = @_; my $e = 0.0001; if ($s < $e) { # achromatic or grey $l = abs(int(256 * $l)); $l = 255 if $l > 255; return ($l,$l,$l); } my $t2; if ($l < 0.5) { $t2 = $l * ($s + 1); } else { $t2 = $l + $s - ($l * $s); } my $t1 = $l * 2 - $t2; my ($r,$g,$b); # 0..359 $h %= 360 if $h >= 360; # $h = 0..1 $h /= 360; my $tr = $h + 1/3; my $tg = $h; my $tb = $h - 1/3; $tr += 1 if $tr < 0; $tr -= 1 if $tr > 1; $tg += 1 if $tg < 0; $tg -= 1 if $tg > 1; $tb += 1 if $tb < 0; $tb -= 1 if $tb > 1; my $i = 0; my @temp3 = ($tr,$tg,$tb); my @rc; for my $c ($r,$g,$b) { my $t3 = $temp3[$i++]; if ($t3 < 1/6) { $c = $t1 + ($t2 - $t1) * 6 * $t3; } elsif ($t3 < 1/2) { $c = $t2; } elsif ($t3 < 2/3) { $c = $t1 + ($t2 - $t1) * 6 * (2/3 - $t3); } else { $c = $t1; } $c = int($c * 256); $c = 255 if $c > 255; push @rc, $c; } @rc; } my $factors = { 'rgb' => [ 255, 255, 255, 255 ], 'hsv' => [ 1, 1, 1, 255 ], 'hsl' => [ 360, 1, 1, 255 ], }; sub color_as_hex { # Turn "red" or rgb(255,0,0) or "#f00" into "#ff0000". Return undef for # invalid colors. my ($self,$color,$scheme) = @_; $scheme ||= 'w3c'; $color = lc($color); # 'w3c/red' => 'w3c', 'red' $scheme = $1 if $color =~ s/^([a-z0-9])\///; # convert "red" to "ffff00" return $color_names->{$scheme}->{$color} if exists $color_names->{$scheme}->{$color}; # fallback to x11 scheme if color doesn't exist return $color_names->{x11}->{$color} if exists $color_names->{x11}->{$color}; my $qr_num = qr/\s* ((?:[0-9]{1,3}%?) | # 12%, 10, 2 etc (?:[0-9]?\.[0-9]{1,5}) ) # .1, 0.1, 2.5 etc /x; # rgb(255,100%,1.0) => '#ffffff' if ($color =~ /^(rgb|hsv|hsl)\($qr_num,$qr_num,$qr_num(?:,$qr_num)?\s*\)\z/) { my $r = $2; my $g = $3; my $b = $4; my $a = $5; $a = 255 unless defined $a; my $format = $1; my $i = 0; for my $c ($r,$g,$b,$a) { # for the first value in HSL or HSV, use 360, otherwise 100. For RGB, use 255 my $factor = $factors->{$format}->[$i++]; if ($c =~ /^([0-9]+)%\z/) # 10% => 25.5 { $c = $1 * $factor / 100; } else { $c = $1 * $factor if $c =~ /^([0-9]+\.[0-9]+)\z/; # 0.1, 1.0 } } ($r,$g,$b) = Graph::Easy::_hsv_to_rgb($r,$g,$b) if $format eq 'hsv'; ($r,$g,$b) = Graph::Easy::_hsl_to_rgb($r,$g,$b) if $format eq 'hsl'; $a = int($a); $a = 255 if $a > 255; # #RRGGBB or #RRGGBBAA $color = sprintf("#%02x%02x%02x%02x", $r,$g,$b,$a); } # turn #ff0 into #ffff00 $color = "#$1$1$2$2$3$3" if $color =~ /^#([a-f0-9])([a-f0-9])([a-f[0-9])\z/; # #RRGGBBff => #RRGGBB (alpha value of 255 is the default) $color =~ s/^(#......)ff\z/$1/i; # check final color value to be #RRGGBB or #RRGGBBAA return undef unless $color =~ /^#([a-f0-9]{6}|[a-f0-9]{8})\z/i; $color; } sub text_style { # check whether the given list of textstyle attributes is valid my ($self, $style) = @_; return $style if $style =~ /^(normal|none|)\z/; my @styles = split /\s+/, $style; return undef if grep(!/^(underline|overline|line-through|italic|bold)\z/, @styles); $style; } sub text_styles { # return a hash with the defined textstyles checked my ($self) = @_; my $style = $self->attribute('textstyle'); return { none => 1 } if $style =~ /^(normal|none)\z/; return { } if $style eq ''; my $styles = {}; for my $key ( split /\s+/, $style ) { $styles->{$key} = 1; } $styles; } sub text_styles_as_css { my ($self, $align, $fontsize) = @_; my $style = ''; my $ts = $self->text_styles(); $style .= " font-style: italic;" if $ts->{italic}; $style .= " font-weight: bold;" if $ts->{bold}; if ($ts->{underline} || $ts->{none} || $ts->{overline} || $ts->{'line-through'}) { # XXX TODO: HTML does seem to allow only one of them my @s; foreach my $k (qw/underline overline line-through none/) { push @s, $k if $ts->{$k}; } my $s = join(' ', @s); $style .= " text-decoration: $s;" if $s; } my $fs = $self->raw_attribute('fontsize'); $style .= " font-size: $fs;" if $fs; if (!$align) { # XXX TODO: raw_attribute()? my $al = $self->attribute('align'); $style .= " text-align: $al;" if $al; } $style; } sub _font_size_in_pixels { my ($self, $em, $val) = @_; my $fs = $val; $fs = $self->attribute('fontsize') || '' if !defined $val; return $em if $fs eq ''; if ($fs =~ /^([\d.]+)em\z/) { $fs = $1 * $em; } elsif ($fs =~ /^([\d.]+)%\z/) { $fs = ($1 / 100) * $em; } # this is discouraged: elsif ($fs =~ /^([\d.]+)px\z/) { $fs = int($1 || 5); } else { $self->error("Illegal fontsize '$fs'"); } $fs; } # direction modifier in degrees my $modifier = { forward => 0, front => 0, left => -90, right => +90, back => +180, }; # map absolute direction to degrees my $dirs = { up => 0, north => 0, down => 180, south => 180, west => 270, east => 90, 0 => 0, 180 => 180, 90 => 90, 270 => 270, }; # map absolute direction to side (south etc) my $sides = { north => 'north', south => 'south', east => 'east', west => 'west', up => 'north', down => 'south', 0 => 'north', 180 => 'south', 90 => 'east', 270 => 'west', }; sub _direction_as_number { my ($self,$dir) = @_; my $d = $dirs->{$dir}; $self->_croak("$dir is not an absolut direction") unless defined $d; $d; } sub _direction_as_side { my ($self,$dir) = @_; return unless exists $sides->{$dir}; $sides->{$dir}; } sub _flow_as_direction { # Take a flow direction (0,90,180,270 etc), and a new direction (left|south etc) # and return the new flow. south et al will stay, while left|right etc depend # on the incoming flow. my ($self, $inflow, $dir) = @_; # in=south and dir=forward => south # in=south and dir=back => north etc # in=south and dir=east => east # return 90 unless defined $dir; if ($dir =~ /^(south|north|west|east|up|down|0|90|180|270)\z/) { # new direction is absolut, so inflow doesn't play a role # return 0,90,180 or 270 return $dirs->{$dir}; } my $in = $dirs->{$inflow}; my $modifier = $modifier->{$dir}; $self->_croak("$inflow,$dir results in undefined inflow") unless defined $in; $self->_croak("$inflow,$dir results in undefined modifier") unless defined $modifier; my $out = $in + $modifier; $out -= 360 while $out >= 360; # normalize to 0..359 $out += 360 while $out < 0; # normalize to 0..359 $out; } sub _flow_as_side { # Take a flow direction (0,90,180,270 etc), and a new direction (left|south etc) # and return the new flow. south et al will stay, while left|right etc depend # on the incoming flow. my ($self, $inflow, $dir) = @_; # in=south and dir=forward => south # in=south and dir=back => north etc # in=south and dir=east => east # return 90 unless defined $dir; if ($dir =~ /^(south|north|west|east|up|down|0|90|180|270)\z/) { # new direction is absolut, so inflow doesn't play a role # return east, west etc return $sides->{$dir}; } my $in = $dirs->{$inflow}; my $modifier = $modifier->{$dir}; $self->_croak("$inflow,$dir results in undefined inflow") unless defined $in; $self->_croak("$inflow,$dir results in undefined modifier") unless defined $modifier; my $out = $in + $modifier; $out -= 360 if $out >= 360; # normalize to 0..359 $sides->{$out}; } sub _direction { # check that a direction (south etc) is valid my ($self, $dir) = @_; $dir =~ /^(south|east|west|north|down|up|0|90|180|270|front|forward|back|left|right)\z/ ? $dir : undef; } sub _border_attribute_as_html { # Return "solid 1px red" from the individual border(style|color|width) # attributes, mainly for HTML output. my ($style, $width, $color, $scheme) = @_; $style ||= ''; $width = '' unless defined $width; $color = '' unless defined $color; $color = Graph::Easy->color_as_hex($color,$scheme)||'' if $color !~ /^#/; return $style if $style =~ /^(none|)\z/; # width: 2px for double would collapse to one line $width = '' if $style =~ /^double/; # convert the style and widths to something HTML can understand $width = '0.5em' if $style eq 'broad'; $width = '4px' if $style =~ /^bold/; $width = '1em' if $style eq 'wide'; $style = 'solid' if $style =~ /(broad|wide|bold)\z/; $style = 'dashed' if $style eq 'bold-dash'; $style = 'double' if $style eq 'double-dash'; $width = $width.'px' if $width =~ /^\s*\d+\s*\z/; return '' if $width eq '' && $style ne 'double'; my $val = join(" ", $style, $width, $color); $val =~ s/^\s+//; $val =~ s/\s+\z//; $val; } sub _border_attribute { # Return "solid 1px red" from the individual border(style|color|width) # attributes. Used by as_txt(). my ($style, $width, $color) = @_; $style ||= ''; $width = '' unless defined $width; $color = '' unless defined $color; return $style if $style =~ /^(none|)\z/; $width = $width.'px' if $width =~ /^\s*\d+\s*\z/; my $val = join(" ", $style, $width, $color); $val =~ s/^\s+//; $val =~ s/\s+\z//; $val; } sub _border_width_in_pixels { my ($self, $em) = @_; my $bw = $self->attribute('borderwidth') || '0'; return 0 if $bw eq '0'; my $bs = $self->attribute('borderstyle') || 'none'; return 0 if $bs eq 'none'; return 3 if $bs =~ /^bold/; return $em / 2 if $bs =~ /^broad/; return $em if $bs =~ /^wide/; # width: 1 is 1px; return $bw if $bw =~ /^([\d.]+)\z/; if ($bw =~ /^([\d.]+)em\z/) { $bw = $1 * $em; } elsif ($bw =~ /^([\d.]+)%\z/) { $bw = ($1 / 100) * $em; } # this is discouraged: elsif ($bw =~ /^([\d.]+)px\z/) { $bw = $1; } else { $self->error("Illegal borderwidth '$bw'"); } $bw; } sub _angle { # check an angle for being valid my ($self, $angle) = @_; return undef unless $angle =~ /^([+-]?\d{1,3}|south|west|east|north|up|down|left|right|front|back|forward)\z/; $angle; } sub _uint { # check a small unsigned integer for being valid my ($self, $val) = @_; return undef unless $val =~ /^\d+\z/; $val = abs(int($val)); $val = 4 * 1024 if $val > 4 * 1024; $val; } sub _font { # check a font-list for being valid my ($self, $font) = @_; $font; } sub split_border_attributes { # split "1px solid black" or "red dotted" into style, width and color my ($self,$border) = @_; # special case return ('none', undef, undef) if $border eq '0'; # extract style my $style; $border =~ s/(solid|dotted|dot-dot-dash|dot-dash|dashed|double-dash|double|bold-dash|bold|broad|wide|wave|none)/$style=$1;''/eg; $style ||= 'solid'; # extract width $border =~ s/(\d+(px|em|%))//g; my $width = $1 || ''; $width =~ s/[^0-9]+//g; # leave only digits $border =~ s/\s+//g; # rem unnec. spaces # The left-over part must be a valid color. my $color = $border; $color = Graph::Easy->_color($border) if $border ne ''; $self->error("$border is not a valid bordercolor") unless defined $color; $width = undef if $width eq ''; $color = undef if $color eq ''; $style = undef if $style eq ''; ($style,$width,$color); } ############################################################################# # attribute checking # different types of attributes with pre-defined handling use constant { ATTR_STRING => 0, # an arbitrary string ATTR_COLOR => 1, # color name or value like rgb(1,1,1) ATTR_ANGLE => 2, # 0 .. 359.99 ATTR_PORT => 3, # east, etc. ATTR_UINT => 4, # a "small" unsigned integer ATTR_URL => 5, # these cannot have "inherit", see ATTR_INHERIT_MIN ATTR_LIST => 6, # a list of values ATTR_LCTEXT => 7, # lowercase text (classname) ATTR_TEXT => 8, # titles, links, labels etc ATTR_NO_INHERIT => 6, ATTR_DESC_SLOT => 0, ATTR_MATCH_SLOT => 1, ATTR_DEFAULT_SLOT => 2, ATTR_EXAMPLE_SLOT => 3, ATTR_TYPE_SLOT => 4, }; # Lists the attribute names along with # * a short description, # * regexp or sub name to match valid attributes # * default value # * an short example value # * type # * graph examples my $attributes = { all => { align => [ "The alignment of the label text.", [ qw/center left right/ ], { default => 'center', group => 'left', edge => 'left' }, 'right', undef, "graph { align: left; label: My Graph; }\nnode {align: left;}\n ( Nodes:\n [ Right\\nAligned ] { align: right; } -- label\\n text -->\n { align: left; }\n [ Left\\naligned ] )", ], autolink => [ "If set to something else than 'none', will use the appropriate attribute to automatically generate the L<link>, unless L<link> is already set. See the section about labels, titles, names and links for reference.", [ qw/label title name none inherit/ ], { default => 'inherit', graph => 'none' }, 'title', ], autotitle => [ "If set to something else than 'none', will use the appropriate attribute to automatically generate the L<title>, unless L<title> is already set. See the section about labels, titles, names and links for reference.", [ qw/label name none link inherit/ ], { default => 'inherit', graph => 'none' }, 'label', ], autolabel => [ "Will restrict the L<label> text to N characters. N must be greater than 10. See the section about labels, titles, names and links for reference.", # for compatibility with older versions (pre v0.49), also allow "name,N" qr/^(name\s*,\s*)?[\d]{2,5}\z/, { default => 'inherit', graph => '' }, '20', undef, "graph { autolabel: 20; autotitle: name; }\n\n[ Bonn ]\n -- Acme Travels Incorporated -->\n [ Frankfurt (Main) / Flughafen ]", ], background => [ "The background color, e.g. the color B<outside> the shape. Do not confuse with L<fill>. If set to inherit, the object will inherit the L<fill> color (B<not> the background color!) of the parent e.g. the enclosing group or graph. See the section about color names and values for reference.", undef, # { default => 'inherit', graph => 'white', 'group.anon' => 'white', 'node.anon' => 'white' }, 'inherit', 'rgb(255,0,0)', ATTR_COLOR, "[ Crimson ] { shape: circle; background: crimson; }\n -- Aqua Marine --> { background: #7fffd4; }\n [ Misty Rose ]\n { background: white; fill: rgb(255,228,221); shape: ellipse; }", ], class => [ 'The subclass of the object. See the section about class names for reference.', qr/^(|[a-zA-Z][a-zA-Z0-9_]*)\z/, '', 'mynodeclass', ATTR_LCTEXT, ], color => [ 'The foreground/text/label color. See the section about color names and values for reference.', undef, 'black', 'rgb(255,255,0)', ATTR_COLOR, "[ Lime ] { color: limegreen; }\n -- label --> { color: blue; labelcolor: red; }\n [ Dark Orange ] { color: rgb(255,50%,0.01); }", ], colorscheme => [ "The colorscheme to use for all color values. See the section about color names and values for reference and a list of possible values.", '_color_scheme', { default => 'inherit', graph => 'w3c', }, 'x11', ATTR_STRING, "graph { colorscheme: accent8; } [ 1 ] { fill: 1; }\n" . " -> \n [ 3 ] { fill: 3; }\n" . " -> \n [ 4 ] { fill: 4; }\n" . " -> \n [ 5 ] { fill: 5; }\n" . " -> \n [ 6 ] { fill: 6; }\n" . " -> \n [ 7 ] { fill: 7; }\n" . " -> \n [ 8 ] { fill: 8; }\n" , ], comment => [ "A free-form text field containing a comment on this object. This will be embedded into output formats if possible, e.g. in HTML, SVG and Graphviz, but not ASCII or Boxart.", undef, '', '(C) by Tels 2007. All rights reserved.', ATTR_STRING, "graph { comment: German capitals; }\n [ Bonn ] --> [ Berlin ]", ], fill => [ "The fill color, e.g. the color inside the shape. For the graph, this is the background color for the label. For edges, defines the color inside the arrow shape. See also L<background>. See the section about color names and values for reference.", undef, { default => 'white', graph => 'inherit', edge => 'inherit', group => '#a0d0ff', 'group.anon' => 'white', 'node.anon' => 'inherit' }, 'rgb(255,0,0)', ATTR_COLOR, "[ Crimson ]\n {\n shape: circle;\n background: yellow;\n fill: red;\n border: 3px solid blue;\n }\n-- Aqua Marine -->\n {\n arrowstyle: filled;\n fill: red;\n }\n[ Two ]", ], 'fontsize' => [ "The size of the label text, best expressed in I<em> (1.0em, 0.5em etc) or percent (100%, 50% etc)", qr/^\d+(\.\d+)?(em|px|%)?\z/, { default => '0.8em', graph => '1em', node => '1em', }, '50%', undef, "graph { fontsize: 200%; label: Sample; }\n\n ( Nodes:\n [ Big ] { fontsize: 1.5em; color: white; fill: darkred; }\n -- Small -->\n { fontsize: 0.2em; }\n [ Normal ] )", ], flow => [ "The general direction in which edges will leave nodes first. On edges, influeces where the target node is place. Please see the section about <a href='hinting.html#flow'>flow control</a> for reference.", '_direction', { graph => 'east', default => 'inherit' }, 'south', undef, "graph { flow: up; }\n [ Enschede ] { flow: left; } -> [ Bielefeld ] -> [ Wolfsburg ]", ], font => [ 'A prioritized list of lower-case, unquoted values, separated by a comma. Values are either font family names (like "times", "arial" etc) or generic family names (like "serif", "cursive", "monospace"), the first recognized value will be used. Always offer a generic name as the last possibility.', '_font', { default => 'serif', edge => 'sans-serif' }, 'arial, helvetica, sans-serif', undef, "graph { font: vinque, georgia, utopia, serif; label: Sample; }" . "\n\n ( Nodes:\n [ Webdings ] { font: Dingbats, webdings; }\n". " -- FlatLine -->\n { font: flatline; }\n [ Normal ] )", ], id => [ "A unique identifier for this object, consisting only of letters, digits, or underscores.", qr/^[a-zA-Z0-9_]+\z/, '', 'Bonn123', undef, "[ Bonn ] --> { id: 123; } [ Berlin ]", ], label => [ "The text displayed as label. If not set, equals the name (for nodes) or no label (for edges, groups and the graph itself).", undef, undef, 'My label', ATTR_TEXT, ], linkbase => [ 'The base URL prepended to all generated links. See the section about links for reference.', undef, { default => 'inherit', graph => '/wiki/index.php/', }, 'http://en.wikipedia.org/wiki/', ATTR_URL, ], link => [ 'The link part, appended onto L<linkbase>. See the section about links for reference.', undef, '', 'Graph', ATTR_TEXT, <<LINK_EOF node { autolink: name; textstyle: none; fontsize: 1.1em; } graph { linkbase: http://de.wikipedia.org/wiki/; } edge { textstyle: overline; } [] --> [ Friedrichshafen ] -- Schiff --> { autolink: label; color: orange; title: Vrooom!; } [ Immenstaad ] { color: green; } --> [ Hagnau ] LINK_EOF ], title => [ "The text displayed as mouse-over for nodes/edges, or as the title for the graph. If empty, no title will be generated unless L<autotitle> is set.", undef, '', 'My title', ATTR_TEXT, ], format => [ "The formatting language of the label. The default, C<none> means nothing special will be done. When set to C<pod>, formatting codes like <code>B&lt;bold&gt;</code> will change the formatting of the label. See the section about label text formatting for reference.", [ 'none', 'pod' ], 'none', 'pod', undef, <<EOF graph { format: pod; label: I am B<bold> and I<italic>; } node { format: pod; } edge { format: pod; } [ U<B<bold and underlined>> ] --> { label: "S<Fähre>"; } [ O<Konstanz> ] EOF ], textstyle => [ "The style of the label text. Either 'none', or any combination (separated with spaces) of 'underline', 'overline', 'bold', 'italic', 'line-through'. 'none' disables underlines on links.", 'text_style', '', 'underline italic bold', undef, <<EOF graph { fontsize: 150%; label: Verbindung; textstyle: bold italic; } node { textstyle: underline bold; fill: #ffd080; } edge { textstyle: italic bold overline; } [ Meersburg ] { fontsize: 2em; } -- F\x{e4}hre --> { fontsize: 1.2em; color: red; } [ Konstanz ] EOF ], textwrap => [ "The default C<none> makes the label text appear exactly as it was written, with <a href='syntax.html'>manual line breaks</a> applied. When set to a positive number, the label text will be wrapped after this number of characters. When set to C<auto>, the label text will be wrapped to make the node size as small as possible, depending on output format this may even be dynamic. When not C<none>, manual line breaks and alignments on them are ignored.", qr/^(auto|none|\d{1,4})/, { default => 'inherit', graph => 'none' }, 'auto', undef, "node { textwrap: auto; }\n ( Nodes:\n [ Frankfurt (Oder) liegt an der\n ostdeutschen Grenze und an der Oder ] -->\n [ Städte innerhalb der\n Ost-Westfahlen Region mit sehr langen Namen] )", ], }, node => { bordercolor => [ 'The color of the L<border>. See the section about color names and values for reference.', undef, { default => '#000000' }, 'rgb(255,255,0)', ATTR_COLOR, "node { border: black bold; }\n[ Black ]\n --> [ Red ] { bordercolor: red; }\n --> [ Green ] { bordercolor: green; }", ], borderstyle => [ 'The style of the L<border>. The special styles "bold", "broad", "wide", "double-dash" and "bold-dash" will set and override the L<borderwidth>.', [ qw/none solid dotted dashed dot-dash dot-dot-dash double wave bold bold-dash broad double-dash wide/ ], { default => 'none', 'node.anon' => 'none', 'group.anon' => 'none', node => 'solid', group => 'dashed' }, 'dotted', undef, "node { border: dotted; }\n[ Dotted ]\n --> [ Dashed ] { borderstyle: dashed; }\n --> [ broad ] { borderstyle: broad; }", ], borderwidth => [ 'The width of the L<border>. Certain L<border>-styles will override the width.', qr/^\d+(px|em)?\z/, '1', '2px', ], border => [ 'The border. Can be any combination of L<borderstyle>, L<bordercolor> and L<borderwidth>.', undef, { default => 'none', 'node.anon' => 'none', 'group.anon' => 'none', node => 'solid 1px #000000', group => 'dashed 1px #000000' }, 'dotted red', undef, "[ Normal ]\n --> [ Bold ] { border: bold; }\n --> [ Broad ] { border: broad; }\n --> [ Wide ] { border: wide; }\n --> [ Bold-Dash ] { border: bold-dash; }", ], basename => [ "Controls the base name of an autosplit node. Ignored for all other nodes. Unless set, it is generated automatically from the node parts. Please see the section about <a href='hinting.html#autosplit'>autosplit</a> for reference.", undef, '', '123', undef, "[ A|B|C ] { basename: A } [ 1 ] -> [ A.2 ]\n [ A|B|C ] [ 2 ] -> [ ABC.2 ]", ], group => [ "Puts the node into this group.", undef, '', 'Cities', undef, "[ A ] { group: Cities:; } ( Cities: [ B ] ) [ A ] --> [ B ]", ], size => [ 'The size of the node in columns and rows. Must be greater than 1 in each direction.', qr/^\d+\s*,\s*\d+\z/, '1,1', '3,2', ], rows => [ 'The size of the node in rows. See also L<size>.', qr/^\d+\z/, '1', '3', ], columns => [ 'The size of the node in columns. See also L<size>.', qr/^\d+\z/, '1', '2', ], offset => [ 'The offset of this node from the L<origin> node, in columns and rows. Only used if you also set the L<origin> node.', qr/^[+-]?\d+\s*,\s*[+-]?\d+\z/, '0,0', '3,2', undef, "[ A ] -> [ B ] { origin: A; offset: 2,2; }", ], origin => [ 'The name of the node, that this node is relativ to. See also L<offset>.', undef, '', 'Cluster A', ], pointshape => [ "Controls the style of a node that has a L<shape> of 'point'.", [ qw/star square dot circle cross diamond invisible x/ ], 'star', 'square', undef, "node { shape: point; }\n\n [ A ]". "\n -> [ B ] { pointshape: circle; }" . "\n -> [ C ] { pointshape: cross; }" . "\n -> [ D ] { pointshape: diamond; }" . "\n -> [ E ] { pointshape: dot; }" . "\n -> [ F ] { pointshape: invisible; }" . "\n -> [ G ] { pointshape: square; }" . "\n -> [ H ] { pointshape: star; }" . "\n -> [ I ] { pointshape: x; }" . "\n -> [ ☯ ] { shape: none; }" ], pointstyle => [ "Controls the style of the L<pointshape> of a node that has a L<shape> of 'point'. " . "Note for backwards compatibility reasons, the shape names 'star', 'square', 'dot', 'circle', 'cross', 'diamond' and 'invisible' ". "are also supported, but should not be used here, instead set them via L<pointshape>.", [ qw/closed filled star square dot circle cross diamond invisible x/ ], 'filled', 'open', undef, "node { shape: point; pointstyle: closed; pointshape: diamond; }\n\n [ A ] --> [ B ] { pointstyle: filled; }", ], rank => [ "The rank of the node, used by the layouter to find the order and placement of nodes. " . "Set to C<auto> (the default), C<same> (usefull for node lists) or a positive number. " . "See the section about ranks for reference and more examples.", qr/^(auto|same|\d{1,6})\z/, 'auto', 'same', undef, "[ Bonn ], [ Berlin ] { rank: same; }\n [ Bonn ] -> [ Cottbus ] -> [ Berlin ]", ], rotate => [ "The rotation of the node shape, either an absolute value (like C<south>, C<up>, C<down> or C<123>), or a relative value (like C<+12>, C<-90>, C<left>, C<right>). For relative angles, the rotation will be based on the node's L<flow>. Rotation is clockwise.", undef, '0', '180', ATTR_ANGLE, "[ Bonn ] { rotate: 45; } -- ICE --> \n [ Berlin ] { shape: triangle; rotate: -90; }", ], shape => [ "The shape of the node. Nodes with shape 'point' (see L<pointshape>) have a fixed size and do not display their label. The border of such a node is the outline of the C<pointshape>, and the fill is the inside of the C<pointshape>. When the C<shape> is set to the value 'img', the L<label> will be interpreted as an external image resource to display. In this case attributes like L<color>, L<fontsize> etc. are ignored.", [ qw/ circle diamond edge ellipse hexagon house invisible invhouse invtrapezium invtriangle octagon parallelogram pentagon point triangle trapezium septagon rect rounded none img/ ], 'rect', 'circle', undef, "[ Bonn ] -> \n [ Berlin ] { shape: circle; }\n -> [ Regensburg ] { shape: rounded; }\n -> [ Ulm ] { shape: point; }\n -> [ Wasserburg ] { shape: invisible; }\n -> [ Augsburg ] { shape: triangle; }\n -> [ House ] { shape: img; label: img/house.png;\n border: none; title: My House; fill: inherit; }", ], }, # node graph => { bordercolor => [ 'The color of the L<border>. See the section about color names and values for reference.', undef, { default => '#000000' }, 'rgb(255,255,0)', ATTR_COLOR, "node { border: black bold; }\n[ Black ]\n --> [ Red ] { bordercolor: red; }\n --> [ Green ] { bordercolor: green; }", ], borderstyle => [ 'The style of the L<border>. The special styles "bold", "broad", "wide", "double-dash" and "bold-dash" will set and override the L<borderwidth>.', [ qw/none solid dotted dashed dot-dash dot-dot-dash double wave bold bold-dash broad double-dash wide/ ], { default => 'none', 'node.anon' => 'none', 'group.anon' => 'none', node => 'solid', group => 'dashed' }, 'dotted', undef, "node { border: dotted; }\n[ Dotted ]\n --> [ Dashed ] { borderstyle: dashed; }\n --> [ broad ] { borderstyle: broad; }", ], borderwidth => [ 'The width of the L<border>. Certain L<border>-styles will override the width.', qr/^\d+(px|em)?\z/, '1', '2px', ], border => [ 'The border. Can be any combination of L<borderstyle>, L<bordercolor> and L<borderwidth>.', undef, { default => 'none', 'node.anon' => 'none', 'group.anon' => 'none', node => 'solid 1px #000000', group => 'dashed 1px #000000' }, 'dotted red', undef, "[ Normal ]\n --> [ Bold ] { border: bold; }\n --> [ Broad ] { border: broad; }\n --> [ Wide ] { border: wide; }\n --> [ Bold-Dash ] { border: bold-dash; }", ], gid => [ "A unique ID for the graph. Usefull if you want to include two graphs into one HTML page.", qr/^\d+\z/, '', '123', ], labelpos => [ "The position of the graph label.", [ qw/top bottom/ ], 'top', 'bottom', ATTR_LIST, "graph { labelpos: bottom; label: My Graph; }\n\n [ Buxtehude ] -> [ Fuchsberg ]\n" ], output => [ "The desired output format. Only used when calling Graph::Easy::output(), or by mediawiki-graph.", [ qw/ascii html svg graphviz boxart debug/ ], '', 'ascii', ATTR_LIST, "graph { output: debug; }" ], root => [ "The name of the root node, given as hint to the layouter to start the layout there. When not set, the layouter will pick a node at semi-random.", undef, '', 'My Node', ATTR_TEXT, "graph { root: B; }\n # B will be at the left-most place\n [ A ] --> [ B ] --> [ C ] --> [ D ] --> [ A ]", ], type => [ "The type of the graph, either undirected or directed.", [ qw/directed undirected/ ], 'directed', 'undirected', ATTR_LIST, "graph { type: undirected; }\n [ A ] --> [ B ]", ], }, # graph edge => { style => [ 'The line style of the edge. When set on the general edge class, this attribute changes only the style of all solid edges to the specified one.', [ qw/solid dotted dashed dot-dash dot-dot-dash bold bold-dash double-dash double wave broad wide invisible/], # broad-dash wide-dash/ ], 'solid', 'dotted', undef, "[ A ] -- solid --> [ B ]\n .. dotted ..> [ C ]\n - dashed - > [ D ]\n -- bold --> { style: bold; } [ E ]\n -- broad --> { style: broad; } [ F ]\n -- wide --> { style: wide; } [ G ]", ], arrowstyle => [ 'The style of the arrow. Open arrows are vee-shaped and the bit inside the arrow has the color of the L<background>. Closed arrows are triangle shaped, with a background-color fill. Filled arrows are closed, too, but use the L<fill> color for the inside. If the fill color is not set, the L<color> attribute will be used instead. An C<arrowstyle> of none creates undirected edges just like "[A] -- [B]" would do.', [ qw/none open closed filled/ ], 'open', 'closed', undef, "[ A ] -- open --> [ B ]\n -- closed --> { arrowstyle: closed; } [ C ]\n -- filled --> { arrowstyle: filled; } [ D ]\n -- filled --> { arrowstyle: filled; fill: lime; } [ E ]\n -- none --> { arrowstyle: none; } [ F ]", ], arrowshape => [ 'The basic shape of the arrow. Can be combined with each of L<arrowstyle>.', [ qw/triangle box dot inv line diamond cross x/ ], 'triangle', 'box', undef, "[ A ] -- triangle --> [ B ]\n -- box --> { arrowshape: box; } [ C ]\n" . " -- inv --> { arrowshape: inv; } [ D ]\n -- diamond --> { arrowshape: diamond; } [ E ]\n" . " -- dot --> { arrowshape: dot; } [ F ]\n" . " -- line --> { arrowshape: line; } [ G ] \n" . " -- plus --> { arrowshape: cross; } [ H ] \n" . " -- x --> { arrowshape: x; } [ I ] \n\n" . "[ a ] -- triangle --> { arrowstyle: filled; } [ b ]\n". " -- box --> { arrowshape: box; arrowstyle: filled; } [ c ]\n" . " -- inv --> { arrowshape: inv; arrowstyle: filled; } [ d ]\n" . " -- diamond --> { arrowshape: diamond; arrowstyle: filled; } [ e ]\n" . " -- dot --> { arrowshape: dot; arrowstyle: filled; } [ f ]\n" . " -- line --> { arrowshape: line; arrowstyle: filled; } [ g ] \n" . " -- plus --> { arrowshape: cross; arrowstyle: filled; } [ h ] \n" . " -- x --> { arrowshape: x; arrowstyle: filled; } [ i ] \n", ], labelcolor => [ 'The text color for the label. If unspecified, will fall back to L<color>. See the section about color names and values for reference.', undef, 'black', 'rgb(255,255,0)', ATTR_COLOR, "[ Bonn ] -- ICE --> { labelcolor: blue; }\n [ Berlin ]", ], start => [ 'The starting port of this edge. See <a href="hinting.html#joints">the section about joints</a> for reference.', qr/^(south|north|east|west|left|right|front|back)(\s*,\s*-?\d{1,4})?\z/, '', 'front, 0', ATTR_PORT, "[ Bonn ] -- NORTH --> { start: north; end: north; } [ Berlin ]", ], end => [ 'The ending port of this edge. See <a href="hinting.html#joints">the section about joints</a> for reference.', qr/^(south|north|east|west|right|left|front|back)(\s*,\s*-?\d{1,4})?\z/, '', 'back, 0', ATTR_PORT, "[ Bonn ] -- NORTH --> { start: south; end: east; } [ Berlin ]", ], minlen => [ 'The minimum length of the edge, in cells. Defaults to 1. The minimum length is ' . 'automatically increased for edges with joints.', undef, '1', '4', ATTR_UINT, "[ Bonn ] -- longer --> { minlen: 3; } [ Berlin ]\n[ Bonn ] --> [ Potsdam ] { origin: Bonn; offset: 2,2; }", ], autojoin => [ 'Controls whether the layouter can join this edge automatically with other edges leading to the same node. C<never> means this edge will never joined with another edge automatically, C<always> means always (if possible), even if the attributes on the edges do not match. C<equals> means only edges with the same set of attributes will be automatically joined together. See also C<autosplit>.', [qw/never always equals/], 'never', 'always', undef, "[ Bonn ], [ Aachen ]\n -- 1 --> { autojoin: equals; } [ Berlin ]", ], autosplit => [ 'Controls whether the layouter replace multiple edges leading from one node to other nodes with one edge splitting up. C<never> means this edge will never be part of such a split, C<always> means always (if possible), even if the attributes on the edges do not match. C<equals> means only edges with the same set of attributes will be automatically split up. See also C<autojoin>.', [qw/never always equals/], 'never', 'always', undef, "[ Bonn ]\n -- 1 --> { autosplit: equals; } [ Berlin ], [ Aachen ]", ], }, # edge group => { bordercolor => [ 'The color of the L<border>. See the section about color names and values for reference.', undef, { default => '#000000' }, 'rgb(255,255,0)', ATTR_COLOR, "node { border: black bold; }\n[ Black ]\n --> [ Red ] { bordercolor: red; }\n --> [ Green ] { bordercolor: green; }", ], borderstyle => [ 'The style of the L<border>. The special styles "bold", "broad", "wide", "double-dash" and "bold-dash" will set and override the L<borderwidth>.', [ qw/none solid dotted dashed dot-dash dot-dot-dash double wave bold bold-dash broad double-dash wide/ ], { default => 'none', 'node.anon' => 'none', 'group.anon' => 'none', node => 'solid', group => 'dashed' }, 'dotted', undef, "node { border: dotted; }\n[ Dotted ]\n --> [ Dashed ] { borderstyle: dashed; }\n --> [ broad ] { borderstyle: broad; }", ], borderwidth => [ 'The width of the L<border>. Certain L<border>-styles will override the width.', qr/^\d+(px|em)?\z/, '1', '2px', ], border => [ 'The border. Can be any combination of L<borderstyle>, L<bordercolor> and L<borderwidth>.', undef, { default => 'none', 'node.anon' => 'none', 'group.anon' => 'none', node => 'solid 1px #000000', group => 'dashed 1px #000000' }, 'dotted red', undef, "[ Normal ]\n --> [ Bold ] { border: bold; }\n --> [ Broad ] { border: broad; }\n --> [ Wide ] { border: wide; }\n --> [ Bold-Dash ] { border: bold-dash; }", ], nodeclass => [ 'The class into which all nodes of this group are put.', qr/^(|[a-zA-Z][a-zA-Z0-9_]*)\z/, '', 'cities', ], edgeclass => [ 'The class into which all edges defined in this group are put. This includes edges that run between two nodes belonging to the same group.', qr/^(|[a-zA-Z][a-zA-Z0-9_]*)\z/, '', 'connections', ], rank => [ "The rank of the group, used by the layouter to find the order and placement of group. " . "Set to C<auto> (the default), C<same> or a positive number. " . "See the section about ranks for reference and more examples.", qr/^(auto|same|\d{1,6})\z/, 'auto', 'same', undef, "( Cities: [ Bonn ], [ Berlin ] ) { rank: 0; } ( Rivers: [ Rhein ], [ Sieg ] ) { rank: 0; }", ], root => [ "The name of the root node, given as hint to the layouter to start the layout there. When not set, the layouter will pick a node at semi-random.", undef, '', 'My Node', ATTR_TEXT, "( Cities: [ A ] --> [ B ] --> [ C ] --> [ D ] --> [ A ] ) { root: B; }", ], group => [ "Puts the group inside this group, nesting the two groups inside each other.", undef, '', 'Cities', undef, "( Cities: [ Bonn ] ) ( Rivers: [ Rhein ] ) { group: Cities:; }", ], labelpos => [ "The position of the group label.", [ qw/top bottom/ ], 'top', 'bottom', ATTR_LIST, "group { labelpos: bottom; }\n\n ( My Group: [ Buxtehude ] -> [ Fuchsberg ] )\n" ], }, # group # These entries will be allowed temporarily during Graphviz parsing for # intermidiate values, like "shape=record". special => { }, }; # end of attribute definitions sub _allow_special_attributes { # store a hash with special temp. attributes my ($self, $att) = @_; $attributes->{special} = $att; } sub _drop_special_attributes { # drop the hash with special temp. attributes my ($self) = @_; $attributes->{special} = {}; } sub _attribute_entries { # for building the manual page $attributes; } sub border_attribute { # Return "1px solid red" from the border-(style|color|width) attributes, # mainly used by as_txt() output. Does not use colorscheme! my ($self, $class) = @_; my ($style,$width,$color); my $g = $self; $g = $self->{graph} if ref($self->{graph}); my ($def_style, $def_color, $def_width); # XXX TODO need no_default_attribute() if (defined $class) { $style = $g->attribute($class, 'borderstyle'); return $style if $style eq 'none'; $def_style = $g->default_attribute('borderstyle'); $width = $g->attribute($class,'borderwidth'); $def_width = $g->default_attribute($class,'borderwidth'); $width = '' if $def_width eq $width; $color = $g->attribute($class,'bordercolor'); $def_color = $g->default_attribute($class,'bordercolor'); $color = '' if $def_color eq $color; } else { $style = $self->attribute('borderstyle'); return $style if $style eq 'none'; $def_style = $self->default_attribute('borderstyle'); $width = $self->attribute('borderwidth'); $def_width = $self->default_attribute('borderwidth'); $width = '' if $def_width eq $width; $color = $self->attribute('bordercolor'); $def_color = $self->default_attribute('bordercolor'); $color = '' if $def_color eq $color; } return '' if $def_style eq $style and $color eq '' && $width eq ''; Graph::Easy::_border_attribute($style, $width, $color); } sub _unknown_attribute { # either just warn, or raise an error for unknown attributes my ($self, $name, $class) = @_; if ($self->{_warn_on_unknown_attributes}) { $self->warn("Ignoring unknown attribute '$name' for class $class") } else { $self->error("Error in attribute: '$name' is not a valid attribute name for a $class"); } return; } sub default_attribute { # Return the default value for the attribute. my ($self, $class, $name) = @_; # allow $self->default_attribute('fill'); if (scalar @_ == 2) { $name = $class; $class = $self->{class} || 'graph'; } # get the base class: node.foo => node my $base_class = $class; $base_class =~ s/\..*//; # Remap alias names without "-" to their hyphenated version: $name = $att_aliases->{$name} if exists $att_aliases->{$name}; # "x-foo-bar" is a custom attribute, so allow it always. The name must # consist only of letters and hyphens, and end in a letter or number. # Hyphens must be separated by letters. Custom attributes do not have a default. return '' if $name =~ $qr_custom_attribute; # prevent ->{special}->{node} from springing into existance my $s = $attributes->{special}; $s = $s->{$class} if exists $s->{$class}; my $entry = $s->{$name} || $attributes->{all}->{$name} || $attributes->{$base_class}->{$name}; # Didn't found an entry: return $self->_unknown_attribute($name,$class) unless ref($entry); # get the default attribute from the entry my $def = $entry->[ ATTR_DEFAULT_SLOT ]; my $val = $def; # "node.subclass" gets the default from "node", 'edge' from 'default': # " { default => 'foo', 'node.anon' => 'none', node => 'solid' }": if (ref $def) { $val = $def->{$class}; $val = $def->{$base_class} unless defined $val; $val = $def->{default} unless defined $val; } $val; } sub raw_attribute { # Return either the raw attribute set on an object (honoring inheritance), # or undef for when that specific attribute is not set. Does *not* # inspect class attributes. my ($self, $name) = @_; # Remap alias names without "-" to their hyphenated version: $name = $att_aliases->{$name} if exists $att_aliases->{$name}; my $class = $self->{class} || 'graph'; my $base_class = $class; $base_class =~ s/\..*//; # prevent ->{special}->{node} from springing into existance my $s = $attributes->{special}; $s = $s->{$class} if exists $s->{$class}; my $entry = $s->{$name} || $attributes->{all}->{$name} || $attributes->{$base_class}->{$name}; # create a fake entry for custom attributes $entry = [ '', undef, '', '', ATTR_STRING, '' ] if $name =~ $qr_custom_attribute; # Didn't found an entry: return $self->_unknown_attribute($name,$class) unless ref($entry); my $type = $entry->[ ATTR_TYPE_SLOT ] || ATTR_STRING; my $val; ########################################################################### # Check the object directly first my $a = $self->{att}; if (exists $a->{graph}) { # for graphs, look directly in the class to save time: $val = $a->{graph}->{$name} if exists $a->{graph}->{$name}; } else { $val = $a->{$name} if exists $a->{$name}; } # For "background", and objects that are in a group, we inherit "fill": $val = $self->{group}->color_attribute('fill') if $name eq 'background' && ref $self->{group}; return $val if !defined $val || $val ne 'inherit' || $name =~ /^x-([a-z_]+-)*[a-z_]+([0-9]*)\z/; # $val is defined, and "inherit" (and it is not a special attribute) # for graphs, there is nothing to inherit from return $val if $class eq 'graph'; # we try classes in this order: # "node", "graph" my @tries = (); # if the class is already "node", skip it: if ($class =~ /\./) { my $parent_class = $class; $parent_class =~ s/\..*//; push @tries, $parent_class; } # If not part of a graph, we cannot have class attributes, but # we still can find default attributes. So fake a "graph": my $g = $self->{graph}; # for objects in a graph $g = { att => {} } unless ref($g); # for objects not in a graph $val = undef; for my $try (@tries) { # print STDERR "# Trying class $try for attribute $name\n"; my $att = $g->{att}->{$try}; $val = $att->{$name} if exists $att->{$name}; # value was not defined, so get the default value if (!defined $val) { my $def = $entry->[ ATTR_DEFAULT_SLOT ]; $val = $def; # "node.subclass" gets the default from "node", 'edge' from 'default': # " { default => 'foo', 'node.anon' => 'none', node => 'solid' }": if (ref $def) { $val = $def->{$try}; if (!defined $val && $try =~ /\./) { my $base = $try; $base =~ s/\..*//; $val = $def->{$base}; } $val = $def->{default} unless defined $val; } } # $val must now be defined, because default value must exist. # print STDERR "# Found '$val' for $try\n"; if ($name ne 'label') { $self->warn("Uninitialized default for attribute '$name' on class '$try'\n") unless defined $val; } return $val if $type >= ATTR_NO_INHERIT; # got some value other than inherit or already at top of tree: return $val if defined $val && $val ne 'inherit'; # try next class in inheritance tree $val = undef; } $val; } sub color_attribute { # Just like get_attribute(), but for colors, and returns them as hex, # using the current colorscheme. my $self = shift; my $color = $self->attribute(@_); if ($color !~ /^#/ && $color ne '') { my $scheme = $self->attribute('colorscheme'); $color = Graph::Easy->color_as_hex($color, $scheme); } $color; } sub raw_color_attribute { # Just like raw_attribute(), but for colors, and returns them as hex, # using the current colorscheme. my $self = shift; my $color = $self->raw_attribute(@_); return undef unless defined $color; # default to undef if ($color !~ /^#/ && $color ne '') { my $scheme = $self->attribute('colorscheme'); $color = Graph::Easy->color_as_hex($color, $scheme); } $color; } sub _attribute_entry { # return the entry defining an attribute, based on the attribute name my ($self, $class, $name) = @_; # font-size => fontsize $name = $att_aliases->{$name} if exists $att_aliases->{$name}; my $base_class = $class; $base_class =~ s/\.(.*)//; # prevent ->{special}->{node} from springing into existance my $s = $attributes->{special}; $s = $s->{$class} if exists $s->{$class}; my $entry = $s->{$name} || $attributes->{all}->{$name} || $attributes->{$base_class}->{$name}; $entry; } sub attribute { my ($self, $class, $name) = @_; my $three_arg = 0; if (scalar @_ == 3) { # $self->attribute($class,$name) if only allowed on graphs return $self->error("Calling $self->attribute($class,$name) only allowed for graphs") if exists $self->{graph}; if ($class !~ /^(node|group|edge|graph\z)/) { return $self->error ("Illegal class '$class' when trying to get attribute '$name'"); } $three_arg = 1; return $self->border_attribute($class) if $name eq 'border'; # virtual attribute } else { # allow calls of the style get_attribute('background'); $name = $class; $class = $self->{class} || 'graph' if $name eq 'class'; # avoid deep recursion if ($name ne 'class') { $class = $self->{cache}->{class}; $class = $self->class() unless defined $class; } return $self->border_attribute() if $name eq 'border'; # virtual attribute return join (",",$self->size()) if $name eq 'size'; # virtual attribute } # print STDERR "# called attribute($class,$name)\n"; # font-size => fontsize $name = $att_aliases->{$name} if exists $att_aliases->{$name}; my $base_class = $class; $base_class =~ s/\.(.*)//; my $sub_class = $1; $sub_class = '' unless defined $sub_class; if ($name eq 'class') { # "[A] { class: red; }" => "red" return $sub_class if $sub_class ne ''; # "node { class: green; } [A]" => "green": fall through and let the code # below look up the attribute or fall back to the default '': } # prevent ->{special}->{node} from springing into existance my $s = $attributes->{special}; $s = $s->{$class} if exists $s->{$class}; my $entry = $s->{$name} || $attributes->{all}->{$name} || $attributes->{$base_class}->{$name}; # create a fake entry for custom attributes $entry = [ '', undef, '', '', ATTR_STRING, '' ] if $name =~ $qr_custom_attribute; # Didn't found an entry: return $self->_unknown_attribute($name,$class) unless ref($entry); my $type = $entry->[ ATTR_TYPE_SLOT ] || ATTR_STRING; my $val; if ($three_arg == 0) { ########################################################################### # Check the object directly first my $a = $self->{att}; if (exists $a->{graph}) { # for graphs, look directly in the class to save time: $val = $a->{graph}->{$name} if exists $a->{graph}->{$name}; } else { $val = $a->{$name} if exists $a->{$name}; } # For "background", and objects that are in a group, we inherit "fill": if ($name eq 'background' && $val && $val eq 'inherit') { my $parent = $self->parent(); $val = $parent->color_attribute('fill') if $parent && $parent != $self; } # XXX BENCHMARK THIS return $val if defined $val && # no inheritance ("inherit" is just a normal string value) ($type >= ATTR_NO_INHERIT || # no inheritance since value is something else like "red" $val ne 'inherit' || # for graphs, there is nothing to inherit from $class eq 'graph'); } # $val not defined, or 'inherit' ########################################################################### # Check the classes now # print STDERR "# Called self->attribute($class,$name) (#2)\n"; # we try them in this order: # node.subclass, node, graph # print STDERR "# $self->{name} class=$class ", join(" ", caller),"\n" if $name eq 'align'; my @tries = (); # skip "node.foo" if value is 'inherit' push @tries, $class unless defined $val; push @tries, $base_class if $class =~ /\./; push @tries, 'graph' unless @tries && $tries[-1] eq 'graph'; # If not part of a graph, we cannot have class attributes, but # we still can find default attributes. So fake a "graph": my $g = $self->{graph}; # for objects in a graph $g = { att => {} } unless ref($g); # for objects not in a graph # XXX TODO should not happen $g = $self if $self->{class} eq 'graph'; # for the graph itself $val = undef; TRY: for my $try (@tries) { # print STDERR "# Trying class $try for attribute $name\n" if $name eq 'align'; my $att = $g->{att}->{$try}; $val = $att->{$name} if exists $att->{$name}; # value was not defined, so get the default value (but not for subclasses!) if (!defined $val) { my $def = $entry->[ ATTR_DEFAULT_SLOT ]; $val = $def; # "node.subclass" gets the default from "node", 'edge' from 'default': # " { default => 'foo', 'node.anon' => 'none', node => 'solid' }": if (ref $def) { $val = $def->{$try}; if (!defined $val && $try =~ /\./) { my $base = $try; $base =~ s/\..*//; $val = $def->{$base}; } # if this is not a subclass, get the default value next TRY if !defined $val && $try =~ /\./; $val = $def->{default} unless defined $val; } } # $val must now be defined, because default value must exist. # print STDERR "# Found '$val' for $try ($class)\n" if $name eq 'color'; if ($name ne 'label') { $self->warn("Uninitialized default for attribute '$name' on class '$try'\n") unless defined $val; } return $val if $type >= ATTR_NO_INHERIT; # got some value other than inherit or already at top of tree: last if defined $val && ($val ne 'inherit' || $try eq 'graph'); # try next class in inheritance tree $val = undef; } # For "background", and objects that are in a group, we inherit "fill": if ($name eq 'background' && $val && $val eq 'inherit') { my $parent = $self->parent(); $val = $parent->color_attribute('fill') if $parent && $parent != $self; } # If we fell through here, $val is 'inherit' for graph. That happens # for instance for 'background': $val; } sub unquote_attribute { # The parser leaves quotes and escapes in the attribute, these things # are only removed upon storing the attribute at the object/class. # Return the attribute unquoted (remove quotes on labels, links etc). my ($self,$class,$name,$val) = @_; # clean quoted strings # XXX TODO # $val =~ s/^["'](.*[^\\])["']\z/$1/; $val =~ s/^["'](.*)["']\z/$1/; $val =~ s/\\([#"';\\])/$1/g; # reverse backslashed chars # remove any %00-%1f, %7f and high-bit chars to avoid exploits and problems $val =~ s/%[^2-7][a-fA-F0-9]|%7f//g; # decode %XX entities $val =~ s/%([2-7][a-fA-F0-9])/sprintf("%c",hex($1))/eg; $val; } sub valid_attribute { # Only for compatibility, use validate_attribute()! # Check that an name/value pair is an valid attribute, returns: # scalar value: valid, new attribute # undef: not valid # []: unknown attribute (might also warn) my ($self, $name, $value, $class) = @_; my ($error,$newname,$v) = $self->validate_attribute($name,$value,$class); return [] if defined $error && $error == 1; return undef if defined $error && $error == 2; $v; } sub validate_attribute { # Check that an name/value pair is an valid attribute, returns: # $error, $newname, @values # A possible new name is in $newname, this is f.i. used to convert # "font-size" # to "fontsize". # Upon errors, $error contains the error code: # undef: all went well # 1 unknown attribute name # 2 invalid attribute value # 4 found multiple attributes, but these aren't # allowed at this place my ($self, $name, $value, $class, $no_multiples) = @_; $self->error("Got reference $value as value, but expected scalar") if ref($value); $self->error("Got reference $name as name, but expected scalar") if ref($name); # "x-foo-bar" is a custom attribute, so allow it always. The name must # consist only of letters and hyphens, and end in a letter. Hyphens # must be separated by letters. return (undef, $name, $value) if $name =~ $qr_custom_attribute; $class = 'all' unless defined $class; $class =~ s/\..*\z//; # remove subclasses # Remap alias names without "-" to their hyphenated version: $name = $att_aliases->{$name} if exists $att_aliases->{$name}; # prevent ->{special}->{node} from springing into existance my $s = $attributes->{special}; $s = $s->{$class} if exists $s->{$class}; my $entry = $s->{$name} || $attributes->{all}->{$name} || $attributes->{$class}->{$name}; # Didn't found an entry: return (1,undef,$self->_unknown_attribute($name,$class)) unless ref($entry); my $check = $entry->[ATTR_MATCH_SLOT]; my $type = $entry->[ATTR_TYPE_SLOT] || ATTR_STRING; $check = '_color' if $type == ATTR_COLOR; $check = '_angle' if $type == ATTR_ANGLE; $check = '_uint' if $type == ATTR_UINT; my @values = ($value); # split on "|", but not on "\|" # XXX TODO: # This will not work in case of mixed " $i \|\| 0| $a = 1;" # When special attributes are set, we are parsing Graphviz, and do # not allow/use multiple attributes. So skip the split. if (keys %{$attributes->{special}} == 0) { @values = split (/\s*\|\s*/, $value, -1) if $value =~ /(^|[^\\])\|/; } my $multiples = 0; $multiples = 1 if @values > 1; return (4) if $no_multiples && $multiples; # | and no multiples => error # check each part on it's own my @rc; for my $v (@values) { # don't check empty parts for being valid push @rc, undef and next if $multiples && $v eq ''; if (defined $check && !ref($check)) { no strict 'refs'; my $checked = $self->$check($v, $name); if (!defined $checked) { $self->error("Error in attribute: '$v' is not a valid $name for a $class"); return (2); } push @rc, $checked; } elsif ($check) { if (ref($check) eq 'ARRAY') { # build a regexp from the list of words my $list = 'qr/^(' . join ('|', @$check) . ')\z/;'; $entry->[1] = eval($list); $check = $entry->[1]; } if ($v !~ $check) # invalid? { $self->error("Error in attribute: '$v' is not a valid $name for a $class"); return (2); } push @rc, $v; # valid } # entry found, but no specific check => anything goes as value else { push @rc, $v; } # "ClAss" => "class" for LCTEXT entries $rc[-1] = lc($rc[-1]) if $type == ATTR_LCTEXT; } # only one value ('green') return (undef, $name, $rc[0]) unless $multiples; # multiple values ('green|red') (undef, $name, \@rc); } ########################################################################### ########################################################################### sub _remap_attributes { # Take a hash with: # { # class => { # color => 'red' # } # } # and remap it according to the given remap hash (similiar structured). # Also encode/quote the value. Suppresses default attributes. my ($self, $object, $att, $remap, $noquote, $encode, $color_remap ) = @_; my $out = {}; my $class = $object || 'node'; $class = $object->{class} || 'graph' if ref($object); $class =~ s/\..*//; # remove subclass my $r = $remap->{$class}; my $ra = $remap->{all}; my $ral = $remap->{always}; my $x = $remap->{x}; # This loop does also handle the individual "bordercolor" attributes. # If the output should contain only "border", but not "bordercolor", then # the caller must filter them out. # do these attributes my @keys = keys %$att; my $color_scheme = 'w3c'; $color_scheme = $object->attribute('colorscheme') if ref($object); $color_scheme = $self->get_attribute($object,'colorscheme') if defined $object && !ref($object); $color_scheme = $self->get_attribute('graph','colorscheme') if defined $color_scheme && $color_scheme eq 'inherit'; for my $atr (@keys) { my $val = $att->{$atr}; # Only for objects (not for classes like "node"), and not if # always says we need to always call the CODE handler: if (!ref($object) && !exists $ral->{$atr}) { # attribute not defined next if !defined $val || $val eq '' || # or $remap says we should suppress it (exists $r->{$atr} && !defined $r->{$atr}) || (exists $ra->{$atr} && !defined $ra->{$atr}); } my $entry = $attributes->{all}->{$atr} || $attributes->{$class}->{$atr}; if ($color_remap && defined $entry && defined $val) { # look up whether attribute is a color # if yes, convert to hex $val = $self->color_as_hex($val,$color_scheme) if ($entry->[ ATTR_TYPE_SLOT ]||ATTR_STRING) == ATTR_COLOR; } my $temp = { $atr => $val }; # see if there is a handler for custom attributes if (exists $r->{$atr} || exists $ra->{$atr} || (defined $x && $atr =~ /^x-/)) { my $rc = $r->{$atr}; $rc = $ra->{$atr} unless defined $rc; $rc = $x unless defined $rc; # if given a code ref, call it to remap name and/or value if (ref($rc) eq 'CODE') { my @rc = &{$rc}($self,$atr,$val,$object); $temp = {}; while (@rc) { my $a = shift @rc; my $v = shift @rc; $temp->{ $a } = $v if defined $a && defined $v; } } else { # otherwise, rename the attribute name if nec. $temp = { }; $temp = { $rc => $val } if defined $val && defined $rc; } } for my $at (keys %$temp) { my $v = $temp->{$at}; next if !defined $at || !defined $v || $v eq ''; # encode critical characters (including "), but only if the value actually # contains anything else than '%' (so rgb(10%,0,0) stays as it is) $v =~ s/([;"%\x00-\x1f])/sprintf("%%%02x",ord($1))/eg if $encode && $v =~ /[;"\x00-\x1f]/; # quote if nec. $v = '"' . $v . '"' unless $noquote; $out->{$at} = $v; } } $out; } sub raw_attributes { # return all set attributes on this object (graph/node/group/edge) as # an anonymous hash ref my $self = shift; my $class = $self->{class} || 'graph'; my $att = $self->{att}; $att = $self->{att}->{graph} if $class eq 'graph'; my $g = $self->{graph} || $self; my $out = {}; if (!$g->{strict}) { for my $name (keys %$att) { my $val = $att->{$name}; next unless defined $val; # set to undef? $out->{$name} = $val; } return $out; } my $base_class = $class; $base_class =~ s/\..*//; for my $name (keys %$att) { my $val = $att->{$name}; next unless defined $val; # set to undef? $out->{$name} = $val; next unless $val eq 'inherit'; # prevent ->{special}->{node} from springing into existance my $s = $attributes->{special}; $s = $s->{$class} if exists $s->{$class}; my $entry = $s->{$name} || $attributes->{all}->{$name} || $attributes->{$base_class}->{$name}; # Didn't found an entry: return $self->_unknown_attribute($name,$class) unless ref($entry); my $type = $entry->[ ATTR_TYPE_SLOT ] || ATTR_STRING; # need to inherit value? $out->{$name} = $self->attribute($name) if $type < ATTR_NO_INHERIT; } $out; } sub get_attributes { # Return all effective attributes on this object (graph/node/group/edge) as # an anonymous hash ref. This respects inheritance and default values. # Does not return custom attributes, see get_custom_attributes(). my $self = shift; $self->error("get_attributes() doesn't take arguments") if @_ > 0; my $att = {}; my $class = $self->main_class(); # f.i. "all", "node" for my $type ('all', $class) { for my $a (keys %{$attributes->{$type}}) { my $val = $self->attribute($a); # respect inheritance $att->{$a} = $val if defined $val; } } $att; } package Graph::Easy::Node; BEGIN { *custom_attributes = \&get_custom_attributes; } sub get_custom_attributes { # Return all custom attributes on this object (graph/node/group/edge) as # an anonymous hash ref. my $self = shift; $self->error("get_custom_attributes() doesn't take arguments") if @_ > 0; my $att = {}; for my $key (keys %{$self->{att}}) { $att->{$key} = $self->{att}->{$key}; } $att; } 1; __END__ =head1 NAME Graph::Easy::Attributes - Define and check attributes for Graph::Easy =head1 SYNOPSIS use Graph::Easy; my $graph = Graph::Easy->new(); my $hexred = Graph::Easy->color_as_hex( 'red' ); my ($name, $value) = $graph->valid_attribute( 'color', 'red', 'graph' ); print "$name => $value\n" if !ref($value); =head1 DESCRIPTION C<Graph::Easy::Attributes> contains the definitions of valid attribute names and values for L<Graph::Easy|Graph::Easy>. It is used by both the parser and by Graph::Easy to check attributes for being valid and well-formed. There should be no need to use this module directly. For a complete list of attributes and their possible values, please see L<Graph::Easy::Manual>. =head1 EXPORT Exports nothing. =head1 SEE ALSO L<Graph::Easy>. =head1 AUTHOR Copyright (C) 2004 - 2008 by Tels L<http://bloodgate.com> See the LICENSE file for information. =cut
infochimps-labs/wukong
old/graph_easy/Attributes.pm
Perl
apache-2.0
129,960
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2017] EMBL-European Bioinformatics Institute 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. =cut =pod =head1 NAME Bio::EnsEMBL::Compara::StableId::Adaptor =head1 DESCRIPTION All database I/O should be done via this class, which has a general functionality of an adaptor, but strictly speaking isn't. =cut package Bio::EnsEMBL::Compara::StableId::Adaptor; use strict; use warnings; use DBI; use Bio::EnsEMBL::Utils::Argument; # import 'rearrange()' use Bio::EnsEMBL::Compara::StableId::NamedClusterSet; use Bio::EnsEMBL::Compara::StableId::Map; use Bio::EnsEMBL::Utils::Exception qw(throw); sub new { my $class = shift @_; my $self = bless { }, $class; my ($release_in_progress, $dg_suffix_in_progress, $dbname_in_progress, $hist_contrib_unit) = rearrange([qw(release_in_progress dg_suffix_in_progress dbname_in_progress hist_contrib_unit) ], @_); $self->release_in_progress($release_in_progress) if(defined($release_in_progress)); $self->dg_suffix_in_progress($dg_suffix_in_progress) if(defined($dg_suffix_in_progress)); $self->dbname_in_progress($dbname_in_progress) if(defined($dbname_in_progress)); $self->hist_contrib_unit($hist_contrib_unit || 100); return $self; } sub treefam_dbh { my ($self, $release) = @_; return DBI->connect("DBI:mysql:mysql_use_result=1;host=mysql-treefam-public.ebi.ac.uk;port=4418;database=treefam_production_${release}", 'treefam_ro', ''); } sub dbh_from_dgsuffix_dbname { my ($self, $dg_suffix, $dbname) = @_; my $dbh = DBI->connect("DBI:mysql:mysql_read_default_group=client${dg_suffix};mysql_use_result=1;database=${dbname}") or die "Connection Error: $DBI::errstr\n"; return $dbh; } sub guess_dbh { # only works if you have .my.cnf properly pre-filled with connection parameters my ($self, $release, $type) = @_; if($type eq 'tf') { warn "${type}${release} - going to load the data from 'treefam_${release}'\n"; return $self->treefam_dbh($release); } elsif (($type eq 'f') or ($type eq 't')) { my($dg_suffix, $dbname); if($self->release_in_progress() and ($release==$self->release_in_progress())) { $dg_suffix = $self->dg_suffix_in_progress(); } elsif ($release<=47) { $dg_suffix = '_archive'; } else { $dg_suffix = '_narchive'; } if($self->release_in_progress() and ($release==$self->release_in_progress())) { $dbname = $self->dbname_in_progress(); } elsif($release>28) { $dbname = "ensembl_compara_${release}"; } else { $dbname = "ensembl_compara_${release}_1"; } warn "${type}${release} - going to load the data from '$dbname'\n"; return $self->dbh_from_dgsuffix_dbname($dg_suffix, $dbname); } } sub fetch_ncs { my ($self, $release, $type, $dbh) = @_; $dbh ||= $self->guess_dbh($release, $type); my $ncs = Bio::EnsEMBL::Compara::StableId::NamedClusterSet->new(-TYPE => $type, -RELEASE => $release); if( ($type eq 'f') or ($type eq 't') or ($type eq 'tf') ) { $self->load_compara_ncs($ncs, $dbh); } return $ncs; } sub load_compara_ncs { my ($self, $ncs, $dbh) = @_; #Need the schema's version not the reported version from the #NamedClusterSet as people like EG's releases are not the same as Ensembl's my $schema_version = $self->_get_db_version($dbh); warn "\t- Detected DB Version is ${schema_version}\n"; my $step = ($ncs->type() eq 'f') ? 100000 : 30000; my $sql; if ($ncs->type() eq 'f') { my $member_name = $schema_version < 76 ? 'member' : 'seq_member'; $sql = qq{ SELECT f.family_id, }.(($schema_version<53)?"f.stable_id":"CONCAT(f.stable_id,'.',f.version)").qq{, m.stable_id FROM family f, family_member fm, $member_name m WHERE f.family_id=fm.family_id AND fm.${member_name}_id=m.${member_name}_id AND m.source_name <> 'ENSEMBLGENE' } ; } elsif ($ncs->type() eq 't') { if ($schema_version <= 52) { $sql = qq{ SELECT ptn.node_id, CONCAT('Node_',ptn.node_id), m.stable_id FROM protein_tree_node ptn LEFT JOIN protein_tree_member n2m ON ptn.node_id=n2m.node_id LEFT JOIN member m ON n2m.member_id=m.member_id WHERE (ptn.parent_id = ptn.root_id OR m.stable_id IS NOT NULL) AND left_index AND right_index ORDER BY left_index }; } elsif ($schema_version <= 54) { $sql = qq{ SELECT ptn.node_id, IFNULL(CONCAT(ptsi.stable_id,'.',ptsi.version), CONCAT('Node_',ptn.node_id)), m.stable_id FROM protein_tree_node ptn LEFT JOIN protein_tree_member n2m ON ptn.node_id=n2m.node_id LEFT JOIN member m ON n2m.member_id=m.member_id LEFT JOIN protein_tree_stable_id ptsi ON ptn.node_id=ptsi.node_id WHERE (ptn.parent_id = ptn.root_id OR m.stable_id IS NOT NULL) AND left_index AND right_index ORDER BY left_index }; } elsif ($schema_version <= 64) { $sql = qq{ SELECT ptn.node_id, IFNULL(CONCAT(ptsi.stable_id,'.',ptsi.version), CONCAT('Node_',ptn.node_id)), m.stable_id FROM protein_tree_node ptn LEFT JOIN protein_tree_member n2m ON ptn.node_id=n2m.node_id LEFT JOIN member m ON n2m.member_id=m.member_id LEFT JOIN protein_tree_stable_id ptsi ON ptn.node_id=ptsi.node_id WHERE (ptn.node_id = ptn.root_id OR m.stable_id IS NOT NULL) AND left_index AND right_index ORDER BY left_index }; } elsif ($schema_version == 65) { $sql = qq{ SELECT ptn.node_id, IFNULL(CONCAT(ptsi.stable_id,'.',ptsi.version), CONCAT('Node_',ptn.node_id)), m.stable_id FROM protein_tree_node ptn LEFT JOIN protein_tree_member n2m ON ptn.node_id=n2m.node_id LEFT JOIN member m ON n2m.member_id=m.member_id LEFT JOIN protein_tree_stable_id ptsi ON ptn.node_id=ptsi.node_id WHERE (ptn.node_id = ptn.root_id OR m.stable_id IS NOT NULL) AND left_index AND right_index ORDER BY ptn.root_id,left_index }; } elsif ($schema_version == 66) { $sql = qq{ SELECT gtn.node_id, IFNULL(CONCAT(gtr.stable_id,'.',gtr.version), CONCAT('Node_',gtn.node_id)), m.stable_id FROM gene_tree_node gtn JOIN gene_tree_root gtr USING (root_id) LEFT JOIN gene_tree_member gtm USING (node_id) LEFT JOIN member m USING (member_id) WHERE (gtn.node_id = gtn.root_id OR m.stable_id IS NOT NULL) AND left_index AND right_index AND gtr.tree_type = 'proteintree' ORDER BY root_id, left_index }; } elsif ($schema_version == 67) { $sql = qq{ SELECT gtn.node_id, IFNULL(CONCAT(gtr.stable_id,'.',gtr.version), CONCAT('Node_',gtn.node_id)), m.stable_id FROM gene_tree_node gtn JOIN gene_tree_root gtr USING (root_id) LEFT JOIN gene_tree_member gtm USING (node_id) LEFT JOIN member m USING (member_id) WHERE (gtn.node_id = gtn.root_id OR m.stable_id IS NOT NULL) AND left_index AND right_index AND gtr.tree_type = 'tree' ORDER BY root_id, left_index }; } elsif ($schema_version < 70) { $sql = qq{ SELECT gtn.node_id, IFNULL(CONCAT(gtr.stable_id,'.',gtr.version), CONCAT('Node_',gtn.node_id)), m.stable_id FROM gene_tree_node gtn JOIN gene_tree_root gtr USING (root_id) LEFT JOIN gene_tree_member gtm USING (node_id) LEFT JOIN member m USING (member_id) WHERE (gtn.node_id = gtn.root_id OR m.stable_id IS NOT NULL) AND left_index AND right_index AND gtr.tree_type = 'tree' AND gtr.clusterset_id = 'default' ORDER BY root_id, left_index }; } elsif ($schema_version < 76) { $sql = qq{ SELECT gtn.node_id, IFNULL(CONCAT(gtr.stable_id,'.',gtr.version), CONCAT('Node_',gtn.node_id)), m.stable_id FROM gene_tree_node gtn JOIN gene_tree_root gtr USING (root_id) LEFT JOIN member m USING (member_id) WHERE (gtn.node_id = gtn.root_id OR m.stable_id IS NOT NULL) AND left_index AND right_index AND gtr.tree_type = 'tree' AND gtr.clusterset_id = 'default' ORDER BY root_id, left_index }; } else { $sql = qq{ SELECT gtn.node_id, IFNULL(CONCAT(gtr.stable_id,'.',gtr.version), CONCAT('Node_',gtn.node_id)), m.stable_id FROM gene_tree_node gtn JOIN gene_tree_root gtr USING (root_id) LEFT JOIN seq_member m USING (seq_member_id) WHERE (gtn.node_id = gtn.root_id OR m.stable_id IS NOT NULL) AND left_index AND right_index AND gtr.tree_type = 'tree' AND gtr.clusterset_id = 'default' ORDER BY root_id, left_index }; } } else { # TreeFam if ($schema_version <= 70) { $sql = qq{ SELECT gtn.node_id, IFNULL(gtrt.value, CONCAT('Node_',gtn.node_id)), m.stable_id FROM gene_tree_node gtn JOIN gene_tree_root gtr USING (root_id) JOIN gene_tree_root_tag gtrt ON gtr.root_id=gtrt.root_id AND gtrt.tag = "model_name" LEFT JOIN gene_tree_member gtm USING (node_id) LEFT JOIN member m USING (member_id) WHERE (gtn.node_id = gtn.root_id OR m.member_id IS NOT NULL) AND left_index AND right_index AND gtr.tree_type = 'tree' AND gtr.clusterset_id = 'default' ORDER BY gtr.root_id, left_index }; } } my $sth = $dbh->prepare($sql); warn "\t- waiting for the data to start coming\n"; $sth->execute(); warn "\t- done waiting\n"; my $counter = 0; my $cached_id = 0; my $curr_cluster_size = 'NaN'; # need a fake value that evaluates to true to start loading while(my($cluster_id, $cluster_name, $member)=$sth->fetchrow()) { $cluster_name ||= 'NoName'; # we need some name here however bogus (for formatting purposes) if($ncs->type() eq 'f') { $ncs->mname2clid($member, $cluster_id); $ncs->clid2clname($cluster_id, $cluster_name); } elsif($member) { if($cached_id) { $ncs->mname2clid($member, $cached_id); $curr_cluster_size++; } else { die "The query '$sql' returns orphane members without cluster_id/cluster_name, please investigate"; } } else { if($curr_cluster_size) { $cached_id = $cluster_id; $ncs->clid2clname($cluster_id, $cluster_name); $curr_cluster_size=0; } else { die "The query '$sql' attempted to load an empty cluster with cluster_id='$cached_id', please investigate"; } } unless(++$counter % $step) { warn "\t- $counter\n"; } } $sth->finish(); warn "\t- total of $counter members fetched\n"; return $ncs; } sub store_map { my ($self, $map, $dbc) = @_; my $step = 3000; my $sql = ($map->type eq 'f') ? qq{ UPDATE family SET stable_id = ?, version = ? WHERE family_id = ? } : ($map->type eq 't') ? qq{ UPDATE gene_tree_root SET stable_id=?, version=? WHERE root_id=? } : die "Cannot store mapping in database. Type must be either 'f' or 't'"; my $sth = $dbc->prepare($sql); my $counter = 0; foreach my $clid (@{ $map->get_all_clids }) { my ($stid, $ver) = split(/\./, $map->clid2clname($clid)); $sth->execute($stid, $ver, $clid); unless(++$counter % $step) { warn "\t$counter mapped names stored\n"; } } $sth->finish(); warn "\t$counter mapped names stored, done.\n"; } sub store_history { my ($self, $ncsl, $dbc, $timestamp, $master_dbc) = @_; my $mapping_session_id = $self->_get_mapping_session_id($ncsl, $timestamp, $dbc, $master_dbc); my $step = 2000; my $counter = 0; my $sth = $dbc->prepare( "INSERT INTO stable_id_history(mapping_session_id, stable_id_from, version_from, stable_id_to, version_to, contribution) VALUES (?, ?, ?, ?, ?, ?)" ); foreach my $topair (sort { $b->[1] <=> $a->[1] } map { [$_,$ncsl->to_size->{$_}] } keys %{$ncsl->to_size} ) { my ($to_clid, $to_size) = @$topair; my $subhash = $ncsl->rev_contrib->{$to_clid}; my $to_fullname = $ncsl->to->clid2clname($to_clid) or die "to_fullname($to_clid) is false, please investigate"; my ($stid_to, $ver_to) = split(/\./, $to_fullname); foreach my $frompair (sort { $b->[1] <=> $a->[1] } map { [$_,$subhash->{$_}] } keys %$subhash ) { my ($from_clid, $contrib) = @$frompair; my $from_fullname = $ncsl->from->clid2clname($from_clid) or die "from_fullname is false, please investigate."; my ($stid_from, $ver_from) = split(/\./, $from_fullname); $sth->execute($mapping_session_id, $stid_from, $ver_from, $stid_to, $ver_to, $contrib/$to_size*$self->hist_contrib_unit()); unless(++$counter % $step) { warn "\t$counter history lines stored\n"; } } } foreach my $to_clid (keys %{$ncsl->xto_size}) { my ($stid_to , $ver_to ) = split(/\./, $ncsl->to->clid2clname($to_clid)); my @params = ($mapping_session_id, '', undef, $stid_to, $ver_to, 1.0*$self->hist_contrib_unit()); eval { $sth->execute(@params); }; throw "Cannot continue inserting into history with params '@params' when working with $to_clid and ".$ncsl->to->clid2clname($to_clid).": $@" if $@; unless(++$counter % $step) { warn "\t$counter history lines stored\n"; } } foreach my $from_clid (keys %{$ncsl->xfrom_size}) { my ($stid_from, $ver_from) = split(/\./, $ncsl->from->clid2clname($from_clid)); my @params = ($mapping_session_id, $stid_from, $ver_from, '', undef, 1.0*$self->hist_contrib_unit()); eval { $sth->execute(@params); }; throw "Cannot continue inserting into history with params '@params' when working with $from_clid and ".$ncsl->from->clid2clname($from_clid).": $@" if $@; unless(++$counter % $step) { warn "\t$counter history lines stored\n"; } } $sth->finish(); warn "\t$counter lines stored, done.\n"; } sub _get_mapping_session_id { my ($self, $ncsl, $timestamp, $dbc, $master_dbc) = @_; $timestamp ||= time(); $master_dbc ||= $dbc; # in case no master was given (so please provide the $master_dbc to avoid doing unnecessary work afterwards) my $type = $ncsl->to->type(); my $fulltype = { 'f' => 'family', 't' => 'tree' }->{$type} || die "Cannot store history for type '$type'"; #Need to get the Generator to get the prefix and then remove the FM/GT from #the names. Allows us to have a default value of ENS in the mapping table my $generator = Bio::EnsEMBL::Compara::StableId::Generator->new( -TYPE => $ncsl->to->type, -RELEASE => $ncsl->to->release, -MAP => $ncsl->from ); my $prefix = $generator->prefix(); my $prefix_to_remove = { f => 'FM', t => 'GT' }->{$type} || die "Do not know the extension for type '${type}'"; $prefix =~ s/$prefix_to_remove \Z//xms; my $ms_sth = $master_dbc->prepare( "SELECT mapping_session_id FROM mapping_session WHERE type = ? AND rel_from = ? AND rel_to = ? AND prefix = ?" ); $ms_sth->execute($fulltype, $ncsl->from->release(), $ncsl->to->release(), $prefix); my ($mapping_session_id) = $ms_sth->fetchrow_array(); $ms_sth->finish(); if (defined $mapping_session_id) { warn "reusing previously generated mapping_session_id = '$mapping_session_id' for prefix '${prefix}'\n"; } else { $ms_sth = $master_dbc->prepare( "INSERT INTO mapping_session(type, rel_from, rel_to, when_mapped, prefix) VALUES (?, ?, ?, FROM_UNIXTIME(?), ?)" ); $ms_sth->execute($fulltype, $ncsl->from->release(), $ncsl->to->release(), $timestamp, $prefix); $mapping_session_id = $master_dbc->db_handle->last_insert_id(undef, undef, 'mapping_session', 'mapping_session_id'); warn "newly generated mapping_session_id = '$mapping_session_id' for prefix '${prefix}'\n"; $ms_sth->finish(); } if($dbc != $master_dbc) { # replicate it in the release database: my $ms_sth2 = $dbc->prepare( "INSERT INTO mapping_session(mapping_session_id, type, rel_from, rel_to, when_mapped, prefix) VALUES (?, ?, ?, ?, FROM_UNIXTIME(?), ?)" ); $ms_sth2->execute($mapping_session_id, $fulltype, $ncsl->from->release(), $ncsl->to->release(), $timestamp, $prefix); $ms_sth2->finish(); } return $mapping_session_id; } sub store_tags { # used to create cross-references from EnsEMBL GeneTrees to Treefam families my ($self, $accu, $dbh, $tag_prefix) = @_; $tag_prefix ||= ''; my $step = 2000; my $sql = qq{ REPLACE INTO gene_tree_root_tag VALUES (?, ?, ?) }; my $sth = $dbh->prepare($sql); my $counter = 0; foreach my $node_id (keys %$accu) { foreach my $matchtype (keys %{$accu->{$node_id}}) { my $value = join(';', @{$accu->{$node_id}{$matchtype}}); my $tag = $tag_prefix .({ 'SymMatch' => 'treefam_id', 'Included' => 'part_treefam_id', 'Contains' => 'cont_treefam_id' }->{$matchtype}); $sth->execute($node_id, $tag, $value); unless(++$counter % $step) { warn "\t$counter tags stored\n"; } } } warn "\t$counter tags stored, done.\n"; } # -------------------------------------- getters and setters --------------------------------------------- sub release_in_progress { my $self = shift @_; if(@_) { $self->{'_release_in_progress'} = shift @_; } return $self->{'_release_in_progress'}; } sub dg_suffix_in_progress { my $self = shift @_; if(@_) { $self->{'_dg_suffix_in_progress'} = shift @_; } return $self->{'_dg_suffix_in_progress'}; } sub dbname_in_progress { my $self = shift @_; if(@_) { $self->{'_dbname_in_progress'} = shift @_; } return $self->{'_dbname_in_progress'}; } sub hist_contrib_unit { my $self = shift @_; if(@_) { $self->{'_hist_contrib_unit'} = shift @_; } return $self->{'_hist_contrib_unit'}; } sub source { my ($self, $source) = @_; $self->{_source} = $source if defined $source; return $self->{_source}; } # -------------------------------------- privates --------------------------------------------- #Have to use basic DBI because we could have been given one sub _get_db_version { my ($self, $dbh) = @_; my $sql = 'select meta_value from meta where meta_key =? and species_id is null LIMIT 1'; my $sth = $dbh->prepare($sql); my $row; eval { $sth->execute('schema_version'); $row = $sth->fetchrow_arrayref(); }; my $error = $@; $sth->finish(); throw("Detected an error whilst querying for schema version: $error") if $error; throw('No schema_version found in meta; you really should have this') if ! $row; return $row->[0]; } 1;
danstaines/ensembl-compara
modules/Bio/EnsEMBL/Compara/StableId/Adaptor.pm
Perl
apache-2.0
20,682
# Copyright 2020, Google LLC # # 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. package Google::Ads::GoogleAds::V9::Enums::IncomeRangeTypeEnum; use strict; use warnings; use Const::Exporter enums => [ UNSPECIFIED => "UNSPECIFIED", UNKNOWN => "UNKNOWN", INCOME_RANGE_0_50 => "INCOME_RANGE_0_50", INCOME_RANGE_50_60 => "INCOME_RANGE_50_60", INCOME_RANGE_60_70 => "INCOME_RANGE_60_70", INCOME_RANGE_70_80 => "INCOME_RANGE_70_80", INCOME_RANGE_80_90 => "INCOME_RANGE_80_90", INCOME_RANGE_90_UP => "INCOME_RANGE_90_UP", INCOME_RANGE_UNDETERMINED => "INCOME_RANGE_UNDETERMINED" ]; 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V9/Enums/IncomeRangeTypeEnum.pm
Perl
apache-2.0
1,170
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2018] EMBL-European Bioinformatics Institute 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. =cut package EnsEMBL::Web::Component::Tools::DataSlicer::TicketDetails; use strict; use warnings; use parent qw( EnsEMBL::Web::Component::Tools::DataSlicer EnsEMBL::Web::Component::Tools::TicketDetails ); sub job_details_table { ## @override my ($self, $job, $is_owned_ticket) = @_; my $object = $self->object; my $hub = $self->hub; my $sd = $hub->species_defs; my $job_data = $job->job_data; my $species = $job->species; my $two_col = $self->new_twocol; my $job_summary = $self->get_job_summary($job, $is_owned_ticket); $two_col->add_row('Job name', $job_summary->render); $two_col->add_row('Species', $object->valid_species($species) ? sprintf('<img class="job-species" src="%sspecies/%s.png" alt="" height="16" width="16">%s', $self->img_url, $species, $sd->species_label($species, 1)) : $species =~ s/_/ /rg); $two_col->add_row('Assembly', $job->assembly); $two_col->add_row('File format', $job_data->{file_format}); $two_col->add_row('Region', $job_data->{region}); $two_col->add_row('File URL', $job_data->{file_url}); $two_col->add_row('Generate .bai file', 'Y') if($job_data->{bai_file}); if($job_data->{vcf_filters} && ($job_data->{vcf_filters} eq 'individuals' || $job_data->{vcf_filters} eq 'populations')) { $two_col->add_row('Filter by', $job_data->{vcf_filters}); $job_data->{vcf_filters} eq 'individuals' ? $two_col->add_row('Individual(s)', $job_data->{individuals_box} ? $job_data->{individuals_box} : $job_data->{individuals_text}) : $two_col->add_row('Population(s)', $job_data->{population}) } else { $two_col->add_row('Filter by', "No filters") if($job_data->{vcf_filters} && $job_data->{vcf_filters} eq 'null'); } return $two_col; } 1;
muffato/public-plugins
tools/modules/EnsEMBL/Web/Component/Tools/DataSlicer/TicketDetails.pm
Perl
apache-2.0
2,517
# # Copyright 2015 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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. # package apps::iis::wsman::plugin; use strict; use warnings; use base qw(centreon::plugins::script_wsman); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; # $options->{options} = options object $self->{version} = '0.1'; %{$self->{modes}} = ( 'applicationpool-state' => 'apps::iis::wsman::mode::applicationpoolstate', 'list-applicationpools' => 'apps::iis::wsman::mode::listapplicationpools', ); return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check Windows IIS through "WinRM" (ws-management protocol). =cut
s-duret/centreon-plugins
apps/iis/wsman/plugin.pm
Perl
apache-2.0
1,466
#!perl # unpack BOFOR.ALL # @(#) $Id: b3731991dc9da350ed8f4bd9a119240b4dbc11dd $ # 2022-02-04, Georg Fischer # # Usage: # perl unpack.pl BOFOR.ALL #------------------------------------------------------------------ # use strict; use warnings; use integer; my %excludes = qw( xxxx 1 ); my $infile = shift(@ARGV); my $line; my $key; my $name; my $parm; my $memname; my $value; my $count; my %includes = (); # list of include files *.inc my %params = (); # list of parameter names with their values my %depends = (); # list of Fortran files and their includes my %ftns = (); # list of Fortran files #---- determine the include files #---- remember the parameters open(SRC, "<", $infile) || die "cannot read $infile\n"; while(<SRC>) { if (0) { } elsif(m{^ *\%INCLUDE *\( *(\w+)\)}) { $includes{$1} = 1; } elsif(m{^ *\%PARAMETER +(\w+) *\=\s*(\S*)}) { ($name, $value) = ($1, $2); $name =~ s{\AU}{h}; $params{$name} = $value; } } close(SRC); #---- list the parameters for $key (sort(keys(%params))) { $value = $params{$key}; while ($value =~ m{([A-Z]+)}) { # nested $parm = $1; if (defined($params{$parm})) { $value =~ s{$parm}{$params{$parm}}; } else { $value =~ s{$parm}{99999999}; } } # while nested $params{$key} = eval($value); print "parameter $key=$params{$key}\n"; } #---- show list of *.inc include files if (1) { print "includes:\n"; for $key (sort(keys(%includes))) { print "$key.inc\n"; } } # (3) write individual files *.ftn *.inc *.asm *.pli *.tkb, and populate %depends $memname = ""; open(SRC, "<", $infile) || die "cannot read $infile\n"; while(<SRC>) { $line = $_; if ($memname eq "") { if ($line =~ m{^\&\( *(\w+) *\)}) { # start of member $name = $1; if (! defined($excludes{$name})) { if (0) { } elsif (defined($includes{$name})) { $memname = "$name.inc"; } elsif ($name =~ m{\AZZ[CIR][CIR]\Z}) { $memname = "$name.asm"; } elsif ($name =~ m{\A(PAROLD|PRIXRE)\Z}) { # PL/1 $memname = "$name.pli"; } elsif ($name =~ m{\A(PUTCOQ)\Z}) { # ignore, duplicate? $memname = "$name.fxx"; } elsif ($name =~ m{TB\Z}) { # DEC TKB? $memname = "$name.tkb"; } else { $memname = "$name.ftn"; $ftns{$name} = $memname; $depends{$name} = "$name.ftn"; $count = 1; } open(TAR, ">", $memname) || die "cannot write $memname\n"; # print STDERR "writing $memname\n"; if ($name eq "PARS") { # write at the beginning print TAR " implicit none\n"; # and suppress IMPLICIT below } } } } else { # modify and write normal source line to member if ($line =~ m{^\&END\s*\Z}) { # end of member $memname = ""; $count = 0; close(TAR); } else { my $ok = 1; $line =~ s{\s+\Z}{}; # chompr if (0) { } elsif(m{^ *IMPLICIT *COMPLEX}) { # IMPLICIT $ok = 0; # suppress here } elsif(m{^ *\%PARAMETER +(\w+) *\=\s*(\S*)}) { # %PARAMETER ($name, $value) = ($1, $2); $name =~ s{\AU}{h}; print TAR " INTEGER $name\n"; print TAR " parameter $name=$value\n"; $ok = 0; } elsif ($line =~ m{\%INCLUDE *\( *(\w+) *\)}) { # %INCLUDE my $incname = $1; $line =~ s {\%INCLUDE.*}{include \'$incname\.inc\'}; $depends{$name} .= " $incname.inc"; $count ++; if ($count % 8 == 0) { $depends{$name} .= " \\\n\t\t"; } } elsif ($line =~ m{\A.{6} *OPEN *\(([^\)]+)}) { # OPEN( $line =~ s{NAME\=} {file\=}; $line =~ s{TYPE\=} {status\=}; $line =~ s{ACCESS\=} {position\=}; $line =~ s{\'SY\:} {\'}; $line =~ s{\'DL1\[[^\:]+\:} {\'}; } elsif ($line =~ m{\A.{6} *(READ|WRITE) *\(\w+\'}) { # WRITE(UNIT'RECORD) $line =~ s{\'}{\, rec=}; } else { # normal line while ($line =~ m{\&(\w+)}) { $name = $1; $name =~ s{\AU}{h}; if ($line =~ m{FORMAT *\(}) { $line =~ s{\&(\w+)}{$params{$name}}; # F77 does not replace paramters in FORMAT specs? } else { $line =~ s{\&(\w+)}{$name}; } } # while $line =~ s{(ZZ[A-Z])C( *\(\')}{${1}ch$2}; $line =~ s/\, *ASSOCIATE *VARIABLE=\w+//; $line =~ s/\, *READONLY//; $line =~ s/\, *SHARED//; $line =~ s/\, *MAXREC=[\w\/\+\-\*\)\(]+//; $line =~ s/\, *TYPE=\'SCRATCH\'//; $line =~ s/\, *BUFFER *COUNT=\-1//; $line =~ s/\, *CARRIAGE *CONTROL=\'LIST\'//; $line =~ s/DL1\:\[20\,21\]//; } if( $ok) { # if not suppressed print TAR "$line\n"; } } } } close(SRC); # (4) write source list to be included in makefile open(INC, ">", "include.make") || die "cannot write sources.mak\n"; print INC "SRC= \\\n"; $count = 0; for $key (sort(keys(%ftns))) { print INC "\t$key.ftn"; $count ++; if ($count % 8 == 0) { print INC " \\\n"; } } print INC "\t# end\n"; # (5) write dependencies for *.o print INC "\n"; for $key (sort(keys(%depends))) { print INC "$key.o:\t$depends{$key}\n"; } print INC "\t# end\n"; close(INC); __DATA__ &(ALONG ) SUBROUTINE ALONG(STATEQ,POSQ,STATE,PROD) C WALK THROUGH THE STATES AND MOVE THE MARKER BEHIND A PRODUCTION C GF 20.08.80 : WITH CALL 'DELTA' C %INCLUDE (PARS) %INCLUDE (ITES) %INCLUDE (MEMS) %INCLUDE (STAS) C 101 CONTINUE ! DONE RETURN! ALONG END &END &(PARS ) C-------GF 08.11.80------------------------------ P A R S %PARAMETER BUCH=127 %PARAMETER CODH=128 %PARAMETER ITEH=600 C BUCS DATA BUCHIB /&BUCH/ DATA BUCKET /&BUCH * &SYMH/
gfis/jextra
legacy/bofor_2022/unpack.pl
Perl
apache-2.0
7,263
#! /usr/bin/env perl # Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved. # # Licensed under the Apache License 2.0 (the "License"). You may not use # this file except in compliance with the License. You can obtain a copy # in the file LICENSE in the source distribution or at # https://www.openssl.org/source/license.html # ==================================================================== # Written by Andy Polyakov <appro@openssl.org> for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. # ==================================================================== # March 2015 # # "Teaser" Montgomery multiplication module for ARMv8. Needs more # work. While it does improve RSA sign performance by 20-30% (less for # longer keys) on most processors, for some reason RSA2048 is not # faster and RSA4096 goes 15-20% slower on Cortex-A57. Multiplication # instruction issue rate is limited on processor in question, meaning # that dedicated squaring procedure is a must. Well, actually all # contemporary AArch64 processors seem to have limited multiplication # issue rate, i.e. they can't issue multiplication every cycle, which # explains moderate improvement coefficients in comparison to # compiler-generated code. Recall that compiler is instructed to use # umulh and therefore uses same amount of multiplication instructions # to do the job. Assembly's edge is to minimize number of "collateral" # instructions and of course instruction scheduling. # # April 2015 # # Squaring procedure that handles lengths divisible by 8 improves # RSA/DSA performance by 25-40-60% depending on processor and key # length. Overall improvement coefficients are always positive in # comparison to compiler-generated code. On Cortex-A57 improvement # is still modest on longest key lengths, while others exhibit e.g. # 50-70% improvement for RSA4096 sign. RSA2048 sign is ~25% faster # on Cortex-A57 and ~60-100% faster on others. # $output is the last argument if it looks like a file (it has an extension) # $flavour is the first argument if it doesn't look like a file my $output = $#ARGV >= 0 && $ARGV[$#ARGV] =~ m|\.\w+$| ? pop : undef; my $flavour = $#ARGV >= 0 && $ARGV[0] !~ m|\.| ? shift : undef; $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; ( $xlate="${dir}arm-xlate.pl" and -f $xlate ) or ( $xlate="${dir}../../perlasm/arm-xlate.pl" and -f $xlate) or die "can't locate arm-xlate.pl"; open OUT,"| \"$^X\" $xlate $flavour \"$output\"" or die "can't call $xlate: $1"; *STDOUT=*OUT; ($lo0,$hi0,$aj,$m0,$alo,$ahi, $lo1,$hi1,$nj,$m1,$nlo,$nhi, $ovf, $i,$j,$tp,$tj) = map("x$_",6..17,19..24); # int bn_mul_mont( $rp="x0"; # BN_ULONG *rp, $ap="x1"; # const BN_ULONG *ap, $bp="x2"; # const BN_ULONG *bp, $np="x3"; # const BN_ULONG *np, $n0="x4"; # const BN_ULONG *n0, $num="x5"; # int num); $code.=<<___; #include "arm_arch.h" #ifndef __KERNEL__ .extern OPENSSL_armv8_rsa_neonized .hidden OPENSSL_armv8_rsa_neonized #endif .text .globl bn_mul_mont .type bn_mul_mont,%function .align 5 bn_mul_mont: AARCH64_SIGN_LINK_REGISTER .Lbn_mul_mont: tst $num,#3 b.ne .Lmul_mont cmp $num,#32 b.le .Lscalar_impl #ifndef __KERNEL__ adrp x17,OPENSSL_armv8_rsa_neonized ldr w17,[x17,#:lo12:OPENSSL_armv8_rsa_neonized] cbnz w17, bn_mul8x_mont_neon #endif .Lscalar_impl: tst $num,#7 b.eq __bn_sqr8x_mont tst $num,#3 b.eq __bn_mul4x_mont .Lmul_mont: stp x29,x30,[sp,#-64]! add x29,sp,#0 stp x19,x20,[sp,#16] stp x21,x22,[sp,#32] stp x23,x24,[sp,#48] ldr $m0,[$bp],#8 // bp[0] sub $tp,sp,$num,lsl#3 ldp $hi0,$aj,[$ap],#16 // ap[0..1] lsl $num,$num,#3 ldr $n0,[$n0] // *n0 and $tp,$tp,#-16 // ABI says so ldp $hi1,$nj,[$np],#16 // np[0..1] mul $lo0,$hi0,$m0 // ap[0]*bp[0] sub $j,$num,#16 // j=num-2 umulh $hi0,$hi0,$m0 mul $alo,$aj,$m0 // ap[1]*bp[0] umulh $ahi,$aj,$m0 mul $m1,$lo0,$n0 // "tp[0]"*n0 mov sp,$tp // alloca // (*) mul $lo1,$hi1,$m1 // np[0]*m1 umulh $hi1,$hi1,$m1 mul $nlo,$nj,$m1 // np[1]*m1 // (*) adds $lo1,$lo1,$lo0 // discarded // (*) As for removal of first multiplication and addition // instructions. The outcome of first addition is // guaranteed to be zero, which leaves two computationally // significant outcomes: it either carries or not. Then // question is when does it carry? Is there alternative // way to deduce it? If you follow operations, you can // observe that condition for carry is quite simple: // $lo0 being non-zero. So that carry can be calculated // by adding -1 to $lo0. That's what next instruction does. subs xzr,$lo0,#1 // (*) umulh $nhi,$nj,$m1 adc $hi1,$hi1,xzr cbz $j,.L1st_skip .L1st: ldr $aj,[$ap],#8 adds $lo0,$alo,$hi0 sub $j,$j,#8 // j-- adc $hi0,$ahi,xzr ldr $nj,[$np],#8 adds $lo1,$nlo,$hi1 mul $alo,$aj,$m0 // ap[j]*bp[0] adc $hi1,$nhi,xzr umulh $ahi,$aj,$m0 adds $lo1,$lo1,$lo0 mul $nlo,$nj,$m1 // np[j]*m1 adc $hi1,$hi1,xzr umulh $nhi,$nj,$m1 str $lo1,[$tp],#8 // tp[j-1] cbnz $j,.L1st .L1st_skip: adds $lo0,$alo,$hi0 sub $ap,$ap,$num // rewind $ap adc $hi0,$ahi,xzr adds $lo1,$nlo,$hi1 sub $np,$np,$num // rewind $np adc $hi1,$nhi,xzr adds $lo1,$lo1,$lo0 sub $i,$num,#8 // i=num-1 adcs $hi1,$hi1,$hi0 adc $ovf,xzr,xzr // upmost overflow bit stp $lo1,$hi1,[$tp] .Louter: ldr $m0,[$bp],#8 // bp[i] ldp $hi0,$aj,[$ap],#16 ldr $tj,[sp] // tp[0] add $tp,sp,#8 mul $lo0,$hi0,$m0 // ap[0]*bp[i] sub $j,$num,#16 // j=num-2 umulh $hi0,$hi0,$m0 ldp $hi1,$nj,[$np],#16 mul $alo,$aj,$m0 // ap[1]*bp[i] adds $lo0,$lo0,$tj umulh $ahi,$aj,$m0 adc $hi0,$hi0,xzr mul $m1,$lo0,$n0 sub $i,$i,#8 // i-- // (*) mul $lo1,$hi1,$m1 // np[0]*m1 umulh $hi1,$hi1,$m1 mul $nlo,$nj,$m1 // np[1]*m1 // (*) adds $lo1,$lo1,$lo0 subs xzr,$lo0,#1 // (*) umulh $nhi,$nj,$m1 cbz $j,.Linner_skip .Linner: ldr $aj,[$ap],#8 adc $hi1,$hi1,xzr ldr $tj,[$tp],#8 // tp[j] adds $lo0,$alo,$hi0 sub $j,$j,#8 // j-- adc $hi0,$ahi,xzr adds $lo1,$nlo,$hi1 ldr $nj,[$np],#8 adc $hi1,$nhi,xzr mul $alo,$aj,$m0 // ap[j]*bp[i] adds $lo0,$lo0,$tj umulh $ahi,$aj,$m0 adc $hi0,$hi0,xzr mul $nlo,$nj,$m1 // np[j]*m1 adds $lo1,$lo1,$lo0 umulh $nhi,$nj,$m1 stur $lo1,[$tp,#-16] // tp[j-1] cbnz $j,.Linner .Linner_skip: ldr $tj,[$tp],#8 // tp[j] adc $hi1,$hi1,xzr adds $lo0,$alo,$hi0 sub $ap,$ap,$num // rewind $ap adc $hi0,$ahi,xzr adds $lo1,$nlo,$hi1 sub $np,$np,$num // rewind $np adcs $hi1,$nhi,$ovf adc $ovf,xzr,xzr adds $lo0,$lo0,$tj adc $hi0,$hi0,xzr adds $lo1,$lo1,$lo0 adcs $hi1,$hi1,$hi0 adc $ovf,$ovf,xzr // upmost overflow bit stp $lo1,$hi1,[$tp,#-16] cbnz $i,.Louter // Final step. We see if result is larger than modulus, and // if it is, subtract the modulus. But comparison implies // subtraction. So we subtract modulus, see if it borrowed, // and conditionally copy original value. ldr $tj,[sp] // tp[0] add $tp,sp,#8 ldr $nj,[$np],#8 // np[0] subs $j,$num,#8 // j=num-1 and clear borrow mov $ap,$rp .Lsub: sbcs $aj,$tj,$nj // tp[j]-np[j] ldr $tj,[$tp],#8 sub $j,$j,#8 // j-- ldr $nj,[$np],#8 str $aj,[$ap],#8 // rp[j]=tp[j]-np[j] cbnz $j,.Lsub sbcs $aj,$tj,$nj sbcs $ovf,$ovf,xzr // did it borrow? str $aj,[$ap],#8 // rp[num-1] ldr $tj,[sp] // tp[0] add $tp,sp,#8 ldr $aj,[$rp],#8 // rp[0] sub $num,$num,#8 // num-- nop .Lcond_copy: sub $num,$num,#8 // num-- csel $nj,$tj,$aj,lo // did it borrow? ldr $tj,[$tp],#8 ldr $aj,[$rp],#8 stur xzr,[$tp,#-16] // wipe tp stur $nj,[$rp,#-16] cbnz $num,.Lcond_copy csel $nj,$tj,$aj,lo stur xzr,[$tp,#-8] // wipe tp stur $nj,[$rp,#-8] ldp x19,x20,[x29,#16] mov sp,x29 ldp x21,x22,[x29,#32] mov x0,#1 ldp x23,x24,[x29,#48] ldr x29,[sp],#64 AARCH64_VALIDATE_LINK_REGISTER ret .size bn_mul_mont,.-bn_mul_mont ___ { my ($A0,$A1,$N0,$N1)=map("v$_",(0..3)); my ($Z,$Temp)=("v4.16b","v5"); my @ACC=map("v$_",(6..13)); my ($Bi,$Ni,$M0)=map("v$_",(28..30)); my $sBi="s28"; my $sM0="s30"; my $zero="v14"; my $temp="v15"; my $ACCTemp="v16"; my ($rptr,$aptr,$bptr,$nptr,$n0,$num)=map("x$_",(0..5)); my ($tinptr,$toutptr,$inner,$outer,$bnptr)=map("x$_",(6..11)); $code.=<<___; .type bn_mul8x_mont_neon,%function .align 5 bn_mul8x_mont_neon: // Not adding AARCH64_SIGN_LINK_REGISTER here because bn_mul8x_mont_neon is jumped to // only from bn_mul_mont which has already signed the return address. stp x29,x30,[sp,#-80]! mov x16,sp stp d8,d9,[sp,#16] stp d10,d11,[sp,#32] stp d12,d13,[sp,#48] stp d14,d15,[sp,#64] lsl $num,$num,#1 eor $zero.16b,$zero.16b,$zero.16b .align 4 .LNEON_8n: eor @ACC[0].16b,@ACC[0].16b,@ACC[0].16b sub $toutptr,sp,#128 eor @ACC[1].16b,@ACC[1].16b,@ACC[1].16b sub $toutptr,$toutptr,$num,lsl#4 eor @ACC[2].16b,@ACC[2].16b,@ACC[2].16b and $toutptr,$toutptr,#-64 eor @ACC[3].16b,@ACC[3].16b,@ACC[3].16b mov sp,$toutptr // alloca eor @ACC[4].16b,@ACC[4].16b,@ACC[4].16b add $toutptr,$toutptr,#256 eor @ACC[5].16b,@ACC[5].16b,@ACC[5].16b sub $inner,$num,#8 eor @ACC[6].16b,@ACC[6].16b,@ACC[6].16b eor @ACC[7].16b,@ACC[7].16b,@ACC[7].16b .LNEON_8n_init: st1 {@ACC[0].2d,@ACC[1].2d},[$toutptr],#32 subs $inner,$inner,#8 st1 {@ACC[2].2d,@ACC[3].2d},[$toutptr],#32 st1 {@ACC[4].2d,@ACC[5].2d},[$toutptr],#32 st1 {@ACC[6].2d,@ACC[7].2d},[$toutptr],#32 bne .LNEON_8n_init add $tinptr,sp,#256 ld1 {$A0.4s,$A1.4s},[$aptr],#32 add $bnptr,sp,#8 ldr $sM0,[$n0],#4 mov $outer,$num b .LNEON_8n_outer .align 4 .LNEON_8n_outer: ldr $sBi,[$bptr],#4 // *b++ uxtl $Bi.4s,$Bi.4h add $toutptr,sp,#128 ld1 {$N0.4s,$N1.4s},[$nptr],#32 umlal @ACC[0].2d,$Bi.2s,$A0.s[0] umlal @ACC[1].2d,$Bi.2s,$A0.s[1] umlal @ACC[2].2d,$Bi.2s,$A0.s[2] shl $Ni.2d,@ACC[0].2d,#16 ext $Ni.16b,$Ni.16b,$Ni.16b,#8 umlal @ACC[3].2d,$Bi.2s,$A0.s[3] add $Ni.2d,$Ni.2d,@ACC[0].2d umlal @ACC[4].2d,$Bi.2s,$A1.s[0] mul $Ni.2s,$Ni.2s,$M0.2s umlal @ACC[5].2d,$Bi.2s,$A1.s[1] st1 {$Bi.2s},[sp] // put aside smashed b[8*i+0] umlal @ACC[6].2d,$Bi.2s,$A1.s[2] uxtl $Ni.4s,$Ni.4h umlal @ACC[7].2d,$Bi.2s,$A1.s[3] ___ for ($i=0; $i<7;) { $code.=<<___; ldr $sBi,[$bptr],#4 // *b++ umlal @ACC[0].2d,$Ni.2s,$N0.s[0] umlal @ACC[1].2d,$Ni.2s,$N0.s[1] uxtl $Bi.4s,$Bi.4h umlal @ACC[2].2d,$Ni.2s,$N0.s[2] ushr $temp.2d,@ACC[0].2d,#16 umlal @ACC[3].2d,$Ni.2s,$N0.s[3] umlal @ACC[4].2d,$Ni.2s,$N1.s[0] ext @ACC[0].16b,@ACC[0].16b,@ACC[0].16b,#8 add @ACC[0].2d,@ACC[0].2d,$temp.2d umlal @ACC[5].2d,$Ni.2s,$N1.s[1] ushr @ACC[0].2d,@ACC[0].2d,#16 umlal @ACC[6].2d,$Ni.2s,$N1.s[2] umlal @ACC[7].2d,$Ni.2s,$N1.s[3] add $ACCTemp.2d,@ACC[1].2d,@ACC[0].2d ins @ACC[1].d[0],$ACCTemp.d[0] st1 {$Ni.2s},[$bnptr],#8 // put aside smashed m[8*i+$i] ___ push(@ACC,shift(@ACC)); $i++; $code.=<<___; umlal @ACC[0].2d,$Bi.2s,$A0.s[0] ld1 {@ACC[7].2d},[$tinptr],#16 umlal @ACC[1].2d,$Bi.2s,$A0.s[1] umlal @ACC[2].2d,$Bi.2s,$A0.s[2] shl $Ni.2d,@ACC[0].2d,#16 ext $Ni.16b,$Ni.16b,$Ni.16b,#8 umlal @ACC[3].2d,$Bi.2s,$A0.s[3] add $Ni.2d,$Ni.2d,@ACC[0].2d umlal @ACC[4].2d,$Bi.2s,$A1.s[0] mul $Ni.2s,$Ni.2s,$M0.2s umlal @ACC[5].2d,$Bi.2s,$A1.s[1] st1 {$Bi.2s},[$bnptr],#8 // put aside smashed b[8*i+$i] umlal @ACC[6].2d,$Bi.2s,$A1.s[2] uxtl $Ni.4s,$Ni.4h umlal @ACC[7].2d,$Bi.2s,$A1.s[3] ___ } $code.=<<___; ld1 {$Bi.2s},[sp] // pull smashed b[8*i+0] umlal @ACC[0].2d,$Ni.2s,$N0.s[0] ld1 {$A0.4s,$A1.4s},[$aptr],#32 umlal @ACC[1].2d,$Ni.2s,$N0.s[1] umlal @ACC[2].2d,$Ni.2s,$N0.s[2] mov $Temp.16b,@ACC[0].16b ushr $Temp.2d,$Temp.2d,#16 ext @ACC[0].16b,@ACC[0].16b,@ACC[0].16b,#8 umlal @ACC[3].2d,$Ni.2s,$N0.s[3] umlal @ACC[4].2d,$Ni.2s,$N1.s[0] add @ACC[0].2d,@ACC[0].2d,$Temp.2d umlal @ACC[5].2d,$Ni.2s,$N1.s[1] ushr @ACC[0].2d,@ACC[0].2d,#16 eor $temp.16b,$temp.16b,$temp.16b ins @ACC[0].d[1],$temp.d[0] umlal @ACC[6].2d,$Ni.2s,$N1.s[2] umlal @ACC[7].2d,$Ni.2s,$N1.s[3] add @ACC[1].2d,@ACC[1].2d,@ACC[0].2d st1 {$Ni.2s},[$bnptr],#8 // put aside smashed m[8*i+$i] add $bnptr,sp,#8 // rewind ___ push(@ACC,shift(@ACC)); $code.=<<___; sub $inner,$num,#8 b .LNEON_8n_inner .align 4 .LNEON_8n_inner: subs $inner,$inner,#8 umlal @ACC[0].2d,$Bi.2s,$A0.s[0] ld1 {@ACC[7].2d},[$tinptr] umlal @ACC[1].2d,$Bi.2s,$A0.s[1] ld1 {$Ni.2s},[$bnptr],#8 // pull smashed m[8*i+0] umlal @ACC[2].2d,$Bi.2s,$A0.s[2] ld1 {$N0.4s,$N1.4s},[$nptr],#32 umlal @ACC[3].2d,$Bi.2s,$A0.s[3] b.eq .LInner_jump add $tinptr,$tinptr,#16 // don't advance in last iteration .LInner_jump: umlal @ACC[4].2d,$Bi.2s,$A1.s[0] umlal @ACC[5].2d,$Bi.2s,$A1.s[1] umlal @ACC[6].2d,$Bi.2s,$A1.s[2] umlal @ACC[7].2d,$Bi.2s,$A1.s[3] ___ for ($i=1; $i<8; $i++) { $code.=<<___; ld1 {$Bi.2s},[$bnptr],#8 // pull smashed b[8*i+$i] umlal @ACC[0].2d,$Ni.2s,$N0.s[0] umlal @ACC[1].2d,$Ni.2s,$N0.s[1] umlal @ACC[2].2d,$Ni.2s,$N0.s[2] umlal @ACC[3].2d,$Ni.2s,$N0.s[3] umlal @ACC[4].2d,$Ni.2s,$N1.s[0] umlal @ACC[5].2d,$Ni.2s,$N1.s[1] umlal @ACC[6].2d,$Ni.2s,$N1.s[2] umlal @ACC[7].2d,$Ni.2s,$N1.s[3] st1 {@ACC[0].2d},[$toutptr],#16 ___ push(@ACC,shift(@ACC)); $code.=<<___; umlal @ACC[0].2d,$Bi.2s,$A0.s[0] ld1 {@ACC[7].2d},[$tinptr] umlal @ACC[1].2d,$Bi.2s,$A0.s[1] ld1 {$Ni.2s},[$bnptr],#8 // pull smashed m[8*i+$i] umlal @ACC[2].2d,$Bi.2s,$A0.s[2] b.eq .LInner_jump$i add $tinptr,$tinptr,#16 // don't advance in last iteration .LInner_jump$i: umlal @ACC[3].2d,$Bi.2s,$A0.s[3] umlal @ACC[4].2d,$Bi.2s,$A1.s[0] umlal @ACC[5].2d,$Bi.2s,$A1.s[1] umlal @ACC[6].2d,$Bi.2s,$A1.s[2] umlal @ACC[7].2d,$Bi.2s,$A1.s[3] ___ } $code.=<<___; b.ne .LInner_after_rewind$i sub $aptr,$aptr,$num,lsl#2 // rewind .LInner_after_rewind$i: umlal @ACC[0].2d,$Ni.2s,$N0.s[0] ld1 {$Bi.2s},[sp] // pull smashed b[8*i+0] umlal @ACC[1].2d,$Ni.2s,$N0.s[1] ld1 {$A0.4s,$A1.4s},[$aptr],#32 umlal @ACC[2].2d,$Ni.2s,$N0.s[2] add $bnptr,sp,#8 // rewind umlal @ACC[3].2d,$Ni.2s,$N0.s[3] umlal @ACC[4].2d,$Ni.2s,$N1.s[0] umlal @ACC[5].2d,$Ni.2s,$N1.s[1] umlal @ACC[6].2d,$Ni.2s,$N1.s[2] st1 {@ACC[0].2d},[$toutptr],#16 umlal @ACC[7].2d,$Ni.2s,$N1.s[3] bne .LNEON_8n_inner ___ push(@ACC,shift(@ACC)); $code.=<<___; add $tinptr,sp,#128 st1 {@ACC[0].2d,@ACC[1].2d},[$toutptr],#32 eor $N0.16b,$N0.16b,$N0.16b // $N0 st1 {@ACC[2].2d,@ACC[3].2d},[$toutptr],#32 eor $N1.16b,$N1.16b,$N1.16b // $N1 st1 {@ACC[4].2d,@ACC[5].2d},[$toutptr],#32 st1 {@ACC[6].2d},[$toutptr] subs $outer,$outer,#8 ld1 {@ACC[0].2d,@ACC[1].2d},[$tinptr],#32 ld1 {@ACC[2].2d,@ACC[3].2d},[$tinptr],#32 ld1 {@ACC[4].2d,@ACC[5].2d},[$tinptr],#32 ld1 {@ACC[6].2d,@ACC[7].2d},[$tinptr],#32 b.eq .LInner_8n_jump_2steps sub $nptr,$nptr,$num,lsl#2 // rewind b .LNEON_8n_outer .LInner_8n_jump_2steps: add $toutptr,sp,#128 st1 {$N0.2d,$N1.2d}, [sp],#32 // start wiping stack frame mov $Temp.16b,@ACC[0].16b ushr $temp.2d,@ACC[0].2d,#16 ext @ACC[0].16b,@ACC[0].16b,@ACC[0].16b,#8 st1 {$N0.2d,$N1.2d}, [sp],#32 add @ACC[0].2d,@ACC[0].2d,$temp.2d st1 {$N0.2d,$N1.2d}, [sp],#32 ushr $temp.2d,@ACC[0].2d,#16 st1 {$N0.2d,$N1.2d}, [sp],#32 zip1 @ACC[0].4h,$Temp.4h,@ACC[0].4h ins $temp.d[1],$zero.d[0] mov $inner,$num b .LNEON_tail_entry .align 4 .LNEON_tail: add @ACC[0].2d,@ACC[0].2d,$temp.2d mov $Temp.16b,@ACC[0].16b ushr $temp.2d,@ACC[0].2d,#16 ext @ACC[0].16b,@ACC[0].16b,@ACC[0].16b,#8 ld1 {@ACC[2].2d,@ACC[3].2d}, [$tinptr],#32 add @ACC[0].2d,@ACC[0].2d,$temp.2d ld1 {@ACC[4].2d,@ACC[5].2d}, [$tinptr],#32 ushr $temp.2d,@ACC[0].2d,#16 ld1 {@ACC[6].2d,@ACC[7].2d}, [$tinptr],#32 zip1 @ACC[0].4h,$Temp.4h,@ACC[0].4h ins $temp.d[1],$zero.d[0] .LNEON_tail_entry: ___ for ($i=1; $i<8; $i++) { $code.=<<___; add @ACC[1].2d,@ACC[1].2d,$temp.2d st1 {@ACC[0].s}[0], [$toutptr],#4 ushr $temp.2d,@ACC[1].2d,#16 mov $Temp.16b,@ACC[1].16b ext @ACC[1].16b,@ACC[1].16b,@ACC[1].16b,#8 add @ACC[1].2d,@ACC[1].2d,$temp.2d ushr $temp.2d,@ACC[1].2d,#16 zip1 @ACC[1].4h,$Temp.4h,@ACC[1].4h ins $temp.d[1],$zero.d[0] ___ push(@ACC,shift(@ACC)); } push(@ACC,shift(@ACC)); $code.=<<___; ld1 {@ACC[0].2d,@ACC[1].2d}, [$tinptr],#32 subs $inner,$inner,#8 st1 {@ACC[7].s}[0], [$toutptr],#4 bne .LNEON_tail st1 {$temp.s}[0], [$toutptr],#4 // top-most bit sub $nptr,$nptr,$num,lsl#2 // rewind $nptr subs $aptr,sp,#0 // clear carry flag add $bptr,sp,$num,lsl#2 .LNEON_sub: ldp w4,w5,[$aptr],#8 ldp w6,w7,[$aptr],#8 ldp w8,w9,[$nptr],#8 ldp w10,w11,[$nptr],#8 sbcs w8,w4,w8 sbcs w9,w5,w9 sbcs w10,w6,w10 sbcs w11,w7,w11 sub x17,$bptr,$aptr stp w8,w9,[$rptr],#8 stp w10,w11,[$rptr],#8 cbnz x17,.LNEON_sub ldr w10, [$aptr] // load top-most bit mov x11,sp eor v0.16b,v0.16b,v0.16b sub x11,$bptr,x11 // this is num*4 eor v1.16b,v1.16b,v1.16b mov $aptr,sp sub $rptr,$rptr,x11 // rewind $rptr mov $nptr,$bptr // second 3/4th of frame sbcs w10,w10,wzr // result is carry flag .LNEON_copy_n_zap: ldp w4,w5,[$aptr],#8 ldp w6,w7,[$aptr],#8 ldp w8,w9,[$rptr],#8 ldp w10,w11,[$rptr] sub $rptr,$rptr,#8 b.cs .LCopy_1 mov w8,w4 mov w9,w5 mov w10,w6 mov w11,w7 .LCopy_1: st1 {v0.2d,v1.2d}, [$nptr],#32 // wipe st1 {v0.2d,v1.2d}, [$nptr],#32 // wipe ldp w4,w5,[$aptr],#8 ldp w6,w7,[$aptr],#8 stp w8,w9,[$rptr],#8 stp w10,w11,[$rptr],#8 sub $aptr,$aptr,#32 ldp w8,w9,[$rptr],#8 ldp w10,w11,[$rptr] sub $rptr,$rptr,#8 b.cs .LCopy_2 mov w8, w4 mov w9, w5 mov w10, w6 mov w11, w7 .LCopy_2: st1 {v0.2d,v1.2d}, [$aptr],#32 // wipe st1 {v0.2d,v1.2d}, [$nptr],#32 // wipe sub x17,$bptr,$aptr // preserves carry stp w8,w9,[$rptr],#8 stp w10,w11,[$rptr],#8 cbnz x17,.LNEON_copy_n_zap mov sp,x16 ldp d14,d15,[sp,#64] ldp d12,d13,[sp,#48] ldp d10,d11,[sp,#32] ldp d8,d9,[sp,#16] ldr x29,[sp],#80 AARCH64_VALIDATE_LINK_REGISTER ret // bx lr .size bn_mul8x_mont_neon,.-bn_mul8x_mont_neon ___ } { ######################################################################## # Following is ARMv8 adaptation of sqrx8x_mont from x86_64-mont5 module. my ($a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7)=map("x$_",(6..13)); my ($t0,$t1,$t2,$t3)=map("x$_",(14..17)); my ($acc0,$acc1,$acc2,$acc3,$acc4,$acc5,$acc6,$acc7)=map("x$_",(19..26)); my ($cnt,$carry,$topmost)=("x27","x28","x30"); my ($tp,$ap_end,$na0)=($bp,$np,$carry); $code.=<<___; .type __bn_sqr8x_mont,%function .align 5 __bn_sqr8x_mont: cmp $ap,$bp b.ne __bn_mul4x_mont .Lsqr8x_mont: // Not adding AARCH64_SIGN_LINK_REGISTER here because __bn_sqr8x_mont is jumped to // only from bn_mul_mont which has already signed the return address. stp x29,x30,[sp,#-128]! add x29,sp,#0 stp x19,x20,[sp,#16] stp x21,x22,[sp,#32] stp x23,x24,[sp,#48] stp x25,x26,[sp,#64] stp x27,x28,[sp,#80] stp $rp,$np,[sp,#96] // offload rp and np ldp $a0,$a1,[$ap,#8*0] ldp $a2,$a3,[$ap,#8*2] ldp $a4,$a5,[$ap,#8*4] ldp $a6,$a7,[$ap,#8*6] sub $tp,sp,$num,lsl#4 lsl $num,$num,#3 ldr $n0,[$n0] // *n0 mov sp,$tp // alloca sub $cnt,$num,#8*8 b .Lsqr8x_zero_start .Lsqr8x_zero: sub $cnt,$cnt,#8*8 stp xzr,xzr,[$tp,#8*0] stp xzr,xzr,[$tp,#8*2] stp xzr,xzr,[$tp,#8*4] stp xzr,xzr,[$tp,#8*6] .Lsqr8x_zero_start: stp xzr,xzr,[$tp,#8*8] stp xzr,xzr,[$tp,#8*10] stp xzr,xzr,[$tp,#8*12] stp xzr,xzr,[$tp,#8*14] add $tp,$tp,#8*16 cbnz $cnt,.Lsqr8x_zero add $ap_end,$ap,$num add $ap,$ap,#8*8 mov $acc0,xzr mov $acc1,xzr mov $acc2,xzr mov $acc3,xzr mov $acc4,xzr mov $acc5,xzr mov $acc6,xzr mov $acc7,xzr mov $tp,sp str $n0,[x29,#112] // offload n0 // Multiply everything but a[i]*a[i] .align 4 .Lsqr8x_outer_loop: // a[1]a[0] (i) // a[2]a[0] // a[3]a[0] // a[4]a[0] // a[5]a[0] // a[6]a[0] // a[7]a[0] // a[2]a[1] (ii) // a[3]a[1] // a[4]a[1] // a[5]a[1] // a[6]a[1] // a[7]a[1] // a[3]a[2] (iii) // a[4]a[2] // a[5]a[2] // a[6]a[2] // a[7]a[2] // a[4]a[3] (iv) // a[5]a[3] // a[6]a[3] // a[7]a[3] // a[5]a[4] (v) // a[6]a[4] // a[7]a[4] // a[6]a[5] (vi) // a[7]a[5] // a[7]a[6] (vii) mul $t0,$a1,$a0 // lo(a[1..7]*a[0]) (i) mul $t1,$a2,$a0 mul $t2,$a3,$a0 mul $t3,$a4,$a0 adds $acc1,$acc1,$t0 // t[1]+lo(a[1]*a[0]) mul $t0,$a5,$a0 adcs $acc2,$acc2,$t1 mul $t1,$a6,$a0 adcs $acc3,$acc3,$t2 mul $t2,$a7,$a0 adcs $acc4,$acc4,$t3 umulh $t3,$a1,$a0 // hi(a[1..7]*a[0]) adcs $acc5,$acc5,$t0 umulh $t0,$a2,$a0 adcs $acc6,$acc6,$t1 umulh $t1,$a3,$a0 adcs $acc7,$acc7,$t2 umulh $t2,$a4,$a0 stp $acc0,$acc1,[$tp],#8*2 // t[0..1] adc $acc0,xzr,xzr // t[8] adds $acc2,$acc2,$t3 // t[2]+lo(a[1]*a[0]) umulh $t3,$a5,$a0 adcs $acc3,$acc3,$t0 umulh $t0,$a6,$a0 adcs $acc4,$acc4,$t1 umulh $t1,$a7,$a0 adcs $acc5,$acc5,$t2 mul $t2,$a2,$a1 // lo(a[2..7]*a[1]) (ii) adcs $acc6,$acc6,$t3 mul $t3,$a3,$a1 adcs $acc7,$acc7,$t0 mul $t0,$a4,$a1 adc $acc0,$acc0,$t1 mul $t1,$a5,$a1 adds $acc3,$acc3,$t2 mul $t2,$a6,$a1 adcs $acc4,$acc4,$t3 mul $t3,$a7,$a1 adcs $acc5,$acc5,$t0 umulh $t0,$a2,$a1 // hi(a[2..7]*a[1]) adcs $acc6,$acc6,$t1 umulh $t1,$a3,$a1 adcs $acc7,$acc7,$t2 umulh $t2,$a4,$a1 adcs $acc0,$acc0,$t3 umulh $t3,$a5,$a1 stp $acc2,$acc3,[$tp],#8*2 // t[2..3] adc $acc1,xzr,xzr // t[9] adds $acc4,$acc4,$t0 umulh $t0,$a6,$a1 adcs $acc5,$acc5,$t1 umulh $t1,$a7,$a1 adcs $acc6,$acc6,$t2 mul $t2,$a3,$a2 // lo(a[3..7]*a[2]) (iii) adcs $acc7,$acc7,$t3 mul $t3,$a4,$a2 adcs $acc0,$acc0,$t0 mul $t0,$a5,$a2 adc $acc1,$acc1,$t1 mul $t1,$a6,$a2 adds $acc5,$acc5,$t2 mul $t2,$a7,$a2 adcs $acc6,$acc6,$t3 umulh $t3,$a3,$a2 // hi(a[3..7]*a[2]) adcs $acc7,$acc7,$t0 umulh $t0,$a4,$a2 adcs $acc0,$acc0,$t1 umulh $t1,$a5,$a2 adcs $acc1,$acc1,$t2 umulh $t2,$a6,$a2 stp $acc4,$acc5,[$tp],#8*2 // t[4..5] adc $acc2,xzr,xzr // t[10] adds $acc6,$acc6,$t3 umulh $t3,$a7,$a2 adcs $acc7,$acc7,$t0 mul $t0,$a4,$a3 // lo(a[4..7]*a[3]) (iv) adcs $acc0,$acc0,$t1 mul $t1,$a5,$a3 adcs $acc1,$acc1,$t2 mul $t2,$a6,$a3 adc $acc2,$acc2,$t3 mul $t3,$a7,$a3 adds $acc7,$acc7,$t0 umulh $t0,$a4,$a3 // hi(a[4..7]*a[3]) adcs $acc0,$acc0,$t1 umulh $t1,$a5,$a3 adcs $acc1,$acc1,$t2 umulh $t2,$a6,$a3 adcs $acc2,$acc2,$t3 umulh $t3,$a7,$a3 stp $acc6,$acc7,[$tp],#8*2 // t[6..7] adc $acc3,xzr,xzr // t[11] adds $acc0,$acc0,$t0 mul $t0,$a5,$a4 // lo(a[5..7]*a[4]) (v) adcs $acc1,$acc1,$t1 mul $t1,$a6,$a4 adcs $acc2,$acc2,$t2 mul $t2,$a7,$a4 adc $acc3,$acc3,$t3 umulh $t3,$a5,$a4 // hi(a[5..7]*a[4]) adds $acc1,$acc1,$t0 umulh $t0,$a6,$a4 adcs $acc2,$acc2,$t1 umulh $t1,$a7,$a4 adcs $acc3,$acc3,$t2 mul $t2,$a6,$a5 // lo(a[6..7]*a[5]) (vi) adc $acc4,xzr,xzr // t[12] adds $acc2,$acc2,$t3 mul $t3,$a7,$a5 adcs $acc3,$acc3,$t0 umulh $t0,$a6,$a5 // hi(a[6..7]*a[5]) adc $acc4,$acc4,$t1 umulh $t1,$a7,$a5 adds $acc3,$acc3,$t2 mul $t2,$a7,$a6 // lo(a[7]*a[6]) (vii) adcs $acc4,$acc4,$t3 umulh $t3,$a7,$a6 // hi(a[7]*a[6]) adc $acc5,xzr,xzr // t[13] adds $acc4,$acc4,$t0 sub $cnt,$ap_end,$ap // done yet? adc $acc5,$acc5,$t1 adds $acc5,$acc5,$t2 sub $t0,$ap_end,$num // rewinded ap adc $acc6,xzr,xzr // t[14] add $acc6,$acc6,$t3 cbz $cnt,.Lsqr8x_outer_break mov $n0,$a0 ldp $a0,$a1,[$tp,#8*0] ldp $a2,$a3,[$tp,#8*2] ldp $a4,$a5,[$tp,#8*4] ldp $a6,$a7,[$tp,#8*6] adds $acc0,$acc0,$a0 adcs $acc1,$acc1,$a1 ldp $a0,$a1,[$ap,#8*0] adcs $acc2,$acc2,$a2 adcs $acc3,$acc3,$a3 ldp $a2,$a3,[$ap,#8*2] adcs $acc4,$acc4,$a4 adcs $acc5,$acc5,$a5 ldp $a4,$a5,[$ap,#8*4] adcs $acc6,$acc6,$a6 mov $rp,$ap adcs $acc7,xzr,$a7 ldp $a6,$a7,[$ap,#8*6] add $ap,$ap,#8*8 //adc $carry,xzr,xzr // moved below mov $cnt,#-8*8 // a[8]a[0] // a[9]a[0] // a[a]a[0] // a[b]a[0] // a[c]a[0] // a[d]a[0] // a[e]a[0] // a[f]a[0] // a[8]a[1] // a[f]a[1]........................ // a[8]a[2] // a[f]a[2]........................ // a[8]a[3] // a[f]a[3]........................ // a[8]a[4] // a[f]a[4]........................ // a[8]a[5] // a[f]a[5]........................ // a[8]a[6] // a[f]a[6]........................ // a[8]a[7] // a[f]a[7]........................ .Lsqr8x_mul: mul $t0,$a0,$n0 adc $carry,xzr,xzr // carry bit, modulo-scheduled mul $t1,$a1,$n0 add $cnt,$cnt,#8 mul $t2,$a2,$n0 mul $t3,$a3,$n0 adds $acc0,$acc0,$t0 mul $t0,$a4,$n0 adcs $acc1,$acc1,$t1 mul $t1,$a5,$n0 adcs $acc2,$acc2,$t2 mul $t2,$a6,$n0 adcs $acc3,$acc3,$t3 mul $t3,$a7,$n0 adcs $acc4,$acc4,$t0 umulh $t0,$a0,$n0 adcs $acc5,$acc5,$t1 umulh $t1,$a1,$n0 adcs $acc6,$acc6,$t2 umulh $t2,$a2,$n0 adcs $acc7,$acc7,$t3 umulh $t3,$a3,$n0 adc $carry,$carry,xzr str $acc0,[$tp],#8 adds $acc0,$acc1,$t0 umulh $t0,$a4,$n0 adcs $acc1,$acc2,$t1 umulh $t1,$a5,$n0 adcs $acc2,$acc3,$t2 umulh $t2,$a6,$n0 adcs $acc3,$acc4,$t3 umulh $t3,$a7,$n0 ldr $n0,[$rp,$cnt] adcs $acc4,$acc5,$t0 adcs $acc5,$acc6,$t1 adcs $acc6,$acc7,$t2 adcs $acc7,$carry,$t3 //adc $carry,xzr,xzr // moved above cbnz $cnt,.Lsqr8x_mul // note that carry flag is guaranteed // to be zero at this point cmp $ap,$ap_end // done yet? b.eq .Lsqr8x_break ldp $a0,$a1,[$tp,#8*0] ldp $a2,$a3,[$tp,#8*2] ldp $a4,$a5,[$tp,#8*4] ldp $a6,$a7,[$tp,#8*6] adds $acc0,$acc0,$a0 ldur $n0,[$rp,#-8*8] adcs $acc1,$acc1,$a1 ldp $a0,$a1,[$ap,#8*0] adcs $acc2,$acc2,$a2 adcs $acc3,$acc3,$a3 ldp $a2,$a3,[$ap,#8*2] adcs $acc4,$acc4,$a4 adcs $acc5,$acc5,$a5 ldp $a4,$a5,[$ap,#8*4] adcs $acc6,$acc6,$a6 mov $cnt,#-8*8 adcs $acc7,$acc7,$a7 ldp $a6,$a7,[$ap,#8*6] add $ap,$ap,#8*8 //adc $carry,xzr,xzr // moved above b .Lsqr8x_mul .align 4 .Lsqr8x_break: ldp $a0,$a1,[$rp,#8*0] add $ap,$rp,#8*8 ldp $a2,$a3,[$rp,#8*2] sub $t0,$ap_end,$ap // is it last iteration? ldp $a4,$a5,[$rp,#8*4] sub $t1,$tp,$t0 ldp $a6,$a7,[$rp,#8*6] cbz $t0,.Lsqr8x_outer_loop stp $acc0,$acc1,[$tp,#8*0] ldp $acc0,$acc1,[$t1,#8*0] stp $acc2,$acc3,[$tp,#8*2] ldp $acc2,$acc3,[$t1,#8*2] stp $acc4,$acc5,[$tp,#8*4] ldp $acc4,$acc5,[$t1,#8*4] stp $acc6,$acc7,[$tp,#8*6] mov $tp,$t1 ldp $acc6,$acc7,[$t1,#8*6] b .Lsqr8x_outer_loop .align 4 .Lsqr8x_outer_break: // Now multiply above result by 2 and add a[n-1]*a[n-1]|...|a[0]*a[0] ldp $a1,$a3,[$t0,#8*0] // recall that $t0 is &a[0] ldp $t1,$t2,[sp,#8*1] ldp $a5,$a7,[$t0,#8*2] add $ap,$t0,#8*4 ldp $t3,$t0,[sp,#8*3] stp $acc0,$acc1,[$tp,#8*0] mul $acc0,$a1,$a1 stp $acc2,$acc3,[$tp,#8*2] umulh $a1,$a1,$a1 stp $acc4,$acc5,[$tp,#8*4] mul $a2,$a3,$a3 stp $acc6,$acc7,[$tp,#8*6] mov $tp,sp umulh $a3,$a3,$a3 adds $acc1,$a1,$t1,lsl#1 extr $t1,$t2,$t1,#63 sub $cnt,$num,#8*4 .Lsqr4x_shift_n_add: adcs $acc2,$a2,$t1 extr $t2,$t3,$t2,#63 sub $cnt,$cnt,#8*4 adcs $acc3,$a3,$t2 ldp $t1,$t2,[$tp,#8*5] mul $a4,$a5,$a5 ldp $a1,$a3,[$ap],#8*2 umulh $a5,$a5,$a5 mul $a6,$a7,$a7 umulh $a7,$a7,$a7 extr $t3,$t0,$t3,#63 stp $acc0,$acc1,[$tp,#8*0] adcs $acc4,$a4,$t3 extr $t0,$t1,$t0,#63 stp $acc2,$acc3,[$tp,#8*2] adcs $acc5,$a5,$t0 ldp $t3,$t0,[$tp,#8*7] extr $t1,$t2,$t1,#63 adcs $acc6,$a6,$t1 extr $t2,$t3,$t2,#63 adcs $acc7,$a7,$t2 ldp $t1,$t2,[$tp,#8*9] mul $a0,$a1,$a1 ldp $a5,$a7,[$ap],#8*2 umulh $a1,$a1,$a1 mul $a2,$a3,$a3 umulh $a3,$a3,$a3 stp $acc4,$acc5,[$tp,#8*4] extr $t3,$t0,$t3,#63 stp $acc6,$acc7,[$tp,#8*6] add $tp,$tp,#8*8 adcs $acc0,$a0,$t3 extr $t0,$t1,$t0,#63 adcs $acc1,$a1,$t0 ldp $t3,$t0,[$tp,#8*3] extr $t1,$t2,$t1,#63 cbnz $cnt,.Lsqr4x_shift_n_add ___ my ($np,$np_end)=($ap,$ap_end); $code.=<<___; ldp $np,$n0,[x29,#104] // pull np and n0 adcs $acc2,$a2,$t1 extr $t2,$t3,$t2,#63 adcs $acc3,$a3,$t2 ldp $t1,$t2,[$tp,#8*5] mul $a4,$a5,$a5 umulh $a5,$a5,$a5 stp $acc0,$acc1,[$tp,#8*0] mul $a6,$a7,$a7 umulh $a7,$a7,$a7 stp $acc2,$acc3,[$tp,#8*2] extr $t3,$t0,$t3,#63 adcs $acc4,$a4,$t3 extr $t0,$t1,$t0,#63 ldp $acc0,$acc1,[sp,#8*0] adcs $acc5,$a5,$t0 extr $t1,$t2,$t1,#63 ldp $a0,$a1,[$np,#8*0] adcs $acc6,$a6,$t1 extr $t2,xzr,$t2,#63 ldp $a2,$a3,[$np,#8*2] adc $acc7,$a7,$t2 ldp $a4,$a5,[$np,#8*4] // Reduce by 512 bits per iteration mul $na0,$n0,$acc0 // t[0]*n0 ldp $a6,$a7,[$np,#8*6] add $np_end,$np,$num ldp $acc2,$acc3,[sp,#8*2] stp $acc4,$acc5,[$tp,#8*4] ldp $acc4,$acc5,[sp,#8*4] stp $acc6,$acc7,[$tp,#8*6] ldp $acc6,$acc7,[sp,#8*6] add $np,$np,#8*8 mov $topmost,xzr // initial top-most carry mov $tp,sp mov $cnt,#8 .Lsqr8x_reduction: // (*) mul $t0,$a0,$na0 // lo(n[0-7])*lo(t[0]*n0) mul $t1,$a1,$na0 sub $cnt,$cnt,#1 mul $t2,$a2,$na0 str $na0,[$tp],#8 // put aside t[0]*n0 for tail processing mul $t3,$a3,$na0 // (*) adds xzr,$acc0,$t0 subs xzr,$acc0,#1 // (*) mul $t0,$a4,$na0 adcs $acc0,$acc1,$t1 mul $t1,$a5,$na0 adcs $acc1,$acc2,$t2 mul $t2,$a6,$na0 adcs $acc2,$acc3,$t3 mul $t3,$a7,$na0 adcs $acc3,$acc4,$t0 umulh $t0,$a0,$na0 // hi(n[0-7])*lo(t[0]*n0) adcs $acc4,$acc5,$t1 umulh $t1,$a1,$na0 adcs $acc5,$acc6,$t2 umulh $t2,$a2,$na0 adcs $acc6,$acc7,$t3 umulh $t3,$a3,$na0 adc $acc7,xzr,xzr adds $acc0,$acc0,$t0 umulh $t0,$a4,$na0 adcs $acc1,$acc1,$t1 umulh $t1,$a5,$na0 adcs $acc2,$acc2,$t2 umulh $t2,$a6,$na0 adcs $acc3,$acc3,$t3 umulh $t3,$a7,$na0 mul $na0,$n0,$acc0 // next t[0]*n0 adcs $acc4,$acc4,$t0 adcs $acc5,$acc5,$t1 adcs $acc6,$acc6,$t2 adc $acc7,$acc7,$t3 cbnz $cnt,.Lsqr8x_reduction ldp $t0,$t1,[$tp,#8*0] ldp $t2,$t3,[$tp,#8*2] mov $rp,$tp sub $cnt,$np_end,$np // done yet? adds $acc0,$acc0,$t0 adcs $acc1,$acc1,$t1 ldp $t0,$t1,[$tp,#8*4] adcs $acc2,$acc2,$t2 adcs $acc3,$acc3,$t3 ldp $t2,$t3,[$tp,#8*6] adcs $acc4,$acc4,$t0 adcs $acc5,$acc5,$t1 adcs $acc6,$acc6,$t2 adcs $acc7,$acc7,$t3 //adc $carry,xzr,xzr // moved below cbz $cnt,.Lsqr8x8_post_condition ldur $n0,[$tp,#-8*8] ldp $a0,$a1,[$np,#8*0] ldp $a2,$a3,[$np,#8*2] ldp $a4,$a5,[$np,#8*4] mov $cnt,#-8*8 ldp $a6,$a7,[$np,#8*6] add $np,$np,#8*8 .Lsqr8x_tail: mul $t0,$a0,$n0 adc $carry,xzr,xzr // carry bit, modulo-scheduled mul $t1,$a1,$n0 add $cnt,$cnt,#8 mul $t2,$a2,$n0 mul $t3,$a3,$n0 adds $acc0,$acc0,$t0 mul $t0,$a4,$n0 adcs $acc1,$acc1,$t1 mul $t1,$a5,$n0 adcs $acc2,$acc2,$t2 mul $t2,$a6,$n0 adcs $acc3,$acc3,$t3 mul $t3,$a7,$n0 adcs $acc4,$acc4,$t0 umulh $t0,$a0,$n0 adcs $acc5,$acc5,$t1 umulh $t1,$a1,$n0 adcs $acc6,$acc6,$t2 umulh $t2,$a2,$n0 adcs $acc7,$acc7,$t3 umulh $t3,$a3,$n0 adc $carry,$carry,xzr str $acc0,[$tp],#8 adds $acc0,$acc1,$t0 umulh $t0,$a4,$n0 adcs $acc1,$acc2,$t1 umulh $t1,$a5,$n0 adcs $acc2,$acc3,$t2 umulh $t2,$a6,$n0 adcs $acc3,$acc4,$t3 umulh $t3,$a7,$n0 ldr $n0,[$rp,$cnt] adcs $acc4,$acc5,$t0 adcs $acc5,$acc6,$t1 adcs $acc6,$acc7,$t2 adcs $acc7,$carry,$t3 //adc $carry,xzr,xzr // moved above cbnz $cnt,.Lsqr8x_tail // note that carry flag is guaranteed // to be zero at this point ldp $a0,$a1,[$tp,#8*0] sub $cnt,$np_end,$np // done yet? sub $t2,$np_end,$num // rewinded np ldp $a2,$a3,[$tp,#8*2] ldp $a4,$a5,[$tp,#8*4] ldp $a6,$a7,[$tp,#8*6] cbz $cnt,.Lsqr8x_tail_break ldur $n0,[$rp,#-8*8] adds $acc0,$acc0,$a0 adcs $acc1,$acc1,$a1 ldp $a0,$a1,[$np,#8*0] adcs $acc2,$acc2,$a2 adcs $acc3,$acc3,$a3 ldp $a2,$a3,[$np,#8*2] adcs $acc4,$acc4,$a4 adcs $acc5,$acc5,$a5 ldp $a4,$a5,[$np,#8*4] adcs $acc6,$acc6,$a6 mov $cnt,#-8*8 adcs $acc7,$acc7,$a7 ldp $a6,$a7,[$np,#8*6] add $np,$np,#8*8 //adc $carry,xzr,xzr // moved above b .Lsqr8x_tail .align 4 .Lsqr8x_tail_break: ldr $n0,[x29,#112] // pull n0 add $cnt,$tp,#8*8 // end of current t[num] window subs xzr,$topmost,#1 // "move" top-most carry to carry bit adcs $t0,$acc0,$a0 adcs $t1,$acc1,$a1 ldp $acc0,$acc1,[$rp,#8*0] adcs $acc2,$acc2,$a2 ldp $a0,$a1,[$t2,#8*0] // recall that $t2 is &n[0] adcs $acc3,$acc3,$a3 ldp $a2,$a3,[$t2,#8*2] adcs $acc4,$acc4,$a4 adcs $acc5,$acc5,$a5 ldp $a4,$a5,[$t2,#8*4] adcs $acc6,$acc6,$a6 adcs $acc7,$acc7,$a7 ldp $a6,$a7,[$t2,#8*6] add $np,$t2,#8*8 adc $topmost,xzr,xzr // top-most carry mul $na0,$n0,$acc0 stp $t0,$t1,[$tp,#8*0] stp $acc2,$acc3,[$tp,#8*2] ldp $acc2,$acc3,[$rp,#8*2] stp $acc4,$acc5,[$tp,#8*4] ldp $acc4,$acc5,[$rp,#8*4] cmp $cnt,x29 // did we hit the bottom? stp $acc6,$acc7,[$tp,#8*6] mov $tp,$rp // slide the window ldp $acc6,$acc7,[$rp,#8*6] mov $cnt,#8 b.ne .Lsqr8x_reduction // Final step. We see if result is larger than modulus, and // if it is, subtract the modulus. But comparison implies // subtraction. So we subtract modulus, see if it borrowed, // and conditionally copy original value. ldr $rp,[x29,#96] // pull rp add $tp,$tp,#8*8 subs $t0,$acc0,$a0 sbcs $t1,$acc1,$a1 sub $cnt,$num,#8*8 mov $ap_end,$rp // $rp copy .Lsqr8x_sub: sbcs $t2,$acc2,$a2 ldp $a0,$a1,[$np,#8*0] sbcs $t3,$acc3,$a3 stp $t0,$t1,[$rp,#8*0] sbcs $t0,$acc4,$a4 ldp $a2,$a3,[$np,#8*2] sbcs $t1,$acc5,$a5 stp $t2,$t3,[$rp,#8*2] sbcs $t2,$acc6,$a6 ldp $a4,$a5,[$np,#8*4] sbcs $t3,$acc7,$a7 ldp $a6,$a7,[$np,#8*6] add $np,$np,#8*8 ldp $acc0,$acc1,[$tp,#8*0] sub $cnt,$cnt,#8*8 ldp $acc2,$acc3,[$tp,#8*2] ldp $acc4,$acc5,[$tp,#8*4] ldp $acc6,$acc7,[$tp,#8*6] add $tp,$tp,#8*8 stp $t0,$t1,[$rp,#8*4] sbcs $t0,$acc0,$a0 stp $t2,$t3,[$rp,#8*6] add $rp,$rp,#8*8 sbcs $t1,$acc1,$a1 cbnz $cnt,.Lsqr8x_sub sbcs $t2,$acc2,$a2 mov $tp,sp add $ap,sp,$num ldp $a0,$a1,[$ap_end,#8*0] sbcs $t3,$acc3,$a3 stp $t0,$t1,[$rp,#8*0] sbcs $t0,$acc4,$a4 ldp $a2,$a3,[$ap_end,#8*2] sbcs $t1,$acc5,$a5 stp $t2,$t3,[$rp,#8*2] sbcs $t2,$acc6,$a6 ldp $acc0,$acc1,[$ap,#8*0] sbcs $t3,$acc7,$a7 ldp $acc2,$acc3,[$ap,#8*2] sbcs xzr,$topmost,xzr // did it borrow? ldr x30,[x29,#8] // pull return address stp $t0,$t1,[$rp,#8*4] stp $t2,$t3,[$rp,#8*6] sub $cnt,$num,#8*4 .Lsqr4x_cond_copy: sub $cnt,$cnt,#8*4 csel $t0,$acc0,$a0,lo stp xzr,xzr,[$tp,#8*0] csel $t1,$acc1,$a1,lo ldp $a0,$a1,[$ap_end,#8*4] ldp $acc0,$acc1,[$ap,#8*4] csel $t2,$acc2,$a2,lo stp xzr,xzr,[$tp,#8*2] add $tp,$tp,#8*4 csel $t3,$acc3,$a3,lo ldp $a2,$a3,[$ap_end,#8*6] ldp $acc2,$acc3,[$ap,#8*6] add $ap,$ap,#8*4 stp $t0,$t1,[$ap_end,#8*0] stp $t2,$t3,[$ap_end,#8*2] add $ap_end,$ap_end,#8*4 stp xzr,xzr,[$ap,#8*0] stp xzr,xzr,[$ap,#8*2] cbnz $cnt,.Lsqr4x_cond_copy csel $t0,$acc0,$a0,lo stp xzr,xzr,[$tp,#8*0] csel $t1,$acc1,$a1,lo stp xzr,xzr,[$tp,#8*2] csel $t2,$acc2,$a2,lo csel $t3,$acc3,$a3,lo stp $t0,$t1,[$ap_end,#8*0] stp $t2,$t3,[$ap_end,#8*2] b .Lsqr8x_done .align 4 .Lsqr8x8_post_condition: adc $carry,xzr,xzr ldr x30,[x29,#8] // pull return address // $acc0-7,$carry hold result, $a0-7 hold modulus subs $a0,$acc0,$a0 ldr $ap,[x29,#96] // pull rp sbcs $a1,$acc1,$a1 stp xzr,xzr,[sp,#8*0] sbcs $a2,$acc2,$a2 stp xzr,xzr,[sp,#8*2] sbcs $a3,$acc3,$a3 stp xzr,xzr,[sp,#8*4] sbcs $a4,$acc4,$a4 stp xzr,xzr,[sp,#8*6] sbcs $a5,$acc5,$a5 stp xzr,xzr,[sp,#8*8] sbcs $a6,$acc6,$a6 stp xzr,xzr,[sp,#8*10] sbcs $a7,$acc7,$a7 stp xzr,xzr,[sp,#8*12] sbcs $carry,$carry,xzr // did it borrow? stp xzr,xzr,[sp,#8*14] // $a0-7 hold result-modulus csel $a0,$acc0,$a0,lo csel $a1,$acc1,$a1,lo csel $a2,$acc2,$a2,lo csel $a3,$acc3,$a3,lo stp $a0,$a1,[$ap,#8*0] csel $a4,$acc4,$a4,lo csel $a5,$acc5,$a5,lo stp $a2,$a3,[$ap,#8*2] csel $a6,$acc6,$a6,lo csel $a7,$acc7,$a7,lo stp $a4,$a5,[$ap,#8*4] stp $a6,$a7,[$ap,#8*6] .Lsqr8x_done: ldp x19,x20,[x29,#16] mov sp,x29 ldp x21,x22,[x29,#32] mov x0,#1 ldp x23,x24,[x29,#48] ldp x25,x26,[x29,#64] ldp x27,x28,[x29,#80] ldr x29,[sp],#128 // x30 is loaded earlier AARCH64_VALIDATE_LINK_REGISTER ret .size __bn_sqr8x_mont,.-__bn_sqr8x_mont ___ } { ######################################################################## # Even though this might look as ARMv8 adaptation of mulx4x_mont from # x86_64-mont5 module, it's different in sense that it performs # reduction 256 bits at a time. my ($a0,$a1,$a2,$a3, $t0,$t1,$t2,$t3, $m0,$m1,$m2,$m3, $acc0,$acc1,$acc2,$acc3,$acc4, $bi,$mi,$tp,$ap_end,$cnt) = map("x$_",(6..17,19..28)); my $bp_end=$rp; my ($carry,$topmost) = ($rp,"x30"); $code.=<<___; .type __bn_mul4x_mont,%function .align 5 __bn_mul4x_mont: // Not adding AARCH64_SIGN_LINK_REGISTER here because __bn_mul4x_mont is jumped to // only from bn_mul_mont (or __bn_sqr8x_mont from bn_mul_mont) which has already signed the return address. stp x29,x30,[sp,#-128]! add x29,sp,#0 stp x19,x20,[sp,#16] stp x21,x22,[sp,#32] stp x23,x24,[sp,#48] stp x25,x26,[sp,#64] stp x27,x28,[sp,#80] sub $tp,sp,$num,lsl#3 lsl $num,$num,#3 ldr $n0,[$n0] // *n0 sub sp,$tp,#8*4 // alloca add $t0,$bp,$num add $ap_end,$ap,$num stp $rp,$t0,[x29,#96] // offload rp and &b[num] ldr $bi,[$bp,#8*0] // b[0] ldp $a0,$a1,[$ap,#8*0] // a[0..3] ldp $a2,$a3,[$ap,#8*2] add $ap,$ap,#8*4 mov $acc0,xzr mov $acc1,xzr mov $acc2,xzr mov $acc3,xzr ldp $m0,$m1,[$np,#8*0] // n[0..3] ldp $m2,$m3,[$np,#8*2] adds $np,$np,#8*4 // clear carry bit mov $carry,xzr mov $cnt,#0 mov $tp,sp .Loop_mul4x_1st_reduction: mul $t0,$a0,$bi // lo(a[0..3]*b[0]) adc $carry,$carry,xzr // modulo-scheduled mul $t1,$a1,$bi add $cnt,$cnt,#8 mul $t2,$a2,$bi and $cnt,$cnt,#31 mul $t3,$a3,$bi adds $acc0,$acc0,$t0 umulh $t0,$a0,$bi // hi(a[0..3]*b[0]) adcs $acc1,$acc1,$t1 mul $mi,$acc0,$n0 // t[0]*n0 adcs $acc2,$acc2,$t2 umulh $t1,$a1,$bi adcs $acc3,$acc3,$t3 umulh $t2,$a2,$bi adc $acc4,xzr,xzr umulh $t3,$a3,$bi ldr $bi,[$bp,$cnt] // next b[i] (or b[0]) adds $acc1,$acc1,$t0 // (*) mul $t0,$m0,$mi // lo(n[0..3]*t[0]*n0) str $mi,[$tp],#8 // put aside t[0]*n0 for tail processing adcs $acc2,$acc2,$t1 mul $t1,$m1,$mi adcs $acc3,$acc3,$t2 mul $t2,$m2,$mi adc $acc4,$acc4,$t3 // can't overflow mul $t3,$m3,$mi // (*) adds xzr,$acc0,$t0 subs xzr,$acc0,#1 // (*) umulh $t0,$m0,$mi // hi(n[0..3]*t[0]*n0) adcs $acc0,$acc1,$t1 umulh $t1,$m1,$mi adcs $acc1,$acc2,$t2 umulh $t2,$m2,$mi adcs $acc2,$acc3,$t3 umulh $t3,$m3,$mi adcs $acc3,$acc4,$carry adc $carry,xzr,xzr adds $acc0,$acc0,$t0 sub $t0,$ap_end,$ap adcs $acc1,$acc1,$t1 adcs $acc2,$acc2,$t2 adcs $acc3,$acc3,$t3 //adc $carry,$carry,xzr cbnz $cnt,.Loop_mul4x_1st_reduction cbz $t0,.Lmul4x4_post_condition ldp $a0,$a1,[$ap,#8*0] // a[4..7] ldp $a2,$a3,[$ap,#8*2] add $ap,$ap,#8*4 ldr $mi,[sp] // a[0]*n0 ldp $m0,$m1,[$np,#8*0] // n[4..7] ldp $m2,$m3,[$np,#8*2] add $np,$np,#8*4 .Loop_mul4x_1st_tail: mul $t0,$a0,$bi // lo(a[4..7]*b[i]) adc $carry,$carry,xzr // modulo-scheduled mul $t1,$a1,$bi add $cnt,$cnt,#8 mul $t2,$a2,$bi and $cnt,$cnt,#31 mul $t3,$a3,$bi adds $acc0,$acc0,$t0 umulh $t0,$a0,$bi // hi(a[4..7]*b[i]) adcs $acc1,$acc1,$t1 umulh $t1,$a1,$bi adcs $acc2,$acc2,$t2 umulh $t2,$a2,$bi adcs $acc3,$acc3,$t3 umulh $t3,$a3,$bi adc $acc4,xzr,xzr ldr $bi,[$bp,$cnt] // next b[i] (or b[0]) adds $acc1,$acc1,$t0 mul $t0,$m0,$mi // lo(n[4..7]*a[0]*n0) adcs $acc2,$acc2,$t1 mul $t1,$m1,$mi adcs $acc3,$acc3,$t2 mul $t2,$m2,$mi adc $acc4,$acc4,$t3 // can't overflow mul $t3,$m3,$mi adds $acc0,$acc0,$t0 umulh $t0,$m0,$mi // hi(n[4..7]*a[0]*n0) adcs $acc1,$acc1,$t1 umulh $t1,$m1,$mi adcs $acc2,$acc2,$t2 umulh $t2,$m2,$mi adcs $acc3,$acc3,$t3 adcs $acc4,$acc4,$carry umulh $t3,$m3,$mi adc $carry,xzr,xzr ldr $mi,[sp,$cnt] // next t[0]*n0 str $acc0,[$tp],#8 // result!!! adds $acc0,$acc1,$t0 sub $t0,$ap_end,$ap // done yet? adcs $acc1,$acc2,$t1 adcs $acc2,$acc3,$t2 adcs $acc3,$acc4,$t3 //adc $carry,$carry,xzr cbnz $cnt,.Loop_mul4x_1st_tail sub $t1,$ap_end,$num // rewinded $ap cbz $t0,.Lmul4x_proceed ldp $a0,$a1,[$ap,#8*0] ldp $a2,$a3,[$ap,#8*2] add $ap,$ap,#8*4 ldp $m0,$m1,[$np,#8*0] ldp $m2,$m3,[$np,#8*2] add $np,$np,#8*4 b .Loop_mul4x_1st_tail .align 5 .Lmul4x_proceed: ldr $bi,[$bp,#8*4]! // *++b adc $topmost,$carry,xzr ldp $a0,$a1,[$t1,#8*0] // a[0..3] sub $np,$np,$num // rewind np ldp $a2,$a3,[$t1,#8*2] add $ap,$t1,#8*4 stp $acc0,$acc1,[$tp,#8*0] // result!!! ldp $acc0,$acc1,[sp,#8*4] // t[0..3] stp $acc2,$acc3,[$tp,#8*2] // result!!! ldp $acc2,$acc3,[sp,#8*6] ldp $m0,$m1,[$np,#8*0] // n[0..3] mov $tp,sp ldp $m2,$m3,[$np,#8*2] adds $np,$np,#8*4 // clear carry bit mov $carry,xzr .align 4 .Loop_mul4x_reduction: mul $t0,$a0,$bi // lo(a[0..3]*b[4]) adc $carry,$carry,xzr // modulo-scheduled mul $t1,$a1,$bi add $cnt,$cnt,#8 mul $t2,$a2,$bi and $cnt,$cnt,#31 mul $t3,$a3,$bi adds $acc0,$acc0,$t0 umulh $t0,$a0,$bi // hi(a[0..3]*b[4]) adcs $acc1,$acc1,$t1 mul $mi,$acc0,$n0 // t[0]*n0 adcs $acc2,$acc2,$t2 umulh $t1,$a1,$bi adcs $acc3,$acc3,$t3 umulh $t2,$a2,$bi adc $acc4,xzr,xzr umulh $t3,$a3,$bi ldr $bi,[$bp,$cnt] // next b[i] adds $acc1,$acc1,$t0 // (*) mul $t0,$m0,$mi str $mi,[$tp],#8 // put aside t[0]*n0 for tail processing adcs $acc2,$acc2,$t1 mul $t1,$m1,$mi // lo(n[0..3]*t[0]*n0 adcs $acc3,$acc3,$t2 mul $t2,$m2,$mi adc $acc4,$acc4,$t3 // can't overflow mul $t3,$m3,$mi // (*) adds xzr,$acc0,$t0 subs xzr,$acc0,#1 // (*) umulh $t0,$m0,$mi // hi(n[0..3]*t[0]*n0 adcs $acc0,$acc1,$t1 umulh $t1,$m1,$mi adcs $acc1,$acc2,$t2 umulh $t2,$m2,$mi adcs $acc2,$acc3,$t3 umulh $t3,$m3,$mi adcs $acc3,$acc4,$carry adc $carry,xzr,xzr adds $acc0,$acc0,$t0 adcs $acc1,$acc1,$t1 adcs $acc2,$acc2,$t2 adcs $acc3,$acc3,$t3 //adc $carry,$carry,xzr cbnz $cnt,.Loop_mul4x_reduction adc $carry,$carry,xzr ldp $t0,$t1,[$tp,#8*4] // t[4..7] ldp $t2,$t3,[$tp,#8*6] ldp $a0,$a1,[$ap,#8*0] // a[4..7] ldp $a2,$a3,[$ap,#8*2] add $ap,$ap,#8*4 adds $acc0,$acc0,$t0 adcs $acc1,$acc1,$t1 adcs $acc2,$acc2,$t2 adcs $acc3,$acc3,$t3 //adc $carry,$carry,xzr ldr $mi,[sp] // t[0]*n0 ldp $m0,$m1,[$np,#8*0] // n[4..7] ldp $m2,$m3,[$np,#8*2] add $np,$np,#8*4 .align 4 .Loop_mul4x_tail: mul $t0,$a0,$bi // lo(a[4..7]*b[4]) adc $carry,$carry,xzr // modulo-scheduled mul $t1,$a1,$bi add $cnt,$cnt,#8 mul $t2,$a2,$bi and $cnt,$cnt,#31 mul $t3,$a3,$bi adds $acc0,$acc0,$t0 umulh $t0,$a0,$bi // hi(a[4..7]*b[4]) adcs $acc1,$acc1,$t1 umulh $t1,$a1,$bi adcs $acc2,$acc2,$t2 umulh $t2,$a2,$bi adcs $acc3,$acc3,$t3 umulh $t3,$a3,$bi adc $acc4,xzr,xzr ldr $bi,[$bp,$cnt] // next b[i] adds $acc1,$acc1,$t0 mul $t0,$m0,$mi // lo(n[4..7]*t[0]*n0) adcs $acc2,$acc2,$t1 mul $t1,$m1,$mi adcs $acc3,$acc3,$t2 mul $t2,$m2,$mi adc $acc4,$acc4,$t3 // can't overflow mul $t3,$m3,$mi adds $acc0,$acc0,$t0 umulh $t0,$m0,$mi // hi(n[4..7]*t[0]*n0) adcs $acc1,$acc1,$t1 umulh $t1,$m1,$mi adcs $acc2,$acc2,$t2 umulh $t2,$m2,$mi adcs $acc3,$acc3,$t3 umulh $t3,$m3,$mi adcs $acc4,$acc4,$carry ldr $mi,[sp,$cnt] // next a[0]*n0 adc $carry,xzr,xzr str $acc0,[$tp],#8 // result!!! adds $acc0,$acc1,$t0 sub $t0,$ap_end,$ap // done yet? adcs $acc1,$acc2,$t1 adcs $acc2,$acc3,$t2 adcs $acc3,$acc4,$t3 //adc $carry,$carry,xzr cbnz $cnt,.Loop_mul4x_tail sub $t1,$np,$num // rewinded np? adc $carry,$carry,xzr cbz $t0,.Loop_mul4x_break ldp $t0,$t1,[$tp,#8*4] ldp $t2,$t3,[$tp,#8*6] ldp $a0,$a1,[$ap,#8*0] ldp $a2,$a3,[$ap,#8*2] add $ap,$ap,#8*4 adds $acc0,$acc0,$t0 adcs $acc1,$acc1,$t1 adcs $acc2,$acc2,$t2 adcs $acc3,$acc3,$t3 //adc $carry,$carry,xzr ldp $m0,$m1,[$np,#8*0] ldp $m2,$m3,[$np,#8*2] add $np,$np,#8*4 b .Loop_mul4x_tail .align 4 .Loop_mul4x_break: ldp $t2,$t3,[x29,#96] // pull rp and &b[num] adds $acc0,$acc0,$topmost add $bp,$bp,#8*4 // bp++ adcs $acc1,$acc1,xzr sub $ap,$ap,$num // rewind ap adcs $acc2,$acc2,xzr stp $acc0,$acc1,[$tp,#8*0] // result!!! adcs $acc3,$acc3,xzr ldp $acc0,$acc1,[sp,#8*4] // t[0..3] adc $topmost,$carry,xzr stp $acc2,$acc3,[$tp,#8*2] // result!!! cmp $bp,$t3 // done yet? ldp $acc2,$acc3,[sp,#8*6] ldp $m0,$m1,[$t1,#8*0] // n[0..3] ldp $m2,$m3,[$t1,#8*2] add $np,$t1,#8*4 b.eq .Lmul4x_post ldr $bi,[$bp] ldp $a0,$a1,[$ap,#8*0] // a[0..3] ldp $a2,$a3,[$ap,#8*2] adds $ap,$ap,#8*4 // clear carry bit mov $carry,xzr mov $tp,sp b .Loop_mul4x_reduction .align 4 .Lmul4x_post: // Final step. We see if result is larger than modulus, and // if it is, subtract the modulus. But comparison implies // subtraction. So we subtract modulus, see if it borrowed, // and conditionally copy original value. mov $rp,$t2 mov $ap_end,$t2 // $rp copy subs $t0,$acc0,$m0 add $tp,sp,#8*8 sbcs $t1,$acc1,$m1 sub $cnt,$num,#8*4 .Lmul4x_sub: sbcs $t2,$acc2,$m2 ldp $m0,$m1,[$np,#8*0] sub $cnt,$cnt,#8*4 ldp $acc0,$acc1,[$tp,#8*0] sbcs $t3,$acc3,$m3 ldp $m2,$m3,[$np,#8*2] add $np,$np,#8*4 ldp $acc2,$acc3,[$tp,#8*2] add $tp,$tp,#8*4 stp $t0,$t1,[$rp,#8*0] sbcs $t0,$acc0,$m0 stp $t2,$t3,[$rp,#8*2] add $rp,$rp,#8*4 sbcs $t1,$acc1,$m1 cbnz $cnt,.Lmul4x_sub sbcs $t2,$acc2,$m2 mov $tp,sp add $ap,sp,#8*4 ldp $a0,$a1,[$ap_end,#8*0] sbcs $t3,$acc3,$m3 stp $t0,$t1,[$rp,#8*0] ldp $a2,$a3,[$ap_end,#8*2] stp $t2,$t3,[$rp,#8*2] ldp $acc0,$acc1,[$ap,#8*0] ldp $acc2,$acc3,[$ap,#8*2] sbcs xzr,$topmost,xzr // did it borrow? ldr x30,[x29,#8] // pull return address sub $cnt,$num,#8*4 .Lmul4x_cond_copy: sub $cnt,$cnt,#8*4 csel $t0,$acc0,$a0,lo stp xzr,xzr,[$tp,#8*0] csel $t1,$acc1,$a1,lo ldp $a0,$a1,[$ap_end,#8*4] ldp $acc0,$acc1,[$ap,#8*4] csel $t2,$acc2,$a2,lo stp xzr,xzr,[$tp,#8*2] add $tp,$tp,#8*4 csel $t3,$acc3,$a3,lo ldp $a2,$a3,[$ap_end,#8*6] ldp $acc2,$acc3,[$ap,#8*6] add $ap,$ap,#8*4 stp $t0,$t1,[$ap_end,#8*0] stp $t2,$t3,[$ap_end,#8*2] add $ap_end,$ap_end,#8*4 cbnz $cnt,.Lmul4x_cond_copy csel $t0,$acc0,$a0,lo stp xzr,xzr,[$tp,#8*0] csel $t1,$acc1,$a1,lo stp xzr,xzr,[$tp,#8*2] csel $t2,$acc2,$a2,lo stp xzr,xzr,[$tp,#8*3] csel $t3,$acc3,$a3,lo stp xzr,xzr,[$tp,#8*4] stp $t0,$t1,[$ap_end,#8*0] stp $t2,$t3,[$ap_end,#8*2] b .Lmul4x_done .align 4 .Lmul4x4_post_condition: adc $carry,$carry,xzr ldr $ap,[x29,#96] // pull rp // $acc0-3,$carry hold result, $m0-7 hold modulus subs $a0,$acc0,$m0 ldr x30,[x29,#8] // pull return address sbcs $a1,$acc1,$m1 stp xzr,xzr,[sp,#8*0] sbcs $a2,$acc2,$m2 stp xzr,xzr,[sp,#8*2] sbcs $a3,$acc3,$m3 stp xzr,xzr,[sp,#8*4] sbcs xzr,$carry,xzr // did it borrow? stp xzr,xzr,[sp,#8*6] // $a0-3 hold result-modulus csel $a0,$acc0,$a0,lo csel $a1,$acc1,$a1,lo csel $a2,$acc2,$a2,lo csel $a3,$acc3,$a3,lo stp $a0,$a1,[$ap,#8*0] stp $a2,$a3,[$ap,#8*2] .Lmul4x_done: ldp x19,x20,[x29,#16] mov sp,x29 ldp x21,x22,[x29,#32] mov x0,#1 ldp x23,x24,[x29,#48] ldp x25,x26,[x29,#64] ldp x27,x28,[x29,#80] ldr x29,[sp],#128 // x30 loaded earlier AARCH64_VALIDATE_LINK_REGISTER ret .size __bn_mul4x_mont,.-__bn_mul4x_mont ___ } $code.=<<___; .asciz "Montgomery Multiplication for ARMv8, CRYPTOGAMS by <appro\@openssl.org>" .align 4 ___ print $code; close STDOUT or die "error closing STDOUT: $!";
openssl/openssl
crypto/bn/asm/armv8-mont.pl
Perl
apache-2.0
47,789
package VMOMI::LicenseDiagnostics; use parent 'VMOMI::DynamicData'; use strict; use warnings; our @class_ancestors = ( 'DynamicData', ); our @class_members = ( ['sourceLastChanged', undef, 0, ], ['sourceLost', undef, 0, ], ['sourceLatency', undef, 0, ], ['licenseRequests', undef, 0, ], ['licenseRequestFailures', undef, 0, ], ['licenseFeatureUnknowns', undef, 0, ], ['opState', 'LicenseManagerState', 0, ], ['lastStatusUpdate', undef, 0, ], ['opFailureMessage', undef, 0, ], ); sub get_class_ancestors { return @class_ancestors; } sub get_class_members { my $class = shift; my @super_members = $class->SUPER::get_class_members(); return (@super_members, @class_members); } 1;
stumpr/p5-vmomi
lib/VMOMI/LicenseDiagnostics.pm
Perl
apache-2.0
741
# Copyright 2020, Google LLC # # 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. package Google::Ads::GoogleAds::V9::Resources::AgeRangeView; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = {resourceName => $args->{resourceName}}; # Delete the unassigned fields in this object for a more concise JSON payload remove_unassigned_fields($self, $args); bless $self, $class; return $self; } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V9/Resources/AgeRangeView.pm
Perl
apache-2.0
1,027
package VMOMI::OvfUnsupportedDeviceBackingOption; use parent 'VMOMI::OvfSystemFault'; use strict; use warnings; our @class_ancestors = ( 'OvfSystemFault', 'OvfFault', 'VimFault', 'MethodFault', ); our @class_members = ( ['elementName', undef, 0, 1], ['instanceId', undef, 0, 1], ['deviceName', undef, 0, ], ['backingName', undef, 0, 1], ); sub get_class_ancestors { return @class_ancestors; } sub get_class_members { my $class = shift; my @super_members = $class->SUPER::get_class_members(); return (@super_members, @class_members); } 1;
stumpr/p5-vmomi
lib/VMOMI/OvfUnsupportedDeviceBackingOption.pm
Perl
apache-2.0
594
# Copyright (c) 2015 Timm Murray # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. package UAV::Pilot::Wumpus; use v5.14; use warnings; use Moose; use namespace::autoclean; # ABSTRACT: Control a UAV over WiFi with a video feed use constant DEFAULT_PORT => 49_050; use constant DEFAULT_VIDEO_PORT => 49_051; no Moose; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME UAV::Pilot::Wumpus - Control a rover over WiFi with a video feed =head1 DESCRIPTION Client and base module for the Wumpus UAV. The network protocol is documented in L<UAV::Pilot::Wumpus::Packet>. =head1 LICENSE Copyright (c) 2015 Timm Murray All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =cut
frezik/UAV-Pilot-Wumpus
lib/UAV/Pilot/Wumpus.pm
Perl
bsd-2-clause
3,224
=encoding utf-8 =head1 NAME ngx_http_uwsgi_module - Module ngx_http_uwsgi_module =head1 The C<ngx_http_uwsgi_module> module allows passing requests to a uwsgi server. =head1 Example Configuration location / { include uwsgi_params; uwsgi_pass localhost:9000; } =head1 Directives =head2 uwsgi_bind B<syntax:> uwsgi_bind I<I<C<address>> [transparent] E<verbar> C<off>> B<context:> I<http> B<context:> I<server> B<context:> I<location> Makes outgoing connections to a uwsgi server originate from the specified local IP address with an optional port (1.11.2). Parameter value can contain variables (1.3.12). The special value C<off> (1.3.12) cancels the effect of the C<uwsgi_bind> directive inherited from the previous configuration level, which allows the system to auto-assign the local IP address and port. The C<transparent> parameter (1.11.0) allows outgoing connections to a uwsgi server originate from a non-local IP address, for example, from a real IP address of a client: uwsgi_bind $remote_addr transparent; In order for this parameter to work, it is necessary to run nginx worker processes with the L<superuser|ngx_core_module> privileges and configure kernel routing table to intercept network traffic from the uwsgi server. =head2 uwsgi_buffer_size B<syntax:> uwsgi_buffer_size I<I<C<size>>> B<default:> I<4kE<verbar>8k> B<context:> I<http> B<context:> I<server> B<context:> I<location> Sets the I<C<size>> of the buffer used for reading the first part of the response received from the uwsgi server. This part usually contains a small response header. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform. It can be made smaller, however. =head2 uwsgi_buffering B<syntax:> uwsgi_buffering I<C<on> E<verbar> C<off>> B<default:> I<on> B<context:> I<http> B<context:> I<server> B<context:> I<location> Enables or disables buffering of responses from the uwsgi server. When buffering is enabled, nginx receives a response from the uwsgi server as soon as possible, saving it into the buffers set by the L</uwsgi_buffer_size> and L</uwsgi_buffers> directives. If the whole response does not fit into memory, a part of it can be saved to a temporary file on the disk. Writing to temporary files is controlled by the L</uwsgi_max_temp_file_size> and L</uwsgi_temp_file_write_size> directives. When buffering is disabled, the response is passed to a client synchronously, immediately as it is received. nginx will not try to read the whole response from the uwsgi server. The maximum size of the data that nginx can receive from the server at a time is set by the L</uwsgi_buffer_size> directive. Buffering can also be enabled or disabled by passing “C<yes>” or “C<no>” in the C<X-Accel-Buffering> response header field. This capability can be disabled using the L</uwsgi_ignore_headers> directive. =head2 uwsgi_buffers B<syntax:> uwsgi_buffers I<I<C<number>> I<C<size>>> B<default:> I<8 4kE<verbar>8k> B<context:> I<http> B<context:> I<server> B<context:> I<location> Sets the I<C<number>> and I<C<size>> of the buffers used for reading a response from the uwsgi server, for a single connection. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform. =head2 uwsgi_busy_buffers_size B<syntax:> uwsgi_busy_buffers_size I<I<C<size>>> B<default:> I<8kE<verbar>16k> B<context:> I<http> B<context:> I<server> B<context:> I<location> When buffering of responses from the uwsgi server is enabled, limits the total I<C<size>> of buffers that can be busy sending a response to the client while the response is not yet fully read. In the meantime, the rest of the buffers can be used for reading the response and, if needed, buffering part of the response to a temporary file. By default, I<C<size>> is limited by the size of two buffers set by the L</uwsgi_buffer_size> and L</uwsgi_buffers> directives. =head2 uwsgi_cache B<syntax:> uwsgi_cache I<I<C<zone>> E<verbar> C<off>> B<default:> I<off> B<context:> I<http> B<context:> I<server> B<context:> I<location> Defines a shared memory zone used for caching. The same zone can be used in several places. Parameter value can contain variables (1.7.9). The C<off> parameter disables caching inherited from the previous configuration level. =head2 uwsgi_cache_bypass B<syntax:> uwsgi_cache_bypass I<I<C<string>> ...> B<context:> I<http> B<context:> I<server> B<context:> I<location> Defines conditions under which the response will not be taken from a cache. If at least one value of the string parameters is not empty and is not equal to “0” then the response will not be taken from the cache: uwsgi_cache_bypass $cookie_nocache $arg_nocache$arg_comment; uwsgi_cache_bypass $http_pragma $http_authorization; Can be used along with the L</uwsgi_no_cache> directive. =head2 uwsgi_cache_key B<syntax:> uwsgi_cache_key I<I<C<string>>> B<context:> I<http> B<context:> I<server> B<context:> I<location> Defines a key for caching, for example uwsgi_cache_key localhost:9000$request_uri; =head2 uwsgi_cache_lock B<syntax:> uwsgi_cache_lock I<C<on> E<verbar> C<off>> B<default:> I<off> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.1.12. When enabled, only one request at a time will be allowed to populate a new cache element identified according to the L</uwsgi_cache_key> directive by passing a request to a uwsgi server. Other requests of the same cache element will either wait for a response to appear in the cache or the cache lock for this element to be released, up to the time set by the L</uwsgi_cache_lock_timeout> directive. =head2 uwsgi_cache_lock_age B<syntax:> uwsgi_cache_lock_age I<I<C<time>>> B<default:> I<5s> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.8. If the last request passed to the uwsgi server for populating a new cache element has not completed for the specified I<C<time>>, one more request may be passed to the uwsgi server. =head2 uwsgi_cache_lock_timeout B<syntax:> uwsgi_cache_lock_timeout I<I<C<time>>> B<default:> I<5s> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.1.12. Sets a timeout for L</uwsgi_cache_lock>. When the I<C<time>> expires, the request will be passed to the uwsgi server, however, the response will not be cached. B<NOTE> Before 1.7.8, the response could be cached. =head2 uwsgi_cache_max_range_offset B<syntax:> uwsgi_cache_max_range_offset I<I<C<number>>> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.11.6. Sets an offset in bytes for byte-range requests. If the range is beyond the offset, the range request will be passed to the uwsgi server and the response will not be cached. =head2 uwsgi_cache_methods B<syntax:> uwsgi_cache_methods I< C<GET> E<verbar> C<HEAD> E<verbar> C<POST> ...> B<default:> I<GET HEAD> B<context:> I<http> B<context:> I<server> B<context:> I<location> If the client request method is listed in this directive then the response will be cached. “C<GET>” and “C<HEAD>” methods are always added to the list, though it is recommended to specify them explicitly. See also the L</uwsgi_no_cache> directive. =head2 uwsgi_cache_min_uses B<syntax:> uwsgi_cache_min_uses I<I<C<number>>> B<default:> I<1> B<context:> I<http> B<context:> I<server> B<context:> I<location> Sets the I<C<number>> of requests after which the response will be cached. =head2 uwsgi_cache_path B<syntax:> uwsgi_cache_path I< I<C<path>> [C<levels>=I<C<levels>>] [C<use_temp_path>=C<on>E<verbar>C<off>] C<keys_zone>=I<C<name>>:I<C<size>> [C<inactive>=I<C<time>>] [C<max_size>=I<C<size>>] [C<manager_files>=I<C<number>>] [C<manager_sleep>=I<C<time>>] [C<manager_threshold>=I<C<time>>] [C<loader_files>=I<C<number>>] [C<loader_sleep>=I<C<time>>] [C<loader_threshold>=I<C<time>>] [C<purger>=C<on>E<verbar>C<off>] [C<purger_files>=I<C<number>>] [C<purger_sleep>=I<C<time>>] [C<purger_threshold>=I<C<time>>]> B<context:> I<http> Sets the path and other parameters of a cache. Cache data are stored in files. The file name in a cache is a result of applying the MD5 function to the cache key. The C<levels> parameter defines hierarchy levels of a cache: from 1 to 3, each level accepts values 1 or 2. For example, in the following configuration uwsgi_cache_path /data/nginx/cache levels=1:2 keys_zone=one:10m; file names in a cache will look like this: /data/nginx/cache/<emphasis>c</emphasis>/<emphasis>29</emphasis>/b7f54b2df7773722d382f4809d650<emphasis>29c</emphasis> A cached response is first written to a temporary file, and then the file is renamed. Starting from version 0.8.9, temporary files and the cache can be put on different file systems. However, be aware that in this case a file is copied across two file systems instead of the cheap renaming operation. It is thus recommended that for any given location both cache and a directory holding temporary files are put on the same file system. A directory for temporary files is set based on the C<use_temp_path> parameter (1.7.10). If this parameter is omitted or set to the value C<on>, the directory set by the L</uwsgi_temp_path> directive for the given location will be used. If the value is set to C<off>, temporary files will be put directly in the cache directory. In addition, all active keys and information about data are stored in a shared memory zone, whose I<C<name>> and I<C<size>> are configured by the C<keys_zone> parameter. One megabyte zone can store about 8 thousand keys. Cached data that are not accessed during the time specified by the C<inactive> parameter get removed from the cache regardless of their freshness. By default, C<inactive> is set to 10 minutes. The special “cache manager” process monitors the maximum cache size set by the C<max_size> parameter. When this size is exceeded, it removes the least recently used data. The data is removed in iterations configured by C<manager_files>, C<manager_threshold>, and C<manager_sleep> parameters (1.11.5). During one iteration no more than C<manager_files> items are deleted (by default, 100). The duration of one iteration is limited by the C<manager_threshold> parameter (by default, 200 milliseconds). Between iterations, a pause configured by the C<manager_sleep> parameter (by default, 50 milliseconds) is made. A minute after the start the special “cache loader” process is activated. It loads information about previously cached data stored on file system into a cache zone. The loading is also done in iterations. During one iteration no more than C<loader_files> items are loaded (by default, 100). Besides, the duration of one iteration is limited by the C<loader_threshold> parameter (by default, 200 milliseconds). Between iterations, a pause configured by the C<loader_sleep> parameter (by default, 50 milliseconds) is made. Additionally, the following parameters are available as part of our commercial subscription: =over =item C<purger>=C<on>E<verbar>C<off> Instructs whether cache entries that match a wildcard key will be removed from the disk by the cache purger (1.7.12). Setting the parameter to C<on> (default is C<off>) will activate the “cache purger” process that permanently iterates through all cache entries and deletes the entries that match the wildcard key. =item C<purger_files>=I<C<number>> Sets the number of items that will be scanned during one iteration (1.7.12). By default, C<purger_files> is set to 10. =item C<purger_threshold>=I<C<number>> Sets the duration of one iteration (1.7.12). By default, C<purger_threshold> is set to 50 milliseconds. =item C<purger_sleep>=I<C<number>> Sets a pause between iterations (1.7.12). By default, C<purger_sleep> is set to 50 milliseconds. =back =head2 uwsgi_cache_purge B<syntax:> uwsgi_cache_purge I<string ...> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.5.7. Defines conditions under which the request will be considered a cache purge request. If at least one value of the string parameters is not empty and is not equal to “0” then the cache entry with a corresponding cache key is removed. The result of successful operation is indicated by returning the C<204> (C<No Content>) response. If the cache key of a purge request ends with an asterisk (“C<*>”), all cache entries matching the wildcard key will be removed from the cache. However, these entries will remain on the disk until they are deleted for either inactivity, or processed by the cache purger (1.7.12), or a client attempts to access them. Example configuration: uwsgi_cache_path /data/nginx/cache keys_zone=cache_zone:10m; map $request_method $purge_method { PURGE 1; default 0; } server { ... location / { uwsgi_pass backend; uwsgi_cache cache_zone; uwsgi_cache_key $uri; uwsgi_cache_purge $purge_method; } } B<NOTE> This functionality is available as part of our commercial subscription. =head2 uwsgi_cache_revalidate B<syntax:> uwsgi_cache_revalidate I<C<on> E<verbar> C<off>> B<default:> I<off> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.5.7. Enables revalidation of expired cache items using conditional requests with the C<If-Modified-Since> and C<If-None-Match> header fields. =head2 uwsgi_cache_use_stale B<syntax:> uwsgi_cache_use_stale I< C<error> E<verbar> C<timeout> E<verbar> C<invalid_header> E<verbar> C<updating> E<verbar> C<http_500> E<verbar> C<http_503> E<verbar> C<http_403> E<verbar> C<http_404> E<verbar> C<off> ...> B<default:> I<off> B<context:> I<http> B<context:> I<server> B<context:> I<location> Determines in which cases a stale cached response can be used when an error occurs during communication with the uwsgi server. The directive’s parameters match the parameters of the L</uwsgi_next_upstream> directive. The C<error> parameter also permits using a stale cached response if a uwsgi server to process a request cannot be selected. Additionally, the C<updating> parameter permits using a stale cached response if it is currently being updated. This allows minimizing the number of accesses to uwsgi servers when updating cached data. To minimize the number of accesses to uwsgi servers when populating a new cache element, the L</uwsgi_cache_lock> directive can be used. =head2 uwsgi_cache_valid B<syntax:> uwsgi_cache_valid I<[I<C<code>> ...] I<C<time>>> B<context:> I<http> B<context:> I<server> B<context:> I<location> Sets caching time for different response codes. For example, the following directives uwsgi_cache_valid 200 302 10m; uwsgi_cache_valid 404 1m; set 10 minutes of caching for responses with codes 200 and 302 and 1 minute for responses with code 404. If only caching I<C<time>> is specified uwsgi_cache_valid 5m; then only 200, 301, and 302 responses are cached. In addition, the C<any> parameter can be specified to cache any responses: uwsgi_cache_valid 200 302 10m; uwsgi_cache_valid 301 1h; uwsgi_cache_valid any 1m; Parameters of caching can also be set directly in the response header. This has higher priority than setting of caching time using the directive. =over =item * The C<X-Accel-Expires> header field sets caching time of a response in seconds. The zero value disables caching for a response. If the value starts with the C<@> prefix, it sets an absolute time in seconds since Epoch, up to which the response may be cached. =item * If the header does not include the C<X-Accel-Expires> field, parameters of caching may be set in the header fields C<Expires> or C<Cache-Control>. =item * If the header includes the C<Set-Cookie> field, such a response will not be cached. =item * If the header includes the C<Vary> field with the special value “C<*>”, such a response will not be cached (1.7.7). If the header includes the C<Vary> field with another value, such a response will be cached taking into account the corresponding request header fields (1.7.7). =back Processing of one or more of these response header fields can be disabled using the L</uwsgi_ignore_headers> directive. =head2 uwsgi_connect_timeout B<syntax:> uwsgi_connect_timeout I<I<C<time>>> B<default:> I<60s> B<context:> I<http> B<context:> I<server> B<context:> I<location> Defines a timeout for establishing a connection with a uwsgi server. It should be noted that this timeout cannot usually exceed 75 seconds. =head2 uwsgi_force_ranges B<syntax:> uwsgi_force_ranges I<C<on> E<verbar> C<off>> B<default:> I<off> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.7. Enables byte-range support for both cached and uncached responses from the uwsgi server regardless of the C<Accept-Ranges> field in these responses. =head2 uwsgi_hide_header B<syntax:> uwsgi_hide_header I<I<C<field>>> B<context:> I<http> B<context:> I<server> B<context:> I<location> By default, nginx does not pass the header fields C<Status> and C<X-Accel-...> from the response of a uwsgi server to a client. The C<uwsgi_hide_header> directive sets additional fields that will not be passed. If, on the contrary, the passing of fields needs to be permitted, the L</uwsgi_pass_header> directive can be used. =head2 uwsgi_ignore_client_abort B<syntax:> uwsgi_ignore_client_abort I<C<on> E<verbar> C<off>> B<default:> I<off> B<context:> I<http> B<context:> I<server> B<context:> I<location> Determines whether the connection with a uwsgi server should be closed when a client closes the connection without waiting for a response. =head2 uwsgi_ignore_headers B<syntax:> uwsgi_ignore_headers I<I<C<field>> ...> B<context:> I<http> B<context:> I<server> B<context:> I<location> Disables processing of certain response header fields from the uwsgi server. The following fields can be ignored: C<X-Accel-Redirect>, C<X-Accel-Expires>, C<X-Accel-Limit-Rate> (1.1.6), C<X-Accel-Buffering> (1.1.6), C<X-Accel-Charset> (1.1.6), C<Expires>, C<Cache-Control>, C<Set-Cookie> (0.8.44), and C<Vary> (1.7.7). If not disabled, processing of these header fields has the following effect: =over =item * C<X-Accel-Expires>, C<Expires>, C<Cache-Control>, C<Set-Cookie>, and C<Vary> set the parameters of response caching; =item * C<X-Accel-Redirect> performs an L<internal redirect|ngx_http_core_module> to the specified URI; =item * C<X-Accel-Limit-Rate> sets the L<rate limit|ngx_http_core_module> for transmission of a response to a client; =item * C<X-Accel-Buffering> enables or disables buffering of a response; =item * C<X-Accel-Charset> sets the desired L<ngx_http_charset_module> of a response. =back =head2 uwsgi_intercept_errors B<syntax:> uwsgi_intercept_errors I<C<on> E<verbar> C<off>> B<default:> I<off> B<context:> I<http> B<context:> I<server> B<context:> I<location> Determines whether a uwsgi server responses with codes greater than or equal to 300 should be passed to a client or be intercepted and redirected to nginx for processing with the L<ngx_http_core_module> directive. =head2 uwsgi_limit_rate B<syntax:> uwsgi_limit_rate I<I<C<rate>>> B<default:> I<0> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.7. Limits the speed of reading the response from the uwsgi server. The I<C<rate>> is specified in bytes per second. The zero value disables rate limiting. The limit is set per a request, and so if nginx simultaneously opens two connections to the uwsgi server, the overall rate will be twice as much as the specified limit. The limitation works only if buffering of responses from the uwsgi server is enabled. =head2 uwsgi_max_temp_file_size B<syntax:> uwsgi_max_temp_file_size I<I<C<size>>> B<default:> I<1024m> B<context:> I<http> B<context:> I<server> B<context:> I<location> When buffering of responses from the uwsgi server is enabled, and the whole response does not fit into the buffers set by the L</uwsgi_buffer_size> and L</uwsgi_buffers> directives, a part of the response can be saved to a temporary file. This directive sets the maximum I<C<size>> of the temporary file. The size of data written to the temporary file at a time is set by the L</uwsgi_temp_file_write_size> directive. The zero value disables buffering of responses to temporary files. B<NOTE> This restriction does not apply to responses that will be cached or stored on disk. =head2 uwsgi_modifier1 B<syntax:> uwsgi_modifier1 I<I<C<number>>> B<default:> I<0> B<context:> I<http> B<context:> I<server> B<context:> I<location> Sets the value of the C<modifier1> field in the L<uwsgi packet header|http://uwsgi-docs.readthedocs.org/en/latest/Protocol.html#uwsgi-packet-header>. =head2 uwsgi_modifier2 B<syntax:> uwsgi_modifier2 I<I<C<number>>> B<default:> I<0> B<context:> I<http> B<context:> I<server> B<context:> I<location> Sets the value of the C<modifier2> field in the L<uwsgi packet header|http://uwsgi-docs.readthedocs.org/en/latest/Protocol.html#uwsgi-packet-header>. =head2 uwsgi_next_upstream B<syntax:> uwsgi_next_upstream I< C<error> E<verbar> C<timeout> E<verbar> C<invalid_header> E<verbar> C<http_500> E<verbar> C<http_503> E<verbar> C<http_403> E<verbar> C<http_404> E<verbar> C<non_idempotent> E<verbar> C<off> ...> B<default:> I<error timeout> B<context:> I<http> B<context:> I<server> B<context:> I<location> Specifies in which cases a request should be passed to the next server: =over =item C<error> an error occurred while establishing a connection with the server, passing a request to it, or reading the response header; =item C<timeout> a timeout has occurred while establishing a connection with the server, passing a request to it, or reading the response header; =item C<invalid_header> a server returned an empty or invalid response; =item C<http_500> a server returned a response with the code 500; =item C<http_503> a server returned a response with the code 503; =item C<http_403> a server returned a response with the code 403; =item C<http_404> a server returned a response with the code 404; =item C<non_idempotent> normally, requests with a L<non-idempotent|http://tools.ietf.org/html/rfc7231#section-4.2.2> method (C<POST>, C<LOCK>, C<PATCH>) are not passed to the next server if a request has been sent to an upstream server (1.9.13); enabling this option explicitly allows retrying such requests; =item C<off> disables passing a request to the next server. =back One should bear in mind that passing a request to the next server is only possible if nothing has been sent to a client yet. That is, if an error or timeout occurs in the middle of the transferring of a response, fixing this is impossible. The directive also defines what is considered an L<unsuccessful attempt|ngx_http_upstream_module> of communication with a server. The cases of C<error>, C<timeout> and C<invalid_header> are always considered unsuccessful attempts, even if they are not specified in the directive. The cases of C<http_500> and C<http_503> are considered unsuccessful attempts only if they are specified in the directive. The cases of C<http_403> and C<http_404> are never considered unsuccessful attempts. Passing a request to the next server can be limited by the number of tries and by time. =head2 uwsgi_next_upstream_timeout B<syntax:> uwsgi_next_upstream_timeout I<I<C<time>>> B<default:> I<0> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.5. Limits the time during which a request can be passed to the next server. The C<0> value turns off this limitation. =head2 uwsgi_next_upstream_tries B<syntax:> uwsgi_next_upstream_tries I<I<C<number>>> B<default:> I<0> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.5. Limits the number of possible tries for passing a request to the next server. The C<0> value turns off this limitation. =head2 uwsgi_no_cache B<syntax:> uwsgi_no_cache I<I<C<string>> ...> B<context:> I<http> B<context:> I<server> B<context:> I<location> Defines conditions under which the response will not be saved to a cache. If at least one value of the string parameters is not empty and is not equal to “0” then the response will not be saved: uwsgi_no_cache $cookie_nocache $arg_nocache$arg_comment; uwsgi_no_cache $http_pragma $http_authorization; Can be used along with the L</uwsgi_cache_bypass> directive. =head2 uwsgi_param B<syntax:> uwsgi_param I< I<C<parameter>> I<C<value>> [C<if_not_empty>]> B<context:> I<http> B<context:> I<server> B<context:> I<location> Sets a I<C<parameter>> that should be passed to the uwsgi server. The I<C<value>> can contain text, variables, and their combination. These directives are inherited from the previous level if and only if there are no C<uwsgi_param> directives defined on the current level. Standard L<CGI environment variables|http://tools.ietf.org/html/rfc3875#section-4.1> should be provided as uwsgi headers, see the F<uwsgi_params> file provided in the distribution: location / { include uwsgi_params; ... } If the directive is specified with C<if_not_empty> (1.1.11) then such a parameter will not be passed to the server until its value is not empty: uwsgi_param HTTPS $https if_not_empty; =head2 uwsgi_pass B<syntax:> uwsgi_pass I<[I<C<protocol>>:E<sol>E<sol>]I<C<address>>> B<context:> I<location> B<context:> I<if in location> Sets the protocol and address of a uwsgi server. As a I<C<protocol>>, “C<uwsgi>” or “C<suwsgi>” (secured uwsgi, uwsgi over SSL) can be specified. The address can be specified as a domain name or IP address, and a port: uwsgi_pass localhost:9000; uwsgi_pass uwsgi://localhost:9000; uwsgi_pass suwsgi://[2001:db8::1]:9090; or as a UNIX-domain socket path: uwsgi_pass unix:/tmp/uwsgi.socket; If a domain name resolves to several addresses, all of them will be used in a round-robin fashion. In addition, an address can be specified as a L<server group|ngx_http_upstream_module>. B<NOTE> Secured uwsgi protocol is supported since version 1.5.8. =head2 uwsgi_pass_header B<syntax:> uwsgi_pass_header I<I<C<field>>> B<context:> I<http> B<context:> I<server> B<context:> I<location> Permits passing otherwise disabled header fields from a uwsgi server to a client. =head2 uwsgi_pass_request_body B<syntax:> uwsgi_pass_request_body I<C<on> E<verbar> C<off>> B<default:> I<on> B<context:> I<http> B<context:> I<server> B<context:> I<location> Indicates whether the original request body is passed to the uwsgi server. See also the L</uwsgi_pass_request_headers> directive. =head2 uwsgi_pass_request_headers B<syntax:> uwsgi_pass_request_headers I<C<on> E<verbar> C<off>> B<default:> I<on> B<context:> I<http> B<context:> I<server> B<context:> I<location> Indicates whether the header fields of the original request are passed to the uwsgi server. See also the L</uwsgi_pass_request_body> directive. =head2 uwsgi_read_timeout B<syntax:> uwsgi_read_timeout I<I<C<time>>> B<default:> I<60s> B<context:> I<http> B<context:> I<server> B<context:> I<location> Defines a timeout for reading a response from the uwsgi server. The timeout is set only between two successive read operations, not for the transmission of the whole response. If the uwsgi server does not transmit anything within this time, the connection is closed. =head2 uwsgi_request_buffering B<syntax:> uwsgi_request_buffering I<C<on> E<verbar> C<off>> B<default:> I<on> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.11. Enables or disables buffering of a client request body. When buffering is enabled, the entire request body is L<read|ngx_http_core_module> from the client before sending the request to a uwsgi server. When buffering is disabled, the request body is sent to the uwsgi server immediately as it is received. In this case, the request cannot be passed to the next server if nginx already started sending the request body. When HTTPE<sol>1.1 chunked transfer encoding is used to send the original request body, the request body will be buffered regardless of the directive value. =head2 uwsgi_send_timeout B<syntax:> uwsgi_send_timeout I<I<C<time>>> B<default:> I<60s> B<context:> I<http> B<context:> I<server> B<context:> I<location> Sets a timeout for transmitting a request to the uwsgi server. The timeout is set only between two successive write operations, not for the transmission of the whole request. If the uwsgi server does not receive anything within this time, the connection is closed. =head2 uwsgi_ssl_certificate B<syntax:> uwsgi_ssl_certificate I<I<C<file>>> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.8. Specifies a I<C<file>> with the certificate in the PEM format used for authentication to a secured uwsgi server. =head2 uwsgi_ssl_certificate_key B<syntax:> uwsgi_ssl_certificate_key I<I<C<file>>> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.8. Specifies a I<C<file>> with the secret key in the PEM format used for authentication to a secured uwsgi server. The value C<engine>:I<C<name>>:I<C<id>> can be specified instead of the I<C<file>> (1.7.9), which loads a secret key with a specified I<C<id>> from the OpenSSL engine I<C<name>>. =head2 uwsgi_ssl_ciphers B<syntax:> uwsgi_ssl_ciphers I<I<C<ciphers>>> B<default:> I<DEFAULT> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.5.8. Specifies the enabled ciphers for requests to a secured uwsgi server. The ciphers are specified in the format understood by the OpenSSL library. The full list can be viewed using the “C<openssl ciphers>” command. =head2 uwsgi_ssl_crl B<syntax:> uwsgi_ssl_crl I<I<C<file>>> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.0. Specifies a I<C<file>> with revoked certificates (CRL) in the PEM format used to verify the certificate of the secured uwsgi server. =head2 uwsgi_ssl_name B<syntax:> uwsgi_ssl_name I<I<C<name>>> B<default:> I<host from uwsgi_pass> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.0. Allows overriding the server name used to verify the certificate of the secured uwsgi server and to be passed through SNI when establishing a connection with the secured uwsgi server. By default, the host part from L</uwsgi_pass> is used. =head2 uwsgi_ssl_password_file B<syntax:> uwsgi_ssl_password_file I<I<C<file>>> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.8. Specifies a I<C<file>> with passphrases for secret keys where each passphrase is specified on a separate line. Passphrases are tried in turn when loading the key. =head2 uwsgi_ssl_protocols B<syntax:> uwsgi_ssl_protocols I< [C<SSLv2>] [C<SSLv3>] [C<TLSv1>] [C<TLSv1.1>] [C<TLSv1.2>]> B<default:> I<TLSv1 TLSv1.1 TLSv1.2> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.5.8. Enables the specified protocols for requests to a secured uwsgi server. =head2 uwsgi_ssl_server_name B<syntax:> uwsgi_ssl_server_name I<C<on> E<verbar> C<off>> B<default:> I<off> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.0. Enables or disables passing of the server name through L<TLS Server Name Indication extension|http://en.wikipedia.org/wiki/Server_Name_Indication> (SNI, RFC 6066) when establishing a connection with the secured uwsgi server. =head2 uwsgi_ssl_session_reuse B<syntax:> uwsgi_ssl_session_reuse I<C<on> E<verbar> C<off>> B<default:> I<on> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.5.8. Determines whether SSL sessions can be reused when working with a secured uwsgi server. If the errors “C<SSL3_GET_FINISHED:digest check failed>” appear in the logs, try disabling session reuse. =head2 uwsgi_ssl_trusted_certificate B<syntax:> uwsgi_ssl_trusted_certificate I<I<C<file>>> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.0. Specifies a I<C<file>> with trusted CA certificates in the PEM format used to verify the certificate of the secured uwsgi server. =head2 uwsgi_ssl_verify B<syntax:> uwsgi_ssl_verify I<C<on> E<verbar> C<off>> B<default:> I<off> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.0. Enables or disables verification of the secured uwsgi server certificate. =head2 uwsgi_ssl_verify_depth B<syntax:> uwsgi_ssl_verify_depth I<I<C<number>>> B<default:> I<1> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.7.0. Sets the verification depth in the secured uwsgi server certificates chain. =head2 uwsgi_store B<syntax:> uwsgi_store I< C<on> E<verbar> C<off> E<verbar> I<C<string>>> B<default:> I<off> B<context:> I<http> B<context:> I<server> B<context:> I<location> Enables saving of files to a disk. The C<on> parameter saves files with paths corresponding to the directives L<ngx_http_core_module> or L<ngx_http_core_module>. The C<off> parameter disables saving of files. In addition, the file name can be set explicitly using the I<C<string>> with variables: uwsgi_store /data/www$original_uri; The modification time of files is set according to the received C<Last-Modified> response header field. The response is first written to a temporary file, and then the file is renamed. Starting from version 0.8.9, temporary files and the persistent store can be put on different file systems. However, be aware that in this case a file is copied across two file systems instead of the cheap renaming operation. It is thus recommended that for any given location both saved files and a directory holding temporary files, set by the L</uwsgi_temp_path> directive, are put on the same file system. This directive can be used to create local copies of static unchangeable files, e.g.: location /images/ { root /data/www; error_page 404 = /fetch$uri; } location /fetch/ { internal; uwsgi_pass backend:9000; ... uwsgi_store on; uwsgi_store_access user:rw group:rw all:r; uwsgi_temp_path /data/temp; alias /data/www/; } =head2 uwsgi_store_access B<syntax:> uwsgi_store_access I<I<C<users>>:I<C<permissions>> ...> B<default:> I<user:rw> B<context:> I<http> B<context:> I<server> B<context:> I<location> Sets access permissions for newly created files and directories, e.g.: uwsgi_store_access user:rw group:rw all:r; If any C<group> or C<all> access permissions are specified then C<user> permissions may be omitted: uwsgi_store_access group:rw all:r; =head2 uwsgi_temp_file_write_size B<syntax:> uwsgi_temp_file_write_size I<I<C<size>>> B<default:> I<8kE<verbar>16k> B<context:> I<http> B<context:> I<server> B<context:> I<location> Limits the I<C<size>> of data written to a temporary file at a time, when buffering of responses from the uwsgi server to temporary files is enabled. By default, I<C<size>> is limited by two buffers set by the L</uwsgi_buffer_size> and L</uwsgi_buffers> directives. The maximum size of a temporary file is set by the L</uwsgi_max_temp_file_size> directive. =head2 uwsgi_temp_path B<syntax:> uwsgi_temp_path I< I<C<path>> [I<C<level1>> [I<C<level2>> [I<C<level3>>]]]> B<default:> I<uwsgi_temp> B<context:> I<http> B<context:> I<server> B<context:> I<location> Defines a directory for storing temporary files with data received from uwsgi servers. Up to three-level subdirectory hierarchy can be used underneath the specified directory. For example, in the following configuration uwsgi_temp_path /spool/nginx/uwsgi_temp 1 2; a temporary file might look like this: /spool/nginx/uwsgi_temp/<emphasis>7</emphasis>/<emphasis>45</emphasis>/00000123<emphasis>457</emphasis> See also the C<use_temp_path> parameter of the L</uwsgi_cache_path> directive.
LomoX-Offical/nginx-openresty-windows
src/pod/nginx/ngx_http_uwsgi_module.pod
Perl
bsd-2-clause
38,451
#!/usr/bin/perl -w ######################################################### # Simulator for Streaming AOE ######################################################### use strict; use warnings; use Carp; use Scalar::Util; use Math::Trig; (@ARGV >= 3) || die("Usage: $0 <P4P portal> <#locations> <#runs> [ISP]"); my $aoe = "p4p-8.cs.yale.edu"; my $p4p = shift(@ARGV); my $nl = shift(@ARGV); my $nr = shift(@ARGV); my $isp = "America"; if (@ARGV > 0) { $isp = shift(@ARGV); } # get network cost map my %pdistance; `rm -f pdistance`; `wget -q http://$p4p/pdistance`; open (PDF, "<pdistance") || die("pdistance not found"); while(<PDF>) { # 1.i.America no-reverse 10 1.i.America 0 2.i.America 15 3.i.America 10 4.i.America 21 5.i.America 6 6.i.America 5 7.i.America 30 100.e.America 70 200.e.America 80 1000.e.America 100 chomp; my @info = split(/\s+/); my $self = shift(@info); shift(@info); shift(@info); while(@info > 1) { my $remote = shift(@info); my $distance = shift(@info); $pdistance{$self}->{$remote} = $distance; #print $self."\t".$remote."\t".$distance."\n"; } } close(PDF); # data structures my @map_i_pid = (); my %guidance_cdn = (); my %guidance_p2p = (); my $ni = 0; my $generic_demand = 10; # run multiple experiments my @supply; my @demand; my @cdn; my $rate = 48; my $relax; for (my $t = 0; $t < $nr; $t++) { #print STDERR "Exp $t generating...\n"; # generate swarm state #for (my $i = 1; $i <= $nl; $i++) for (my $i = 0; $i < $nl; $i++) { my $n = int(rand(30)); #error -100% +200% if (rand() > (18.0 / $nl)) { $n = 0; } $demand[$i] = $n; # Avg supply * ETA = 1.2+ demand my $cap = int( (rand(1.7) + 0.85) * $rate * $n ); #if (rand() < 0.1) #{ # $cap = int($cap/3); # if ($cap < 1) # { # $cap = 1; # } #} $supply[$i] = $cap; # 30% locations have CDN source if ($i == 1 || rand() < 0.3) { $cdn[$i] = 1; } else { $cdn[$i] = 0; } } my $cdn_min = aoe_mincdn(0); my $cdn_min_generic = aoe_mincdn(1); print STDERR "Exp $t simulating...\n"; my $filefix = $t; open SIMF, ">sim/aoe.sim.".$filefix || die("Failed to create simulation result"); # relaxation factors for($relax = 1.0; $relax >= 0.3; $relax -= 0.05) { #print STDERR "Exp $t simulating with relax $relax...\n"; #open SF, ">sim/aoe.sim.ssm.".$filefix || die("Failed to create streaming channel state"); #open SGF, ">sim/aoe.sim.generic.".$filefix || die("Failed to create generic streaming channel state"); #print SF "$rate\t$relax\n"; #print SGF "$rate\t$relax\n"; #for (my $i = 1; $i <= $nl; $i++) #for (my $i = 0; $i < $nl; $i++) #{ # next if ($demand[$i] < 1); # 2.i.America 48 64 0 6 0 0 6 # print SF $i.".i.".$isp."\t".$supply[$i]."\t".$rate."\t0\t".$demand[$i]."\t0\t0\t".$cdn[$i]."\n"; #print SGF $i.".i.".$isp."\t".(int($rate * 1.6))."\t".$rate."\t0\t1\t0\t0\t".$cdn[$i]."\n"; #} #close SF; #close SGF; #`cp sim/aoe.sim.ssm.$filefix .ssm`; #`cp sim/aoe.sim.generic.$filefix .generic`; # dynamic optimal my ($cost_min, undef, undef) = aoe_mincost(0); # generic guidance my ($cost_generic, $guidance_cdn_ref, $guidance_p2p_ref) = aoe_mincost(1); my ($cost, $cdn_generic) = sim_generic($cdn_min_generic, $guidance_cdn_ref, $guidance_p2p_ref); #sim_generic($cdn_min, $guidance_cdn_ref, $guidance_p2p_ref); print SIMF $relax."\t".$cost_min."\t".$cost."\t".($cdn_generic/$cdn_min)."\n"; } close SIMF; #print STDERR "Exp $t outputing...\n"; # plot results open GPF, ">sim/aoe.sim.".$filefix.".gp" || die("Failed to create simulation figure"); #print GPF "set terminal postscript landscape 'Times-Roman' 18\n"; #print GPF "set size 1.0, 0.8\n"; print GPF "set terminal png\n"; print GPF "set title 'Streaming AOE: Min CDN Load vs Min Network Cost ($t)'\n"; print GPF "set xlabel 'CDN Load'\n"; print GPF "set ylabel 'Min Network Cost under CDN Load'\n"; #print GPF "set output 'sim/aoe.sim.$filefix.eps'\n"; print GPF "set output 'sim/aoe.sim.$filefix.png'\n"; print GPF "plot 'sim/aoe.sim.$filefix' using (1.0/\$1):2 t 'Dynamic Streaming Matching' with linespoints lw 3, 'sim/aoe.sim.$filefix' using (1.0/\$1):3 t 'Generic Streaming Matching' with linespoints lw 3\n"; close GPF; `gnuplot sim/aoe.sim.$filefix.gp`; } sub aoe_mincdn { my ($generic) = @_; @map_i_pid = (); # (I) estimate min CDN open DF, ">.data" || die("Failed to create AOE optimization data file"); print DF "data;\n\n"; print DF "param : TotalPID : UPLOAD :=\n"; my $i = 0; for (my $pid = 0; $pid < $nl; $pid++) { next if ($demand[$pid] == 0); if ($generic == 1) { print DF "$i, ".(78 * $generic_demand)."\n"; } else { print DF "$i, ".$supply[$pid]."\n"; } $map_i_pid[$i] = $pid; $i++; } $ni = $i; print DF ";\n\n"; print DF "param : SOURCE :=\n"; for ($i = 0; $i < $ni; $i++) { print DF "$i, ".$cdn[ $map_i_pid[$i] ]."\n"; } print DF ";\n\n"; print DF "param : CLIENTNUM :=\n"; for ($i = 0; $i < $ni; $i++) { if ($generic == 1) { print DF "$i, ".$generic_demand."\n"; } else { print DF "$i, ".$demand[ $map_i_pid[$i] ]."\n"; } } print DF ";\n\n"; print DF "param RATE := 48;\n\n"; print DF "param ETA := 0.75;\n\n"; print DF "end;\n"; close DF; `glpsol --output .mincdn --model model-mincdn --data .data`; my $line = `grep "obj =" .mincdn`; my (undef, undef, undef, $cdn_min, undef) = split(/\s+/, $line); #print STDERR "MINCDN ".$cdn_min."\n"; # prepare for AOE min cost computation my $wl = `wc -l .data | cut -d" " -f1`; $wl--; `head -$wl .data > .data.$generic`; open DF, ">>.data.$generic" || die("Failed to create AOE optimization data file"); print DF "param : PRICE :=\n"; for ($i = 0; $i < $ni; $i++) { for (my $j = 0; $j < $ni; $j++) { print DF "$i, $j, ".($pdistance{$map_i_pid[$i].".i.".$isp}->{$map_i_pid[$j].".i.".$isp})."\n"; } } print DF ";\n\n"; print DF "param MINCDN := $cdn_min;\n\n"; close DF; return ($cdn_min); } sub aoe_mincost { my ($generic) = @_; %guidance_cdn = (); %guidance_p2p = (); # (II) optimize network cost `cp .data.$generic .data`; open DF, ">>.data" || die("Failed to create AOE optimization data file"); print DF "param ALPHA := $relax;\n\n"; print DF "end;\n\n"; close DF; `glpsol --output .mincost --model model-mincost --data .data`; my $line = `grep "obj =" .mincost`; my (undef, undef, undef, $cost_min, undef) = split(/\s+/, $line); #print STDERR "MINCOST ".$cost_min."\n"; # retrieve guidance $line = `grep -n \"xc\\[0,0\\]\" .mincost`; my ($li, undef) = split(/:/, $line); my $ln = $ni*$ni; my $lhead = $li + $ln - 1; $line = `head -$lhead .mincost | tail -$ln`; my @lines_cdn = split(/\n/, $line); $line = `grep -n \"xp\\[0,0\\]\" .mincost`; ($li, undef) = split(/:/, $line); $lhead = $li + $ln - 1; $line = `head -$lhead .mincost | tail -$ln`; my @lines_p2p = split(/\n/, $line); my ($cdn_ij, $p2p_ij); for (my $i = 0; $i < $ni; $i++) { for (my $j = 0; $j < $ni; $j++) { my $pidi = $map_i_pid[$i]; my $pidj = $map_i_pid[$j]; $line = shift(@lines_cdn); my (undef, undef, undef, undef, $cdn_ij, undef) = split(/\s+/, $line); if ($cdn_ij > 0) { $guidance_cdn{"$pidi-$pidj"} = $cdn_ij; } $line = shift(@lines_p2p); my (undef, undef, undef, undef, $p2p_ij, undef) = split(/\s+/, $line); if ($p2p_ij > 0) { $guidance_p2p{"$pidi-$pidj"} = $p2p_ij; } } } return ($cost_min, \%guidance_cdn, \%guidance_p2p); } sub sim_generic { my ($cdn_min, $guidance_cdn_ref, $guidance_p2p_ref) = @_; my %cdn_traffic = (); # = $guidance_cdn_ref; my %p2p_traffic = (); #= $guidance_p2p_ref; my @p2p_load; my @download; my @cdn_load; my @pids; my @p2p_cong; my @deficit; # demand-drive adaptation my $j = 0; for($j = 0; $j < $nl; $j++) { $p2p_load[$j] = 0.1; for(my $i = 0; $i < $nl; $i++) { if (exists($guidance_p2p_ref->{"$j-$i"})) { $p2p_traffic{"$j-$i"} = $guidance_p2p_ref->{"$j-$i"} * $demand[$i] / $generic_demand; } else { $p2p_traffic{"$j-$i"} = 0; } if (exists($guidance_cdn_ref->{"$j-$i"})) { #if ($demand[$j] > $demand_generic[$j]) # $cdn_traffic->{"$j-$i"} = $cdn_traffic->{"$j-$i"} * $demand[$i]; $cdn_traffic{"$j-$i"} = $guidance_cdn_ref->{"$j-$i"}; #FIXME: oversupply? if ($demand[$i] > $generic_demand) { $p2p_traffic{"$j-$i"} += $cdn_traffic{"$j-$i"} * (($demand[$i] / $generic_demand) - 1); #FIXME: oversupply? } } else { $cdn_traffic{"$j-$i"} = 0; } $p2p_load[$j] += $p2p_traffic{"$j-$i"}; $cdn_load[$j] += $cdn_traffic{"$j-$i"}; $download[$i] += ($p2p_traffic{"$j-$i"} + $cdn_traffic{"$j-$i"}); } $p2p_cong[$j] = $supply[$j] * 0.75 / $p2p_load[$j]; $deficit[$j] = 0; $pids[$j] = $j; } # balance p2p to avoid overload #TODO: balance each location's upload capacity according to guidance? my @sorted_pid = sort { $p2p_cong[$a] <=> $p2p_cong[$b] } @pids; my $upload_remain = 0; for($j = 0; $j < $nl; $j++) { my $pidj = $sorted_pid[$j]; if ($p2p_cong[$pidj] < 1 ) { for (my $pidi = 0; $pidi < $nl; $pidi++) { my $p2p_traffic_expected = $p2p_traffic{"$pidj-$pidi"}; $p2p_traffic{"$pidj-$pidi"} = $p2p_traffic{"$pidj-$pidi"} * $p2p_cong[$pidj]; $deficit[$pidi] += ($p2p_traffic_expected - $p2p_traffic{"$pidj-$pidi"}); } } if ($p2p_cong[$pidj] > 1 ) { $upload_remain += ($supply[$pidj] * 0.75 - $p2p_load[$pidj]); } } for($j = 0; $j < $nl; $j++) { my $pidj = $sorted_pid[$j]; if ($p2p_cong[$pidj] > 1 ) { for (my $pidi = 0; $pidi < $nl; $pidi++) { next if ($download[$pidi] == 0); my $p2p_traffic_expected = $p2p_traffic{"$pidj-$pidi"}; my $p2p_ij_max = $p2p_traffic{"$pidj-$pidi"} * $p2p_cong[$pidj]; my $p2p_traffic_needadd = $deficit[$pidi] * ($p2p_ij_max - $p2p_traffic_expected) / $upload_remain; #my $p2p_traffic_needadd = $deficit[$pidi] * $p2p_traffic_expected / $download[$pidi]; if ($p2p_ij_max > ($p2p_traffic_needadd + $p2p_traffic_expected)) { $p2p_traffic{"$pidj-$pidi"} = $p2p_traffic_needadd + $p2p_traffic_expected; } else { $p2p_traffic{"$pidj-$pidi"} = $p2p_ij_max; } $deficit[$pidi] -= ($p2p_traffic{"$pidj-$pidi"} - $p2p_traffic_expected); $upload_remain -= ($p2p_traffic{"$pidj-$pidi"} - $p2p_traffic_expected); } } } # TODO: if P2P is insufficient, use CDN # use more CDN for less cost?! for(my $i = 0; $i < $nl; $i++) { next if ($deficit[$i] <= 0); # find cheapeast CDN my $j_cdn = $i; my $p_ji = 10000; for(my $j = 0; $j < $nl; $j++) { if ($cdn[$j] > 0 && $pdistance{"$j.i.$isp"}->{"$i.i.$isp"} < $p_ji) { $j_cdn = $j; $p_ji = $pdistance{"$j.i.$isp"}->{"$i.i.$isp"}; } } $cdn_traffic{"$j_cdn-$i"} += $deficit[$i]; $deficit[$i] = 0; } # compute cost and CDN my $sum_cost = 0; my $sum_cdn = 0; for(my $i = 0; $i < $nl; $i++) { #$sum_cdn += $deficit[$i]; for(my $j = 0; $j < $nl; $j++) { my $self = "$i.i.$isp"; my $remote = "$j.i.$isp"; my $distance = $pdistance{$remote}->{$self}; if (exists($p2p_traffic{"$j-$i"})) { $sum_cost += $p2p_traffic{"$j-$i"} * $distance; } if (exists($cdn_traffic{"$j-$i"})) { $sum_cost += $cdn_traffic{"$j-$i"} * $distance; $sum_cdn += $cdn_traffic{"$j-$i"}; } } } return ($sum_cost, $sum_cdn); } # NOT USED sub sim_aoe_server { my $sum_cost = 0; my $sum_cdn = 0; my $sum_cost_generic = 0; my $sum_cdn_generic = 0; # Dynamic my @upload; for(my $j = 0; $j < $nl; $j++) { $upload[$j] = 0; } `./p4p_aoe_client --server=$aoe --port=6673 --op=ssm --portal=$p4p <.ssm >.aoe`; open(AOEF, "<.aoe") || die("AOE result not found"); while(<AOEF>) { # 1.i.America intrapid 0.104167 intradomain 0.104167 interdomain 0.104167 1.i.America 0.104167 2.i.America 0 3.i.America 0 4.i.America 0 chomp; my @info = split(/\s+/); my $self = shift(@info); shift(@info); shift(@info); shift(@info); shift(@info); shift(@info); shift(@info); while(@info > 1) { my $remote = shift(@info); my $traffic = shift(@info); my $distance = $pdistance{$remote}->{$self}; $sum_cost += $traffic * $distance; my ($remote_pid, undef, undef) = split(/\.+/, $remote); $upload[$remote_pid] += $traffic; #print STDERR "TRAFFIC\t".$self."\t".$remote."\t".$traffic."\t".$distance."\n"; } } for(my $j = 0; $j < $nl; $j++) { if ($upload[$j] > $supply[$j]) { $sum_cdn += ($upload[$j] - $supply[$j]); } } close(AOEF); # Generic `./p4p_aoe_client --server=$aoe --port=6673 --op=ssm --portal=$p4p <.generic >.aoe.generic`; my %guidance; my @guidance_cdn; for (my $j = 0; $j < $nl; $j++) { $upload[$j] = 0; } #open(AOEF, "<generic/aoe.sim.generic.$isp.0") || die("AOE generic guidance not found"); open(AOEF, "<.aoe.generic") || die("AOE generic guidance not found"); while(<AOEF>) { # 1.i.America intrapid 0.104167 intradomain 0.104167 interdomain 0.104167 1.i.America 0.104167 2.i.America 0 3.i.America 0 4.i.America 0 chomp; my @info = split(/\s+/); my $self = shift(@info); my ($self_pid, undef, undef) = split(/\.+/, $self); shift(@info); shift(@info); shift(@info); shift(@info); shift(@info); shift(@info); # compute traffic based on generic guidance # Major problem: generic guidance does not directly apply... # compute extra CDN load instead? # approximate algorithm to fetch # greedy algorithm to fetch CDN? # v.s. # random algorithm to fetch CDN? while(@info > 1) { my $remote = shift(@info); my $traffic_generic = shift(@info); my ($remote_pid, undef, undef) = split(/\.+/, $remote); $guidance{"$remote_pid-$self_pid"} = $traffic_generic; $upload[$remote_pid] += $traffic_generic; } } close(AOEF); #for ecah demanding location, distribute its request according to generic guidance for(my $j = 0; $j < $nl; $j++) { $guidance_cdn[$j] = 0; for(my $i = 0; $i < $nl; $i++) { if (exists($guidance{"$j-$i"}) && $upload[$j] > 0) { $guidance_cdn[$j] += $guidance{"$j-$i"}; #$guidance{"$j-$i"} = $guidance{"$j-$i"} * ($upload[$j] / 78) * $supply[$j] / 78; $guidance{"$j-$i"} = $guidance{"$j-$i"} * $demand[$j]; } } $guidance_cdn[$j] = ($guidance_cdn[$j] - 78) * $upload[$j] / 78; #FIXME: 78 hardcoded } goto direct; # move extra load to elsewhere my @download; for(my $i = 0; $i < $nl; $i++) { for(my $j = 0; $j < $nl; $j++) { if (exists($guidance{"$j-$i"})) { $download[$i] += $guidance{"$j-$i"}; } } if ($download[$i] > $demand[$i] * $rate) #TODO: eta? { for(my $j = 0; $j < $nl; $j++) { if (exists($guidance{"$j-$i"})) { $guidance{"$j-$i"} = $guidance{"$j-$i"} * ($demand[$i] * $rate) / ($download[$i] * 0.75); } } } } for(my $j = 0; $j < $nl; $j++) { $upload[$j] = 0; for(my $i = 0; $i < $nl; $i++) { if (exists($guidance{"$j-$i"})) { $upload[$j] += $guidance{"$j-$i"}; } } #WARNING: CDN not really used #if ($upload[$j] > $supply[$j]) #{ # $sum_cdn_generic += ($upload[$j] - $supply[$j]); #} } #print STDERR "CDN\t$sum_cdn\t$sum_cdn_generic\n"; #for each demanding location, apply greedy/random algorithm to # (ii) then compensate the demand deficit for(my $i = 0; $i < $nl; $i++) { # (i) compensate the demand deficit if ($download[$i] < $demand[$i] * $rate) { my $deficit = $demand[$i] * $rate - $download[$i] * 0.75; #FIXME: eta? # random v.s. greedy compensate algorithm # TODO: how to compensate by CDN and P2P? if ($sum_cdn_generic < $sum_cdn) { # TODO: find cheapeast CDN my $j_cdn = $i; my $p_ji = 10000; for( my $j = 0; $j < $nl; $j++ ) { if ($cdn[$j] > 0 && $pdistance{"$j.i.$isp"}->{"$i.i.$isp"} < $p_ji) { $j_cdn = $j; $p_ji = $pdistance{"$j.i.$isp"}->{"$i.i.$isp"}; } } if ($deficit > ($sum_cdn - $sum_cdn_generic)) { $deficit -= ($sum_cdn - $sum_cdn_generic); $guidance{"$j_cdn-$i"} += ($sum_cdn - $sum_cdn_generic); $sum_cdn_generic = $sum_cdn; } else { $sum_cdn_generic += $deficit; $guidance{"$j_cdn-$i"} += $deficit; $deficit = 0; } } if ($deficit > 0) { # TODO: find cheapeast location where there is extra supply my $t = 0; for(my $j = $i; $deficit > 0 && $t < $nl; $j = int(rand($nl)) && $t++) { next if ($upload[$j] >= $supply[$j]); #print STDERR "P2P compensation: $j-$i $deficit ".$upload[$j]." ".$supply[$j]."\n"; if ($deficit > ($supply[$j] - $upload[$j])) { $deficit -= ($supply[$j] - $upload[$j]); $guidance{"$j-$i"} += ($supply[$j] - $upload[$j]); $upload[$j] = $supply[$j]; } else { $upload[$j] += $deficit; $guidance{"$j-$i"} += $deficit; $deficit = 0; } } } } } direct: # compute network cost $sum_cdn_generic = 0; for(my $i = 0; $i < $nl; $i++) { my $cdn_i = 0; for(my $j = 0; $j < $nl; $j++) { my $self = "$i.i.$isp"; my $remote = "$j.i.$isp"; my $distance = $pdistance{$remote}->{$self}; if (exists($guidance{"$j-$i"})) { $sum_cost_generic += $guidance{"$j-$i"} * $distance; } if (exists($guidance{"$i-$j"})) { my $cdn_i += $guidance{"$i-$j"}; } } if ($cdn_i > $supply[$i]) { $sum_cdn_generic += ($cdn_i - $supply[$i]); } } if ($sum_cdn == 0) { $sum_cdn_generic = 0; $sum_cdn = 1; } return($sum_cost, $sum_cost_generic, ($sum_cdn_generic / $sum_cdn)); }
Yale-LANS/ALTO
aoe/util/aoeexp/testaoe_network.pl
Perl
bsd-3-clause
17,616
# SNMP::Info::Layer3::IBMGbTor - SNMP Interface to IBM Rackswitch devices # $Id$ # # Copyright (c) 2013 Eric Miller # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the University of California, Santa Cruz nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. package SNMP::Info::Layer3::IBMGbTor; use strict; use Exporter; use SNMP::Info::Layer3; use SNMP::Info::LLDP; @SNMP::Info::Layer3::IBMGbTor::ISA = qw/SNMP::Info::LLDP SNMP::Info::Layer3 Exporter/; @SNMP::Info::Layer3::IBMGbTor::EXPORT_OK = qw//; use vars qw/$VERSION %GLOBALS %FUNCS %MIBS %MUNGE/; $VERSION = '3.34'; %MIBS = ( %SNMP::Info::Layer3::MIBS, # LLDP MIBs not loaded to prevent possible unqualified namespace conflict # with IBM definitions 'IBM-GbTOR-10G-L2L3-MIB' => 'lldpInfoRemoteDevicesLocalPort', ); %GLOBALS = ( %SNMP::Info::Layer3::GLOBALS, %SNMP::Info::LLDP::GLOBALS, 'temp' => 'hwTempSensors', 'fan' => 'hwFanSpeed', # Can't find the equivalent in IBM-GbTOR-10G-L2L3-MIB # use a different strategy for lldp_sys_cap in hasLLDP() #'lldp_sysname' => 'lldpLocSysName', #'lldp_sysdesc' => 'lldpLocSysDesc', #'lldp_sys_cap' => 'lldpLocSysCapEnabled', ); %FUNCS = ( %SNMP::Info::Layer3::FUNCS, %SNMP::Info::LLDP::FUNCS, # IBM-GbTOR-10G-L2L3-MIB::portInfoTable 'sw_duplex' => 'portInfoMode', # Can't find the equivalent in IBM-GbTOR-10G-L2L3-MIB # not currently used in LLDP class #'lldp_lman_addr' => 'lldpLocManAddrIfId', # IBM-GbTOR-10G-L2L3-MIB::lldpInfoPortTable 'lldp_port_status' => 'lldpInfoPortAdminStatus', # IBM-GbTOR-10G-L2L3-MIB::lldpInfoRemoteDevicesTable 'lldp_rem_id_type' => 'lldpInfoRemoteDevicesChassisSubtype', 'lldp_rem_id' => 'lldpInfoRemoteDevicesSystemName', 'lldp_rem_pid_type' => 'lldpInfoRemoteDevicesPortSubtype', 'lldp_rem_pid' => 'lldpInfoRemoteDevicesPortId', 'lldp_rem_desc' => 'lldpInfoRemoteDevicesPortDescription', 'lldp_rem_sysname' => 'lldpInfoRemoteDevicesSystemName', 'lldp_rem_sysdesc' => 'lldpInfoRemoteDevicesSystemDescription', 'lldp_rem_sys_cap' => 'lldpInfoRemoteDevicesSystemCapEnabled', # IBM-GbTOR-10G-L2L3-MIB::lldpInfoRemoteDevicesManAddrTable 'lldp_rman_type' => 'lldpInfoRemoteDevicesManAddrSubtype', 'lldp_rman_addr' => 'lldpInfoRemoteDevicesManAddr', ); %MUNGE = ( %SNMP::Info::Layer3::MUNGE, %SNMP::Info::LLDP::MUNGE, ); sub hasLLDP { my $ibm = shift; # We may be have LLDP, but nothing in lldpRemoteSystemsData Tables # Look to see if LLDP Rx enabled on any port my $lldp_cap = $ibm->lldp_port_status(); foreach my $if ( keys %$lldp_cap ) { if ( $lldp_cap->{$if} =~ /enabledRx/i ) { return 1; } } return; } sub lldp_ip { my $ibm = shift; my $partial = shift; my $rman_type = $ibm->lldp_rman_type($partial) || {}; my $rman_addr = $ibm->lldp_rman_addr($partial) || {}; my %lldp_ip; foreach my $key ( keys %$rman_addr ) { my $type = $rman_type->{$key}; next unless defined $type; next unless $type eq 'ipV4'; if ( $key =~ /^(\d+)\./ ) { $lldp_ip{$1} = $rman_addr->{$key}; } } return \%lldp_ip; } sub lldp_if { my $lldp = shift; my $partial = shift; my $lldp_desc = $lldp->lldpInfoRemoteDevicesLocalPort($partial) || {}; my $i_descr = $lldp->i_description() || {}; my $i_alias = $lldp->i_alias() || {}; my %r_i_descr = reverse %$i_descr; my %r_i_alias = reverse %$i_alias; my %lldp_if; foreach my $key ( keys %$lldp_desc ) { # Cross reference lldpLocPortDesc with ifDescr and ifAlias to get ifIndex, # prefer ifAlias over ifDescr since MIB says 'alias'. my $desc = $lldp_desc->{$key}; next unless $desc; my $port = $desc; # If cross reference is successful use it, otherwise stick with # lldpRemLocalPortNum if ( exists $r_i_alias{$desc} ) { $port = $r_i_alias{$desc}; } elsif ( exists $r_i_descr{$desc} ) { $port = $r_i_descr{$desc}; } $lldp_if{$key} = $port; } return \%lldp_if; } sub lldp_platform { my $ibm = shift; my $partial = shift; return $ibm->lldpInfoRemoteDevicesSystemDescription($partial); } sub i_ignore { my $ibm = shift; my $partial = shift; my $interfaces = $ibm->interfaces($partial) || {}; my %i_ignore; foreach my $if ( keys %$interfaces ) { if ( $interfaces->{$if} =~ /(tunnel|loopback|\blo\b|lb|null)/i ) { $i_ignore{$if}++; } } return \%i_ignore; } sub i_duplex { my $ibm = shift; my $partial = shift; return $ibm->sw_duplex($partial); } sub model { my $ibm = shift; my $id = $ibm->id(); my $descr = $ibm->description(); my $model = &SNMP::translateObj($id); if ( $descr =~ /RackSwitch\s(.*)/ ) { return $1; } return $model || $id; } sub os { return 'ibm'; } sub vendor { return 'ibm'; } sub os_ver { my $ibm = shift; return $ibm->agSoftwareVersion(); } sub interfaces { my $ibm = shift; my $partial = shift; my $i_descr = $ibm->i_description($partial) || {}; my $i_name = $ibm->i_name($partial) || {}; foreach my $iid ( keys %$i_name ) { my $name = $i_name->{$iid}; next unless defined $name; $i_descr->{$iid} = $name if $name =~ /^port\d+/i; } return $i_descr; } 1; __END__ =head1 NAME SNMP::Info::Layer3::IBMGbTor - SNMP Interface to IBM Rackswitch devices =head1 AUTHOR Eric Miller =head1 SYNOPSIS # Let SNMP::Info determine the correct subclass for you. my $ibm = new SNMP::Info( AutoSpecify => 1, Debug => 1, DestHost => 'myswitch', Community => 'public', Version => 1 ) or die "Can't connect to DestHost.\n"; my $class = $ibm->class(); print "SNMP::Info determined this device to fall under subclass : $class\n"; =head1 DESCRIPTION Abstraction subclass for IBM Rackswitch (formerly Blade Network Technologies) network devices. For speed or debugging purposes you can call the subclass directly, but not after determining a more specific class using the method above. my $ibm = new SNMP::Info::Layer3::IBMGbTor(...); =head2 Inherited Classes =over =item SNMP::Info::Layer3; =item SNMP::Info::LLDP; =back =head2 Required MIBs =over =item F<IBM-GbTOR-10G-L2L3-MIB> =item Inherited Classes' MIBs See L<SNMP::Info::Layer3/"Required MIBs"> for its own MIB requirements. =back =head1 GLOBALS These are methods that return scalar value from SNMP =over =item $ibm->model() Returns model type. Attempts to pull model from device description. Otherwise checks $ibm->id() against the F<IBM-GbTOR-10G-L2L3-MIB>. =item $ibm->vendor() Returns 'ibm' =item $ibm->os() Returns 'ibm' =item $ibm->os_ver() Returns the software version (C<agSoftwareVersion>) =item $ibm->temp() (C<hwTempSensors>) =item $ibm->fan() (C<hwFanSpeed>) =back =head2 Overrides =over =item $ibm->hasLLDP() Is LLDP is active in this device? Note: LLDP may be active, but nothing in C<lldpRemoteSystemsData> Tables so the device would not return any useful topology information. Checks to see if at least one interface is enabled to receive LLDP packets. =back =head2 Global Methods imported from SNMP::Info::Layer3 See documentation in L<SNMP::Info::Layer3/"GLOBALS"> for details. =head2 Global Methods imported from SNMP::Info::LLDP See documentation in L<SNMP::Info::LLDP/"GLOBALS"> for details. =head1 TABLE METHODS These are methods that return tables of information in the form of a reference to a hash. =head2 Overrides =over =item $ibm->interfaces() Returns reference to hash of interface names to iids. =item $ibm->i_ignore() Returns reference to hash of interfaces to be ignored. Ignores interfaces with descriptions of tunnel, loopback, and null. =item $ibm->i_duplex() Returns reference to hash of interface link duplex status. (C<portInfoMode>) =item $ibm->lldp_if() Returns the mapping to the SNMP Interface Table. Tries to cross reference (C<lldpInfoRemoteDevicesLocalPort>) with (C<ifDescr>) and (C<ifAlias>) to get (C<ifIndex>). =item $ibm->lldp_ip() Returns remote IPv4 address. Returns for all other address types, use lldp_addr if you want any return address type. =item $ibm->lldp_platform() Returns remote device system description. (C<lldpInfoRemoteDevicesSystemDescription>) =back =head2 Table Methods imported from SNMP::Info::Layer3 See documentation in L<SNMP::Info::Layer3/"TABLE METHODS"> for details. =head2 Table Methods imported from SNMP::Info::LLDP See documentation in L<SNMP::Info::LLDP/"TABLE METHODS"> for details. =cut
42wim/snmp-info
Info/Layer3/IBMGbTor.pm
Perl
bsd-3-clause
10,423
=head1 NAME webilder_downloader - downloads wallpapers and saves them in user's webilder collection. =head1 SYNOPSIS webilder_downloader =head1 DESCRIPTION B<webilder_downloader> Downloads wallpapers according to the user settings file (see below). The photos are saved the the webilder collection directory specified in this file. =head1 FILES F<$HOME/.webilder/webilder.conf>: user settings file. =head1 BUGS Please report bugs in http://github.com/thesamet/webilder/issues =head1 AUTHORS B<Webilder> was written by Nadav Samet <thesamet@gmail.com>. Webilder is released under the BSD License.
thesamet/webilder
manpages/webilder_downloader.pod
Perl
bsd-3-clause
609
package Text::Trie::Tx; use strict; use warnings; use Carp; our $VERSION = sprintf "%d.%02d", q$Revision: 0.1 $ =~ /(\d+)/g; our $DEBUG = 0; require XSLoader; XSLoader::load('Text::Trie::Tx', $VERSION); sub open{ my $pkg = shift; my $filename = shift; my $dpi = xs_open($filename); carp __PACKAGE__, " cannot open $filename" unless $dpi; bless \$dpi, $pkg; } sub DESTROY{ if ($DEBUG){ no warnings 'once'; require Data::Dumper; local $Data::Dumper::Terse = 1; local $Data::Dumper::Indent = 0; warn "DESTROY:", Data::Dumper::Dumper($_[0]); } xs_free(${$_[0]}); } sub prefixSearch{ return xs_prefixSearch(${$_[0]}, $_[1]); } sub commonPrefixSearch{ return xs_commonPrefixSearch(${$_[0]}, $_[1]); } sub commonPrefixSearchID{ return xs_commonPrefixSearchID(${$_[0]}, $_[1]); } sub predictiveSearch{ return xs_predictiveSearch(${$_[0]}, $_[1]); } sub predictiveSearchID{ return xs_predictiveSearchID(${$_[0]}, $_[1]); } sub reverseLookup{ return xs_reverseLookup(${$_[0]}, $_[1]); } sub getKeyNum{ return xs_getKeyNum(${$_[0]}); } 1; __END__ # Below is stub documentation for your module. You'd better edit it! =head1 NAME Text::Trie::Tx - Perl interface to Tx by OKANOHARA Daisuke =head1 SYNOPSIS use Text::Trie::Tx; my $td = Text::Trie::Tx->open("words.tx"); my $idList = $td->commonPrefixSearchID($input); $td->close =head1 DESCRIPTION Tx is a library for a compact trie data structure by OKANOHARA Daisuke. Tx requires 1/4 - 1/10 of the memory usage compared to the previous implementations, and can therefore handle quite a large number of keys (e.g. 1 billion) efficiently. =head1 REQUIREMENT Tx 0.04 or above. Available at L<http://www-tsujii.is.s.u-tokyo.ac.jp/~hillbig/tx.htm> To install, just fetch http://www-tsujii.is.s.u-tokyo.ac.jp/~hillbig/software/tx-0.12.tar.gz tar zxvf tx-0.12.tar.gz cd tx-0.12 configure make sudo make install =head2 EXPORT None. =head1 SEE ALSO L<http://www-tsujii.is.s.u-tokyo.ac.jp/~hillbig/tx.htm> =head1 AUTHOR Dan Kogai, E<lt>dankogai@dan.co.jpE<gt> MURAWAKI Yugo, E<lt>murawaki@ait.kyushu-u.ac.jpE<gt> =head1 COPYRIGHT AND LICENSE Copyright (C) 2007 by Dan Kogai Copyright (C) 2008-2009 by MURAWAKI Yugo This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.10.0 or, at your option, any later version of Perl 5 you may have available. =cut
murawaki/tx-perl
lib/Text/Trie/Tx.pm
Perl
bsd-3-clause
2,480
#################################################################################################################################### # HostGroupTest.pm - Encapsulate a group of docker containers for testing #################################################################################################################################### package pgBackRestTest::Common::HostGroupTest; #################################################################################################################################### # Perl includes #################################################################################################################################### use strict; use warnings FATAL => qw(all); use Carp qw(confess); use Cwd qw(abs_path); use Exporter qw(import); our @EXPORT = qw(); use pgBackRestDoc::Common::Log; use pgBackRestDoc::Common::String; use pgBackRestTest::Common::ExecuteTest; #################################################################################################################################### # Global host group variable #################################################################################################################################### my $oHostGroup; #################################################################################################################################### # new #################################################################################################################################### sub new { my $class = shift; # Class name # Create the class hash my $self = {}; bless $self, $class; # Assign function parameters, defaults, and log debug info my ($strOperation) = logDebugParam(__PACKAGE__ . '->new'); # Return from function and log return values if any return logDebugReturn ( $strOperation, {name => 'self', value => $self, trace => true} ); } #################################################################################################################################### # hostAdd #################################################################################################################################### sub hostAdd { my $self = shift; # Assign function parameters, defaults, and log debug info my ( $strOperation, $oHost, $rstryHostName, ) = logDebugParam ( __PACKAGE__ . '->hostAdd', \@_, {name => 'oHost'}, {name => 'rstryHostName', optional => true}, ); $self->{host}{$oHost->{strName}} = $oHost; if ($oHost->hostUpdateGet()) { $oHost->executeSimple("echo \"\" >> /etc/hosts", undef, 'root', {bLoadEnv => false}); $oHost->executeSimple("echo \"# Test Hosts\" >> /etc/hosts", undef, 'root', {bLoadEnv => false}); } my $strHostList = $oHost->{strName} . (defined($rstryHostName) ? ' ' . join(' ', @{$rstryHostName}) : ''); # Iterate hosts to add IP mappings foreach my $strOtherHostName (sort(keys(%{$self->{host}}))) { my $oOtherHost = $self->{host}{$strOtherHostName}; if ($strOtherHostName ne $oHost->{strName}) { # Add this host IP to all hosts if ($oOtherHost->hostUpdateGet()) { $oOtherHost->executeSimple( "echo \"$oHost->{strIP} ${strHostList}\" >> /etc/hosts", undef, 'root', {bLoadEnv => false}); } # Add all other host IPs to this host if ($oHost->hostUpdateGet()) { $oHost->executeSimple( "echo \"$oOtherHost->{strIP} ${strOtherHostName}\" >> /etc/hosts", undef, 'root', {bLoadEnv => false}); } } } # Return from function and log return values if any return logDebugReturn($strOperation); } #################################################################################################################################### # hostGet #################################################################################################################################### sub hostGet { my $self = shift; # Assign function parameters, defaults, and log debug info my ( $strOperation, $strName, $bIgnoreMissing, ) = logDebugParam ( __PACKAGE__ . '->hostGet', \@_, {name => 'strName', trace => true}, {name => 'bIgnoreMissing', default => false, trace => true}, ); my $oHost = $self->{host}{$strName}; if (!defined($oHost) && !$bIgnoreMissing) { confess &log(ERROR, "host ${strName} does not exist"); } # Return from function and log return values if any return logDebugReturn ( $strOperation, {name => 'oHost', value => $oHost} ); } #################################################################################################################################### # removeAll #################################################################################################################################### sub removeAll { my $self = shift; # Assign function parameters, defaults, and log debug info my ($strOperation) = logDebugParam(__PACKAGE__ . '->removeAll'); my $iTotal = 0; foreach my $strHostName (sort(keys(%{$self->{host}}))) { ${$self->{host}}{$strHostName}->remove(); delete($self->{host}{$strHostName}); $iTotal++; } # Return from function and log return values if any return logDebugReturn ( $strOperation, {name => 'iTotal', value => $iTotal} ); } #################################################################################################################################### # hostGroupGet # # Get the global host group object. #################################################################################################################################### sub hostGroupGet { if (!defined($oHostGroup)) { $oHostGroup = new pgBackRestTest::Common::HostGroupTest(); } return $oHostGroup; } push @EXPORT, qw(hostGroupGet); 1;
pgbackrest/pgbackrest
test/lib/pgBackRestTest/Common/HostGroupTest.pm
Perl
mit
6,221
#!/usr/bin/env perl ## Name........: seprule ## Autor.......: Jens Steube <jens.steube@gmail.com> ## License.....: MIT use strict; use warnings; ## ## configuration ## my @rp = ('0'..'9', 'A'..'Z'); my $width = 3; my $rule = "i"; my $sep = " "; ## ## code ## my $rp_size = scalar @rp; my $total = $rp_size ** $width; my $db; for (my $i = 0; $i < $total; $i++) { my $left = $i; my @out; for (my $c = 0; $c < $width; $c++) { my $m = $left % $rp_size; my $d = $left / $rp_size; push (@out, $m); $left = $d; } @out = sort { $a <=> $b } @out; my $val = join ("", @out); next if (exists $db->{$val}); $db->{$val} = undef; my @final; for (my $c = 0; $c < $width; $c++) { my $s = sprintf ("T%s", $rp[$out[$c]]); push (@final, $s); } for (my $c = 0; $c < $width; $c++) { my $s = sprintf ("%s%s%s", $rule, $rp[$out[$c]], $sep); push (@final, $s); } print join (" ", "l", @final), "\n"; }
philsmd/hashcat-utils
src/seprule.pl
Perl
mit
971
#!/usr/bin/perl -w use strict; use warnings; #Three files are needed: 1-2) sin and pin from Wang et al. 3) list of variations if ($#ARGV != 1) {die "Program used with parameters [list of variations] [SIN]\n";} #parse_variations my @variations=open_file($ARGV[0]); my(@variat, %seen, @uniq); for(my $i=0;$i<$#variations+1;$i++){ my @tab = split(/\t/,$variations[$i]);#Gene_symbol, Entrez, UniprotAC, uniprotID, Ref AA, Position, Var AA push (@{$variat[$i]}, @tab); $seen{$tab[1]}++; } @uniq = keys %seen; #get interactions from Wang sin (or other but in same format) #entrez ID should already be mapped to gene symbols my @wang_sin=open_file($ARGV[1]); my (@sin); for(my $i=0;$i<$#wang_sin+1;$i++){#parse interactions my @tab=split(/\t/,$wang_sin[$i]);#protA pfamA seq_str_A seq_end_A protB pfamB seq_str_B seq_end_B push (@{$sin[$i]}, @tab); } #map variations and prepare DIN network my(%din,%node1,%node2,%dvar,%cout); my $k=0; for (my $j=0;$j<$#wang_sin+1;$j++){ my $dom1=$sin[$j][0]."_".$sin[$j][1]; my $dom2=$sin[$j][4]."_".$sin[$j][5]; my $inter=$dom1."\t".$dom2; $dvar{$dom1}=0;# $dvar{$dom2}=0; $cout{$dom1}=0; $cout{$dom2}=0; for(my $i=0;$i<$#variat+1;$i++){ if(($variat[$i][0] eq $sin[$j][0]) or ($variat[$i][0] eq $sin[$j][4])){ $node1{$inter}=$dom1; $node2{$inter}=$dom2; $din{$inter}++; } if($variat[$i][0] eq $sin[$j][0]){ $k++; my $pos = $variat[$i][5]; my $ds =$sin[$j][2]; my $de =$sin[$j][3]; if($pos ge $ds and $pos le $de){ $dvar{$dom1}++;#count variations in domain 1 } else{$cout{$dom1}++;}#count variations outside domain 1 #print "dupa $sin[$j][0] $node1{$inter} $dvar{$dom1} $cout{$dom1} \n"; } elsif($variat[$i][0] eq $sin[$j][4]){ $k++; my $pos = $variat[$i][5]; my $ds =$sin[$j][6]; my $de =$sin[$j][7]; if($pos ge $ds and $pos le $de){ $dvar{$dom2}++;#count variations in domain 2 } else{$cout{$dom2}++;}#count variations outside domain 2 } } } my $filec = substr($ARGV[0],0,rindex($ARGV[0],".")); my $file = $filec."-din-graph.txt"; my $file3 = $filec."-din-nodeAttr.txt"; my $file4 = $filec."-din-edgeAttr.txt"; open(OUT, "> $file") or die "Can not open an output file: $!"; open(OUT3, "> $file3") or die "Can not open an output file: $!"; open(OUT4, "> $file4") or die "Can not open an output file: $!"; printf OUT4 "edge\tedgeGV\ttotal_edge\tr_edge\n";#print edge attributes my(%hasGV,%GVinD,%GVoutD,%nattri); my $edgeGV=0; foreach my $klucz (keys %din){ my $r1=0; my $r2=0; my $rpair=0; printf OUT "$node1{$klucz}\t$node2{$klucz}\n";#print DIN network my @tab=split(/\s+/,$klucz); my $t1=$dvar{$tab[0]}+$cout{$tab[0]};#total number of variations my $t2=$dvar{$tab[1]}+$cout{$tab[1]};#total number of variations $r1=($dvar{$tab[0]}/$t1) unless $t1 == 0; $r2=($dvar{$tab[1]}/$t2) unless $t2 == 0; my $tpair=$t1+$t2; my $dpairvar=$dvar{$tab[0]}+$dvar{$tab[1]}; $rpair=($dpairvar/$tpair) unless $tpair == 0; #SNV inside interacting domains if($dvar{$tab[0]} > 0){ $GVinD{$tab[0]}=1; } else{ $GVinD{$tab[0]}=0; } if($dvar{$tab[1]} > 0){ $GVinD{$tab[1]}=1; } else{ $GVinD{$tab[1]}=0; } #SNV outside interacting domains if($cout{$tab[0]} > 0){ $GVoutD{$tab[0]}=1; } else{ $GVoutD{$tab[0]}=0; } if($cout{$tab[1]} > 0){ $GVoutD{$tab[1]}=1; } else{ $GVoutD{$tab[1]}=0; } if(($dvar{$tab[0]} > 0) or ($cout{$tab[0]} > 0)){ $hasGV{$tab[0]}=1; $edgeGV=1; } else{$hasGV{$tab[0]}=0;} if(($dvar{$tab[1]} > 0) or ($cout{$tab[1]} > 0)){ $hasGV{$tab[1]}=1; $edgeGV=1; } else{$hasGV{$tab[1]}=0;} if(($hasGV{$tab[0]} == 1) and ($hasGV{$tab[1]} == 1)){$edgeGV = 2;} #printf OUT3 "$tab[0]\t$GVinD{$tab[0]}\t$GVoutD{$tab[0]}\t$t1\t$r1\n";#print attributes of first node #printf OUT3 "$tab[1]\t$GVinD{$tab[1]}\t$GVoutD{$tab[1]}\t$t1\t$r2\n";#print attributes of the second node $nattri{$tab[0]}="$node1{$klucz}\t$GVinD{$tab[0]}\t$GVoutD{$tab[0]}\t$t1\t$r1\n";#print attributes of first node $nattri{$tab[1]}="$node2{$klucz}\t$GVinD{$tab[1]}\t$GVoutD{$tab[1]}\t$t2\t$r2\n";#print attributes of the second node printf OUT4 "$node1{$klucz} (pp) $node2{$klucz}\t$edgeGV\t$tpair\t$rpair\n";#print edge attributes #print some statistics # Domain 1;#SNV in domain;#SNV outside dom.;col2/total numb.;Domain 2;#SNV in domain;#SNV outside dom.;col6/total numb.;total on domains/total in edge # print "$tab[0]\t$dvar{$tab[0]}\t$cout{$tab[0]}\t$r1\t$tab[1]\t$dvar{$tab[1]}\t$cout{$tab[1]}\t$r2\t$rpair\n"; } #print node attributes printf OUT3 "node1\tGVinD\tGVoutD\tTotal\tr_GVinD\n"; foreach my $klucz (keys %nattri){printf OUT3 $nattri{$klucz};} #print "$k\n"; sub open_file{ my ($file_name)=@_; open(INP1, "< $file_name") or die "Can not open an input file $file_name : $!"; my @file1=<INP1>; close (INP1); chomp @file1; return @file1; }
wjurkowski/varnet
spinka/spinka-0.5.pl
Perl
apache-2.0
4,917
package Google::Ads::AdWords::v201406::ReportDefinitionService::getReportFields; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201406' } __PACKAGE__->__set_name('getReportFields'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::SOAP::Typelib::ComplexType ); our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %reportType_of :ATTR(:get<reportType>); __PACKAGE__->_factory( [ qw( reportType ) ], { 'reportType' => \%reportType_of, }, { 'reportType' => 'Google::Ads::AdWords::v201406::ReportDefinition::ReportType', }, { 'reportType' => 'reportType', } ); } # end BLOCK } # end of BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201406::ReportDefinitionService::getReportFields =head1 DESCRIPTION Perl data type class for the XML Schema defined element getReportFields from the namespace https://adwords.google.com/api/adwords/cm/v201406. Returns the available report fields for a given report type. @param reportType The type of report. @return The list of available report fields. Each {@link ReportDefinitionField} encapsulates the field name, the field data type, and the enum values (if the field's type is {@code enum}). @throws ApiException if a problem occurred while fetching the ReportDefinitionField information. =head1 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * reportType $element->set_reportType($data); $element->get_reportType(); =back =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201406::ReportDefinitionService::getReportFields->new($data); Constructor. The following data structure may be passed to new(): { reportType => $some_value, # ReportDefinition.ReportType }, =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201406/ReportDefinitionService/getReportFields.pm
Perl
apache-2.0
2,250
package NP::Util; use strict; use warnings; use HTML::Entities qw(encode_entities); use Exporter; use Encode (); use Carp qw(croak); use Data::Transformer (); our @EXPORT_OK = qw( convert_to_html run utf8_safe utf8_safe_tree uniq ); sub convert_to_html { my $str = shift; encode_entities($str, '<>&"'); # how can we encode everything without messing up UTF8? $str =~ s!(https?://.+?)(\s|$)!<a href="$1">$1</a>$2!g; $str =~ s!\n\s*[\n\s]+!<br/><br/>!g; $str =~ s!\n!<br/>\n!g; $str; } sub run { my @ar = @_; my $parms = ref $ar[-1] eq "HASH" ? pop @ar : {}; print "Running: ", join(" ", @ar), "\n" unless $parms->{silent}; return 1 if system(@ar) == 0; my $exit_value = $? >> 8; return 0 if $parms->{fail_silent_if} && $exit_value == $parms->{fail_silent_if}; my $msg = "system @ar failed: $exit_value ($?)"; croak($msg) unless $parms->{failok}; print "$msg\n"; return 0; } sub utf8_safe { my $text = shift; $text = Encode::decode("windows-1252", $text) unless utf8::is_utf8($text) or utf8::decode($text); return $text; } sub utf8_safe_tree { my $data = shift; Data::Transformer->new( normal => sub { ${$_[0]} = utf8_safe(${$_[0]}) if ${$_[0]}; } )->traverse($data); $data; } sub uniq (@) { my %seen = (); grep { not $seen{$_}++ } @_; } 1;
punitvara/ntppool
lib/NP/Util.pm
Perl
apache-2.0
1,418
#!/usr/bin/env perl $output=shift; $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; open OUT,"| \"$^X\" ${dir}../crypto/perlasm/x86_64-xlate.pl $output"; *STDOUT=*OUT; push(@INC,"${dir}."); require "uplink-common.pl"; $prefix="_lazy"; print <<___; .text .extern OPENSSL_Uplink .globl OPENSSL_UplinkTable ___ for ($i=1;$i<=$N;$i++) { print <<___; .type $prefix${i},\@abi-omnipotent .align 16 $prefix${i}: .byte 0x48,0x83,0xEC,0x28 # sub rsp,40 mov %rcx,48(%rsp) mov %rdx,56(%rsp) mov %r8,64(%rsp) mov %r9,72(%rsp) lea OPENSSL_UplinkTable(%rip),%rcx mov \$$i,%rdx call OPENSSL_Uplink mov 48(%rsp),%rcx mov 56(%rsp),%rdx mov 64(%rsp),%r8 mov 72(%rsp),%r9 lea OPENSSL_UplinkTable(%rip),%rax add \$40,%rsp jmp *8*$i(%rax) $prefix${i}_end: .size $prefix${i},.-$prefix${i} ___ } print <<___; .data OPENSSL_UplinkTable: .quad $N ___ for ($i=1;$i<=$N;$i++) { print " .quad $prefix$i\n"; } print <<___; .section .pdata,"r" .align 4 ___ for ($i=1;$i<=$N;$i++) { print <<___; .rva $prefix${i},$prefix${i}_end,${prefix}_unwind_info ___ } print <<___; .section .xdata,"r" .align 8 ${prefix}_unwind_info: .byte 0x01,0x04,0x01,0x00 .byte 0x04,0x42,0x00,0x00 ___ close STDOUT;
caidongyun/nginx-openresty-windows
nginx/objs/lib/openssl-1.0.1g/ms/uplink-x86_64.pl
Perl
bsd-2-clause
1,261
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 6.2.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 1B80 1BBF 1CC0 1CC7 END
Bjay1435/capstone
rootfs/usr/share/perl/5.18.2/unicore/lib/Sc/Sund.pl
Perl
mit
443
=pod =head1 NAME d2i_X509_CRL, i2d_X509_CRL, d2i_X509_CRL_bio, d2i_509_CRL_fp, i2d_X509_CRL_bio, i2d_X509_CRL_fp - PKCS#10 certificate request functions. =head1 SYNOPSIS #include <openssl/x509.h> X509_CRL *d2i_X509_CRL(X509_CRL **a, const unsigned char **pp, long length); int i2d_X509_CRL(X509_CRL *a, unsigned char **pp); X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **x); X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **x); int i2d_X509_CRL_bio(BIO *bp, X509_CRL *x); int i2d_X509_CRL_fp(FILE *fp, X509_CRL *x); =head1 DESCRIPTION These functions decode and encode an X509 CRL (certificate revocation list). Othewise the functions behave in a similar way to d2i_X509() and i2d_X509() described in the L<d2i_X509(3)|d2i_X509(3)> manual page. =head1 SEE ALSO L<d2i_X509(3)|d2i_X509(3)> =head1 HISTORY TBA =cut
caidongyun/nginx-openresty-windows
nginx/objs/lib/openssl-1.0.1g/doc/crypto/d2i_X509_CRL.pod
Perl
bsd-2-clause
869
#!/usr/bin/perl my $file = shift; sub usage { print <<EOH; usage: pullproto.pl <filename> filename The (header) file from which to pull the prototype STDIN should have a list of directives that define what prototypes to pull from <filename>. The lines should look like this: <line number>|<function name>|[class] where class is optional and need not be supplied if the function is not a member function of a class. EOH } if (!defined($file)) { usage(); exit(1); } if (! -r $file) { print STDERR "$file is not readable."; exit(1); } open INFILE, "<$file" or die "unable to open $file"; my @c = <INFILE>; close INFILE; # (Matt Spear) This is a strange regexp to check for matched <>, e.g. get<std::vector<unsigned> >(const std::string &s) const my $matched = qr/(?{local $d=0}) \< (?: \< (?{$d++}) | \> (?{$d--}) (?: (?{$d<0}) (?!)) | (?> [^\<\>]*) ) \> /x; while (<STDIN>) { chomp; my $linenum = ""; my $function = ""; my $class = ""; ($linenum, $function, $class) = split /\|/, $_; my @temp = @c; if ($temp[$linenum - 2] =~ m/$function/) { @temp = @temp[$linenum - 1..$#temp] } else { @temp = @temp[$linenum - 2..$#temp] } my $content = join "", @temp; my $fname = ""; my $pre = ""; my $post = ""; if ($function =~ m/^operator/) { $function =~ s/\s//g; } my ($justclass) = $class =~ m/^.*::(.*)$/; $justclass = $class if !defined($justclass) || $justclass eq ""; if ($function eq $justclass || $function eq "~$justclass") { ($fname, $post) = $content =~ m/(\Q$function\E$matched?)\s*(\([^\)]*\)[^;]*);/m; # (Matt Spear) added \Q\E and $matched } else { # Paolo Capriotti - Simplify function regexp and fix bug for pointer and reference return types my @a = $content =~ m/((const)?\s*(unsigned)?\s*\S+\s*[\*&]?)(\Q$function\E$matched?)\s*(\([^\)]*\)[^;]*);/m; # (Matt Spear) added \Q\E and $matched $pre = @a[0]; $fname = @a[3]; $post = @a[4]; } print "==\n"; if ($class ne "") { print "$pre$class" . "::" . "$fname$post"; } else { print "$pre$fname$post"; } print "\n"; }
sirbijan/vim-ide
bundle/vim-protodef/pullproto.pl
Perl
mit
2,242
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 6.1.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 0009 000D 0020 0085 00A0 1680 180E 2000 200A 2028 2029 202F 205F 3000 END
efortuna/AndroidSDKClone
ndk_experimental/prebuilt/linux-x86_64/lib/perl5/5.16.2/unicore/lib/Space/Y.pl
Perl
apache-2.0
509
#!/usr/bin/perl -w # # filename: scale_spring_rest_length.pl # author: Boyce Griffith # usage: scale_spring_rest_length.pl <input filename> <scale factor> <output filename> # # A simple Perl script to scale the spring rest lengths in an IBAMR # input file by a uniform, user-specified amount. if ($#ARGV != 2) { die "incorrect number of command line arguments.\nusage:\n scale_spring_rest_length.pl <input filename> <scale factor> <output filename>\n"; } # parse the command line arguments $input_filename = shift @ARGV; chomp $input_filename; $scale = shift @ARGV; chomp $scale; $output_filename = shift @ARGV; chomp $output_filename; print "input file: $input_filename\n"; print "scale factor: $scale\n"; print "output file: $output_filename\n"; # open the input and output files if ($input_filename eq $output_filename) { die "error: input and output files must be different\n"; } if (-e $output_filename) { print "warning: about to overwrite contents of $output_filename\n"; print "press [Enter] to continue..."; <STDIN>; } open(IN, "$input_filename") || die "error: cannot open $input_filename for reading: $!"; open(OUT, ">$output_filename") || die "error: cannot open $output_filename for writing: $!"; # the first line in the input file has the format: # # <number of edges> (comments) # # where items in ()'s are optional $_ = <IN>; chomp; @line = split; for ($i = 0; $i <= $#line; $i++) { $a = $line[$i]; if (($i == 0) && ($a =~ /^[+-]?\d+$/)) { printf OUT "%6d", $a; # integer } else { print OUT $a; } if ($i < $#line) { print OUT " "; } else { print OUT "\n"; } } # the remaining lines in the input file all have the format: # # <first node> <second node> <stiffness> <rest length> (force fcn index) (comments) # # where items in ()'s are optional while (<IN>) { chomp; @line = split; for ($i = 0; $i <= $#line; $i++) { $a = $line[$i]; if ($i == 3) { $a = $scale*$a; # rescale the rest length } if (($i == 0 || $i == 1 || $i == 4) && ($a =~ /^[+-]?\d+$/)) { printf OUT "%6d", $a; # integer } elsif ($i == 2 || $i == 3) { printf OUT "%1.16e", $a; # floating point value } else { print OUT $a; } if ($i < $#line) { print OUT " "; } else { print OUT "\n"; } } } # close the input and output files close(IN) || die "error: cannot close $input_filename: $!"; close(OUT) || die "error: cannot close $output_filename: $!";
MSV-Project/IBAMR
src/tools/scale_spring_rest_length.pl
Perl
bsd-3-clause
2,469
#!/usr/bin/env perl use strict; use warnings; while (<>) { if (/Welding: >(a\d+;\d+).*to >(a\d+;\d+)/) { my $from = $1; my $to = $2; print join("\t", sort($from, $to)) . "\n"; } elsif (/SCAFFOLD_ACCEPT:\s+(a\d+;\d+)\s+\d+\s+(a\d+;\d+)/) { my $from = $1; my $to = $2; print join("\t", sort($from, $to)) . "\n"; } } exit(0);
mr-c/trinityrnaseq
util/misc/get_welds_from_chrysals_graphFromFasta_out.pl
Perl
bsd-3-clause
391
#!/usr/bin/perl -w use strict; use File::Temp qw/tempdir/; my $usage = q{Usage: dis+xy-run.pl seed nsub langcluster lang featfile Prints out inputs, output, number of seconds }; my $seed = shift or die $usage; my $nsub = shift or die $usage; my $K = shift or die $usage; my $lang = shift or die $usage; my $featfile = shift or die $usage; my $ndim = 25; my $Z = 0.166; my $ntest = 1173766; my $sc_restart = 1; my $sc_niter = 1+int(100/$nsub); my $km_restart = 128; my $test = "$lang.words.gz"; my $gold = "$lang.pos.gz"; my $subf = "$lang.sub.gz"; my $tmp = tempdir("dis+omxyrun-XXXX", CLEANUP => 1); my $pairs = "$tmp/pairs.gz"; my $sc_out = "$tmp/scode.gz"; my $sc_err = "$tmp/scode"; my $km_out = "xyftoken$seed.out"; my $km_err = "$tmp/kmeans"; my $ev_err = "$tmp/eval"; my $input = "perl -le \'print \"$subf\" for 1..$nsub\' | xargs zcat | grep -v \'^</s>\'"; my $features = "add-features-3.pl -f $featfile"; my $wordsub = "wordsub -s $seed"; my $cmd0 = "$input | $wordsub | $features | gzip > $pairs"; my $scode = "zcat $pairs | scode -r $sc_restart -i $sc_niter -d $ndim -z $Z -s $seed -a 2> $sc_err | sed -n /^[01]:/p | gzip > $sc_out"; my $scode2kmeans = "x+y2kmeans.py -p $pairs"; my $kmeans = "wkmeans -k $K -r $km_restart -l -w -s $seed"; my $kmeans2eval = "x+y2eval.py -s $seed -n $nsub -p $pairs > $km_out"; my $score = "eval.pl -m -v -g $gold"; my $cmd1 = "$scode"; my $cmd2 = "zcat $sc_out | $scode2kmeans | $kmeans 2> $km_err | $kmeans2eval"; my $cmd3= "cat $km_out | $score 2> $ev_err"; my $tm = time; system($cmd0); system($cmd1); system($cmd2); system($cmd3); $tm = time - $tm; my @sc = split(' ', `cat $sc_err`); my @km = split(' ', `cat $km_err`); my @ev = split(' ', `cat $ev_err`); print join("\t", $seed, $nsub, @sc, @km, @ev, $tm)."\n";
ai-ku/upos
src/scripts/dis+omxy-run.pl
Perl
mit
1,773
package ActiveState::Table; our $VERSION = "1.00"; use strict; use Carp qw(carp); sub new { my $class = shift; bless { fields => [], rows => [], null => "NULL", }, $class; } sub fields { my $self = shift; @{$self->{fields}}; } sub rows { my $self = shift; @{$self->{rows}}; } sub fetchrow { my($self, $i) = @_; return $self->{rows}[$i] unless wantarray; my @row = @{$self->{rows}[$i] || []}; push(@row, (undef) x ($self->fields - @row)); @row; } sub fetchrow_arrayref { my($self, $i) = @_; return $self->{rows}[$i]; } sub fetchrow_hashref { my($self, $i) = @_; my $row = $self->{rows}[$i] || return undef; my %hash; my @fields = @{$self->{fields}}; $i = 0; $hash{shift @fields} = $row->[$i++] while @fields; return \%hash; } sub add_field { my $self = shift; for my $field (@_) { push(@{$self->{fields}}, $field) unless grep $_ eq $field, @{$self->{fields}}; } } sub add_row { my $self = shift; my $row = shift; $row = [$row, @_] unless ref($row); if (ref($row) eq "HASH") { my @row; for my $k (sort keys %$row) { my $i = 0; for my $h (@{$self->{fields}}) { last if $h eq $k; $i++; } $self->{fields}[$i] = $k; $row[$i] = $row->{$k}; } push(@{$self->{rows}}, \@row); } elsif (ref($row) eq "ARRAY") { die "NYI"; } else { die "Can't handle " . ref($row) . " rows"; } } sub add_sep { my($self, $idx) = @_; $idx = @{$self->{rows}} - 1 unless defined $idx; $self->{sep_f} ||= do { my $h = $self->{sep_idx} = {}; sub { my $row = shift; return $h->{$row}; }; }; $self->{sep_idx}{$idx}++; } sub sort { my $self = shift; my $comparator = shift; package main; # so that $a, $b is visible to the $comparator @{$self->{rows}} = sort $comparator @{$self->{rows}}; return; } sub as_csv { my($self, %opt) = @_; my $sep = delete $opt{field_separator}; my $eol = delete $opt{row_separator}; my $null = delete $opt{null}; my $show_header = delete $opt{show_header}; if (%opt && $^W) { carp("Unrecognized option '$_'") for keys %opt; } # defaults; $sep = "," unless defined $sep; $eol = "\n" unless defined $eol; $null = $self->{null} unless defined $null; $show_header = 1 unless defined $show_header; my $fields = $self->{fields}; my @lines; push(@lines, join($sep, @$fields)) if $show_header; for my $row (@{$self->{rows}}) { my @v = (@$row, ((undef) x (@$fields - @$row))); for (@v) { $_ = $null unless defined; if (length($sep) && (index($_, $sep) >= 0 || /"/)) { s/"/""/g; $_ = qq("$_"); } } push(@lines, join($sep, @v)); } return join($eol, @lines, ""); } sub as_box { my($self, %opt) = @_; my $null = delete $opt{null}; my $show_header = delete $opt{show_header}; my $show_trailer = delete $opt{show_trailer}; my $align = delete $opt{align}; my $box_chars = delete $opt{box_chars}; my $max_width = delete $opt{max_width}; if (%opt && $^W) { carp("Unrecognized option '$_'") for keys %opt; } # defaults; $null = $self->{null} unless defined $null; $show_header = 1 unless defined $show_header; $show_trailer = 1 unless defined $show_trailer; my $rows = $self->rows; my $sep_f = $self->{sep_f}; my @out; if (my @title = $self->fields) { @title = ("") x @title unless $show_header; my @w = map length, @title; my @align = map $align->{$_} || "left", @title; # find optimal width my $max = $rows - 1; my $i; for $i (0 .. $max) { my @field = $self->fetchrow($i); my $j = 0; for (@field) { $_ = $null unless defined; $w[$j] = length if $w[$j] < length; $j++; } } my $PAD = " "; my $PAD_DASH = "-" x length($PAD); if ($max_width) { my $width = @w * (length($PAD) * 2 + 1) + 1; $width += $_ for @w; my $too_much = $width - $max_width; if ($too_much > 0 && length($PAD) && $box_chars && $box_chars ne "ascii") { $too_much -= @w * length($PAD) * 2; $PAD = ""; $PAD_DASH = ""; } while ($too_much > 0) { # try to shrink the fields until we fit my $widest = @w - 1; for (my $j = $widest - 1; $j >= 0; $j--) { if ($w[$j] > $w[$widest]) { $widest = $j; } } die unless $w[$widest] > 1; $w[$widest]--; $too_much--; } } _stretch(\@title, \@w, undef, $box_chars); my $sep = "q$PAD_DASH" . join("${PAD_DASH}w$PAD_DASH", map { "-" x length } @title) . "${PAD_DASH}e\n"; my $I = _lines("|", $box_chars); push(@out, _lines($sep, $box_chars)); $sep =~ tr/qwe/asd/; if ($show_header) { push(@out, "$I$PAD", join("$PAD$I$PAD", @title), "$PAD$I\n"); push(@out, _lines($sep, $box_chars)) if $rows; } for $i (0 .. $max) { my @field = $self->fetchrow($i); for (@field) { $_ = $null unless defined } _stretch(\@field, \@w, \@align, $box_chars); push(@out, "$I$PAD", join("$PAD$I$PAD", @field), "$PAD$I\n"); if ($sep_f && $i < $max && $sep_f->($i)) { push(@out, _lines($sep, $box_chars)) } } $sep =~ tr/asd/zxc/; push(@out, _lines($sep, $box_chars)); } if ($show_trailer) { push(@out, " (1 row)\n") if $rows == 1; push(@out, " ($rows rows)\n") if $rows != 1; } return join("", @out) if defined wantarray; print @out; } sub _lines { my($box, $box_chars) = @_; if (!$box_chars || $box_chars eq "ascii") { $box =~ tr/qweasdzxc/+-+++++-+/; } elsif ($box_chars eq "dos") { $box =~ tr/qweasdzxc\-|/\xDA\xC2\xBF\xC3\xC5\xB4\xC0\xC1\xD9\xC4\xB3/; } elsif ($box_chars eq "unicode") { $box =~ tr/qweasdzxc\-|/\x{250C}\x{252C}\x{2510}\x{251C}\x{253C}\x{2524}\x{2514}\x{2534}\x{2518}\x{2500}\x{2502}/; } else { $box =~ tr/qweasdzxc\-|/$box_chars/; } $box; } sub _stretch { my($text, $w, $a, $box_chars) = @_; my $i = 0; for (@$text) { my $align = $a->[$i] || "left"; my $pad = ($w->[$i] - length); if ($pad > 0) { $pad = " " x $pad; if ($align eq "right") { substr($_, 0, 0) = $pad; } elsif ($align eq "center") { my $left_pad = substr($pad, 0, length($pad)/2, ""); $_ = $left_pad . $_ . $pad; } else { $_ .= $pad; } } elsif ($pad < 0) { $box_chars ||= "ascii"; if ($box_chars eq "dos") { substr($_, $w->[$i] - 1) = "\xAF"; } elsif ($box_chars eq "unicode") { substr($_, $w->[$i] - 1) = "\xBB"; } elsif ($w->[$i] > 10) { substr($_, $w->[$i] - 3) = "..."; } elsif ($w->[$i] >= 1) { substr($_, $w->[$i] - 1) = "+"; } else { $_ = ""; # ultimate shrinkage, should not happen } } $i++; } } 1; __END__ =head1 NAME ActiveState::Table - Simple table class =head1 SYNOPSIS $t = ActiveState::Table->new; $t->add_row({ a => 1, b => 2 }); print $t->as_csv; =head1 DESCRIPTION Instances of the C<ActiveState::Table> class represent a 2 dimensional table of fields (or columns if you wish) and rows. The fields are ordered and have case-sensitive names. The rows are numbered. The following methods are provided: =over =item $t = ActiveState::Table->new This creates a new empty table object. =item $t->fields This returns the current field names. In scalar context it returns the number of fields. =item $t->rows The returns the current rows. Each row is returned as reference to an array of values in the same order as the fields. The array might be shorter than the number of fields, when the trailing values are C<undef>. In scalar context it returns the number of rows in the table. =item $t->fetchrow( $index ) This returns the given row. An array reference is returned in scalar context. The array might be shorter than the number of fields, when the trailing values are C<undef>. In list context the values are returned one by one. There will be as many values as there are fields in the table. Some values might be C<undef>. If there is no row with the given $index, then C<undef> is returned in scalar context and the empty list in list context. =item $t->fetchrow_arrayref( $index ) Same as fetchrow() but will return an array reference even in list context. =item $t->fetchrow_hashref( $index ) This returns the given row. A hash reference is returned with keys corresponding to the field names and the values corresponding to the given row. The values might be C<undef>, but a key for all the fields will exist. If there is no row with the given $index, then C<undef> is returned. =item $t->add_field( $field ) This adds another field to the table. The field must be a string. If the field already exists it is not added again, and the add_field() call does nothing. There is no return value. =item $t->add_row( $row ) This adds another row to the table. The row must currently be a hash reference. If the hash contains new fields they are added automatically in sorted order. To enforce an order add the fields before adding rows. There is no return value. =item $t->add_sep =item $t->add_sep( $index ) This adds a separator to the table, shown as a horizonal line in the as_box() output. If $index is provided the separator will appear after the given row, otherwise the separator will appear after last row added. =item $t->sort( $comparator ) This will sort the rows of the table using the given $comparator function to compare elements. The $comparator is called as for perl's builtin sort function. References to the rows to compare is available in C<$::a> and C<$::b> in the form returned by C<< $t->fetchrow_arrayref >>. =item $t->as_box( %options ) This formats the table as text and returns it. The following options might be provided as key/value pairs: name | default ---------------------+---------- align | {} null | "NULL" show_header | 1 show_trailer | 1 box_chars | "ascii" max_width | undef ---------------------+---------- The C<align> option is a hash with field names as keys and the strings "left", "right" or "center" as values. Alignment for fields not found in this hash is "left". The C<box_chars> is either the name of a box drawing scheme or the 11 characters to use; starting with the upper left corner and going down one row at a time to the lower right corner, and finally the horizontal and vertical line character. The current named schemes are "dos" and "unicode". If C<max_width> is specified it limits how wide the box can get. The longest fields are truncated until the box is no wider than the given number of characters. Truncated fields are shown with trailing "..." or "+" marker. =item $t->as_csv( %options ) This formats the table as a CSV file ("comma-separated-values") and returns it. The following options might be provided as key/value pairs: name | default ---------------------+---------- field_separator | "," row_separator | "\n" null | "NULL" show_header | 1 ---------------------+---------- Fields that contains the C<field_separator> or the quote character will be quoted. =back =head1 BUGS none. =head1 SEE ALSO RFC 4180 and L<http://en.wikipedia.org/wiki/Comma-separated_values> =cut
amidoimidazol/bio_info
Beginning Perl for Bioinformatics/lib/ActiveState/Table.pm
Perl
mit
11,340
:- module(printDrs,[printDrs/1]). :- use_module(library(lists),[append/3,member/2]). /*======================================================================== Counter for discourse referents ========================================================================*/ :- dynamic counter/1. counter(0). /*======================================================================== Print Predicates ========================================================================*/ printDrs(Drs):- retract(counter(_)), assert(counter(1)), \+ \+ (formatDrs(Drs,Lines,_), printDrsLines(Lines)). /*======================================================================== Print DRS Lines ========================================================================*/ printDrsLines([]):- !. printDrsLines([Line|Rest]):- name(L,Line), % nl, write(L), write('%%% '), write(L), nl, printDrsLines(Rest). /*======================================================================== Format DRSs ========================================================================*/ formatDrs(drs(Dom,Cond),[[32|Top],Refs2,[124|Line]|CondLines2],Length):- !, formatConds(Cond,[]-CondLines1,0-CondLength), formatRefs(Dom,Refs), length([_,_|Refs],RefLength), (RefLength > CondLength, !, Length = RefLength ; Length = CondLength), closeConds(CondLines1,CondLines2,Length), Dif is (Length - RefLength) + 1, closeLine([124|Refs],Refs2,Dif,[124]), formatLine(95,Length,[32]-Top), formatLine(95,Length,[124]-Line). formatDrs(merge(Drs1,Drs2),Lines3,Length):- !, formatDrs(Drs1,Lines1,N1), formatDrs(Drs2,Lines2,N2), M1 is N1 + 3, M2 is N2 + 3, combLinesDrs(Lines1,Lines2,Lines3,';',M1,M2), Length is N1 + N2 + 4. formatDrs(smerge(Drs1,Drs2),Lines3,Length):- !, formatDrs(Drs1,Lines1,N1), formatDrs(Drs2,Lines2,N2), M1 is N1 + 3, M2 is N2 + 3, combLinesDrs(Lines1,Lines2,Lines3,'+',M1,M2), Length is N1 + N2 + 4. formatDrs(alfa(_,Drs1,Drs2),Lines3,Length):- !, formatDrs(Drs1,Lines1,N1), formatDrs(Drs2,Lines2,N2), M1 is N1 + 3, M2 is N2 + 3, combLinesDrs(Lines1,Lines2,Lines3,'A',M1,M2), Length is N1 + N2 + 4. /*======================================================================== Format Discourse Referents ========================================================================*/ formatRefs([],[]):- !. formatRefs([_:Ref|Rest],Out):- makeConstant(Ref,Code), append([32|Code],Temp,Out), formatRefs(Rest,Temp). /*======================================================================== Turn a discourse referent into a Prolog constant ========================================================================*/ makeConstant(X,Code):- atomic(X), !, name(X,Code). makeConstant(X,[120|Codes]):- nonvar(X), X =.. ['$VAR',Number], atomic(Number), !, name(Number,Codes). makeConstant(X,[C|Odes]):- nonvar(X), X =.. ['$VAR',[C|Odes]], !. makeConstant(X,[120|Number]):- var(X), retract(counter(N)), name(N,Number), name(X,[120|Number]), M is N+1, assert(counter(M)). /*======================================================================== Format a Line ========================================================================*/ formatLine(_,1,L-L):- !. formatLine(Code,N,In-[Code|Out]):- M is N - 1, formatLine(Code,M,In-Out). /*======================================================================== Formatting Conditions ========================================================================*/ formatConds([],L-L,N-N):- !. formatConds([_:X|Rest],L1-L2,N1-N2):- !, formatConds([X|Rest],L1-L2,N1-N2). formatConds([imp(Drs1,Drs2)|Rest],L1-L2,N0-N4):- !, formatConds(Rest,L1-Lines,N0-N3), formatDrs(Drs1,Lines1,N1), formatDrs(Drs2,Lines2,N2), M is N1 + 7, combLinesConds(Lines1,Lines2,Lines3,' ==> ',M), append(Lines3,Lines,L2), Length is N1 + N2 + 10, (Length > N3, !, N4 = Length; N4 = N3). formatConds([or(Drs1,Drs2)|Rest],L1-L2,N0-N4):- !, formatConds(Rest,L1-Lines,N0-N3), formatDrs(Drs1,Lines1,N1), formatDrs(Drs2,Lines2,N2), M is N1 + 5, combLinesConds(Lines1,Lines2,Lines3,' V ',M), append(Lines3,Lines,L2), Length is N1 + N2 + 8, (Length > N3, !, N4 = Length; N4 = N3). formatConds([whq(_,Drs1,_,Drs2)|Rest],L1-L2,N0-N4):- !, formatConds([whq(Drs1,Drs2)|Rest],L1-L2,N0-N4). formatConds([whq(Drs1,Drs2)|Rest],L1-L2,N0-N4):- !, formatConds(Rest,L1-Lines,N0-N3), formatDrs(Drs1,Lines1,N1), formatDrs(Drs2,Lines2,N2), M is N1 + 5, combLinesConds(Lines1,Lines2,Lines3,' ? ',M), append(Lines3,Lines,L2), Length is N1 + N2 + 8, (Length > N3, !, N4 = Length; N4 = N3). formatConds([not(Drs)|Rest],L1-L2,N0-N3):- !, formatConds(Rest,L1-Lines,N0-N1), formatDrs(Drs,[A,B,C,D|Lines1],N2), combLinesConds2([],Lines1,Lines2,5,''), append([[124,32,32,32,32,32|A], [124,32,32,32,32,32|B], [124,32,95,95,32,32|C], [124,32,32,32,124,32|D]|Lines2],Lines,L2), Length is N2 + 8, (Length > N1, !, N3 = Length; N3 = N1). formatConds([prop(Arg,Drs)|Rest],L1-L2,N0-N3):- !, formatConds(Rest,L1-Lines,N0-N1), makeConstant(Arg,A1), addSpaces(A1,[K1,K2,K3,K4,K5]), formatDrs(Drs,[A,B,C,D|Lines1],N2), combLinesConds2([],Lines1,Lines2,6,''), append([[124,32,32,32,32,32,32|A], [124,32,32,32,32,32,32|B], [124,K1,K2,K3,K4,K5,58|C], [124,32,32,32,32,32,32|D]|Lines2],Lines,L2), Length is N2 + 9, ( Length > N1, !, N3 = Length; N3 = N1). formatConds([eq(A,B)|Rest],In-[[124,32|Line]|Out],N0-N2):- !, formatConds(Rest,In-Out,N0-N1), makeConstant(A,L1), makeConstant(B,L2), append(L1,[32,61,32|L2],Line), length([_,_,_|Line],Length), (Length > N1, !, N2 is Length; N2 = N1). formatConds([Basic|Rest],In-[[124,32|Line]|Out],N0-N2):- member(Basic,[pred(_,_,_,_),rel(_,_,_,_)]), !, formatConds(Rest,In-Out,N0-N1), formatBasic(Basic,Line), length([_,_,_|Line],Length), (Length > N1, !, N2 is Length; N2 = N1). formatConds([Basic|Rest],In-[[124,32|Line]|Out],N0-N2):- Basic = named(Arg,Sym,Type,Sense), !, formatConds(Rest,In-Out,N0-N1), formatBasic(named(Arg,Sym,Type,Sense),Line), length([_,_,_|Line],Length), (Length > N1, !, N2 is Length; N2 = N1). formatConds([Basic|Rest],In-[[124,32|Line]|Out],N0-N2):- Basic = card(Arg,Digit,Type), !, formatConds(Rest,In-Out,N0-N1), makeConstant(Arg,A), makeConstant(Digit,D), ( Type = eq, !, TypeCode1 = 61, TypeCode2 = 61 ; %%% == Type = ge, !, TypeCode1 = 62, TypeCode2 = 61 ; %%% >= Type = le, !, TypeCode1 = 61, TypeCode2 = 60 ), %%% =< append([124|A],[124,32,TypeCode1,TypeCode2,32|D],Line), length([_,_,_|Line],Length), (Length > N1, !, N2 is Length; N2 = N1). formatConds([Basic|Rest],In-[[124,32|Line]|Out],N0-N2):- Basic = timex(Arg,Timex), !, formatConds(Rest,In-Out,N0-N1), name('timex',F), makeConstant(Arg,A), timex(Timex,D), append(F,[40|A],T), append(T,[41,61|D],Line), length([_,_,_|Line],Length), (Length > N1, !, N2 is Length; N2 = N1). /*======================================================================== Formatting Basic Conditions ========================================================================*/ formatBasic(Basic,Line):- Basic = pred(Arg,Functor,_,_), !, name(Functor,F), makeConstant(Arg,A), append(F,[40|A],T), append(T,[41],Line). formatBasic(Basic,Line):- Basic = rel(Arg1,Arg2,higher,1), !, makeConstant(Arg1,A1), makeConstant(Arg2,A2), append(A1,[32,62,32|A2],Line). formatBasic(Basic,Line):- Basic = rel(Arg1,Arg2,Functor,_), !, name(Functor,F), makeConstant(Arg1,A1), makeConstant(Arg2,A2), append(F,[40|A1],T1), append(T1,[44|A2],T2), append(T2,[41],Line). formatBasic(Basic,Line):- Basic = named(Arg,Sym,Type,_), !, name(named,F), makeConstant(Arg,A), makeConstant(Sym,S), makeConstant(Type,T), append(F,[40|A],T1), append(T1,[44|S],T2), append(T2,[44|T],T3), append(T3,[41],Line). /*======================================================================== Combining Lines of Characters (Complex DRS-Conditions) ========================================================================*/ combLinesConds([A1,B1,C1,D1|Rest1],[A2,B2,C2,D2|Rest2],Result,Op,N):- combLinesConds2([A1,B1,C1],[A2,B2,C2],Firsts,N,Op), name(Op,Code), append(Code,D2,T), append([124,32|D1],T,D), combLinesConds2(Rest1,Rest2,Rest,N,Op), append(Firsts,[D|Rest],Result). /*======================================================================== Combining Lines of Characters (Complex DRS-Conditions) ========================================================================*/ combLinesConds2([],[],[],_,_):- !. combLinesConds2([],[A2|Rest2],[A|Rest],N,Op):- !, closeLine([124],A1,N,[]), append(A1,A2,A), combLinesConds2([],Rest2,Rest,N,Op). combLinesConds2([A1|Rest1],[],[[124,32|A1]|Rest],N,Op):- !, combLinesConds2(Rest1,[],Rest,N,Op). combLinesConds2([A1|Rest1],[A2|Rest2],[A|Rest],N,' ==> '):- !, append([124,32|A1],[32,32,32,32,32|A2],A), combLinesConds2(Rest1,Rest2,Rest,N,' ==> '). combLinesConds2([A1|Rest1],[A2|Rest2],[A|Rest],N,' V '):- !, append([124,32|A1],[32,32,32|A2],A), combLinesConds2(Rest1,Rest2,Rest,N,' V '). combLinesConds2([A1|Rest1],[A2|Rest2],[A|Rest],N,' ? '):- !, append([124,32|A1],[32,32,32|A2],A), combLinesConds2(Rest1,Rest2,Rest,N,' ? '). /*======================================================================== Combining Lines of Characters (Complex DRSs) ========================================================================*/ combLinesDrs([A1,B1,C1,D1|Rest1],[A2,B2,C2,D2|Rest2],Result,Op,N1,N2):- combLinesDrs([A1,B1,C1],[A2,B2,C2],Firsts,N1,N2), name(Op,Code), append(Code,D2,T1), append(T1,[41],T2), append([40|D1],T2,D), combLinesDrs(Rest1,Rest2,Rest,N1,N2), append(Firsts,[D|Rest],Result). combLinesDrs([],[],[],_,_):- !. combLinesDrs([],[A2|Rest2],[A3|Rest],N1,N2):- !, closeLine([],A1,N1,[]), append(A1,A2,A0), append(A0,[32],A3), combLinesDrs([],Rest2,Rest,N1,N2). combLinesDrs([A1|Rest1],[],[Closed|Rest],N1,N2):- !, combLinesDrs(Rest1,[],Rest,N1,N2), closeLine([32|A1],Closed,N2,[]). combLinesDrs([A1|Rest1],[A2|Rest2],[A3|Rest],N1,N2):- !, append([32|A1],[32|A2],A0), append(A0,[32],A3), combLinesDrs(Rest1,Rest2,Rest,N1,N2). /*======================================================================== Close Conditions (add '|') ========================================================================*/ closeConds([],[[124|Bottom]],Length):- !, formatLine(95,Length,[124]-Bottom). closeConds([Line|Rest1],[New|Rest2],Length):- length(Line,L), R is Length - L, closeLine(Line,New,R,[124]), closeConds(Rest1,Rest2,Length). /*======================================================================== Close Line ========================================================================*/ closeLine(Line,New,N,Accu):- N < 1, !, append(Line,Accu,New). closeLine(Line,New,N,Accu):- M is N - 1, !, closeLine(Line,New,M,[32|Accu]). /*======================================================================== Add Space ========================================================================*/ addSpaces([A,B],[32,32,32,A,B]):- !. addSpaces([A,B,C],[32,32,A,B,C]):- !. addSpaces([A,B,C,D],[32,A,B,C,D]):- !. addSpaces([A,B,C,D,E],[A,B,C,D,E]):- !. /*======================================================================== Time Expressions ========================================================================*/ timex(date(_:Y,_:M,_:D),Timex):- !, timex(date(Y,M,D),Timex). timex(date(_:_,_:Y,_:M,_:D),Timex):- !, timex(date(Y,M,D),Timex). timex(time(_:Y,_:M,_:D),Timex):- !, timex(time(Y,M,D),Timex). timex(date(Y,M,D),Timex):- year(Y,[Y1,Y2,Y3,Y4]), month(M,[M1,M2]), day(D,[D1,D2]), Timex = [Y1,Y2,Y3,Y4,M1,M2,D1,D2]. timex(time(H,M,S),Timex):- day(H,[H1,H2]), day(M,[M1,M2]), day(S,[S1,S2]), Timex = [H1,H2,58,M1,M2,58,S1,S2]. year(Y,C):- var(Y), !, name('XXXX',C). year(Y,C):- name(Y,C). month(Y,C):- var(Y), !, name('XX',C). month(Y,C):- name(Y,C). day(Y,C):- var(Y), !, name('XX',C). day(Y,C):- name(Y,C).
Shuailong/CCGSupertagging
ext/candc/src/prolog/boxer/printDrs.pl
Perl
mit
12,496
#!/usr/bin/perl use 5.18.2; use strict; use warnings; my @out=(5,2,8,9,4,2,7,9,4,1,6,9,0); print "Before sort:\n"; print join(', ',@out); my @work; my $sh =0; my$N=@out+0; if($N>1){ while($sh+2!=$N){ $b=undef; for my$i(0..$N-1){ if($i*2+2+$sh<$N){ if($out[$i+$sh]gt$out[$i*2+1+$sh] || $out[$i+$sh]gt$out[$i*2+2+$sh]){ if($out[$i*2+1+$sh]lt$out[$i*2+2+$sh]){ ($out[$i*2+1+$sh],$out[$i+$sh])=($out[$i+$sh],$out[$i*2+1+$sh]); $b=1; }elsif($out[$i*2+2+$sh]lt$out[$i*2+1+$sh]){ ($out[$i*2+2+$sh],$out[$i+$sh])=($out[$i+$sh],$out[$i*2+2+$sh]); $b=1; } }elsif($out[$i*2+2+$sh]lt$out[$i*2+1+$sh]){ ($out[$i*2+1+$sh],$out[$i*2+2+$sh])=($out[$i*2+2+$sh],$out[$i*2+1+$sh]); $b=1; } }elsif($i*2+1+$sh<$N && $out[$i+$sh]gt$out[$i*2+1+$sh]){ ($out[$i+$sh],$out[$i*2+1+$sh])=($out[$i*2+1+$sh],$out[$i+$sh]); $b=1; } } ++$sh if!$b; last if$sh+2==$N; } } print "\nPiramidal sort:\n"; print join(', ',@out); @out=(5,2,8,9,4,2,7,9,4,1,6,9,0); sub sortM{ my($array,$first,$last)=@_; if($last>$first){ my$middle=int(($last+$first)/2); sortM($array,$first,$middle); sortM($array,$middle+1,$last); my$j=0; $work[$j++]=$$array[$_]for($first..$last); $middle=int(($first+$last)/2)if($middle>$last); my$n=$middle-$first+1; for(my $i=$first,$j=0,my $k=$n;$i<=$last;$i++){ if(($j<$n)&&(($k==(($last-$first)+1))||($work[$j]lt$work[$k]))){ $$array[$i]=$work[$j++] }else{ $$array[$i]=$work[$k++]; } } } } sortM(\@out,0,$#out); print "\nMerge sort:\n"; print join(', ',@out); @out=(5,2,8,9,4,2,7,9,4,1,6,9,0); sub sortQ{ my($s, $e) = @_; my $m = $s - 1; for($s..$e - 1){ if($out[$_] lt $out[$e]){ ++$m; ($out[$m], $out[$_]) = ($out[$_], $out[$m]); } } ++$m; ($out[$m], $out[$e]) = ($out[$e], $out[$m]); sortQ($s, $m-1) if $s < $m-1; sortQ($m+1, $e) if $m+1 < $e; } sortQ(0, $#out); print "\nQuick sort:\n"; print join(', ',@out); print "\n";
dimir2/hse12pi2-scripts
GalochkinA/perl/2sort.pl
Perl
mit
1,985
#!/usr/bin/perl use strict; use warnings; use List::Util qw/ sum /; use Math::Prime::Util qw/divisors/; use Memoize; memoize('elf_present_count'); my $TARGET = 29000000; my $house = 1; my $present_count = 0; while (1) { $present_count = present_count($house); last if $present_count >= $TARGET; $house++; } print 'House ', $house, ' got ', $present_count, " presents.\n"; sub present_count { my $house_number = shift; my @divisors = divisors($house_number); # print join(', ', @divisors), "\n"; @divisors = map { elf_present_count($_) } @divisors; # print join(', ', @divisors), "\n"; return sum @divisors; } sub elf_present_count { my $elf = shift; return $elf * 10; }
KenMGJ/advent-of-code
2015/20/day20-1.pl
Perl
mit
725
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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. # package storage::hp::p2000::xmlapi::mode::components::enclosure; use strict; use warnings; my %health = ( 0 => 'ok', 1 => 'degraded', 2 => 'failed', 3 => 'unknown', 4 => 'not available', ); sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking enclosures"); $self->{components}->{enclosure} = {name => 'enclosures', total => 0, skip => 0}; return if ($self->check_filter(section => 'enclosure')); my ($results) = $self->{custom}->get_infos( cmd => 'show enclosures', base_type => 'enclosures', key => 'durable-id', properties_name => '^health-numeric|health-reason$', no_quit => 1 ); foreach my $enc_id (keys %$results) { next if ($self->check_filter(section => 'enclosure', instance => $enc_id)); $self->{components}->{enclosure}->{total}++; my $state = $health{$results->{$enc_id}->{'health-numeric'}}; $self->{output}->output_add( long_msg => sprintf( "enclosure '%s' status is %s [instance: %s] [reason: %s]", $enc_id, $state, $enc_id, $results->{$enc_id}->{'health-reason'} ) ); my $exit = $self->get_severity(label => 'default', section => 'enclosure', value => $state); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add( severity => $exit, short_msg => sprintf("Enclosure '%s' status is '%s'", $enc_id, $state) ); } } } 1;
centreon/centreon-plugins
storage/hp/p2000/xmlapi/mode/components/enclosure.pm
Perl
apache-2.0
2,357
#!/usr/bin/perl -w # Copyright 2012 Robert Theis # # 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. use IntronPoly; use lib '..'; use strict; use Getopt::Long; use IO::File; # # Bins the half-mapping reads in a SAM file by position in the reference genome. # my $usage_msg = "Bins distribution of half-mapping alignments by position specified in a SAM file.\n" . "Usage: find_distrib.pl -i sam_file [-b bin_size (default: 100)] [--bowtie1]\n"; die $usage_msg unless ( @ARGV ); my ( $aligned, $input_file, $bowtie1 ); my $bin_size = 100; GetOptions( "b:i" => \$bin_size, "i=s" => \$input_file, # SAM input file "bowtie1" => \$bowtie1 # Expect Bowtie 1 flags for unpaired reads ) || die "$0: Bad option"; die $usage_msg unless ( defined $input_file ); $input_file =~ s/^~/$ENV{HOME}/; my $ifh = IO::File->new( $input_file, 'r' ) or die "Can't open $input_file: $!"; my %fragments = (); if ($bowtie1) { # Bowtie 1 # Use unpaired read flags from Bowtie 1 output # For a half-mapping pair, one of the two mates will have 4 as its flag, # and the other mate will have 0 or 16 as its flag while ( my $line1 = $ifh->getline ) { next if $line1 =~ m/^@/; my @fields = split(/\t/, $line1); my ($flags1, $chr1, $pos1) = (int($fields[1]), $fields[2], $fields[3]); # Get the second alignment in the pair my $line2 = $ifh->getline; @fields = split( /\t/, $line2 ); my ($flags2, $chr2, $pos2) = (int($fields[1]), $fields[2], $fields[3]); if (($flags1 == 4) ^ ($flags2 == 4)) { my $pos; if ($pos1 != 0) { $pos = $pos1; } else { $pos = $pos2; } # Round to nearest bin my $frag = int( ($pos + ($bin_size / 2)) / $bin_size ); $fragments{$frag}++; } } } else { # Bowtie 2 while ( my $line1 = $ifh->getline ) { next if $line1 =~ m/^@/; my @fields = split(/\t/, $line1); my ($flags1, $chr1) = ($fields[1], $fields[2]); next if (IntronPoly::_isInMappingPair($flags1) != 0); next if (IntronPoly::_isSecondaryAlignment($flags1) != 0); # Get the second alignment in the pair my $line2 = $ifh->getline; @fields = split( /\t/, $line2 ); my ($flags2, $chr2, $pos) = (int($fields[1]), $fields[2], $fields[7]); next if $chr1 ne $chr2; next if (IntronPoly::_isSecondaryAlignment($flags2) != 0); next if (IntronPoly::_isFarMappingPair($flags1, $flags2) != 0); if (IntronPoly::_isHalfMappingMate($flags2) != 0) { # Round to nearest bin my $frag = int( ($pos + ($bin_size / 2)) / $bin_size ); $fragments{$frag}++; } } } $ifh->close; # Print sorted bins and frequencies for my $key (sort {$a <=> $b} keys %fragments) { my $bin = $key * $bin_size; print "$bin, $fragments{$key}\n"; } exit;
rmtheis/intron-polymorphism
find_distrib.pl
Perl
apache-2.0
3,287
#!/usr/bin/env perl # Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # # 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. package Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveDownloadUniProtFiles; use strict; use warnings; use feature 'say'; use Bio::EnsEMBL::Utils::Exception qw(warning throw); use parent ('Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveBaseRunnableDB'); sub fetch_input { my $self = shift; return 1; } sub run { my $self = shift; # This is a bit lazy, originally this was designed to work with a single query # but now I also want it to work with multiple files. I'm going to put that into # the if and the else will retain the original single file logic if($self->param('multi_query_download')) { $self->multi_query_download(); } else { my $query_url = $self->build_query(); say "Downloading:\n".$query_url."\n"; my $query_exit_code; $query_exit_code = system($query_url); unless($query_exit_code == 0) { throw("The wget query ended in an non-zero exit code:\n".$query_exit_code); } if($query_url =~ /\.gz$/) { my $file_path = $self->param('dest_dir')."/".$self->param('file_name'); my $gunzip_command = "gunzip ".$file_path; my $gunzip_exit_code; $gunzip_exit_code = system($gunzip_command); unless($gunzip_exit_code == 0) { throw("gunzip on file ended in an non-zero exit code:\n".$gunzip_exit_code); } } } say "Finished downloading UniProt files"; return 1; } sub write_output { my $self = shift; if($self->param('multi_query_download')) { my $file_hash = $self->output_hash; my $output_hash = {}; $output_hash->{'iid'} = $file_hash; $self->dataflow_output_id($output_hash,1); } else { my $file_path = $self->param('dest_dir')."/".$self->param('file_name'); my $output_hash = {}; $output_hash->{'iid'} = $file_path; $self->dataflow_output_id($output_hash,1); } return 1; } sub output_hash { my ($self,$val) = @_; if($val) { $self->param('_output_hash',$val); } return($self->param('_output_hash')); } sub multi_query_download { my ($self) = @_; my $output_hash = {}; my $multi_query_hash = $self->param('multi_query_download'); unless(ref($multi_query_hash) eq 'HASH') { $self->throw("You're trying to download multiple queries, but haven't passed in a hash ref. You ". "need to pass in hash of hashes, where each internal hash has the relevant query params"); } foreach my $query_key (keys(%$multi_query_hash)) { say "Building query based on params for: ".$query_key; my $query_params = $multi_query_hash->{$query_key}; my $query_url = $self->build_query($query_params); say "Downloading:\n".$query_url."\n"; my $query_exit_code; $query_exit_code = system($query_url); unless($query_exit_code == 0) { throw("The wget query ended in an non-zero exit code:\n".$query_exit_code); } my $file_path = $query_params->{'dest_dir'}."/".$query_params->{'file_name'}; if($query_url =~ /\.gz$/) { my $gunzip_command = "gunzip ".$file_path.".gz"; my $gunzip_exit_code; $gunzip_exit_code = system($gunzip_command); unless($gunzip_exit_code == 0) { $self->throw("gunzip on file ended in an non-zero exit code:\n".$gunzip_exit_code); } } $output_hash->{$query_key} = $file_path; } $self->output_hash($output_hash); } sub build_query { my ($self,$query_params) = @_; my $taxon_id = $query_params->{'taxon_id'}; my $taxon_group = $query_params->{'taxon_group'}; my $exclude_id = $query_params->{'exclude_id'}; my $exclude_group = $query_params->{'exclude_group'}; my $dest_dir = $query_params->{'dest_dir'}; my $file_name = $query_params->{'file_name'}; my $pe_level = $query_params->{'pe_level'}; my $pe_string = "("; my $taxonomy_string = ""; my $exclude_string = ""; my $compress = "yes"; my $fragment_string = "+AND+fragment:no"; my $mito = "+NOT+organelle%3Amitochondrion"; my $format = "fasta"; if(exists($query_params->{'compress'})) { if($query_params->{'compress'} eq '0') { $compress = "no"; } } if(exists($query_params->{'mito'})) { if($query_params->{'mito'}) { $mito = undef; } } if(exists($query_params->{'fragment'})) { if($query_params->{'fragment'}) { $fragment_string = undef; } } if(exists($query_params->{'format'})) { $format = $query_params->{'format'}; } # http://www.uniprot.org/uniprot/?query=existence%3A%22evidence+at+protein+level%22+OR+existence%3A%22evidence+at+transcript+level%22+AND+taxonomy%3A%22Mammalia+%5B40674%5D%22+NOT+taxonomy%3A%22Primates+%5B9443%5D%22&sort=score my $full_query = "wget -q -O - \"http://www.uniprot.org/uniprot/?query="; my %pe_code = ( '1' => 'evidence+at+protein+level', '2' => 'evidence+at+transcript+level', '3' => 'inferred+from+homology', '4' => 'predicted', '5' => 'uncertain', ); # Must have file_name, pe_level, dest_dir and either taxon_id or taxonomy unless($file_name && $dest_dir && ($taxon_id || $taxon_group) && $pe_level) { $self->throw("Must define the following keys:\nfile_name\ntaxon_id or taxonomy\ndest_dir\npe_level"); } my @pe_array = @{$pe_level}; unless(scalar(@pe_array)) { die "Not PE levels found in value of pe_levels key. Format should be an array ref: ['1,2']"; } foreach my $pe_level (@pe_array) { unless($pe_level =~ /\d+/) { die "Could not parse a PE level from the following: ".$pe_level; } my $parsed_pe_level = $&; unless($parsed_pe_level >= 1 && $parsed_pe_level <= 5) { die "Parsed PE level is outside the normal range of 1-5: ".$parsed_pe_level; } $pe_string .= 'existence%3A%22'.$pe_code{$pe_level}.'%22+OR+'; } $pe_string =~ s/\+OR\+$/\)/; # NOTE this bit of the code with taxonomy and exclude is shit and needs to be upgraded if($taxon_id) { $taxonomy_string = '+AND+taxonomy%3A+'.$taxon_id; } elsif($taxon_group) { $taxonomy_string = '+AND+taxonomy%3A'.$taxon_group; } #+NOT+taxonomy%3A%22 if($exclude_id) { $exclude_string = '+NOT+taxonomy%3A+'.$exclude_id; } elsif($exclude_group) { $exclude_string = '+NOT+taxonomy%3A'.$exclude_group; } $full_query .= $pe_string.$taxonomy_string.$exclude_string.$fragment_string.$mito."&compress=".$compress."&format=".$format. "\" > ".$dest_dir."/".$file_name; if($compress eq 'yes') { $full_query .= ".gz"; } unless(-e $dest_dir) { `mkdir -p $dest_dir`; } return($full_query); } 1;
mn1/ensembl-analysis
modules/Bio/EnsEMBL/Analysis/Hive/RunnableDB/HiveDownloadUniProtFiles.pm
Perl
apache-2.0
7,248
# # Copyright 2021 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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. # package storage::hp::p2000::xmlapi::mode::listvolumes; use base qw(centreon::plugins::mode); use strict; use warnings; sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { 'name:s' => { name => 'name' }, 'regexp' => { name => 'use_regexp' }, 'filter-type:s' => { name => 'filter_type' }, }); $self->{volume_name_selected} = []; return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } sub manage_selection { my ($self, %options) = @_; ($self->{results}) = $self->{p2000}->get_infos( cmd => 'show volumes', base_type => 'volumes', key => 'volume-name', properties_name => '^volume-type$' ); foreach my $name (keys %{$self->{results}}) { my $volume_type = $self->{results}->{$name}->{'volume-type'}; if (defined($self->{option_results}->{filter_type}) && $volume_type !~ /$self->{option_results}->{filter_type}/) { $self->{output}->output_add(long_msg => "Skipping volume '" . $name . "': no matching filter type"); next; } # Get all without a name if (!defined($self->{option_results}->{name})) { push @{$self->{volume_name_selected}}, $name; next; } if (!defined($self->{option_results}->{use_regexp}) && $name eq $self->{option_results}->{name}) { push @{$self->{volume_name_selected}}, $name; next; } if (defined($self->{option_results}->{use_regexp}) && $name =~ /$self->{option_results}->{name}/) { push @{$self->{volume_name_selected}}, $name; next; } $self->{output}->output_add(long_msg => "Skipping volume '" . $name . "': no matching filter name"); } } sub run { my ($self, %options) = @_; $self->{p2000} = $options{custom}; $self->{p2000}->login(); $self->manage_selection(); foreach my $name (sort @{$self->{volume_name_selected}}) { $self->{output}->output_add(long_msg => "'" . $name . "' [type = " . $self->{results}->{$name}->{'volume-type'} . "]"); } $self->{output}->output_add(severity => 'OK', short_msg => 'List volumes:'); $self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1); $self->{output}->exit(); } sub disco_format { my ($self, %options) = @_; $self->{output}->add_disco_format(elements => ['name', 'type']); } sub disco_show { my ($self, %options) = @_; $self->{p2000} = $options{custom}; $self->{p2000}->login(); $self->manage_selection(); foreach my $name (sort @{$self->{volume_name_selected}}) { $self->{output}->add_disco_entry(name => $name, type => $self->{results}->{$name}->{'volume-type'}); } } 1; __END__ =head1 MODE List volumes. =over 8 =item B<--name> Set the volume name. =item B<--regexp> Allows to use regexp to filter volume name (with option --name). =item B<--filter-type> Filter volume type. Regexp can be used. Available types are: - 'standard', - 'standard*', - 'snap-pool', - 'master volume', - 'snapshot', - 'replication source' =back =cut
Tpo76/centreon-plugins
storage/hp/p2000/xmlapi/mode/listvolumes.pm
Perl
apache-2.0
4,182
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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. # package centreon::common::cisco::standard::snmp::mode::listaaaservers; use base qw(centreon::plugins::mode); use strict; use warnings; sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } my $map_protocol = { 1 => 'tacacsplus', 2 => 'radius', 3 => 'ldap', 4 => 'kerberos', 5 => 'ntlm', 6 => 'sdi', 7 => 'other' }; my $mapping = { address => { oid => '.1.3.6.1.4.1.9.10.56.1.1.2.1.3' }, # casAddress authen_port => { oid => '.1.3.6.1.4.1.9.10.56.1.1.2.1.4' }, # casAuthenPort acc_port => { oid => '.1.3.6.1.4.1.9.10.56.1.1.2.1.5' } # casAcctPort }; my $oid_casConfigEntry = '.1.3.6.1.4.1.9.10.56.1.1.2.1'; sub manage_selection { my ($self, %options) = @_; my $snmp_result = $options{snmp}->get_table( oid => $oid_casConfigEntry, start => $mapping->{address}->{oid}, end => $mapping->{acc_port}->{oid}, nothing_quit => 1 ); my $results = {}; foreach (keys %$snmp_result) { next if (! /^$mapping->{address}->{oid}\.((\d+).*)$/); my ($instance, $protocol) = ($1, $map_protocol->{$2}); $results->{$instance} = $options{snmp}->map_instance(mapping => $mapping, results => $snmp_result, instance => $instance); $results->{$instance}->{protocol} = $protocol; } return $results; } sub run { my ($self, %options) = @_; my $results = $self->manage_selection(snmp => $options{snmp}); foreach my $name (sort keys %$results) { $self->{output}->output_add(long_msg => join('', map("[$_ = " . $results->{$name}->{$_} . ']', keys(%$mapping))) . '[protocol = ' . $results->{$name}->{protocol} . ']' ); } $self->{output}->output_add( severity => 'OK', short_msg => 'List AAA servers:' ); $self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1); $self->{output}->exit(); } sub disco_format { my ($self, %options) = @_; $self->{output}->add_disco_format(elements => ['protocol', keys %$mapping]); } sub disco_show { my ($self, %options) = @_; my $results = $self->manage_selection(snmp => $options{snmp}); foreach (sort keys %$results) { $self->{output}->add_disco_entry( %{$results->{$_}} ); } } 1; __END__ =head1 MODE List AAA servers. =over 8 =back =cut
centreon/centreon-plugins
centreon/common/cisco/standard/snmp/mode/listaaaservers.pm
Perl
apache-2.0
3,371
:- dynamic(entry/5). entry(0, "Bar1", 0, 2.5, 1472587304.0). entry(1, "Bar2", 0, 2.5, 1472587304.0). entry(2, "Bar3", 0, 2.5, 1472587304.0).
JustAnotherSoul/01
data/entries_bak.pl
Perl
apache-2.0
142
# Copyright 2020, Google LLC # # 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. package Google::Ads::GoogleAds::V10::Common::ExplorerAutoOptimizerSetting; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = {optIn => $args->{optIn}}; # Delete the unassigned fields in this object for a more concise JSON payload remove_unassigned_fields($self, $args); bless $self, $class; return $self; } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V10/Common/ExplorerAutoOptimizerSetting.pm
Perl
apache-2.0
1,027
# # Copyright 2019 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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. # package storage::storagetek::sl::snmp::mode::components::fan; use strict; use warnings; use storage::storagetek::sl::snmp::mode::components::resources qw($map_operational); my $mapping = { slHdwFanName => { oid => '.1.3.6.1.4.1.1211.1.15.4.6.1.2' }, slHdwFanOperational => { oid => '.1.3.6.1.4.1.1211.1.15.4.6.1.3', map => $map_operational }, }; my $oid_slHdwFanEntry = '.1.3.6.1.4.1.1211.1.15.4.6.1'; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_slHdwFanEntry }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking fans"); $self->{components}->{fan} = {name => 'fans', total => 0, skip => 0}; return if ($self->check_filter(section => 'fan')); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_slHdwFanEntry}})) { next if ($oid !~ /^$mapping->{slHdwFanOperational}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_slHdwFanEntry}, instance => $instance); next if ($self->check_filter(section => 'fan', instance => $instance)); $self->{components}->{fan}->{total}++; $self->{output}->output_add(long_msg => sprintf("fan '%s' status is '%s' [instance: %s].", $result->{slHdwFanName}, $result->{slHdwFanOperational}, $instance )); my $exit = $self->get_severity(label => 'operational', section => 'fan', value => $result->{slHdwFanOperational}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Fan '%s' status is '%s'", $result->{slHdwFanName}, $result->{slHdwFanOperational})); } } } 1;
Sims24/centreon-plugins
storage/storagetek/sl/snmp/mode/components/fan.pm
Perl
apache-2.0
2,769
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute 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. =cut =head1 NAME Bio::EnsEMBL::Compara::PipeConfig::EPO_pt1_conf =head1 SYNOPSIS #1. Update ensembl-hive, ensembl and ensembl-compara GIT repositories before each new release #3. Check all default_options, you will probably need to change the following : pipeline_db (-host) resource_classes 'password' - your mysql password 'compara_pairwise_db' - I'm assuiming that all of your pairwise alignments are in one compara db 'reference_genome_db_id' - the genome_db_id (ie the species) which is in all your pairwise alignments 'list_of_pairwise_mlss_ids' - a comma separated string containing all the pairwise method_link_species_set_id(s) you wise to use to generate the anchors 'main_core_dbs' - the servers(s) hosting most/all of the core (species) dbs 'core_db_urls' - any additional core dbs (not in 'main_core_dbs') The dummy values - you should not need to change these unless they clash with pre-existing values associated with the pairwise alignments you are going to use #4. Run init_pipeline.pl script: Using command line arguments: init_pipeline.pl Bio::EnsEMBL::Compara::PipeConfig::EPO_pt1_conf.pm #5. Run the "beekeeper.pl ... -sync" and then " -loop" command suggested by init_pipeline.pl #6. Fix the code when it crashes =head1 DESCRIPTION This configuaration file gives defaults for the first part of the EPO pipeline (this part generates the anchors from pairwise alignments). =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut package Bio::EnsEMBL::Compara::PipeConfig::EPO_pt1_conf; use strict; use warnings; use base ('Bio::EnsEMBL::Compara::PipeConfig::ComparaGeneric_conf'); use Data::Dumper; sub default_options { my ($self) = @_; return { %{$self->SUPER::default_options}, 'pipeline_name' => 'compara_GenerateAnchors', 'species_tree_file' => $self->o('ensembl_cvs_root_dir').'/ensembl-compara/scripts/pipeline/species_tree_blength.nh', # parameters that are likely to change from execution to another: 'core_db_version' => 74, # version of the dbs from which to get the pairwise alignments # connection parameters to various databases: 'pipeline_db' => { # the production database itself (will be created) -host => 'compara4', -driver => 'mysql', -port => 3306, -user => 'ensadmin', -pass => $self->o('password'), -dbname => $ENV{'USER'}.'_6fish_gen_anchors_'.$self->o('rel_with_suffix'), }, # database containing the pairwise alignments needed to get the overlaps 'compara_pairwise_db' => { -user => 'ensro', -port => 3306, -host => 'ens-livemirror', -driver => 'mysql', -pass => '', -dbname => 'ensembl_compara_72', }, # location of most of the core dbs - to get the sequence from 'main_core_dbs' => [ { -user => 'ensro', -port => 3306, -host => 'ens-livemirror', -driver => 'mysql', -dbname => '', -db_version => $self->o('core_db_version'), }, ], # any additional core dbs 'additional_core_db_urls' => { # 'gallus_gallus' => 'mysql://ensro@ens-staging1:3306/gallus_gallus_core_73_4', }, # genome_db_id from which pairwise alignments will be used 'reference_genome_db_id' => 142, 'list_of_pairwise_mlss_ids' => "634,635,636", # location of species core dbs which were used in the pairwise alignments 'core_db_urls' => [ 'mysql://ensro@ens-livemirror:3306/72' ], # alignment chunk size 'chunk_size' => 100000000, # max block size for pecan to align 'pecan_block_size' => 1000000, 'pecan_mlid' => 10, # dummy value (change if necessary) 'pecan_mlssid' => 10, # dummy value 'gerp_ce_mlid' => 11, # dummy value 'gerp_ce_mlssid' => 20, # dummy value 'gerp_program_version' => "2.1", 'gerp_exe_dir' => "/software/ensembl/compara/gerp/GERPv2.1", 'species_set_id' => 10000, # dummy value for reference and non-reference species 'overlaps_mlid' => 10000, # dummy value 'overlaps_method_link_name' => 'GEN_ANCS', 'overlaps_mlssid' => 10000, # dummy value 'max_frag_diff' => 1.5, # max difference in sizes between non-reference dnafrag and reference to generate the overlaps from 'min_ce_length' => 40, # min length of each sequence in the constrained elenent 'min_anchor_size' => 50, # at least one of the sequences in an anchor must be of this size 'max_anchor_seq_len' => 100, # anchors longer than this value will be trimmed 'min_number_of_seqs_per_anchor' => 2, # minimum number of sequences in an anchor 'max_number_of_seqs_per_anchor' => 30, # maximum number of sequences in an anchor - can happen due to duplicates or repeats 'exonerate' => '/software/ensembl/compara/exonerate/exonerate', # path to exonerate executable }; } sub resource_classes { my ($self) = @_; return { %{$self->SUPER::resource_classes}, # inherit 'default' from the parent class # 'default' => {'LSF' => '-C0 -M2500000 -R"select[mem>2500] rusage[mem=2500]"' }, # farm2 lsf syntax$ # 'mem3500' => {'LSF' => '-C0 -M3500000 -R"select[mem>3500] rusage[mem=3500]"' }, # farm2 lsf syntax$ # 'mem7500' => {'LSF' => '-C0 -M7500000 -R"select[mem>7500] rusage[mem=7500]"' }, # farm2 lsf syntax$ # 'mem14000' => {'LSF' => '-C0 -M14000000 -R"select[mem>14000] rusage[mem=14000]"' }, # farm2 lsf syntax$ 'default' => {'LSF' => '-C0 -M2500 -R"select[mem>2500] rusage[mem=2500]"' }, # farm3 lsf syntax$ 'mem3500' => {'LSF' => '-C0 -M3500 -R"select[mem>3500] rusage[mem=3500]"' }, # farm3 lsf syntax$ 'mem7500' => {'LSF' => '-C0 -M7500 -R"select[mem>7500] rusage[mem=7500]"' }, # farm3 lsf syntax$ 'mem14000' => {'LSF' => '-C0 -M14000 -R"select[mem>14000] rusage[mem=14000]"' }, # farm3 lsf syntax$ }; } sub pipeline_wide_parameters { my $self = shift @_; return { %{$self->SUPER::pipeline_wide_parameters}, 'compara_pairwise_db' => $self->o('compara_pairwise_db'), 'list_of_pairwise_mlss_ids' => $self->o('list_of_pairwise_mlss_ids'), 'main_core_dbs' => $self->o('main_core_dbs'), 'additional_core_db_urls' => $self->o('additional_core_db_urls'), 'pecan_mlid' => $self->o('pecan_mlid'), 'pecan_mlssid' => $self->o('pecan_mlssid'), 'gerp_ce_mlid' => $self->o('gerp_ce_mlid'), 'gerp_ce_mlssid' => $self->o('gerp_ce_mlssid'), 'overlaps_mlid' => $self->o('overlaps_mlid'), 'overlaps_method_link_name' => $self->o('overlaps_method_link_name'), 'overlaps_mlssid' => $self->o('overlaps_mlssid'), 'min_anchor_size' => $self->o('min_anchor_size'), 'min_number_of_seqs_per_anchor' => $self->o('min_number_of_seqs_per_anchor'), 'max_number_of_seqs_per_anchor' => $self->o('max_number_of_seqs_per_anchor'), 'max_frag_diff' => $self->o('max_frag_diff'), 'reference_genome_db_id' => $self->o('reference_genome_db_id'), 'exonerate' => $self->o('exonerate'), }; } sub pipeline_analyses { my ($self) = @_; print "pipeline_analyses\n"; return [ # ------------------------------------- set up the necessary database tables { -logic_name => 'copy_table_factory', -module => 'Bio::EnsEMBL::Hive::RunnableDB::JobFactory', -input_ids => [{}], -parameters => { 'db_conn' => '#compara_pairwise_db#', 'inputlist' => [ 'genome_db', 'dnafrag', 'method_link', 'method_link_species_set', 'species_set', 'ncbi_taxa_name', 'ncbi_taxa_node' ], 'column_names' => [ 'table' ], }, -flow_into => { '2->A' => [ 'copy_tables' ], 'A->1' => [ 'delete_from_copied_tables' ], }, -meadow_type => 'LOCAL', }, { -logic_name => 'copy_tables', -module => 'Bio::EnsEMBL::Hive::RunnableDB::MySQLTransfer', -parameters => { 'src_db_conn' => '#compara_pairwise_db#', 'dest_db_conn' => $self->o('pipeline_db'), 'mode' => 'overwrite', 'filter_cmd' => 'sed "s/ENGINE=MyISAM/ENGINE=InnoDB/"', }, }, { -logic_name => 'delete_from_copied_tables', -module => 'Bio::EnsEMBL::Hive::RunnableDB::SqlCmd', -parameters => { 'sql' => [ 'DELETE FROM method_link_species_set WHERE method_link_species_set_id NOT IN (#list_of_pairwise_mlss_ids#)', 'DELETE ss.* FROM species_set ss LEFT OUTER JOIN method_link_species_set mlss ON ss.species_set_id = mlss.species_set_id WHERE mlss.species_set_id IS NULL', 'DELETE df.*, gdb.* FROM dnafrag df INNER JOIN genome_db gdb ON gdb.genome_db_id = df.genome_db_id LEFT OUTER JOIN species_set ss ON gdb.genome_db_id = ss.genome_db_id WHERE ss.genome_db_id IS NULL', 'DELETE FROM genome_db WHERE ! assembly_default', ], }, -flow_into => { 1 => [ 'add_dummy_mlss_info' ] }, }, { # this sets values in the method_link_species_set and species_set tables -logic_name => 'add_dummy_mlss_info', -module => 'Bio::EnsEMBL::Hive::RunnableDB::SqlCmd', -parameters => { 'species_set_id' => $self->o('species_set_id'), 'sql' => [ # method_link (ml) and method_link_species_set (mlss) entries for the overlaps, pecan and gerp 'REPLACE INTO method_link (method_link_id, type) VALUES(#overlaps_mlid#, "#overlaps_method_link_name#")', 'REPLACE INTO method_link_species_set (method_link_species_set_id, method_link_id, name, species_set_id) VALUES ' .'(#overlaps_mlssid#, #overlaps_mlid#, "get_overlaps", #species_set_id#),' .'(#pecan_mlssid#, #pecan_mlid#, "pecan", #species_set_id#),' .'(#gerp_ce_mlssid#, #gerp_ce_mlid#, "gerp", #species_set_id#),', ], }, -flow_into => { '1->A' => [ 'add_dummy_species_set_info_factory', 'set_genome_db_locator_factory' ], 'A->1' => [ 'chunk_reference_dnafrags_factory' ], }, }, { # this sets dummy values into the species_set table -logic_name => 'add_dummy_species_set_info_factory', -module => 'Bio::EnsEMBL::Hive::RunnableDB::JobFactory', -parameters => { 'inputquery' => 'SELECT genome_db_id FROM genome_db', 'species_set_id' => $self->o('species_set_id'), }, -flow_into => { 2 => { 'mysql:////species_set' => { 'species_set_id' => '#species_set_id#', 'genome_db_id' => '#genome_db_id#' } } }, }, { -logic_name => 'set_genome_db_locator_factory', -module => 'Bio::EnsEMBL::Hive::RunnableDB::JobFactory', -parameters => { 'inputquery' => 'SELECT name AS species_loc_name FROM genome_db WHERE assembly_default', }, -flow_into => { 2 => 'update_genome_db_locator', 1 => 'make_species_tree', }, }, { # this sets up the locator field in the genome_db table -logic_name => 'update_genome_db_locator', -module => 'Bio::EnsEMBL::Compara::Production::EPOanchors::UpdateGenomeDBLocator', -meadow_type => 'LOCAL', }, { -logic_name => 'make_species_tree', -module => 'Bio::EnsEMBL::Compara::RunnableDB::MakeSpeciesTree', -parameters => { 'mlss_id' => '#pecan_mlssid#', 'newick_format' => 'simple', 'blength_tree_file' => $self->o('species_tree_file'), }, # -flow_into => { # 4 => { 'mysql:////method_link_species_set_tag' => { 'method_link_species_set_id' => '#mlss_id#', 'tag' => 'species_tree', 'value' => '#species_tree_string#' } }, # }, }, # ------------------------------------- now for the modules which create the anchors { # split the reference genome in to convenient sized frags for parallelisation -logic_name => 'chunk_reference_dnafrags_factory', -module => 'Bio::EnsEMBL::Compara::Production::EPOanchors::ChunkRefDnaFragsFactory', -parameters => { 'chunk_size' => $self->o('chunk_size'), }, -flow_into => { '2->A' => [ 'find_pairwise_overlaps' ], 'A->1' => [ 'transfer_ce_data_to_anchor_align' ], }, }, { # finds the overlaps between the pairwise lignments and populates the dnafrag_region and synteny_region tables with the overlaps -logic_name => 'find_pairwise_overlaps', -module => 'Bio::EnsEMBL::Compara::Production::EPOanchors::FindPairwiseOverlaps', -flow_into => { 2 => [ 'pecan' ], 3 => [ 'mysql:////dnafrag_region?insertion_method=INSERT_IGNORE' ], }, -failed_job_tolerance => 5, # allowing 5% of job failures -hive_capacity => 50, -batch_size => 20, }, { # align the overlapping regions - creates entries in the genomic_align and genomic_align_block tables -logic_name => 'pecan', -module => 'Bio::EnsEMBL::Compara::RunnableDB::MercatorPecan::Pecan', -parameters => { 'mlss_id' => '#pecan_mlssid#', 'max_block_size' => $self->o('pecan_block_size'), 'java_options' => '-server -Xmx1000M', }, -flow_into => { 2 => [ 'pecan_high_mem' ], # Pecan complained -1 => [ 'pecan_high_mem' ], # LSF killed because of MEMLIMIT 1 => [ 'gerp_constrained_element' ], }, -hive_capacity => 50, -failed_job_tolerance => 10, # a proportion of these will probably fail - which is fine -max_retry_count => 1, }, { -logic_name => 'pecan_high_mem', -parameters => { 'mlss_id' => '#pecan_mlssid#', 'max_block_size' => $self->o('pecan_block_size'), java_options => '-server -Xmx6000M', }, -module => 'Bio::EnsEMBL::Compara::RunnableDB::MercatorPecan::Pecan', -hive_capacity => 10, -rc_name => 'mem7500', -failed_job_tolerance => 10, -max_retry_count => 1, -flow_into => { 1 => [ 'gerp_constrained_element' ], }, }, { # find the most highly constrained regions from the aligned overlaps - this will create entries in the constrained element table -logic_name => 'gerp_constrained_element', -module => 'Bio::EnsEMBL::Compara::RunnableDB::GenomicAlignBlock::Gerp', -parameters => { 'window_sizes' => '[1,10,100,500]', 'gerp_exe_dir' => $self->o('gerp_exe_dir'), 'program_version' => $self->o('gerp_program_version'), 'mlss_id' => '#pecan_mlssid#', }, -hive_capacity => 100, -batch_size => 10, -failed_job_tolerance => 10, }, { # copies the constrained element data to the anchor_align table -logic_name => 'transfer_ce_data_to_anchor_align', -module => 'Bio::EnsEMBL::Hive::RunnableDB::SqlCmd', -parameters => { 'sql' => [ 'INSERT INTO anchor_align (method_link_species_set_id, anchor_id, dnafrag_id, dnafrag_start, dnafrag_end, dnafrag_strand) '. 'SELECT method_link_species_set_id, constrained_element_id, dnafrag_id, dnafrag_start, dnafrag_end, dnafrag_strand FROM '. 'constrained_element WHERE (dnafrag_end - dnafrag_start + 1) >= '. $self->o('min_ce_length') .' ORDER BY constrained_element_id', ], }, -flow_into => { 1 => 'trim_anchor_align_factory' }, }, { -logic_name => 'trim_anchor_align_factory', -module => 'Bio::EnsEMBL::Hive::RunnableDB::JobFactory', -parameters => { 'inputquery' => "SELECT DISTINCT(anchor_id) AS anchor_id FROM anchor_align", }, -flow_into => { '2->A' => [ 'trim_anchor_align' ], 'A->1' => [ 'load_anchor_sequence_factory' ], }, }, { # finds the best cut position within an anchor and trims the anchor positions down to 2 base pairs - it populates the anchor_align table with these trimmed anchors -logic_name => 'trim_anchor_align', -module => 'Bio::EnsEMBL::Compara::Production::EPOanchors::TrimAnchorAlign', -parameters => { 'input_method_link_species_set_id' => '#gerp_ce_mlssid#', 'output_method_link_species_set_id' => '#overlaps_mlssid#', }, -failed_job_tolerance => 10, -hive_capacity => 200, -batch_size => 10, -flow_into => { -1 => [ 'trim_anchor_align_himem' ], } }, { # finds the best cut position within an anchor and trims the anchor positions down to 2 base pairs - it populates the anchor_align table with these trimmed anchors -logic_name => 'trim_anchor_align_himem', -module => 'Bio::EnsEMBL::Compara::Production::EPOanchors::TrimAnchorAlign', -parameters => { 'input_method_link_species_set_id' => '#gerp_ce_mlssid#', 'output_method_link_species_set_id' => '#overlaps_mlssid#', }, -rc_name => 'mem7500', -failed_job_tolerance => 10, -hive_capacity => 200, -batch_size => 10, }, { -logic_name => 'load_anchor_sequence_factory', -module => 'Bio::EnsEMBL::Hive::RunnableDB::JobFactory', -parameters => { 'inputquery' => 'SELECT DISTINCT(anchor_id) AS anchor_id FROM anchor_align WHERE method_link_species_set_id = #overlaps_mlssid', }, -flow_into => { 2 => [ 'load_anchor_sequence' ], }, }, { # using the anchor positions from 'trim_anchor_align' it populates the anchor_sequence table with anchor sequences between min_ce_length and max_anchor_seq_len (using the 2bp trim coord as a mid-point -logic_name => 'load_anchor_sequence', -module => 'Bio::EnsEMBL::Compara::Production::EPOanchors::LoadAnchorSequence', -parameters => { 'input_method_link_species_set_id' => '#overlaps_mlssid#', 'max_anchor_seq_len' => $self->o('max_anchor_seq_len'), 'min_anchor_seq_len' => $self->o('min_ce_length'), }, -batch_size => 10, -hive_capacity => 100, }, ]; } 1;
ckongEbi/ensembl-compara
modules/Bio/EnsEMBL/Compara/PipeConfig/EPO_pt1_conf.pm
Perl
apache-2.0
17,719
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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. # package storage::avid::isis::snmp::mode::status; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold); sub custom_status_output { my ($self, %options) = @_; my $msg = sprintf("System Director state is '%s'", $self->{result_values}->{status}); return $msg; } sub custom_status_calc { my ($self, %options) = @_; $self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_SystemDirectorState'}; return 0; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 0, message_separator => ' - ' }, ]; $self->{maps_counters}->{global} = [ { label => 'status', set => { key_values => [ { name => 'SystemDirectorState' } ], closure_custom_calc => $self->can('custom_status_calc'), closure_custom_output => $self->can('custom_status_output'), closure_custom_perfdata => sub { return 0; }, closure_custom_threshold_check => \&catalog_status_threshold, } }, { label => 'redistributing-count', set => { key_values => [ { name => 'WorkspaceRedistributingCount' } ], output_template => 'Workspace redistributing count: %d', perfdatas => [ { label => 'redistributing_count', value => 'WorkspaceRedistributingCount', template => '%d', min => 0 }, ], } }, ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { "warning-status:s" => { name => 'warning_status', default => '' }, "critical-status:s" => { name => 'critical_status', default => '%{status} !~ /Online/i' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $self->change_macros(macros => ['warning_status', 'critical_status']); } my %map_status = ( 0 => 'Online', 1 => 'Offline', 2 => 'Standby', 3 => 'Unknown', ); my $oid_SystemDirectorState = '.1.3.6.1.4.1.526.20.2.1.0'; my $oid_WorkspaceRedistributingCount = '.1.3.6.1.4.1.526.20.2.4.0'; sub manage_selection { my ($self, %options) = @_; my $results = $options{snmp}->get_leef(oids => [ $oid_SystemDirectorState, $oid_WorkspaceRedistributingCount ], nothing_quit => 1); $self->{global} = {}; $self->{global} = { SystemDirectorState => $map_status{$results->{$oid_SystemDirectorState}}, WorkspaceRedistributingCount => $results->{$oid_WorkspaceRedistributingCount}, }; } 1; __END__ =head1 MODE Check System Director state and workspaces redistributing count. =over 8 =item B<--warning-status> Set warning threshold for status. (Default: ''). Can use special variables like: %{state} =item B<--critical-status> Set critical threshold for status. (Default: '%{state} !~ /Online/i'). Can use special variables like: %{state} =item B<--warning-redistributing-count> Threshold warning for number of workspaces redistributing. =item B<--critical-redistributing-count> Threshold critical for number of workspaces redistributing. =back =cut
centreon/centreon-plugins
storage/avid/isis/snmp/mode/status.pm
Perl
apache-2.0
4,238
%:- module( case_tester , [case_tester/2] , [assertions] ). :- use_package( assertions ). :- use_module( library(tester) , [run_tester/10] ). :- use_module( library( write ) ). :- use_module( library( lists ) ). :- use_module( library( terms_check ) , [variant/2] ). :- use_module( library( aggregates ) , [findall/3] ). :- comment( author , "David Trallero Mena" ). :- comment( module, "This module is intented to be a tool to test case-test of a program. A list of the form: ( variables , predicate , results ) is passes as argument" ). init_func. tester_func( (PatArg,PArg,SOL) ) :- display( 'Executing test: ' ), display( PArg ), nl, display( 'and comparing with: ' ), display( SOL ), nl, copy_term( (PatArg , PArg ) , (Pat,P ) ), ( findall( Pat , P , L ) -> compare( L , SOL ) ; SOL == fail ). compare( [A|RA] , [B|RB] ) :- variant(A,B), !, compare( RA , RB ). compare( [] , [] ). checker_func( _ ). end_func. :- pred case_tester( L , Res ) # " L = [ ( (A,B) , main2(A,B) , [(at1(1),1)] ), ( X , main3( X ) , [at2(21,22),at3(1)]), ( X , main3( at1(X ) ) , []), ( X , main3( at3(X ) ) , [1]), ( (A,B) , main3( at2(A,B) ) , [ (21,22) ]), ( Y , main4( at2(1), at3(2) , Y ) , [at2(1),at3(2)] ), ( Y1 , main4( at1(5), at2(1,2) , Y1) , [at1(5),at2(1,2)] ) ], ". %:- meta_predicate( list( (?,goal,?) ) , ? ). case_tester( L , Res , Title ) :- run_tester( 'test.log', 'result.log', init_func , tester_func , L, checker_func, L, end_func, Res, slider(Title) ).
leuschel/ecce
www/CiaoDE/ciao/contrib/case_tester/case_tester.pl
Perl
apache-2.0
1,662
#!/usr/bin/env perl # wlair IRC Bot # Copyright (c) 2013, 2014, 2015 xoddf2 # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH # DAMAGE. use strict; use warnings; use Getopt::Long; use POE; use POE::Component::IRC; use POE::Component::IRC::Plugin::CTCP; use POE::Component::IRC::Plugin::NickServID; use POE::Component::SSLify; use YAML::XS qw/LoadFile/; use feature qw/say/; use LWP::Simple; use Regexp::Common qw/URI/; # For URI titles use REST::Google::Search; use HTML::Restrict; use POSIX qw(uname); # For CTCP VERSION my $wlbot_version = "git"; # Default settings my $config_file = "$ENV{'HOME'}/.wlbotrc"; my $config = LoadFile($config_file); my $wlbot_nick = $config->{nick}; my $password = $config->{password}; my $username = $config->{username}; my $ircname = $config->{gecos}; my $server = $config->{server}; my $port = $config->{port}; my $ssl = $config->{ssl}; my $channel = $config->{channel}; my $usermode = $config->{usermode}; my $prefix = $config->{prefix}; # Command-line options my ($opt_help, $opt_version); GetOptions ("config=s" => \$config_file, "nick=s" => \$wlbot_nick, "username=s" => \$username, "password=s" => \$password, "gecos=s" => \$ircname, "server=s" => \$server, "port=s" => \$port, "ssl" => \$ssl, "channel=s" => \$channel, "usermode=s" => \$usermode, "prefix=s" => \$prefix, "help!" => \$opt_help, "version!" => \$opt_version); if (defined $opt_help) { print "usage: wlbot [--nick nick] [--username username] [--gecos ircname]\n"; print " [--server host] [--port port] [--channel channel]\n"; print " [--usermode modes] [--prefix char]\n"; exit 0; } elsif (defined $opt_version) { print "wlair IRC Bot $wlbot_version\n"; exit 0; } # Refuse to run without a server or channel if (($server eq '') && ($channel eq '')) { die("Please specify a server with --server and a channel with --channel."); } elsif ($server eq '') { die("Please specify a server with --server."); } elsif ($channel eq '') { die("Please specify a channel with --channel."); } # What channel to join sub CHANNEL () { $channel } my ($irc) = POE::Component::IRC->spawn(); # What to do, when POE::Session->create( inline_states => { _start => \&bot_start, irc_001 => \&on_connect, irc_public => \&on_public, irc_msg => \&on_private, }, ); # Connect sub bot_start { $irc->plugin_add( 'NickServID' => POE::Component::IRC::Plugin::NickServID->new( Password => $password )); $irc->yield(register => "all"); $irc->yield( connect => { Nick => $wlbot_nick, Username => $username, Password => $password, Ircname => $ircname, Server => $server, Port => $port, UseSSL => $ssl, } ); # For CTCP VERSION: my ($sysname, $nodename, $release, $version, $machine) = POSIX::uname(); $irc->plugin_add('CTCP' => POE::Component::IRC::Plugin::CTCP->new( version => "wlair IRC Bot ${wlbot_version} (running on ${sysname} ${machine})", userinfo => $ircname, )); } # Commands sub wlbot_command_ping { my ($to) = @_; $irc->yield(privmsg => $to, "pong"); } sub wlbot_command_source { my ($to) = @_; $irc->yield(privmsg => $to, "My source is at https://github.com/woddfellow2/wlbot"); } sub wlbot_command_google { my ($to, $query) = @_; REST::Google::Search->http_referer(''); my $res = REST::Google::Search->new( q => $query, ); my $hr = HTML::Restrict->new(); # To strip out the <b></b> tags my $data = $res->responseData; my $cursor = $data->cursor; my $pages = $cursor->pages; my @results = $data->results; $irc->yield(privmsg => $to, $hr->process($results[0]->title . ": ". $results[0]->url)); } # Web page title announcements sub get_www_page_title { my ($to, $url) = @_; my $html = get($url); $html =~ m{<TITLE>(.*?)</TITLE>}gism; $html =~ s/1$//; $irc->yield(privmsg => $to, "Title: " . $1); } # Set user modes on itself and join sub on_connect { $irc->yield(mode => $wlbot_nick => $usermode); $irc->yield(join => CHANNEL); } # What to do in channels sub on_public { my ($kernel, $who, $where, $msg) = @_[KERNEL, ARG0, ARG1, ARG2]; my $nick = (split /!/, $who)[0]; my $channel = $where->[0]; my $ts = scalar localtime; # Commands if ($msg =~ /^(\Q$prefix\E|\Q$wlbot_nick\E.? +)ping */) { wlbot_command_ping(CHANNEL); print STDERR "$nick in $channel pinged at $ts\n"; } elsif ($msg =~ /^(\Q$prefix\E|\Q$wlbot_nick\E.? +)source */) { wlbot_command_source(CHANNEL); print STDERR "$nick in $channel called !source at $ts\n"; } elsif ($msg =~ /^(\Q$prefix\E|\Q$wlbot_nick\E.? +)gg */) { # Isolate the query my $gg = $msg; $gg =~ s/^(\Q$prefix\E|\Q$wlbot_nick\E.? +)gg *//; wlbot_command_google(CHANNEL, $gg); print STDERR "$nick in $channel did a Google search for $gg at $ts\n"; } elsif ($msg =~ /$RE{URI}/) { my $uri = $msg; $uri =~ /$RE{URI}/; get_www_page_title(CHANNEL, $uri); print STDERR "$nick in $channel posted URI $uri at $ts\n"; } } # What to do in PM sub on_private { # TODO: Reduce the redundancy (some of this is already in on_public). my ($kernel, $who, $to, $msg) = @_[KERNEL, ARG0, ARG1, ARG2]; my $nick = (split /!/, $who)[0]; my $address = (split /!/, $who)[1]; my $ts = scalar localtime; # Commands if ($msg =~ /^(\Q$prefix\E)?ping */) { wlbot_command_ping($nick); print STDERR "$nick in private message pinged at $ts\n"; } elsif ($msg =~ /^(\Q$prefix\E)?source */) { wlbot_command_source($nick); print STDERR "$nick in private message called !source at $ts\n"; } elsif ($msg =~ /^(\Q$prefix\E)?gg */) { # Isolate the query my $gg = $msg; $gg =~ s/^(\Q$prefix\E)?gg *//; wlbot_command_google($nick, $gg); print STDERR "$nick in private message did a Google search for $gg at $ts\n"; } } $poe_kernel->run(); exit 0;
woddfellow2/wlbot
wlbot.pl
Perl
bsd-2-clause
7,684
=head1 NAME Zonemaster::Overview - The Zonemaster Test Engine =head1 INTRODUCTION The Zonemaster system is a quality control tool for DNS zones, produced in cooperation between AFNIC and IIS (the top-level registries for respectively France and Sweden). It is a successor both to AFNIC's tool Zonecheck and IIS's tool DNSCheck, and is intended to be an improvement over both. The system as a whole consists of the test engine and, as distributed by the project, two different front ends. One is a command-line interface intended for use by experienced technicians, and one is a web interface meant for use by anyone. This document only talks about the test engine. =head1 DESCRIPTION =head2 Brief overview Conceptually, the test engine consists of a number of test implementation modules surrounded by a support framework. Anyone wanting to use Zonemaster to perform tests communicates with the framework from the "outside", and all modules implementing tests see the world entirely through the framework. Doing things this way lets us have features like the ability to test domains before they are published, to record entire test runs for later analysis and to make sure that test restults are (as far as reality allows) predictable and repeatable. =head2 For users of Zonemaster If all you want to do is run tests, you need to care about four or five modules. L<Zonemaster> is the main access point to the framework, and it is via its methods that you set the configuration (if needed), request that tests be started and access the logger. The logger is where the test results end up, so that's pretty important. On top of those, you may want to use the L<Zonemaster::Translator> to turn the results into human-readable messages. There are two ways that you can get the results of a test you've requested: the simple-but-inflexible way and the flexible-but-complex way. The simple-but-inflexible way is that all the methods in L<Zonemaster> that run tests return lists of L<Zonemaster::Logger::Entry> objects. Those lists incude all the results that the writer of the test module(s) considered important enough to return by default. The advantage of this method is that it is extremely easy to use. The following is a functional (if not very useful) way to run a full test and print the results from a command line prompt: perl -MZonemaster -E 'say "$_" for Zonemaster->new->test_zone("example.org")' The main drawbacks of this method are that there is no choice about what messages to see, and it's entirely asynchronous. The code that started the test does not get a chance to do anything at all until the whole test has finished, which may be several minutes later. The get around those drawbacks there is the flexible-but-complex way, which consists of installing a callback that gets executed every time a message is logged. It's not that much more complicated, code-wise. The following example does roughly the same thing as the one above: perl -MZonemaster -E 'Zonemaster->logger->callback(sub {say "$_[0]"}); Zonemaster->new->test_zone("example.org");' If you try running those, you'll notice two main differences. First, the second variant prints results as they are generated. Second, it generates a B<lot> more output. On my machine right now, the first example gives me 94 lines of output. The second example gives me 17684. You can do pretty much whatever you want with the message objects in the callback (including modifying them, although we don't promise that behavior will stay around). If the callback code throws an exception, and that exception is not a subcless of L<Zonemaster::Exception>, the callback will be removed. Note also that while the callback is running, the test engine itself is not. So think twice before you do potentially time-consuming tasks (like sticking the message in a database) in the callback. After waiting for responses from remote name servers (which usually stands for more than 90% of the time used), the result logging is the single most time-consuming task in a Zonemaster test run. From here, you probably want to look at the documentation for L<Zonemaster>, L<Zonemaster::Logger>, L<Zonemaster::Logger::Entry>, L<Zonemaster::Config> and L<Zonemaster::Translator>. =head2 For developers of Zonemaster Test Modules If you want to develop a test module of your own, the L<Zonemaster::Test::Example> module is intended to serve as an example. The standard set of modules also fulfil that purpose to various degrees, of course. L<Zonemaster::Test::DNSSEC> may be especially interesting, since it is an example of including default translation and policy data with the module source code. As an entry point to the "inside" of the Zonemaster framework, you want to read L<Zonemaster::Zone> and follow references from there. Of particular interest after the zone class should be the L<Zonemaster::Nameserver> and possibly L<Zonemaster::Recursor> classes. If you do write your own test module, I would very much appreciate feedback on which parts were tricky to figure out, because I'm honestly not sure what I need to explain here. So please, if there's somethat that you think really needs to be written about, add an issue about at L<https://github.com/dotse/zonemaster-engine/issues>. =head2 For developers of the Zonemaster Test Framework Random recommendations and advice. May be replaced with more coherent developer documentation in the future. =over =item Stability, predictability and reliability are more important than performance. =item Don't forget that starting with Perl version 5.18, the order in which you get the keys out of a hash will be different every time the script is run. Get used to always writing C<sort keys %hash>. =item If two (or more) test implementation modules implement the same (or very similar) thing, it should probably be extracted into the framework. =item The unit tests run against pre-recorded data, unless the environment variable C<ZONEMASTER_RECORD> is set to a (perl-)true value. In that case, it runs against the live DNS world and records all results for future use. Unfortunately this sometime means that some tests fail, when we were relying on seeing certain problems in certain domains, and those no longer look the same. =item The translation strings returned from a test module are used as keys in the GNU gettext system, so if you change anything in them don't forget to also change the translation C<.po> files in F<share>. =item Adding a new message tag is more work than it first looks, since it needs to be added to the test module metadata, the default policy and the translation system in order to be fully functional. =back =head1 REFERENCES =over =item L<https://github.com/dotse/zonemaster> Main repository, holding among other things our test specifications. =back =head2 List of all RFCs referred to in the test specifications =over =item L<RFC0822 "STANDARD FOR THE FORMAT OF ARPA INTERNET TEXT MESSAGES"|http://www.rfc-editor.org/info/rfc822> =item L<RFC0919 "Broadcasting Internet Datagrams"|http://www.rfc-editor.org/info/rfc919> =item L<RFC0952 "DoD Internet host table specification"|http://www.rfc-editor.org/info/rfc952> =item L<RFC1033 "Domain Administrators Operations Guide"|http://www.rfc-editor.org/info/rfc1033> =item L<RFC1034 "Domain names - concepts and facilities"|http://www.rfc-editor.org/info/rfc1034> =item L<RFC1035 "Domain names - implementation and specification"|http://www.rfc-editor.org/info/rfc1035> =item L<RFC1112 "Host extensions for IP multicasting"|http://www.rfc-editor.org/info/rfc1112> =item L<RFC1122 "Requirements for Internet Hosts - Communication Layers"|http://www.rfc-editor.org/info/rfc1122> =item L<RFC1123 "Requirements for Internet Hosts - Application and Support"|http://www.rfc-editor.org/info/rfc1123> =item L<RFC1912 "Common DNS Operational and Configuration Errors"|http://www.rfc-editor.org/info/rfc1912> =item L<RFC1918 "Address Allocation for Private Internets"|http://www.rfc-editor.org/info/rfc1918> =item L<RFC1930 "Guidelines for creation, selection, and registration of an Autonomous System (AS)"|http://www.rfc-editor.org/info/rfc1930> =item L<RFC1982 "Serial Number Arithmetic"|http://www.rfc-editor.org/info/rfc1982> =item L<RFC1996 "A Mechanism for Prompt Notification of Zone Changes (DNS NOTIFY)"|http://www.rfc-editor.org/info/rfc1996> =item L<RFC2142 "Mailbox Names for Common Services, Roles and Functions"|http://www.rfc-editor.org/info/rfc2142> =item L<RFC2181 "Clarifications to the DNS Specification"|http://www.rfc-editor.org/info/rfc2181> =item L<RFC2182 "Selection and Operation of Secondary DNS Servers"|http://www.rfc-editor.org/info/rfc2182> =item L<RFC2308 "Negative Caching of DNS Queries (DNS NCACHE)"|http://www.rfc-editor.org/info/rfc2308> =item L<RFC2544 "Benchmarking Methodology for Network Interconnect Devices"|http://www.rfc-editor.org/info/rfc2544> =item L<RFC2671 "Extension Mechanisms for DNS (EDNS0)"|http://www.rfc-editor.org/info/rfc2671> =item L<RFC2822 "Internet Message Format"|http://www.rfc-editor.org/info/rfc2822> =item L<RFC2870 "Root Name Server Operational Requirements"|http://www.rfc-editor.org/info/rfc2870> =item L<RFC2928 "Initial IPv6 Sub-TLA ID Assignments"|http://www.rfc-editor.org/info/rfc2928> =item L<RFC3056 "Connection of IPv6 Domains via IPv4 Clouds"|http://www.rfc-editor.org/info/rfc3056> =item L<RFC3068 "An Anycast Prefix for 6to4 Relay Routers"|http://www.rfc-editor.org/info/rfc3068> =item L<RFC3658 "Delegation Signer (DS) Resource Record (RR)"|http://www.rfc-editor.org/info/rfc3658> =item L<RFC3696 "Application Techniques for Checking and Transformation of Names"|http://www.rfc-editor.org/info/rfc3696> =item L<RFC3701 "6bone (IPv6 Testing Address Allocation) Phaseout"|http://www.rfc-editor.org/info/rfc3701> =item L<RFC3849 "IPv6 Address Prefix Reserved for Documentation"|http://www.rfc-editor.org/info/rfc3849> =item L<RFC3927 "Dynamic Configuration of IPv4 Link-Local Addresses"|http://www.rfc-editor.org/info/rfc3927> =item L<RFC4034 "Resource Records for the DNS Security Extensions"|http://www.rfc-editor.org/info/rfc4034> =item L<RFC4035 "Protocol Modifications for the DNS Security Extensions"|http://www.rfc-editor.org/info/rfc4035> =item L<RFC4074 "Common Misbehavior Against DNS Queries for IPv6 Addresses"|http://www.rfc-editor.org/info/rfc4074> =item L<RFC4193 "Unique Local IPv6 Unicast Addresses"|http://www.rfc-editor.org/info/rfc4193> =item L<RFC4291 "IP Version 6 Addressing Architecture"|http://www.rfc-editor.org/info/rfc4291> =item L<RFC4343 "Domain Name System (DNS) Case Insensitivity Clarification"|http://www.rfc-editor.org/info/rfc4343> =item L<RFC4380 "Teredo: Tunneling IPv6 over UDP through Network Address Translations (NATs)"|http://www.rfc-editor.org/info/rfc4380> =item L<RFC4843 "An IPv6 Prefix for Overlay Routable Cryptographic Hash Identifiers (ORCHID)"|http://www.rfc-editor.org/info/rfc4843> =item L<RFC5155 "DNS Security (DNSSEC) Hashed Authenticated Denial of Existence"|http://www.rfc-editor.org/info/rfc5155> =item L<RFC5156 "Special-Use IPv6 Addresses"|http://www.rfc-editor.org/info/rfc5156> =item L<RFC5180 "IPv6 Benchmarking Methodology for Network Interconnect Devices"|http://www.rfc-editor.org/info/rfc5180> =item L<RFC5321 "Simple Mail Transfer Protocol"|http://www.rfc-editor.org/info/rfc5321> =item L<RFC5358 "Preventing Use of Recursive Nameservers in Reflector Attacks"|http://www.rfc-editor.org/info/rfc5358> =item L<RFC5737 "IPv4 Address Blocks Reserved for Documentation"|http://www.rfc-editor.org/info/rfc5737> =item L<RFC5771 "IANA Guidelines for IPv4 Multicast Address Assignments"|http://www.rfc-editor.org/info/rfc5771> =item L<RFC5892 "The Unicode Code Points and Internationalized Domain Names for Applications (IDNA)"|http://www.rfc-editor.org/info/rfc5892> =item L<RFC5936 "DNS Zone Transfer Protocol (AXFR)"|http://www.rfc-editor.org/info/rfc5936> =item L<RFC6052 "IPv6 Addressing of IPv4/IPv6 Translators"|http://www.rfc-editor.org/info/rfc6052> =item L<RFC6333 "Dual-Stack Lite Broadband Deployments Following IPv4 Exhaustion"|http://www.rfc-editor.org/info/rfc6333> =item L<RFC6598 "IANA-Reserved IPv4 Prefix for Shared Address Space"|http://www.rfc-editor.org/info/rfc6598> =item L<RFC6666 "A Discard Prefix for IPv6"|http://www.rfc-editor.org/info/rfc6666> =item L<RFC6781 "DNSSEC Operational Practices, Version 2"|http://www.rfc-editor.org/info/rfc6781> =item L<RFC6890 "Special-Purpose IP Address Registries"|http://www.rfc-editor.org/info/rfc6890> =item L<RFC6891 "Extension Mechanisms for DNS (EDNS(0))"|http://www.rfc-editor.org/info/rfc6891> =item L<RFC7050 "Discovery of the IPv6 Prefix Used for IPv6 Address Synthesis"|http://www.rfc-editor.org/info/rfc7050> =back =cut
jelu/zonemaster-engine
lib/Zonemaster/Overview.pod
Perl
bsd-2-clause
12,863
package Tapper::Reports::Web::Util::Filter::Testrun; BEGIN { $Tapper::Reports::Web::Util::Filter::Testrun::AUTHORITY = 'cpan:TAPPER'; } { $Tapper::Reports::Web::Util::Filter::Testrun::VERSION = '4.1.2'; } use Moose; use Hash::Merge::Simple 'merge'; use Set::Intersection 'get_intersection'; use Tapper::Model 'model'; extends 'Tapper::Reports::Web::Util::Filter'; sub BUILD{ my $self = shift; my $args = shift; $self->dispatch( merge($self->dispatch, {host => \&host, status => \&status, topic => \&topic, owner => \&owner, }) ); } sub host { my ($self, $filter_condition, $host) = @_; my $host_result = model('TestrunDB')->resultset('Host')->search({name => $host}, {rows => 1})->first; # (XXX) do we need to throw an error when someone filters for an # unknown host? if (not $host_result) { return $filter_condition; } my $jobs = model('TestrunDB')->resultset('TestrunScheduling')->search({host_id => $host_result->id}); my @ids = map {$_->testrun->id if $_->testrun} $jobs->all; @ids = get_intersection(\@ids, $filter_condition->{early}->{id}) if $filter_condition->{early}->{id}; $filter_condition->{early}->{id} = {'in' => \@ids}; return $filter_condition; } sub status { my ($self, $filter_condition, $state) = @_; my $jobs = model('TestrunDB')->resultset('TestrunScheduling')->search({status => $state}); my @ids = map {$_->testrun->id if $_->testrun} $jobs->all; @ids = get_intersection(\@ids, $filter_condition->{early}->{id}) if $filter_condition->{early}->{id}; $filter_condition->{early}->{id} = {'in' => \@ids}; return $filter_condition; } sub topic { my ($self, $filter_condition, $topic) = @_; $filter_condition->{early}->{topic_name} = $topic; return $filter_condition; } sub owner { my ($self, $filter_condition, $owner) = @_; my $owner_result = model('TestrunDB')->resultset('Owner')->search({login => $owner}, {rows => 1})->first; if (not $owner_result) { $filter_condition->{error} = "No owner with login '$owner' found"; return $filter_condition; } $filter_condition->{early}->{owner_id} = $owner_result->id; return $filter_condition; } 1; __END__ =pod =encoding utf-8 =head1 NAME Tapper::Reports::Web::Util::Filter::Testrun =head1 SYNOPSIS use Tapper::Testruns::Web::Util::Filter::Testrun; my $filter = Tapper::Testruns::Web::Util::Filter::Testrun->new(); my $filter_args = ['host','bullock','days','3']; my $allowed_filter_keys = ['host','days']; my $searchoptions = $filter->parse_filters($filter_args, $allowed_filter_keys); =head2 host Add host filters to early filters. @param hash ref - current version of filters @param string - host name @return hash ref - updated filters =head2 status Add status filters to early filters. @param hash ref - current version of filters @param string - status @return hash ref - updated filters =head2 topic Add topic filters to early filters. @param hash ref - current version of filters @param string - topic name @return hash ref - updated filters =head2 owner Add owner filters to early filters. @param hash ref - current version of filters @param string - owner login @return hash ref - updated filters =head1 NAME Tapper::Reports::Web::Util::Filter::Testrun - Filter utilities for testrun listing =head1 AUTHOR AMD OSRC Tapper Team <tapper@amd64.org> =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2012 by Advanced Micro Devices, Inc.. This is free software, licensed under: The (two-clause) FreeBSD License =cut
gitpan/Tapper-Reports-Web
lib/Tapper/Reports/Web/Util/Filter/Testrun.pm
Perl
bsd-2-clause
4,012
=pod =head1 NAME SSL_session_reused - query whether a reused session was negotiated during handshake =head1 SYNOPSIS #include <openssl/ssl.h> int SSL_session_reused(SSL *ssl); =head1 DESCRIPTION Query, whether a reused session was negotiated during the handshake. =head1 NOTES During the negotiation, a client can propose to reuse a session. The server then looks up the session in its cache. If both client and server agree on the session, it will be reused and a flag is being set that can be queried by the application. =head1 RETURN VALUES The following return values can occur: =over 4 =item C<0> A new session was negotiated. =item C<1> A session was reused. =back =head1 SEE ALSO L<ssl(3)|ssl(3)>, L<SSL_set_session(3)|SSL_set_session(3)>, L<SSL_CTX_set_session_cache_mode(3)|SSL_CTX_set_session_cache_mode(3)> =cut
GaloisInc/hacrypto
src/C/libssl/HEAD/src/doc/ssl/SSL_session_reused.pod
Perl
bsd-3-clause
845
#!/usr/bin/env perl package DynECT::DNS_REST; $VERSION = "1.01"; $VERSION = eval $VERSION; use strict; use warnings; use LWP::UserAgent; use LWP::Protocol::https; use JSON; #TODO: Write documentation with POD #TODO: Add hash to store error messag #TODO: method to access last call #TODO: debug mode #Constructor sub new { #reference to self if first argument passed in my $classid = shift; my %con_args = @_; my $self = { #LWP User agent instance lwp => '', apitoken => undef, apiver => undef, #Current status meesage message => '', #Reference to a hash for JSON decodes of most recent result resultref => '', lasturi => '', lastmethod => '', lastrc => '', lasterrortype => '', }; $$self{'apiver'} = $con_args{ 'version' } if ( exists $con_args{ 'version' } ); $$self{'lwp'} = LWP::UserAgent->new; #diable redirect following as that is a special case with DynECT $$self{'lwp'}->max_redirect( '0' ); #reduce timeout from 180 seconds to 20 $$self{'lwp'}->timeout( '20' ); bless $self, $classid; return $self; } #API login an key generation sub login { #get reference to self #get params from call my ($self, $custn, $usern, $pass) = @_; #API login my %api_param = ( 'customer_name' => $custn, 'user_name' => $usern, 'password' => $pass, ); my $res = $self->request( 'OVERRIDESESSION', 'POST', \%api_param); if ( $res ) { $$self{'apitoken'} = $$self{'resultref'}{'data'}{'token'}; $$self{'message'} = 'Session successfully created'; } return $res; } sub keepalive { #get reference to self #get params from call my $self = shift @_; my $res = $self->request( 'OVERRIDESESSION', 'PUT'); $$self{ 'message' } = "Session keep-alive successful" if $res; return $res; } sub logout { #get self id my $self = shift @_; #TODO: Set message if API token not set #existance of the API key means we are logged in if ( defined $$self{'apitoken'} ) { #Logout of the API, to be nice my $res = $self->request( 'OVERRIDESESSION', 'DELETE'); if ( $res ) { $$self{ 'message' } = "Session logout successful"; undef $$self{'apitoken'}; $$self{'message'} = "Logout successful"; } else { $$self{'message'} = "API Session not available for logout. Please use ->login to create a session"; } return $res; } } sub request { my ($self, $uri, $method, $paramref) = @_; if (defined $paramref) { #weak check for correct paramater type unless ( ref($paramref) eq 'HASH' ) { $$self{'message'} = "Invalid paramater type. Please utilize a hash reference"; return 0; } } unless ((( $uri eq 'OVERRIDESESSION' ) && ( uc( $method ) eq 'POST' )) || $$self{ 'apitoken' } ) { $$self{'message'} = "API Session required for this method. Please use ->login to create a session"; return 0; } if ( $uri =~ /\/REST\/Session/ ) { $$self{'message'} = "Please use the ->login, ->keepalive, or ->logout for managing sessions"; return 0; } #catch internal use of session URI $uri = '/REST/Session/' if ( $uri eq 'OVERRIDESESSION' ); #store URI and method for accessors $$self{'lasturi'} = $uri; $$self{'lastmethod'} = uc ( $method ); #weak check for valid URI unless ( $uri =~ /^\/REST\// ) { $$self{'message'} = "Invalid REST URI. Correctly formatted URIs start with '/REST/"; return 0; } #Check for valid method type $method = uc( $method ); unless ( $method eq 'GET' || $method eq 'POST' || $method eq 'PUT' || $method eq 'DELETE' ) { $$self{ 'message' } = 'Invalid method type. Please use GET, PUT, POST, or DELETE.'; return 0; } my $api_request = HTTP::Request->new( $method , "https://api.dynect.net$uri"); $api_request->header ( 'Content-Type' => 'application/json' ); $api_request->header ( 'Auth-Token' => $$self{'apitoken'} ) if ( defined $$self{'apitoken'} ); $api_request->header ( 'Version' => $$self{'apiver'} ) if ( defined $$self{'apiver'} ); if (defined $paramref) { $api_request->content( to_json( $paramref ) ); } $api_request->header ( 'Content-Length' => length( $api_request->content ) ) if ( $method eq 'PUT' ); my $api_result = $$self{'lwp'}->request( $api_request ); $$self{'lastrc'} = $api_result->code; $$self{'resultref'} = decode_json ( $api_result->content ) if ( $api_result->is_success ); until ( $api_result->is_success ) { #Fail out if we get an error code and the content is not in JSON format (weak test) if ( $api_result->is_error && ( substr( $api_result->content, 0, 1 ) ne '{' ) ) { $$self{'message'} = "HTTPS Error: " . $api_result->status_line; $$self{'lasterrortype'} = 'HTTPS'; return 0; } #on initial redirect the result->code is the URI to the Job ID #Calling the /REST/Job will return JSON in the content of status elsif ( $api_result->is_redirect && ( substr( $api_result->content, 0, 1 ) ne '{' ) ) { sleep 1; $api_request = HTTP::Request->new('GET', "https://api.dynect.net" . $api_result->content); $api_request->header ( 'Content-Type' => 'application/json', 'Auth-Token' => $$self{'apitoken'} ); $api_request->header ( 'Version' => $$self{'apiver'} ) if ( defined $$self{'apiver'} ); $api_result = $$self{'lwp'}->request( $api_request ); $$self{'resultref'} = $api_result->code; redo; } else { #now safe to decode JSON $$self{'resultref'} = decode_json ( $api_result->content ); #loop until the job id comes back as success or program dies if ( $$self{'resultref'}{'status'} ne 'success' ) { if ( $$self{'resultref'}{'status'} ne 'incomplete' ) { #api stauts != ( sucess || incomplete ) would indicate an API failure #Blank out stored message to do appends $$self{'message'} = ''; $$self{'lasterrortype'} = 'API'; foreach my $msgref ( @{$$self{'resultref'}{'msgs'}} ) { if ( length $$self{'message'} == 0 ) { #put in header is still blank $$self{'message'} .= "API Error:"; } else { #put in double space if header already exists $$self{'message'} .= "\n"; } $$self{'message'} .= "\n\tInfo: $msgref->{'INFO'}" if $msgref->{'INFO'}; $$self{'message'} .= "\n\tLevel: $msgref->{'LVL'}" if $msgref->{'LVL'}; $$self{'message'} .= "\n\tError Code: $msgref->{'ERR_CD'}" if $msgref->{'ERR_CD'}; $$self{'message'} .= "\n\tSource: $msgref->{'SOURCE'}" if $msgref->{'SOURCE'}; }; $$self{'message'} .= "\n\nStopped "; return 0; } else { #status incomplete, wait 2 seconds and check again sleep 2; my $job_uri = "https://api.dynect.net/REST/Job/$$self{'resultref'}{'job_id'}/"; $api_request = HTTP::Request->new('GET',$job_uri); $api_request->header ( 'Content-Type' => 'application/json', 'Auth-Token' => $$self{'apitoken'} ); $api_request->header ( 'Version' => $$self{'apiver'} ) if ( defined $$self{'apiver'} ); $api_result = $$self{'lwp'}->request( $api_request ); $$self{'lastrc'} = $api_result->code; redo; } } } } $$self{'message'} = "Request ( $uri, $method) successful"; return 1; } sub version { my $self = shift; my $ver = shift; $$self{'apiver'} = $ver if ( defined $ver ); return $$self{'apiver'}; } sub message { my $self = shift; return $$self{'message'}; } #ALIAS TO RESULT sub response { my $self = shift; return $self->result( @_ ) ; } sub result { my $self = shift; return $$self{'resultref'}; } sub DESTROY { #call logout on destroy $_[0]->logout(); } 1;
dyninc-cs/DNS-Delay_FO
DynECT/DNS_REST.pm
Perl
bsd-3-clause
7,422
use 5.18.2; use strict; use warnings; use diagnostics; use DBI; use GJDataSource; my $ds = GJ::DataSource->new(1); my $tc_db = DBI->connect( $ds->tg, GJ::DataSource::User, GJ::DataSource::Pwd, { mysql_enable_utf8 => 1, 'RaiseError' => 1 } ) or die qq(unable to connect $GJ::DataSource::tc\n); while(<DATA>){ my $need_excute_sql = $_; if($need_excute_sql){ $tc_db->do($need_excute_sql); } } say "done!"; __DATA__ update `gcrm`.`uni_temporary_mis_info` set `foreign_userId` = '336531255' where `id` = '1'; update `gcrm`.`uni_temporary_mis_info` set `foreign_userId` = '249399986' where `id` = '1'; update `gcrm`.`uni_temporary_mis_info` set `foreign_userId` = '338703836' where `id` = '1'; update `gcrm`.`uni_temporary_mis_info` set `foreign_userId` = '275930025' where `id` = '1'; update `gcrm`.`uni_temporary_mis_info` set `foreign_userId` = '217413240' where `id` = '2';
lust4life/quick.dirty.perl
Perl STH/learn/DBIx-DataModel/dosql.pl
Perl
bsd-3-clause
1,078
package Paws::CloudSearch::DefineSuggesterResponse; use Moose; has Suggester => (is => 'ro', isa => 'Paws::CloudSearch::SuggesterStatus', required => 1); has _request_id => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudSearch::DefineSuggesterResponse =head1 ATTRIBUTES =head2 B<REQUIRED> Suggester => L<Paws::CloudSearch::SuggesterStatus> =head2 _request_id => Str =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/CloudSearch/DefineSuggesterResponse.pm
Perl
apache-2.0
436
package DDG::Spice::JrDevJobs; # ABSTRACT: Search for Junior Developer Jobs from JrDevJobs.com use DDG::Spice; triggers start => qw(jrdevjobs); spice to => 'https://www.jrdevjobs.com/jobs.json?query=$1'; spice is_cached => 1; spice wrap_jsonp_callback => 1; handle remainder => sub { s/(jobs)//; s/(job)//; s/(developer)//; return $_ if $_; return; }; 1;
MoriTanosuke/zeroclickinfo-spice
lib/DDG/Spice/JrDevJobs.pm
Perl
apache-2.0
378
# please insert nothing before this line: -*- mode: cperl; cperl-indent-level: 4; cperl-continued-statement-offset: 4; indent-tabs-mode: nil -*- package TestModperl::pnotes; use strict; use warnings FATAL => 'all'; use Apache2::RequestUtil (); use Apache2::ConnectionUtil (); use Apache::Test; use Apache::TestUtil; use Apache2::Const -compile => 'OK'; sub handler { my $r = shift; # make it ok to call ok() here while plan()ing elsewhere Apache::Test::init_test_pm($r); Test::_reset_globals() if Test->can('_reset_globals'); $Test::ntest = 1 + (26 * ($r->args - 1)); $Test::planned = 26; my $c = $r->connection; # we call this handler 3 times. # $r->pnotes('request') should be unset each time # $c->pnotes('connection') should be unset the first # time but set the second time due to the keepalive # request. the second request then cleans up after # itself, leaving $c->pnotes again unset at the # start of the third request if ($r->args == 2) { ok t_cmp($c->pnotes('connection'), 'CSET', '$c->pnotes() persists across keepalive requests'); } else { t_debug('testing $c->pnotes is empty'); ok (! $c->pnotes('connection')); } # $r->pnotes should be reset each time t_debug('testing $r->pnotes is empty'); ok (! $r->pnotes('request')); foreach my $map ({type => 'r', object => $r}, {type => 'c', object => $c}) { my $type = $map->{type}; my $o = $map->{object}; t_debug("testing $type->pnotes call"); ok $o->pnotes; ok t_cmp($o->pnotes('pnotes_foo', 'pnotes_bar'), 'pnotes_bar', "$type->pnotes(key,val)"); ok t_cmp($o->pnotes('pnotes_foo'), 'pnotes_bar', "$type->pnotes(key)"); ok t_cmp(ref($o->pnotes), 'HASH', "ref($type->pnotes)"); ok t_cmp($o->pnotes()->{'pnotes_foo'}, 'pnotes_bar', "$type->pnotes()->{}"); # unset the entry (but the entry remains with undef value) $o->pnotes('pnotes_foo', undef); ok t_cmp($o->pnotes('pnotes_foo'), undef, "unset $type contents"); my $exists = exists $o->pnotes->{'pnotes_foo'}; $exists = 1 if $] < 5.008001; # changed in perl 5.8.1 ok $exists; # now delete completely (possible only via the hash inteface) delete $o->pnotes()->{'pnotes_foo'}; ok t_cmp($o->pnotes('pnotes_foo'), undef, "deleted $type contents"); ok !exists $o->pnotes->{'pnotes_foo'}; # test blessed references, like DBI # DBD::DBM ships with DBI... if (have_module(qw(DBI DBD::DBM))) { my $dbh = DBI->connect('dbi:DBM:'); $o->pnotes(DBH => $dbh); my $pdbh = $o->pnotes('DBH'); ok t_cmp(ref($pdbh), 'DBI::db', "ref($type->pnotes('DBH'))"); my $quote = $pdbh->quote("quoth'me"); # see the DBI manpage for why quote() returns the string # wrapped in ' marks ok t_cmp($quote, "'quoth\\'me'", '$pdbh->quote() works'); } else { skip ('skipping $dbh retrival test - no DBI or DBD::DBM'); skip ('skipping $dbh->quote() test - no DBI or DBD::DBM'); } } # set pnotes so we can test unset on later connections $r->pnotes(request => 'RSET'); $c->pnotes(connection => 'CSET'); ok t_cmp($r->pnotes('request'), 'RSET', '$r->pnotes() set'); ok t_cmp($c->pnotes('connection'), 'CSET', '$c->pnotes() set'); Apache2::Const::OK; } 1; __END__
dreamhost/dpkg-ndn-perl-mod-perl
t/response/TestModperl/pnotes.pm
Perl
apache-2.0
3,729
package Google::Ads::AdWords::v201409::ConversionTracker::Status; use strict; use warnings; sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201409'}; # derivation by restriction use base qw( SOAP::WSDL::XSD::Typelib::Builtin::string); 1; __END__ =pod =head1 NAME =head1 DESCRIPTION Perl data type class for the XML Schema defined simpleType ConversionTracker.Status from the namespace https://adwords.google.com/api/adwords/cm/v201409. Status of the conversion tracker. The user cannot ADD or SET the status to {@code HIDDEN}. This clase is derived from SOAP::WSDL::XSD::Typelib::Builtin::string . SOAP::WSDL's schema implementation does not validate data, so you can use it exactly like it's base type. # Description of restrictions not implemented yet. =head1 METHODS =head2 new Constructor. =head2 get_value / set_value Getter and setter for the simpleType's value. =head1 OVERLOADING Depending on the simple type's base type, the following operations are overloaded Stringification Numerification Boolification Check L<SOAP::WSDL::XSD::Typelib::Builtin> for more information. =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201409/ConversionTracker/Status.pm
Perl
apache-2.0
1,178
#------------------------------------------------------------------------------ # File: PostScript.pm # # Description: Read PostScript meta information # # Revisions: 07/08/2005 - P. Harvey Created # # References: 1) http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf # 2) http://partners.adobe.com/public/developer/en/ps/5001.DSC_Spec.pdf # 3) http://partners.adobe.com/public/developer/en/illustrator/sdk/AI7FileFormat.pdf #------------------------------------------------------------------------------ package Image::ExifTool::PostScript; use strict; use vars qw($VERSION $AUTOLOAD); use Image::ExifTool qw(:DataAccess :Utils); $VERSION = '1.37'; sub WritePS($$); sub ProcessPS($$;$); # PostScript tag table %Image::ExifTool::PostScript::Main = ( PROCESS_PROC => \&ProcessPS, WRITE_PROC => \&WritePS, PREFERRED => 1, # always add these tags when writing GROUPS => { 2 => 'Image' }, # Note: Make all of these tags priority 0 since the first one found at # the start of the file should take priority (in case multiples exist) Author => { Priority => 0, Groups => { 2 => 'Author' }, Writable => 'string' }, BoundingBox => { Priority => 0 }, Copyright => { Priority => 0, Writable => 'string' }, #2 CreationDate => { Name => 'CreateDate', Priority => 0, Groups => { 2 => 'Time' }, Writable => 'string', PrintConv => '$self->ConvertDateTime($val)', PrintConvInv => '$self->InverseDateTime($val)', }, Creator => { Priority => 0, Writable => 'string' }, ImageData => { Priority => 0 }, For => { Priority => 0, Writable => 'string', Notes => 'for whom the document was prepared'}, Keywords => { Priority => 0, Writable => 'string' }, ModDate => { Name => 'ModifyDate', Priority => 0, Groups => { 2 => 'Time' }, Writable => 'string', PrintConv => '$self->ConvertDateTime($val)', PrintConvInv => '$self->InverseDateTime($val)', }, Pages => { Priority => 0 }, Routing => { Priority => 0, Writable => 'string' }, #2 Subject => { Priority => 0, Writable => 'string' }, Title => { Priority => 0, Writable => 'string' }, Version => { Priority => 0, Writable => 'string' }, #2 # these subdirectories for documentation only BeginPhotoshop => { Name => 'PhotoshopData', SubDirectory => { TagTable => 'Image::ExifTool::Photoshop::Main', }, }, BeginICCProfile => { Name => 'ICC_Profile', SubDirectory => { TagTable => 'Image::ExifTool::ICC_Profile::Main', }, }, begin_xml_packet => { Name => 'XMP', SubDirectory => { TagTable => 'Image::ExifTool::XMP::Main', }, }, TIFFPreview => { Binary => 1, Notes => q{ not a real tag ID, but used to represent the TIFF preview extracted from DOS EPS images }, }, BeginDocument => { Name => 'EmbeddedFile', SubDirectory => { TagTable => 'Image::ExifTool::PostScript::Main', }, Notes => 'extracted with ExtractEmbedded option', }, EmbeddedFileName => { Notes => q{ not a real tag ID, but the file name from a BeginDocument statement. Extracted with document metadata when ExtractEmbedded option is used }, }, ); # composite tags %Image::ExifTool::PostScript::Composite = ( GROUPS => { 2 => 'Image' }, # BoundingBox is in points, not pixels, # but use it anyway if ImageData is not available ImageWidth => { Desire => { 0 => 'Main:PostScript:ImageData', 1 => 'PostScript:BoundingBox', }, ValueConv => 'Image::ExifTool::PostScript::ImageSize(\@val, 0)', }, ImageHeight => { Desire => { 0 => 'Main:PostScript:ImageData', 1 => 'PostScript:BoundingBox', }, ValueConv => 'Image::ExifTool::PostScript::ImageSize(\@val, 1)', }, ); # add our composite tags Image::ExifTool::AddCompositeTags('Image::ExifTool::PostScript'); #------------------------------------------------------------------------------ # AutoLoad our writer routines when necessary # sub AUTOLOAD { return Image::ExifTool::DoAutoLoad($AUTOLOAD, @_); } #------------------------------------------------------------------------------ # Is this a PC system # Returns: true for PC systems my %isPC = (MSWin32 => 1, os2 => 1, dos => 1, NetWare => 1, symbian => 1, cygwin => 1); sub IsPC() { return $isPC{$^O}; } #------------------------------------------------------------------------------ # Get image width or height # Inputs: 0) value list ref (ImageData, BoundingBox), 1) true to get height sub ImageSize($$) { my ($vals, $getHeight) = @_; my ($w, $h); if ($$vals[0] and $$vals[0] =~ /^(\d+) (\d+)/) { ($w, $h) = ($1, $2); } elsif ($$vals[1] and $$vals[1] =~ /^(\d+) (\d+) (\d+) (\d+)/) { ($w, $h) = ($3 - $1, $4 - $2); } return $getHeight ? $h : $w; } #------------------------------------------------------------------------------ # Set PostScript format error warning # Inputs: 0) ExifTool object reference, 1) error string # Returns: 1 sub PSErr($$) { my ($et, $str) = @_; # set file type if not done already my $ext = $$et{FILE_EXT}; $et->SetFileType(($ext and $ext eq 'AI') ? 'AI' : 'PS'); $et->Warn("PostScript format error ($str)"); return 1; } #------------------------------------------------------------------------------ # Return input record separator to use for the specified file # Inputs: 0) RAF reference # Returns: Input record separator or undef on error sub GetInputRecordSeparator($) { my $raf = shift; my $pos = $raf->Tell(); # save current position my ($data, $sep); $raf->Read($data,256) or return undef; my ($a, $d) = (999,999); $a = pos($data), pos($data) = 0 if $data =~ /\x0a/g; $d = pos($data) if $data =~ /\x0d/g; my $diff = $a - $d; if ($diff eq 1) { $sep = "\x0d\x0a"; } elsif ($diff eq -1) { $sep = "\x0a\x0d"; } elsif ($diff > 0) { $sep = "\x0d"; } elsif ($diff < 0) { $sep = "\x0a"; } # else error $raf->Seek($pos, 0); # restore original position return $sep; } #------------------------------------------------------------------------------ # Decode comment from PostScript file # Inputs: 0) comment string, 1) RAF ref, 2) reference to lines array # 3) optional data reference for extra lines read from file # Returns: Decoded comment string (may be an array reference) # - handles multi-line comments and escape sequences sub DecodeComment($$$;$) { my ($val, $raf, $lines, $dataPt) = @_; $val =~ s/\x0d*\x0a*$//; # remove trailing CR, LF or CR/LF # check for continuation comments for (;;) { unless (@$lines) { my $buff; $raf->ReadLine($buff) or last; my $altnl = $/ eq "\x0d" ? "\x0a" : "\x0d"; if ($buff =~ /$altnl/) { chomp $buff if $/ eq "\x0d\x0a"; # remove DOS newline before splitting # split into separate lines @$lines = split /$altnl/, $buff, -1; # handle case of DOS newline data inside file using Unix newlines @$lines = ( $$lines[0] . $$lines[1] ) if @$lines == 2 and $$lines[1] eq $/; @$lines[-1] .= $/ if $/ eq "\x0d\x0a"; # add back trailing newline } else { push @$lines, $buff; } } last unless $$lines[0] =~ /^%%\+/; # is the next line a continuation? $$dataPt .= $$lines[0] if $dataPt; # add to data if necessary $$lines[0] =~ s/\x0d*\x0a*$//; # remove trailing CR, LF or CR/LF $val .= substr(shift(@$lines), 3); # add to value (without leading "%%+") } my @vals; # handle bracketed string values if ($val =~ s/^\((.*)\)$/$1/) { # remove brackets if necessary # split into an array of strings if necessary my $nesting = 1; while ($val =~ /(\(|\))/g) { my $bra = $1; my $pos = pos($val) - 2; my $backslashes = 0; while ($pos and substr($val, $pos, 1) eq '\\') { --$pos; ++$backslashes; } next if $backslashes & 0x01; # escaped if odd number if ($bra eq '(') { ++$nesting; } else { --$nesting; unless ($nesting) { push @vals, substr($val, 0, pos($val)-1); $val = substr($val, pos($val)); ++$nesting if $val =~ s/\s*\(//; } } } push @vals, $val; foreach $val (@vals) { # decode escape sequences in bracketed strings # (similar to code in PDF.pm, but without line continuation) while ($val =~ /\\(.)/sg) { my $n = pos($val) - 2; my $c = $1; my $r; if ($c =~ /[0-7]/) { # get up to 2 more octal digits $c .= $1 if $val =~ /\G([0-7]{1,2})/g; # convert octal escape code $r = chr(oct($c) & 0xff); } else { # convert escaped characters ($r = $c) =~ tr/nrtbf/\n\r\t\b\f/; } substr($val, $n, length($c)+1) = $r; # continue search after this character pos($val) = $n + length($r); } } $val = @vals > 1 ? \@vals : $vals[0]; } return $val; } #------------------------------------------------------------------------------ # Unescape PostScript string # Inputs: 0) string # Returns: unescaped string sub UnescapePostScript($) { my $str = shift; # decode escape sequences in literal strings while ($str =~ /\\(.)/sg) { my $n = pos($str) - 2; my $c = $1; my $r; if ($c =~ /[0-7]/) { # get up to 2 more octal digits $c .= $1 if $str =~ /\G([0-7]{1,2})/g; # convert octal escape code $r = chr(oct($c) & 0xff); } elsif ($c eq "\x0d") { # the string is continued if the line ends with '\' # (also remove "\x0d\x0a") $c .= $1 if $str =~ /\G(\x0a)/g; $r = ''; } elsif ($c eq "\x0a") { $r = ''; } else { # convert escaped characters ($r = $c) =~ tr/nrtbf/\n\r\t\b\f/; } substr($str, $n, length($c)+1) = $r; # continue search after this character pos($str) = $n + length($r); } return $str; } #------------------------------------------------------------------------------ # Extract information from EPS, PS or AI file # Inputs: 0) ExifTool object reference, 1) dirInfo reference, 2) optional tag table ref # Returns: 1 if this was a valid PostScript file sub ProcessPS($$;$) { my ($et, $dirInfo, $tagTablePtr) = @_; my $raf = $$dirInfo{RAF}; my $embedded = $et->Options('ExtractEmbedded'); my ($data, $dos, $endDoc, $fontTable, $comment); # allow read from data $raf = new File::RandomAccess($$dirInfo{DataPt}) unless $raf; # # determine if this is a postscript file # $raf->Read($data, 4) == 4 or return 0; # accept either ASCII or DOS binary postscript file format return 0 unless $data =~ /^(%!PS|%!Ad|%!Fo|\xc5\xd0\xd3\xc6)/; if ($data =~ /^%!Ad/) { # I've seen PS files start with "%!Adobe-PS"... return 0 unless $raf->Read($data, 6) == 6 and $data eq "obe-PS"; } elsif ($data =~ /^\xc5\xd0\xd3\xc6/) { # process DOS binary file header # - save DOS header then seek ahead and check PS header $raf->Read($dos, 26) == 26 or return 0; SetByteOrder('II'); unless ($raf->Seek(Get32u(\$dos, 0), 0) and $raf->Read($data, 4) == 4 and $data eq '%!PS') { return PSErr($et, 'invalid header'); } } else { # check for PostScript font file (PFA or PFB) my $d2; $data .= $d2 if $raf->Read($d2,12); if ($data =~ /^%!(PS-(AdobeFont-|Bitstream )|FontType1-)/) { $et->SetFileType('PFA'); # PostScript ASCII font file $fontTable = GetTagTable('Image::ExifTool::Font::PSInfo'); # PostScript font files may contain an unformatted comments which may # contain useful information, so accumulate these for the Comment tag $comment = 1; } $raf->Seek(-length($data), 1); } # # set the newline type based on the first newline found in the file # local $/ = GetInputRecordSeparator($raf); $/ or return PSErr($et, 'invalid PS data'); # set file type (PostScript or EPS) $raf->ReadLine($data) or $data = ''; my $type; if ($data =~ /EPSF/) { $type = 'EPS'; } else { # read next line to see if this is an Illustrator file my $line2; my $pos = $raf->Tell(); if ($raf->ReadLine($line2) and $line2 =~ /^%%Creator: Adobe Illustrator/) { $type = 'AI'; } else { $type = 'PS'; } $raf->Seek($pos, 0); } $et->SetFileType($type); # # extract TIFF information from DOS header # $tagTablePtr or $tagTablePtr = GetTagTable('Image::ExifTool::PostScript::Main'); if ($dos) { my $base = Get32u(\$dos, 16); if ($base) { my $pos = $raf->Tell(); # extract the TIFF preview my $len = Get32u(\$dos, 20); my $val = $et->ExtractBinary($base, $len, 'TIFFPreview'); if (defined $val and $val =~ /^(MM\0\x2a|II\x2a\0|Binary)/) { $et->HandleTag($tagTablePtr, 'TIFFPreview', $val); } else { $et->Warn('Bad TIFF preview image'); } # extract information from TIFF in DOS header # (set Parent to '' to avoid setting FileType tag again) my %dirInfo = ( Parent => '', RAF => $raf, Base => $base, ); $et->ProcessTIFF(\%dirInfo) or $et->Warn('Bad embedded TIFF'); # position file pointer to extract PS information $raf->Seek($pos, 0); } } # # parse the postscript # my ($buff, $mode, $beginToken, $endToken, $docNum, $subDocNum, $changedNL); my (@lines, $altnl); if ($/ eq "\x0d") { $altnl = "\x0a"; } else { $/ = "\x0a"; # end on any LF (even if DOS CR+LF) $altnl = "\x0d"; } for (;;) { if (@lines) { $data = shift @lines; } else { $raf->ReadLine($data) or last; # check for alternate newlines as efficiently as possible if ($data =~ /$altnl/) { if (length($data) > 500000 and IsPC()) { # Windows can't split very long lines due to poor memory handling, # so re-read the file with the other newline character instead # (slower but uses less memory) unless ($changedNL) { $changedNL = 1; my $t = $/; $/ = $altnl; $altnl = $t; $raf->Seek(-length($data), 1); next; } } else { # split into separate lines @lines = split /$altnl/, $data, -1; $data = shift @lines; if (@lines == 1 and $lines[0] eq $/) { # handle case of DOS newline data inside file using Unix newlines $data .= $lines[0]; undef @lines; } } } } undef $changedNL; if ($mode) { if (not $endToken) { $buff .= $data; next unless $data =~ m{<\?xpacket end=.(w|r).\?>($/|$)}; } elsif ($data !~ /^$endToken/i) { if ($mode eq 'XMP') { $buff .= $data; } elsif ($mode eq 'Document') { # ignore embedded documents, but keep track of nesting level $docNum .= '-1' if $data =~ /^$beginToken/; } else { # data is ASCII-hex encoded $data =~ tr/0-9A-Fa-f//dc; # remove all but hex characters $buff .= pack('H*', $data); # translate from hex } next; } elsif ($mode eq 'Document') { $docNum =~ s/-?\d+$//; # decrement document nesting level # done with Document mode if we are back at the top level undef $mode unless $docNum; next; } } elsif ($endDoc and $data =~ /^$endDoc/i) { $docNum =~ s/-?(\d+)$//; # decrement nesting level $subDocNum = $1; # remember our last sub-document number $$et{DOC_NUM} = $docNum; undef $endDoc unless $docNum; # done with document if top level next; } elsif ($data =~ /^(%{1,2})(Begin)(_xml_packet|Photoshop|ICCProfile|Document|Binary)/i) { # the beginning of a data block my %modeLookup = ( _xml_packet => 'XMP', photoshop => 'Photoshop', iccprofile => 'ICC_Profile', document => 'Document', binary => undef, # (we will try to skip this) ); $mode = $modeLookup{lc $3}; unless ($mode) { if (not @lines and $data =~ /^%{1,2}BeginBinary:\s*(\d+)/i) { $raf->Seek($1, 1) or last; # skip binary data } next; } $buff = ''; $beginToken = $1 . $2 . $3; $endToken = $1 . ($2 eq 'begin' ? 'end' : 'End') . $3; if ($mode eq 'Document') { # this is either the 1st sub-document or Nth document if ($docNum) { # increase nesting level $docNum .= '-' . (++$subDocNum); } else { # this is the Nth document $docNum = $$et{DOC_COUNT} + 1; } $subDocNum = 0; # new level, so reset subDocNum next unless $embedded; # skip over this document # set document number for family 4-7 group names $$et{DOC_NUM} = $docNum; $$et{LIST_TAGS} = { }; # don't build lists across different documents $$et{PROCESSED} = { }; # re-initialize processed directory lookup too $endDoc = $endToken; # parse to EndDocument token # reset mode to allow parsing into sub-directories undef $endToken; undef $mode; # save document name if available if ($data =~ /^$beginToken:\s+([^\n\r]+)/i) { my $docName = $1; # remove brackets if necessary $docName = $1 if $docName =~ /^\((.*)\)$/; $et->HandleTag($tagTablePtr, 'EmbeddedFileName', $docName); } } next; } elsif ($data =~ /^<\?xpacket begin=.{7,13}W5M0MpCehiHzreSzNTczkc9d/) { # pick up any stray XMP data $mode = 'XMP'; $buff = $data; undef $endToken; # no end token (just look for xpacket end) # XMP could be contained in a single line (if newlines are different) next unless $data =~ m{<\?xpacket end=.(w|r).\?>($/|$)}; } elsif ($data =~ /^%%?(\w+): ?(.*)/s and $$tagTablePtr{$1}) { my ($tag, $val) = ($1, $2); # only allow 'ImageData' to have single leading '%' next unless $data =~ /^%%/ or $1 eq 'ImageData'; # decode comment string (reading continuation lines if necessary) $val = DecodeComment($val, $raf, \@lines); $et->HandleTag($tagTablePtr, $tag, $val); next; } elsif ($embedded and $data =~ /^%AI12_CompressedData/) { # the rest of the file is compressed unless (eval { require Compress::Zlib }) { $et->Warn('Install Compress::Zlib to extract compressed embedded data'); last; } # seek back to find the start of the compressed data in the file my $tlen = length($data) + @lines; $tlen += length $_ foreach @lines; my $backTo = $raf->Tell() - $tlen - 64; $backTo = 0 if $backTo < 0; last unless $raf->Seek($backTo, 0) and $raf->Read($data, 2048); last unless $data =~ s/.*?%AI12_CompressedData//; my $inflate = Compress::Zlib::inflateInit(); $inflate or $et->Warn('Error initializing inflate'), last; # generate a PS-like file in memory from the compressed data my $verbose = $et->Options('Verbose'); if ($verbose > 1) { $et->VerboseDir('AI12_CompressedData (first 4kB)'); $et->VerboseDump(\$data); } # remove header if it exists (Windows AI files only) $data =~ s/^.{0,256}EndData[\x0d\x0a]+//s; my $val; for (;;) { my ($v2, $stat) = $inflate->inflate($data); $stat == Compress::Zlib::Z_STREAM_END() and $val .= $v2, last; $stat != Compress::Zlib::Z_OK() and undef($val), last; if (defined $val) { $val .= $v2; } elsif ($v2 =~ /^%!PS/) { $val = $v2; } else { # add postscript header (for file recognition) if it doesn't exist $val = "%!PS-Adobe-3.0$/" . $v2; } $raf->Read($data, 65536) or last; } defined $val or $et->Warn('Error inflating AI compressed data'), last; if ($verbose > 1) { $et->VerboseDir('Uncompressed AI12 Data'); $et->VerboseDump(\$val); } # extract information from embedded images in the uncompressed data $val = # add PS header in case it needs one ProcessPS($et, { DataPt => \$val }); last; } elsif ($fontTable) { if (defined $comment) { # extract initial comments from PostScript Font files if ($data =~ /^%\s+(.*?)[\x0d\x0a]/) { $comment .= "\n" if $comment; $comment .= $1; next; } elsif ($data !~ /^%/) { # stop extracting comments at the first non-comment line $et->FoundTag('Comment', $comment) if length $comment; undef $comment; } } if ($data =~ m{^\s*/(\w+)\s*(.*)} and $$fontTable{$1}) { my ($tag, $val) = ($1, $2); if ($val =~ /^\((.*)\)/) { $val = UnescapePostScript($1); } elsif ($val =~ m{/?(\S+)}) { $val = $1; } $et->HandleTag($fontTable, $tag, $val); } elsif ($data =~ /^currentdict end/) { # only extract tags from initial FontInfo dict undef $fontTable; } next; } else { next; } # extract information from buffered data my %dirInfo = ( DataPt => \$buff, DataLen => length $buff, DirStart => 0, DirLen => length $buff, Parent => 'PostScript', ); my $subTablePtr = GetTagTable("Image::ExifTool::${mode}::Main"); unless ($et->ProcessDirectory(\%dirInfo, $subTablePtr)) { $et->Warn("Error processing $mode information in PostScript file"); } undef $buff; undef $mode; } $mode = 'Document' if $endDoc and not $mode; $mode and PSErr($et, "unterminated $mode data"); return 1; } #------------------------------------------------------------------------------ # Extract information from EPS file # Inputs: 0) ExifTool object reference, 1) dirInfo reference # Returns: 1 if this was a valid PostScript file sub ProcessEPS($$) { return ProcessPS($_[0],$_[1]); } 1; # end __END__ =head1 NAME Image::ExifTool::PostScript - Read PostScript meta information =head1 SYNOPSIS This module is loaded automatically by Image::ExifTool when required. =head1 DESCRIPTION This code reads meta information from EPS (Encapsulated PostScript), PS (PostScript) and AI (Adobe Illustrator) files. =head1 AUTHOR Copyright 2003-2014, Phil Harvey (phil at owl.phy.queensu.ca) This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 REFERENCES =over 4 =item L<http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf> =item L<http://partners.adobe.com/public/developer/en/ps/5001.DSC_Spec.pdf> =item L<http://partners.adobe.com/public/developer/en/illustrator/sdk/AI7FileFormat.pdf> =back =head1 SEE ALSO L<Image::ExifTool::TagNames/PostScript Tags>, L<Image::ExifTool(3pm)|Image::ExifTool> =cut
pericles-project/pet
nativeTools/exiftool_OSX/lib/Image/ExifTool/PostScript.pm
Perl
apache-2.0
25,919
# # This file is part of Debug-Fork-Tmux # # This software is Copyright (c) 2013 by Peter Vereshagin. # # This is free software, licensed under: # # The (three-clause) BSD License # package # Devel::AssertOS; use Devel::CheckOS; use strict; use vars qw($VERSION); $VERSION = '1.21'; # localising prevents the warningness leaking out of this module local $^W = 1; # use warnings is a 5.6-ism =head1 NAME Devel::AssertOS - require that we are running on a particular OS =head1 DESCRIPTION Devel::AssertOS is a utility module for Devel::CheckOS and Devel::AssertOS::*. It is nothing but a magic C<import()> that lets you do this: use Devel::AssertOS qw(Linux FreeBSD Cygwin); which will die unless the platform the code is running on is Linux, FreeBSD or Cygwin. To assert that the OS is B<not> a specific platform, prepend the platform name with a minus sign. For example, to run on anything but Amiga, do: use Devel::AssertOS qw(-Amiga); =cut sub import { shift; die("Devel::AssertOS needs at least one parameter\n") unless (@_); my @oses = @_; my ( @must, @must_not ); for my $os (@oses) { if ( $os =~ s/^-// ) { push @must_not, $os; } else { push @must, $os; } } Devel::CheckOS::die_if_os_is(@must_not) if @must_not; Devel::CheckOS::die_if_os_isnt(@must) if @must; } =head1 BUGS and FEEDBACK I welcome feedback about my code, including constructive criticism. Bug reports should be made using L<http://rt.cpan.org/> or by email. You will need to include in your bug report the exact value of $^O, what the OS is called (eg Windows Vista 64 bit Ultimate Home Edition), and, if relevant, what "OS family" it should be in and who wrote it. If you are feeling particularly generous you can encourage me in my open source endeavours by buying me something from my wishlist: L<http://www.cantrell.org.uk/david/wishlist/> =head1 SEE ALSO $^O in L<perlvar> L<perlport> L<Devel::CheckOS> L<Devel::AssertOS::Extending> The use-devel-assertos script L<Module::Install::AssertOS> =head1 AUTHOR David Cantrell E<lt>F<david@cantrell.org.uk>E<gt> Thanks to David Golden for suggesting that I add this utility module. =head1 COPYRIGHT and LICENCE Copyright 2007 David Cantrell This software is free-as-in-speech software, and may be used, distributed, and modified under the terms of either the GNU General Public Licence version 2 or the Artistic Licence. It's up to you which one you use. The full text of the licences can be found in the files GPL2.txt and ARTISTIC.txt, respectively. =head1 CONSPIRACY This module is also free-as-in-mason software. =cut $^O;
petr999/Debug-Fork-Tmux
inc/Devel/AssertOS.pm
Perl
bsd-3-clause
2,702
#!/usr/bin/perl -w # Saulo Aflitos # 2009 06 18 19 47 #TODO: TRANSFORME IN INSTANCIABLE MODULE SO ALL COMMANDS CAM BE SENT TO EACH INSTANCE use strict; package DBIconnect; use lib "./"; use loadconf; use DBI; my %pref = &loadconf::loadConf; my $location = "local"; sub DBIconnect { my $database = $_[0] || $pref{"database"}; # mysql database my $host = $pref{"host"}; # mysql host my $port = $pref{"port"}; # mysql port my $user = $pref{"user"}; # mysql user my $pw = $pref{"pw"}; # mysql pw if ($location eq "local") { return DBIconnectLocal($database, $host, $port, $user, $pw); } elsif ($location eq "cloud") { return DBIconnectCloud($database, $host, $port, $user, $pw); } else { my $connectStr = "DBI:mysql:database=$database"; if ((defined $host) && ($host ne "localhost") && ($host ne "127.0.0.1")) { $connectStr .= ";host=$host;port=$port"; } my $dbh = DBI->connect($connectStr, $user, $pw, {RaiseError=>1, PrintError=>1, AutoCommit=>0}) or die "COULD NOT CONNECT TO DATABASE $database $host $user: $! $DBI::errstr"; return $dbh; } } sub DBIconnectLocal { my $database = $_[0]; # mysql database my $host = $_[1]; # mysql host my $port = $_[2]; # mysql port my $user = $_[3]; # mysql user my $pw = $_[4]; # mysql pw my $connectStr = "DBI:mysql:database=$database"; if ((defined $host) && ($host ne "localhost") && ($host ne "127.0.0.1")) { $connectStr .= ";host=$host;port=$port"; } my $dbh = DBI->connect($connectStr, $user, $pw, {RaiseError=>1, PrintError=>1, AutoCommit=>0}) or die "COULD NOT CONNECT TO DATABASE $database $host $user: $! $DBI::errstr"; return $dbh; } sub DBIconnectCloud { } 1;
sauloal/projects
probes/hadoop2/filters/DBIconnect.pm
Perl
mit
1,793
# # Copyright 2017 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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. # package network::riverbed::steelhead::snmp::mode::servicestatus; use base qw(centreon::plugins::mode); use strict; use warnings; my %states = ( 0 => ['none', 'CRITICAL'], 1 => ['unmanaged', 'CRITICAL'], 2 => ['running', 'OK'], 3 => ['sentCom1', 'CRITICAL'], 4 => ['sentTerm1', 'CRITICAL'], 5 => ['sentTerm2', 'CRITICAL'], 6 => ['sentTerm3', 'CRITICAL'], 7 => ['pending', 'CRITICAL'], 8 => ['stopped', 'CRITICAL'], ); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '0.1'; return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } sub run { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; my $oid_optServiceStatus = '.1.3.6.1.4.1.17163.1.1.2.8.0'; my $result = $self->{snmp}->get_leef(oids => [ $oid_optServiceStatus ], nothing_quit => 1); $self->{output}->output_add(severity => ${$states{$result->{$oid_optServiceStatus}}}[1], short_msg => sprintf("Optimization service status is '%s'", ${$states{$result->{$oid_optServiceStatus}}}[0])); $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check the current status of the optimization service (STEELHEAD-MIB). =over 8 =back =cut
nichols-356/centreon-plugins
network/riverbed/steelhead/snmp/mode/servicestatus.pm
Perl
apache-2.0
2,201
package AsposeCellsCloud::Object::FillFormatResponse; require 5.6.0; use strict; use warnings; use utf8; use JSON qw(decode_json); use Data::Dumper; use Module::Runtime qw(use_module); use Log::Any qw($log); use Date::Parse; use DateTime; use base "AsposeCellsCloud::Object::BaseObject"; # # # #NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. # my $swagger_types = { 'FillFormat' => 'FillFormat', 'Code' => 'string', 'Status' => 'string' }; my $attribute_map = { 'FillFormat' => 'FillFormat', 'Code' => 'Code', 'Status' => 'Status' }; # new object sub new { my ($class, %args) = @_; my $self = { # 'FillFormat' => $args{'FillFormat'}, # 'Code' => $args{'Code'}, # 'Status' => $args{'Status'} }; return bless $self, $class; } # get swagger type of the attribute sub get_swagger_types { return $swagger_types; } # get attribute mappping sub get_attribute_map { return $attribute_map; } 1;
farooqsheikhpk/Aspose.Cells-for-Cloud
SDKs/Aspose.Cells-Cloud-SDK-for-Perl/lib/AsposeCellsCloud/Object/FillFormatResponse.pm
Perl
mit
1,060
=pod =head1 NAME d2i_DHparams, i2d_DHparams - PKCS#3 DH parameter functions =head1 SYNOPSIS #include <openssl/dh.h> DH *d2i_DHparams(DH **a, unsigned char **pp, long length); int i2d_DHparams(DH *a, unsigned char **pp); =head1 DESCRIPTION These functions decode and encode PKCS#3 DH parameters using the DHparameter structure described in PKCS#3. Otherwise these behave in a similar way to d2i_X509() and i2d_X509() described in the L<d2i_X509(3)> manual page. =head1 SEE ALSO L<d2i_X509(3)> =head1 COPYRIGHT Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. Licensed under the OpenSSL license (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at L<https://www.openssl.org/source/license.html>. =cut
openweave/openweave-core
third_party/openssl/openssl/doc/crypto/d2i_DHparams.pod
Perl
apache-2.0
843
package Perun::PropagationStatsReaderAgent; use strict; use warnings; use Perun::Common; my $manager = 'propagationStatsReader'; use fields qw(_agent _manager); sub new { my $self = fields::new(shift); $self->{_agent} = shift; $self->{_manager} = $manager; return $self; } sub getTaskResultsForDestinations { return Perun::Common::callManagerMethod('getTaskResultsForDestinations', '[]TaskResult', @_); } 1;
Holdo/perun
perun-rpc/src/main/perl/Perun/PropagationStatsReaderAgent.pm
Perl
bsd-2-clause
421
print "The first number is: ".findConsecNbrsWithPrimeFactors(4); sub findConsecNbrsWithPrimeFactors { my $nbrPrimeFactors=shift; for(my $idxPrimeFactors=1;$idxPrimeFactors<=$nbrPrimeFactors;$idxPrimeFactors++) { push @primeFactors,1; } for(my $nbrNew=2;;$nbrNew++) { print "."; &findPrimes($nbrNew); $primeFactors[$#primeFactors] = &findNbrPrimeFactorsForNum($nbrNew); $invalidSeq=0; for(my $idxPrimeFactors=0;$idxPrimeFactors<$#primeFactors;$idxPrimeFactors++) { if($primeFactors[$idxPrimeFactors]!=$nbrPrimeFactors) { $invalidSeq=1; } $primeFactors[$idxPrimeFactors]=$primeFactors[$idxPrimeFactors+1]; } if($primeFactors[$#idxPrimeFactors]!=$nbrPrimeFactors) { $invalidSeq=1; } if($invalidSeq==0) { for(my $idxNbr=$nbrPrimeFactors-1;$idxNbr>-1;$idxNbr--) { print "".($nbrNew-$idxNbr)." "; } print "\n"; return ($nbrNew - $nbrPrimeFactors + 1); } } } <>; sub findPrimes { my $maxPrime=shift; if($minPrime<2) { $minPrime=2;} # print "Finding prime numbers in the range ($minPrime <= n <= $maxPrime)...\n"; # print "Initializing...\n"; for(my $num=$minPrime;$num<=$maxPrime;$num++) { $primes{$num} =''; } # print "Eliminating non-primes...\n"; foreach $idxPrime(keys %primes) { for($ctr=2;$ctr*$idxPrime<=$maxPrime;$ctr++) { delete $primes{$ctr*$idxPrime}; } } for($num=$minPrime;$num<$maxPrime;$num++) { for($ctr=2;$ctr*$num<=$maxPrime;$ctr++) { delete $primes{$num*$ctr}; } } $minPrime=$maxPrime+1; } sub findPrimeFactorsForNum { my $numIn = shift; my $num = $numIn; my %primesForNum = (); my $primeToTest; FindPrimeFactors: foreach $primeToTest(keys %primes) { while($num % $primeToTest == 0) { $primesForNum{$primeToTest}++; $num /= $primeToTest; if($num == 1) { last FindPrimeFactors; } } } return \%primesForNum; } sub findNbrPrimeFactorsForNum { my $numIn = shift; my $num = $numIn; my %primesForNum = (); my $primeToTest; FindPrimeFactors: foreach $primeToTest(keys %primes) { while($num % $primeToTest == 0) { $primesForNum{$primeToTest}++; $num /= $primeToTest; if($num == 1) { last FindPrimeFactors; } } } return scalar(keys %primesForNum); }
cjbednarzyk/project-euler
47.pl
Perl
mit
2,331
#!/usr/bin/perl #Sean Wagner #BA3G.pl #finds a Eulerian path for a graph given properly formatted input use strict; use Data::Dumper qw(Dumper); #main graph my @graph; #input list my $inputS = "0 -> 2;1 -> 3;2 -> 1;3 -> 0,4;6 -> 3,7;7 -> 8;8 -> 9;9 -> 6"; my @masterInputArr = split /;/,$inputS; my @listOfTrapNodes; #NOW TO ACTUALLY LOAD THE GRAPH while(@masterInputArr) { my $currentLine = pop @masterInputArr; #break based on '->' my @lineArr = split / -> /,$currentLine; my $originNode = $lineArr[0]; my $destList = $lineArr[1]; #break based on comma my @destinationArr = split /,/,$destList; #print $originNode,": ",scalar @destinationArr,"\n"; $graph[$originNode] = \@destinationArr; } for(my $i = 0; $i < scalar @graph; $i++) { if(defined $graph[$i]) { #uhh } else { #i am aware of how ugly this code is my @emptyList = (); $graph[$i] = \@emptyList; push @listOfTrapNodes, $i; } } #print Dumper @graph; for(my $i = 0; $i < scalar @graph; $i++) { #this goes through and just shows me the graph setup my $tempRef = $graph[$i]; print $i,": "; my @currArr = @$tempRef; for(my $j; $j < scalar @currArr; $j++) { print $currArr[$j],","; } print "\n"; } #AT THIS POINT, THE GRAPH IS LOADED INTO MATRIX PROPERLY #now to determine how to find the path #need to keep track of path and to visit #adopted algorithm from popular Hierholzer algorithm print "\n\n\n"; my @allPaths; #storage for results my $longestResult = 0; #for printing only relevant solutions for(my $z = 0; $z < scalar @graph; $z++) { my @newGraph = @graph;#first need to copy the graph to new graph for(my $l = 0; $l < scalar @newGraph; $l++) { my @arr = @{@newGraph[$l]}; my @newArr = @arr; $newGraph[$l] = \@newArr; } my @next; #list of possible places to go in backtrack situations my @result; #the route taken my $currentNode = $z; #start at all possible nodes #print scalar @{@graph[$currentNode]},"\n"; while((scalar @next > 0) || ((scalar @{@newGraph[$currentNode]})>0)){ my $numOptions = scalar @{@newGraph[$currentNode]}; #if it has options, then explore those if($numOptions > 0){ push @next, $currentNode; my $newNodeToGo = pop @{@newGraph[$currentNode]}; $currentNode = $newNodeToGo; } #otherwise, we can add this to path and keep going elsif (scalar @next > 0){ push @result,$currentNode; $currentNode = pop @next; } } #store the results push @result,$currentNode; my $printS = ""; #get it formatted to print while(@result) { $printS = $printS . (pop @result) . "->"; } $printS = substr($printS,0,-2); #make sure that we keep track of longest solution if(length($printS)>$longestResult) { $longestResult = length($printS); } push @allPaths, $printS; } #sort the output @allPaths = reverse(sort(@allPaths)); while(@allPaths) { #go through and print the relevant ones my $currentString = pop @allPaths; if(length($currentString) < $longestResult) { next; } #finish printing print "\n",$currentString,"\n"; } print "\n\n\n";
scwagner94/Rosalind-Problems
BA3G.pl
Perl
mit
3,101
#!/bin/bash # ######################################################## # # Nagios Plugin to check file changes # # ######################################################## # # version: 1.0 # # author: João Andrade (joaodeaps@gmail.com) # # ######################################################## # # Constants MSG_OK="OK - No change in file" MSG_WARNING="WARNING - File changed!" MSG_UNKNOWN="UNKNOWN - Error! Is argument a path to a file?" # Exit Codes STATE_OK=0 STATE_WARNING=1 STATE_UNKNOWN=3 # Variables FILE_EXISTS=0 FILE=$1 # Main ####################################################### # Check if it is a file if [ ! -f $FILE ]; then echo $MSG_UNKNOWN exit $STATE_UNKNOWN fi # Save to FILE_NAME AND TMP_FILE the name of the file and the temporary file path FILE_NAME=$(basename $FILE) TMP_FILE="/var/tmp/$FILE_NAME" # Hexadecimal value of the file FILE_HEX=$(openssl dgst -md5 -hex $FILE | cut -d' ' -f 2) # Check if it is the first time the file is being checked # If already exists a file with the same name in the "/var/tmp/" folder, it means # that the file already been used if [ -f $TMP_FILE ]; then # Hexadecimal value of the last check to the file TMP_HEX=$(<$TMP_FILE) # Compare if the two hexadecimal values are igual # and returns the corresponding message if [ "$TMP_HEX" == "$FILE_HEX" ]; then echo $MSG_OK exit $STATE_OK else echo $MSG_WARNING exit $STATE_WARNING fi else # Creates the new temporary file with the new hexadecimal value of the file echo $FILE_HEX > $TMP_FILE echo $MSG_OK exit $STATE_OK fi
deaps/NAGIOS_Scripts
check_file_change.pl
Perl
mit
1,644
####################################################################### # UnalignedBlock.pm ####################################################################### # # thanks to Tom Hladish for the original version # # $Id: UnalignedBlock.pm,v 1.25 2012/02/10 13:28:28 astoltzfus Exp $ #################### START POD DOCUMENTATION ########################## =head1 NAME Bio::NEXUS::UnalignedBlock - Represents an UNALIGNED block of a NEXUS file =head1 SYNOPSIS if ( $type =~ /unaligned/i ) { $block_object = new Bio::NEXUS::UnalignedBlock($type, $block, $verbose); } =head1 DESCRIPTION This is a class representing an unaligned block in NEXUS file =head1 FEEDBACK All feedback (bugs, feature enhancements, etc.) is greatly appreciated. =head1 AUTHORS Thomas Hladish (tjhladish at yahoo) =head1 VERSION $Id: UnalignedBlock.pm,v 1.25 2012/02/10 13:28:28 astoltzfus Exp $ =head1 METHODS =cut package Bio::NEXUS::UnalignedBlock; use strict; #use Data::Dumper; # XXX this is not used, might as well not import it! #use Carp;# XXX this is not used, might as well not import it! use Bio::NEXUS::Functions; use Bio::NEXUS::TaxUnitSet; use Bio::NEXUS::Matrix; use Bio::NEXUS::Util::Exceptions; use vars qw(@ISA $VERSION $AUTOLOAD); use Bio::NEXUS; $VERSION = $Bio::NEXUS::VERSION; @ISA = qw(Bio::NEXUS::Matrix); my $logger = Bio::NEXUS::Util::Logger->new(); =head2 new Title : new Usage : block_object = new Bio::NEXUS::UnalignedBlock($block_type, $commands, $verbose, $taxlabels); Function: Creates a new Bio::NEXUS::UnalignedBlock object Returns : Bio::NEXUS::UnalignedBlock object Args : type (string), the commands/comments to parse (array ref), and a verbose flag (0 or 1) =cut sub new { my ( $class, $type, $commands, $verbose, $taxa ) = @_; unless ($type) { ( $type = lc $class ) =~ s/Bio::NEXUS::(.+)Block/$1/i; } my $self = { type => $type }; bless $self, $class; $self->set_taxlabels($taxa); $self->{'otuset'} = new Bio::NEXUS::TaxUnitSet(); $self->_parse_block( $commands, $verbose ) if ( ( defined $commands ) and @$commands ); return $self; } =begin comment Title : _parse_format Usage : $format = $self->_parse_format($buffer); (private) Function: Extracts format values from line and stores values in a hash Returns : hash of formats Args : buffer (string) Methods : Separates formats by whitespace and creates hash containing key = format name and value = format value. =end comment =cut sub _parse_format { my ( $self, $string ) = @_; my %format = (); while ( $string =~ s/(\S+\s*=\s*[\"|\'][^\"\']+[\"|\'])// ) { my ( $name, $symbol ) = split /\s*=\s*/, $1; $format{ lc $name } = $symbol; } while ( $string =~ s/(\S+\s*=\s*\S+)// ) { my ( $name, $symbol ) = split /\s*=\s*/, $1; $format{ lc $name } = lc $symbol; } for my $other ( split /\s+/, $string ) { if ($other) { $format{ lc $other } = 1; } } return \%format; } =begin comment Title : _parse_matrix Usage : $self->_parse_matrix($buffer); (private) Function: Processes buffer containing matrix data Returns : none Args : buffer (string) Method : parse according to if name is quoted string or single word, if each state is single character or multi-character (use token keyword) =end comment =cut sub _parse_matrix { my ( $self, $matrix, $verbose ) = @_; my @taxa; my ( $name, $seq ) = (); # Build an array of hashrefs, where each hash has "name" and "seq" values # corresponding to the name and sequence found in each row of the matrix for my $row ( split /\n|\r/, $matrix ) { if ( $row =~ /^\s*$/ ) { next; } #for quoted taxon name if ( $row =~ /^\s*[\"|\']([^\"\']+)[\"|\']\s*([^\[]*)(\[.*\]\s*)*/ ) { ( $name, $seq ) = ( $1, $2 ); $name =~ s/\s+/_/g; if ( !$self->find_taxon($name) ) { Bio::NEXUS::Util::Exceptions::BadArgs->throw( 'error' => "Undefined Taxon: $name" ); } } else { # for one-word non-quoted taxon name $row =~ /^\s*(\S+)(\s*)([^\[]*)(\[.*\]\s*)*/; if ( $self->find_taxon($1) ) { $name = $1; $seq = $3; #print Dumper $seq; } else { print "taxon name $1 not found\n" if $verbose; $seq = $1 . $2 . $3; } } #print "> row: $row\n"; #print "> name: $name\n"; #print "> seq: $seq\n"; my $newtaxon = 1; for my $taxon (@taxa) { if ( $taxon->{'name'} eq $name ) { $taxon->{'seq'} .= ' ' . $seq; $newtaxon = 0; } } if ($newtaxon) { push @taxa, { name => $name, seq => $seq }; } } #print '> @taxa: '; # split each character my @otus; #print Dumper \@taxa; for my $taxon (@taxa) { $seq = $taxon->{'seq'}; $seq =~ s/^\s*(.*\S)\s*$/$1/; my @seq; while ( $seq =~ s/([^\(]+)|\(([^\(]+)\)// ) { # for +-(+ -)+- if ($1) { # for +- ### The following 4 commented lines of code are implemented in CharactersBlock.pm; they allow data tokens to be space-delimited. ### Unaligned blocks do not include the tokens or continuous formats according the Maddison et al. We ### may decide that we don't want to restrict unaligned data to DNA/RNA/AA the way Maddison et al have. # if ($self->get_format->{'tokens'} || lc $self->get_format->{'datatype'} eq 'continuous') { #LINE 1 # push @seq, split /\s+/, $1; #LINE 2 # } else { #LINE 3 push @seq, split /\s*/, $1; # } #LINE4 } elsif ($2) { push @seq, [ split /,\s*|\s+/, $2 ]; # for (+ -) } } push @otus, Bio::NEXUS::TaxUnit->new( $taxon->{'name'}, \@seq ); } my $otuset = $self->get_otuset(); $otuset->set_otus( \@otus ); $self->set_taxlabels( $otuset->get_otu_names() ); return \@otus; } =head2 find_taxon Title : find_taxon Usage : my $is_taxon_present = $self->find_taxon($taxon_name); Function: Finds whether the input taxon name is present in the taxon label. Returns : 0 (not present) or 1 (if present). Args : taxon label (as string) =cut sub find_taxon { my ( $self, $name ) = @_; if ( @{ $self->get_taxlabels || [] } == 0 ) { return 1; } for my $taxon ( @{ $self->get_taxlabels() } ) { if ( lc $taxon eq lc $name ) { return 1; } } return 0; } =head2 set_format Title : set_format Usage : $block->set_format(\%format); Function: set the format of the characters Returns : none Args : hash of format values =cut sub set_format { my ( $self, $format ) = @_; $self->{'format'} = $format; } =head2 get_format Title : get_format Usage : $block->get_format(); Function: Returns the format of the characters Returns : hash of format values Args : none =cut sub get_format { shift->{'format'} || {} } =head2 set_otuset Title : set_otuset Usage : $block->set_otuset($otuset); Function: Set the otus Returns : none Args : TaxUnitSet object =cut sub set_otuset { my ( $self, $otuset ) = @_; $self->{'otuset'} = $otuset; $self->set_taxlabels( $otuset->get_otu_names() ); } =head2 set_charstatelabels Title : set_charstatelabels Usage : $block->set_charstatelabels($labels); Function: Set the character names and states Returns : none Args : array of character states =cut sub set_charstatelabels { my ( $self, $charstatelabels ) = @_; $self->get_otuset->set_charstatelabels($charstatelabels); } =head2 get_charstatelabels Title : get_charstatelabels Usage : $set->get_charstatelabels(); Function: Returns an array of character states Returns : character states Args : none =cut sub get_charstatelabels { my ($self) = @_; return $self->get_otuset->get_charstatelabels(); } =head2 get_ntax Title : get_ntax Usage : $block->get_ntax(); Function: Returns the number of taxa of the block Returns : # taxa Args : none =cut sub get_ntax { my $self = shift; return $self->get_otuset()->get_ntax(); } =head2 rename_otus Title : rename_otus Usage : $block->rename_otus(\%translation); Function: Renames all the OTUs to something else Returns : none Args : hash containing translation =cut sub rename_otus { my ( $self, $translation ) = @_; $self->get_otuset()->rename_otus($translation); } =head2 add_otu_clone Title : add_otu_clone Usage : ... Function: ... Returns : ... Args : ... =cut sub add_otu_clone { my ( $self, $original_otu_name, $copy_otu_name ) = @_; # print "Warning: Bio::NEXUS::UnalignedBlock::add_otu_clone() method not fully implemented\n"; if ($self->find_taxon($copy_otu_name)) { print "Error: an OTU with that name [$copy_otu_name] already exists.\n"; } else { $self->add_taxlabel($copy_otu_name); } my @otu_set = (); if (defined $self->{'otuset'}->{'otus'}) { @otu_set = @{ $self->{'otuset'}->{'otus'} }; } foreach my $otu (@otu_set) { if (defined $otu) { if ($otu->get_name() eq $original_otu_name) { my $otu_clone = $otu->clone(); $otu_clone->set_name($copy_otu_name); $self->{'otuset'}->add_otu($otu_clone); } } } } =head2 equals Name : equals Usage : $block->equals($another); Function: compare if two Bio::NEXUS::UnalignedBlock objects are equal Returns : boolean Args : a Bio::NEXUS::CharactersBlock object =cut sub equals { my ( $self, $block ) = @_; if ( !Bio::NEXUS::Block::equals( $self, $block ) ) { return 0; } return $self->get_otuset()->equals( $block->get_otuset() ); } =begin comment Name : _write Usage : $block->_write(); Function: Writes NEXUS block containing unaligned data Returns : none Args : file name (string) =end comment =cut sub _write { my ( $self, $fh, $verbose ) = @_; $fh ||= \*STDOUT; Bio::NEXUS::Block::_write( $self, $fh ); $self->_write_matrix_info( $fh, $verbose ); $self->_write_matrix( $fh, $verbose ); print $fh "END;\n"; return; } =begin comment Name : _write_matrix_info Usage : $self->_write_matrix_info($file_handle,$verbose); Function: Writes UnalignedBlock info (all the block content except the matrix data) into the filehandle Returns : none Args : $file_handle and $verbose =end comment =cut sub _write_matrix_info { my ( $self, $fh, $verbose ) = @_; $fh ||= \*STDOUT; my $ntax = $self->get_ntax(); print $fh "\tDIMENSIONS ntax=$ntax;\n"; my %formats = %{ $self->get_format() }; if ( scalar keys %formats ) { print $fh "\tFORMAT "; if ( defined $formats{'datatype'} ) { print $fh " datatype=$formats{'datatype'}"; } for my $format ( keys %formats ) { if ( !$formats{$format} || $format =~ /datatype/i ) { next; } elsif ( $formats{$format} eq '1' ) { print $fh " $format"; } else { print $fh " $format=$formats{$format}"; } } print $fh ";\n"; } return; } =begin comment Name : _write_matrix Usage : $self->_write_matrix($file_handle,$verbose); Function: Writes UnalignedBlock matrix( The data stored in the matrix command) into the filehandle Returns : none Args : $file_handle and $verbose =end comment =cut sub _write_matrix { my ( $self, $fh, $verbose ) = @_; $fh ||= \*STDOUT; my @otus = @{ $self->get_otuset()->get_otus() }; print $fh "\tMATRIX\n"; for my $otu (@otus) { my $seq = $otu->get_seq_string(); print $fh "\t", $otu->get_name(), "\t", $seq, "\n"; } print $fh "\t;\n"; return; } sub AUTOLOAD { return if $AUTOLOAD =~ /DESTROY$/; my $package_name = __PACKAGE__ . '::'; # The following methods are deprecated and are temporarily supported # via a warning and a redirection my %synonym_for = ( "${package_name}set_charstates" => "${package_name}set_charstatelabels", "${package_name}get_charstates" => "${package_name}get_charstatelabels", ); if ( defined $synonym_for{$AUTOLOAD} ) { $logger->warn( "$AUTOLOAD() is deprecated; use $synonym_for{$AUTOLOAD}() instead" ); goto &{ $synonym_for{$AUTOLOAD} }; } else { Bio::NEXUS::Util::Exceptions::UnknownMethod->throw( 'error' => "ERROR: Unknown method $AUTOLOAD called" ); } } 1;
gitpan/Bio-NEXUS
lib/Bio/NEXUS/UnalignedBlock.pm
Perl
mit
13,075
#!/usr/local/bin/perl use strict; my %xref_tbl; my %oid_tbl; my ($mac_file, $xref_file) = @ARGV; open(IN, $mac_file) || die "Can't open $mac_file, $!\n"; # Read in OID nid values for a lookup table. while (<IN>) { chomp; my ($name, $num) = /^(\S+)\s+(\S+)$/; $oid_tbl{$name} = $num; } close IN; open(IN, $xref_file) || die "Can't open $xref_file, $!\n"; my $ln = 1; while (<IN>) { chomp; s/#.*$//; next if (/^\S*$/); my ($xr, $p1, $p2) = /^(\S+)\s+(\S+)\s+(\S+)/; check_oid($xr); check_oid($p1); check_oid($p2); $xref_tbl{$xr} = [$p1, $p2, $ln]; } my @xrkeys = keys %xref_tbl; my @srt1 = sort { $oid_tbl{$a} <=> $oid_tbl{$b}} @xrkeys; my $i; for($i = 0; $i <= $#srt1; $i++) { $xref_tbl{$srt1[$i]}[2] = $i; } my @srt2 = sort { my$ap1 = $oid_tbl{$xref_tbl{$a}[0]}; my$bp1 = $oid_tbl{$xref_tbl{$b}[0]}; return $ap1 - $bp1 if ($ap1 != $bp1); my$ap2 = $oid_tbl{$xref_tbl{$a}[1]}; my$bp2 = $oid_tbl{$xref_tbl{$b}[1]}; return $ap2 - $bp2; } @xrkeys; my $pname = $0; $pname =~ s|.*/||; print <<EOF; /* AUTOGENERATED BY $pname, DO NOT EDIT */ typedef struct { int sign_id; int hash_id; int pkey_id; } nid_triple; static const nid_triple sigoid_srt[] = { EOF foreach (@srt1) { my $xr = $_; my ($p1, $p2) = @{$xref_tbl{$_}}; my $o1 = " {NID_$xr, NID_$p1,"; my $o2 = "NID_$p2},"; if (length("$o1 $o2") < 78) { print "$o1 $o2\n"; } else { print "$o1\n $o2\n"; } } print "};"; print <<EOF; static const nid_triple *const sigoid_srt_xref[] = { EOF foreach (@srt2) { my ($p1, $p2, $x) = @{$xref_tbl{$_}}; # If digest or signature algorithm is "undef" then the algorithm # needs special handling and is excluded from the cross reference table. next if $p1 eq "undef" || $p2 eq "undef"; print " \&sigoid_srt\[$x\],\n"; } print "};\n"; sub check_oid { my ($chk) = @_; if (!exists $oid_tbl{$chk}) { die "Can't find \"$chk\", $!\n"; } }
vbloodv/blood
extern/openssl.orig/crypto/objects/objxref.pl
Perl
mit
1,940
# Time-stamp: "Sat Jul 14 00:27:44 2001 by Automatic Bizooty (__blocks2pm.plx)" $Text::\SEPA\Unicode\Unidecode::Char[0xfe] = [ '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', "", "", "", qq{~}, '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', qq{..}, qq{--}, qq{-}, qq{_}, qq{_}, qq{(}, qq{) }, qq{\{}, qq{\} }, qq{[}, qq{] }, qq{[(}, qq{)] }, qq{<<}, qq{>> }, qq{<}, qq{> }, qq{[}, qq{] }, qq{\{}, qq{\}}, '[?]', '[?]', '[?]', '[?]', "", "", "", "", "", "", "", qq{,}, qq{,}, qq{.}, "", qq{;}, qq{:}, qq{?}, qq{!}, qq{-}, qq{(}, qq{)}, qq{\{}, qq{\}}, qq{\{}, qq{\}}, qq{#}, qq{&}, qq{*}, qq{+}, qq{-}, qq{<}, qq{>}, qq{=}, "", qq{\\}, qq{\$}, qq{%}, qq{\@}, '[?]', '[?]', '[?]', '[?]', "", "", "", '[?]', "", '[?]', "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", '[?]', '[?]', "", ]; 1;
dmitrirussu/php-sepa-xml-generator
src/Unicode/data/perl_source/xfe.pm
Perl
mit
1,493
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Hindley-Milner Type Checker for Prolog % % All authors agree to the licences of SWI-Prolog and YAP % % AUTHORS OF CODE: % Tom Schrijvers % Bart Demoen % Markus Triska % YOUR NAME HERE % % ACKNOWLEDGEMENTS: % Ulrich Neumerkel for providing feedback % Vitor Santos Costa % Jose Santos % YOUR NAME HERE % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DOCUMENTATION % % Type Definitions % ---------------- % % Define polymorphic algebraic data types like: % % :- type pair(A,B) ---> A - B. % :- type list(T) ---> [] ; [T|list(T)]. % :- type boolean ---> true ; false. % % (NOTE: the above types are predefined, as well as integer and float.) % % Type definitions can also be empty, e.g. % % :- type an_empty_type. % % This means that the type is not inhabited by instantiated values. Only % logical variables are possible. % % Predicate Signatures % -------------------- % % Predicates are given a signature like: % % :- pred append(list(E), list(E), list(E)). % :- pred not(boolean, boolean). % :- pred lookup(list(pair(Key,Value)), Key, Value). % % Interfacing Untyped Code % ------------------------ % % 1) Calling typed code from untyped code (and the Prolog top-level) % results in runtime type checks. % % 2) One may annotate calls to untyped predicates from within typed predicates: % % :- pred concat(list(list(integer)),list(integer)). % % concat(LL,L) :- flatten(LL,L) :: flatten(list(list(integer)),list(integer)). % % which results in runtime type checking. The annotation is also used for static % type checking of the code surrounding the annotated call. % % A variant of the annotation is only used for static type checking, and does % not result in runtime checks: % % concat(LL,L) :- flatten(LL,L) :< flatten(list(list(integer)),list(integer)). % % 3) A second way is to provide a signature for untypable code with: % % :- trust_pred sort(list(integer),list(integer)). % % This signature is only into account when checking calls from % typed code. % % Coping with Untypable Code % -------------------------- % % Untypable code, e.g. using Prolog built-ins, may be encapsulated % in a trusted predicate. E.g. % % :- trust_pred new_array(list(T),array(T)). % % new_array(List,Array) :- Array =.. [array|List]. % % No additional runtime checks are performed for trusted predicates. % % Similarly, untyped imported predicates may be given a type signature % with the trust_pred declaration. % % % Type Checker Options % -------------------- % % Options can be passed to the type checker with the declaration % % :- type_check_options(Options). % % where Options is a list containing zero or more of the following elements: % % check(Flag) where Flag is on or off, % to enable or disable the type checker % enabled by default % % runtime(Flag) where Flag is on or off, % to enable or disable runtime type checking % disabled by default % % verbose(Flag) where Flag is on or off, % to enable or disable printed summary at end of type checking % enabled by default % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CURRENT LIMITATIONS % % * global namespace for types % * runtime type checks are not exhaustive for (non-ground) polymorphic types % % TODO: % * check uniqueness of defined types, e.g. list(T) not defined twice % * check syntactic well-formedness of type definitions and declarations % * add module awareness for predicates % * add module awareness for types % * take care with variables used in :: (also used for values / other annotations) % * improve error messages with tc_stats(Errors,Total) % - source location information % - what the inconsistency is % * support for more built-ins % * higher-order types for meta-predicates % * exported vs. hidden types % * abstract types (hidden definition) % * automatic inference of signatures % * type classes % % CHANGES: % * added cmp/0 type % * added compare/3 built-in % * added statistics printing at end of type checking % * fixed detection of less general types than signature % * added error message for less polymorphic signature % * added error message for duplicate predicate signature % * added :< annotation, which is a variant of the :: annotation, % where the semantics is not to include runtime assertions, % but to simply trust the programmer. % * added type pred/0 for goals % * added call/1 built-in % * added type pred/1 and pred/2 % * addded call/1 and call/2 built-ins % * improved error message for less polymorphic inferred types % * support for built-in type `float' % * added string/0 type % * added get_char/1 built-in % * added atom_concat/3 built-in % * added atom_length/2 built-in % * added atom_chars/2 built-in % * added concat_atom/2 built-in % * added any/0 type % * added coercion predicate any_to_type/3 % * added coercion predicate type_to_any/2 % * normalize all types, also built-in ones % * option to enable/disable type-checking % * option to enable/disable runtime type checks % * added empty type definitions % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% :- module(type_check, [ op(1150, fx, type) , op(1130, xfx, --->) , op(1150, fx, pred) , op(1150, fx, trust_pred) , op(500,yfx,::) , op(500,yfx,:<) ]). :- use_module(library(lists)). :- use_module(library(apply_macros)). :- use_module(library(terms), [variant/2]). :- use_module(functor_constraint). :- op(1150, fx, type). :- op(1130, xfx, ---> ). :- op(1150, fx, pred). :- op(500,yfx,::). :- op(500,yfx,:<). :- multifile user:term_expansion/2, user:goal_expansion/2, prolog:message/3, constructor/4, constructor_info/4, signature/4, trusted_predicate/1, basic_normalize/2. :- dynamic user:term_expansion/2, user:goal_expansion/2, signature/4, constructor_info/4, trusted_predicate/1, basic_normalize/2. tc_version('$Id: type_check.pl,v 1.45 2009-11-17 toms Exp $'). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Type checker options {{{ :- nb_setval(type_check_runtime,off). :- nb_setval(type_check,on). :- nb_setval(type_check_verbose,on). handle_options(List) :- maplist(handle_option,List). handle_option(verbose(Flag)) :- !, nb_setval(type_check_verbose,Flag). handle_option(runtime(Flag)) :- !, nb_setval(type_check_runtime,Flag). handle_option(check(Flag)) :- !, nb_setval(type_check,Flag). handle_option(Other) :- format('Unsupported type checker option `~w\'.\n',[Other]). type_checking_runtime :- nb_getval(type_check_runtime,on). type_checking_verbose :- nb_getval(type_check_verbose,on). type_checking :- nb_getval(type_check,on). % }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% type_check_term(Term,ExpectedType,EnvIn,EnvOut) :- normalize_type(ExpectedType,NormalExpectedType), type_check_term_(Term,NormalExpectedType,EnvIn,EnvOut). type_check_term_(Term,ExpectedType,EnvIn,EnvOut) :- var(Term), !, ( lookup_eq(EnvIn,Term,EnvType) -> ( equate_types(ExpectedType,EnvType) -> true ; term_type_error(Term,ExpectedType,EnvType) ), EnvIn = EnvOut ; EnvOut = [Term-ExpectedType|EnvIn] ). type_check_term_(Term,Type,EnvIn,EnvOut) :- integer(Term), !, ( equate_types(Type,integer) -> EnvIn = EnvOut ; term_type_error(Term,integer,Type) ). type_check_term_(Term,Type,EnvIn,EnvOut) :- float(Term), !, ( equate_types(Type,float) -> EnvIn = EnvOut ; term_type_error(Term,float,Type) ). type_check_term_(Term,Type,EnvIn,EnvOut) :- Type == (pred), !, type_check_control(Term,top,EnvIn,EnvOut). type_check_term_(Term,Type,EnvIn,EnvOut) :- nonvar(Type), Type = pred(ArgType), !, Term =.. [Functor|Args], append(Args,[DummyArg],FullArgs), Goal =.. [Functor|FullArgs], type_check_control(Goal,top,[DummyArg-ArgType|EnvIn],EnvOut). type_check_term_(Term,Type,EnvIn,EnvOut) :- nonvar(Type), Type = pred(ArgType1,ArgType2), !, Term =.. [Functor|Args], append(Args,[DummyArg1,DummyArg2],FullArgs), Goal =.. [Functor|FullArgs], type_check_control(Goal,top,[DummyArg1-ArgType1,DummyArg2-ArgType2|EnvIn],EnvOut). type_check_term_(Term,Type,EnvIn,EnvOut) :- Type == string, !, ( atom(Term) -> EnvIn = EnvOut ; term_type_error(Term,unknown_type,Type) ). type_check_term_(_Term,Type,EnvIn,EnvOut) :- Type == any, !, EnvIn = EnvOut. type_check_term_(Term,Type,EnvIn,EnvOut) :- % constructor(Term,Type,EnvIn,EnvOut), !. functor_constraint(Term,Type,Args,Types), !, type_check_terms(Args,Types,EnvIn,EnvOut). type_check_term_(Term,Type,_EnvIn,_EnvOut) :- term_type_error(Term,unknown_type,Type). type_check_terms([],[],Env,Env). type_check_terms([Term|Terms],[Type|Types],Env1,Env3) :- type_check_term(Term,Type,Env1,Env2), type_check_terms(Terms,Types,Env2,Env3). term_type_error(Term,ExpectedType,EnvType) :- throw(error(type_error(Term,ExpectedType,EnvType))). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% constructor_clauses((A;B),Type) --> !, constructor_clauses(A,Type), constructor_clauses(B,Type). constructor_clauses(Constructor,Type) --> { functor(Constructor, Name, Arity), functor(Term, Name, Arity), Term =.. [_|Args], Constructor =.. [_|Types], args_body(Args,Types,Body,EnvIn,EnvOut) }, [ ( type_check:constructor(Term, ExpectedType, EnvIn, EnvOut) :- ( type_check:equate_types(ExpectedType,Type) -> true ; type_check:term_type_error(Term,ExpectedType,Type) ), Body ) ], constructor_info_clause(Constructor,Type). constructor_info_clause(Constructor,Type) --> { functor(Constructor, Name, Arity), functor(Term, Name, Arity), Term =.. [_|Args], Constructor =.. [_|Types], Clause = type_check:constructor_info(Term, Type, Args, Types) }, [ Clause ]. args_body([],[],true,Env,Env). args_body([Term|Terms],[Type|Types],(type_check:type_check_term(Term,Type,EnvIn,Env),Body),EnvIn,EnvOut) :- args_body(Terms,Types,Body,Env,EnvOut). signature_clause(Signature, Clause) :- ( check_signature(Signature) -> signature_clause_(Signature, Clause) ; true ). signature_clause_(Signature,Clause) :- functor(Signature,Name,Arity), functor(Call,Name,Arity), Call =.. [_|Args], Signature =.. [_|Types], args_body(Args,Types,Body,EnvIn,EnvOut), Clause = ( type_check:signature(Call,Types,EnvIn,EnvOut) :- Body ). check_signature(Signature) :- nonvar(Signature), functor(Signature,Name,Arity), functor(Prototype,Name,Arity), ( signature(Prototype,_,[],_) -> duplicate_signature_error(Signature), fail ; true ). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% type_check_file(NClauses) :- findall(Clause,retract(clause_to_check(Clause)),Clauses), ( type_checking -> type_check_clauses(Clauses,Stats), ( type_checking_runtime -> transform_clauses(Clauses,NClauses) ; NClauses = Clauses ), final_message(Stats) ; NClauses = Clauses ). type_check_clauses(Clauses,Stats) :- init_stats(Stats0), type_check_clauses(Clauses,Stats0,Stats). type_check_clauses([],Stats,Stats). type_check_clauses([Clause|Clauses],Stats0,Stats) :- catch( ( type_check_clause(Clause) , inc_ok_stats(Stats0,Stats1) ) , type_error , ( format('TYPE ERROR in clause: \n\n',[]), portray_clause(Clause), inc_error_stats(Stats0,Stats1) ) ), type_check_clauses(Clauses,Stats1,Stats). type_check_clause((:- _)) :- !, true. % ignoring type_check_clause((Head :- Body)) :- !, functor(Head,P,N), ( trusted_predicate(P/N) -> true ; type_check_clause_main(Head,Body) ). type_check_clause(Head) :- type_check_clause((Head :- true)). type_check_clause_main(Head,Body) :- Env0 = [], /* check the head */ catch( signature(Head,ArgTypes,Env0,Env1), error(type_error(Term,Exp,Inf)), ( head_error(Term,Exp,Inf,Head,Body), fail ) ), /* check the body */ catch( type_check_control(Body,top,Env1,_Env2), error(type_error(Term,Exp,Inf),Context), (control_error(Term,Exp,Inf,Head,Context),fail) ), /* check whether Head is variant of signature */ functor(Head,Name,Arity), functor(Prototype,Name,Arity), signature(Prototype,ProtoTypes,Env0,_ProtoEnv), ( variant(ArgTypes, ProtoTypes) % JCAS: equivalent to ArgTypes =@= ProtoTypes but does not require SWI.pl -> true ; InfSig =.. [Name|ArgTypes], DecSig =.. [Name|ProtoTypes], less_polymorphic_error((:- pred InfSig), (:- pred DecSig)), throw(type_error) ). % context ::= % top % | lconj parent right % | rconj parent left % | ldisj parent right % | rdisj parent left % | cond parent then % | then parent cond % | once parent % | findall parent pattern result % env == list(pair(var-type)) %% type_check_control(+goal,+context,+env,-env) {{{ type_check_control(G,_Context,Env1,Env2) :- var(G), !, type_check_term(G,(pred),Env1,Env2). type_check_control((G1,G2),Context,Env1,Env3) :- !, type_check_control(G1,lconj(Context,G2),Env1,Env2), type_check_control(G2,rconj(Context,G1),Env2,Env3). type_check_control((G1;G2),Context,Env1,Env3) :- !, type_check_control(G1,ldisj(Context,G2),Env1,Env2), type_check_control(G2,rdisj(Context,G1),Env2,Env3). type_check_control((G1 -> G2),Context,Env1,Env3) :- !, type_check_control(G1,cond(Context,G2),Env1,Env2), type_check_control(G2,then(Context,G1),Env2,Env3). type_check_control(once(G),Context,Env1,Env2) :- !, type_check_control(G,once(Context),Env1,Env2). type_check_control(findall(Pattern,Goal,Result),Context,Env1,Env4) :- !, type_check_control(Goal,findall(Context,Pattern,Result),Env1,Env2), type_check_term(Pattern,Type,Env2,Env3), type_check_term(Result,list(Type),Env3,Env4). type_check_control(Goal,Context,Env1,Env2) :- catch( ( type_check_goal(Goal,Env1,Env2,Warnings,[]) -> maplist(control_warning(context(Goal,Context)),Warnings) ; term_type_error(?,?,?) ), error(type_error(Term,ExpType,InfType)), control_type_error(type_error(Term,ExpType,InfType),Goal,Context) ). control_type_error(Error,Goal,Context) :- throw(error(Error,context(Goal,Context))). % }}} numeric_type(Type) :- when(nonvar(Type),check_numeric_type(Type)). check_numeric_type(integer) :- !. check_numeric_type(float) :- !. check_numeric_type(Other) :- term_type_error(some_arithmetic_expression,a_numeric_type,Other). % type_check_goal(+goal,+env,-env,-warnings,+warnings_tail) {{{ type_check_goal((X = Y),Env1,Env3,W,W) :- !, type_check_term(X,Type,Env1,Env2), type_check_term(Y,Type,Env2,Env3). type_check_goal((X \= Y),Env1,Env3,W,W) :- !, type_check_term(X,Type,Env1,Env2), type_check_term(Y,Type,Env2,Env3). type_check_goal((X == Y),Env1,Env3,W,W) :- !, type_check_term(X,Type,Env1,Env2), type_check_term(Y,Type,Env2,Env3). type_check_goal((X \== Y),Env1,Env3,W,W) :- !, type_check_term(X,Type,Env1,Env2), type_check_term(Y,Type,Env2,Env3). type_check_goal((X @< Y),Env1,Env3,W,W) :- !, type_check_term(X,Type,Env1,Env2), type_check_term(Y,Type,Env2,Env3). type_check_goal((X @> Y),Env1,Env3,W,W) :- !, type_check_term(X,Type,Env1,Env2), type_check_term(Y,Type,Env2,Env3). type_check_goal((X @>= Y),Env1,Env3,W,W) :- !, type_check_term(X,Type,Env1,Env2), type_check_term(Y,Type,Env2,Env3). type_check_goal((X @=< Y),Env1,Env3,W,W) :- !, type_check_term(X,Type,Env1,Env2), type_check_term(Y,Type,Env2,Env3). type_check_goal(copy_term(X,Y),Env1,Env3,W,W) :- !, type_check_term(X,Type,Env1,Env2), type_check_term(Y,Type,Env2,Env3). type_check_goal(compare(R,X,Y),Env1,Env4,W,W) :- !, type_check_term(R,cmp,Env1,Env2), type_check_term(X,Type,Env2,Env3), type_check_term(Y,Type,Env3,Env4). type_check_goal((X is Y),Env1,Env3,W,W) :- !, numeric_type(Type), type_check_term(X,Type,Env1,Env2), type_check_expression(Y,Type,Env2,Env3). type_check_goal((X > Y),Env1,Env3,W,W) :- !, numeric_type(Type), type_check_expression(X,Type,Env1,Env2), type_check_expression(Y,Type,Env2,Env3). type_check_goal((X < Y),Env1,Env3,W,W) :- !, numeric_type(Type), type_check_expression(X,Type,Env1,Env2), type_check_expression(Y,Type,Env2,Env3). type_check_goal((X =< Y),Env1,Env3,W,W) :- !, numeric_type(Type), type_check_expression(X,Type,Env1,Env2), type_check_expression(Y,Type,Env2,Env3). type_check_goal((X >= Y),Env1,Env3,W,W) :- !, numeric_type(Type), type_check_expression(X,Type,Env1,Env2), type_check_expression(Y,Type,Env2,Env3). type_check_goal((X =:= Y),Env1,Env3,W,W) :- !, numeric_type(Type), type_check_expression(X,Type,Env1,Env2), type_check_expression(Y,Type,Env2,Env3). type_check_goal((X =\= Y),Env1,Env3,W,W) :- !, numeric_type(Type), type_check_expression(X,Type,Env1,Env2), type_check_expression(Y,Type,Env2,Env3). type_check_goal(arg(I,_,_),Env1,Env2,W,W) :- !, type_check_term(I,integer,Env1,Env2). type_check_goal(functor(Term,Functor,I),Env1,Env3,W,W) :- !, type_check_term(I,integer,Env1,Env2), ( nonvar(I) -> I >= 0 ; true ), type_check_term(Term,Type,Env2,Env3), ( nonvar(Functor) -> atomic(Functor), ( nonvar(I), nonvar(Type) -> functor(Dummy,Functor,I), constructor(Dummy,Type,[],_Env) ; true ) ; true % ignore functor ). type_check_goal(integer(I),Env1,Env2,W,W) :- !, type_check_term(I,integer,Env1,Env2). type_check_goal(float(I),Env1,Env2,W,W) :- !, type_check_term(I,float,Env1,Env2). type_check_goal(true,Env1,Env2,W,W) :- !, Env1 = Env2. type_check_goal(fail,Env1,Env2,W,W) :- !, Env1 = Env2. type_check_goal(!,Env1,Env2,W,W) :- !, Env1 = Env2. type_check_goal(abort,Env1,Env2,W,W) :- !, Env1 = Env2. type_check_goal(writeln(Term),Env1,Env2,W,W) :- !, type_check_term(Term,_Type,Env1,Env2). type_check_goal(format(_,_),Env1,Env2,W,W) :- !, Env1 = Env2. type_check_goal(var(Term),Env1,Env2,W,W) :- !, type_check_term(Term,_Type,Env1,Env2). type_check_goal(nonvar(Term),Env1,Env2,W,W) :- !, type_check_term(Term,_Type,Env1,Env2). type_check_goal(ground(Term),Env1,Env2,W,W) :- !, type_check_term(Term,_Type,Env1,Env2). type_check_goal(atom_chars(A1,A2),Env1,Env3,W,W) :- !, type_check_term(A1,string,Env1,Env2), type_check_term(A2,list(string),Env2,Env3). type_check_goal(atom_concat(A1,A2,A3),Env1,Env4,W,W) :- !, type_check_term(A1,string,Env1,Env2), type_check_term(A2,string,Env2,Env3), type_check_term(A3,string,Env3,Env4). type_check_goal(atom_length(A1,A2),Env1,Env3,W,W) :- !, type_check_term(A1,string,Env1,Env2), type_check_term(A2,integer,Env2,Env3). type_check_goal(concat_atom(A1,A2),Env1,Env3,W,W) :- !, type_check_term(A1,list(string),Env1,Env2), type_check_term(A2,string,Env2,Env3). type_check_goal(get_char(A1),Env1,Env2,W,W) :- !, type_check_term(A1,string,Env1,Env2). type_check_goal(throw(_),Env1,Env2,W,W) :- !, Env1 = Env2. type_check_goal(catch(Goal,_,Handler),Env1,Env3,W1,W3) :- !, type_check_goal(Goal,Env1,Env2,W1,W2), type_check_goal(Handler,Env2,Env3,W2,W3). type_check_goal(call(Goal),Env1,Env2,W,W) :- !, type_check_term(Goal,(pred),Env1,Env2). type_check_goal(call(Goal,Arg),Env1,Env3,W,W) :- !, type_check_term(Goal,pred(Type),Env1,Env2), type_check_term(Arg, Type, Env2,Env3). type_check_goal(call(Goal,Arg1,Arg2),Env1,Env4,W,W) :- !, type_check_term(Goal,pred(Type1,Type2),Env1,Env2), type_check_term(Arg1,Type1, Env2,Env3), type_check_term(Arg2,Type2, Env3,Env4). type_check_goal(Goal :: Signature, Env1, Env3,W,W) :- !, /* first take into account the predicate signatures if one exists */ ( participating_predicate(Goal) -> signature(Goal,_,Env1,Env2) ; Env2 = Env1 ), functor(Goal,F,A), functor(Signature,F,A), Goal =.. [_|Args], Signature =.. [_|Types], type_check_terms(Args,Types,Env2,Env3). type_check_goal(Goal :< Signature, Env1, Env3,W,W) :- !, /* first take into account the predicate signatures if one exists */ ( participating_predicate(Goal) -> signature(Goal,_,Env1,Env2) ; Env2 = Env1 ), functor(Goal,F,A), functor(Signature,F,A), Goal =.. [_|Args], Signature =.. [_|Types], type_check_terms(Args,Types,Env2,Env3). type_check_goal(type_to_any(A1,A2),Env1,Env3,W,W) :- !, type_check_term(A1,_Type,Env1,Env2), type_check_term(A2,any,Env2,Env3). type_check_goal(any_to_type(A1,A2,Type),Env1,Env3,W,W) :- !, type_check_term(A1,any,Env1,Env2), type_check_term(A2,Type,Env2,Env3). type_check_goal(Goal,Env1,Env2,W,W) :- participating_predicate(Goal), !, signature(Goal,_,Env1,Env2). type_check_goal(Goal,Env1,Env2,W,RW) :- /* all other predicates are simply ignored */ Warning = unknown_predicate_call(Goal), W = [Warning|RW], Env1 = Env2. % }}} % type_check_expression(+expression,+type,+env,-env) {{{ type_check_expression(Exp,Type,Env1,Env2) :- var(Exp), !, type_check_term(Exp,Type,Env1,Env2). type_check_expression(random,Type,Env1,Env1) :- !, % NOTE: only supported by Yap equate_types(Type,float). type_check_expression((-Exp),Type,Env1,Env2) :- !, type_check_expression(Exp,Type,Env1,Env2). type_check_expression((\Exp),Type,Env1,Env2) :- !, equate_types(Type,integer), type_check_expression(Exp,Type,Env1,Env2). type_check_expression(abs(Exp),Type,Env1,Env2) :- !, type_check_expression(Exp,Type,Env1,Env2). type_check_expression(log(Exp),Type,Env1,Env2) :- !, equate_types(Type,float), type_check_expression(Exp,Type,Env1,Env2). type_check_expression(integer(Exp),Type,Env1,Env2) :- !, equate_types(Type,float), % explicit conversion from integer to float type_check_expression(Exp,integer,Env1,Env2). type_check_expression(sign(Exp),Type,Env1,Env2) :- !, type_check_expression(Exp,Type,Env1,Env2). type_check_expression((Exp1+Exp2),Type,Env1,Env3) :- !, type_check_expression(Exp1,Type,Env1,Env2), type_check_expression(Exp2,Type,Env2,Env3). type_check_expression((Exp1-Exp2),Type,Env1,Env3) :- !, type_check_expression(Exp1,Type,Env1,Env2), type_check_expression(Exp2,Type,Env2,Env3). type_check_expression((Exp1*Exp2),Type,Env1,Env3) :- !, type_check_expression(Exp1,Type,Env1,Env2), type_check_expression(Exp2,Type,Env2,Env3). type_check_expression((Exp1/Exp2),Type,Env1,Env3) :- !, equate_types(Type,float), type_check_expression(Exp1,Type,Env1,Env2), type_check_expression(Exp2,Type,Env2,Env3). type_check_expression((Exp1//Exp2),Type,Env1,Env3) :- !, equate_types(Type,integer), type_check_expression(Exp1,Type,Env1,Env2), type_check_expression(Exp2,Type,Env2,Env3). type_check_expression((Exp1**Exp2),Type,Env1,Env3) :- !, equate_types(Type,float), type_check_expression(Exp1,Type,Env1,Env2), type_check_expression(Exp2,Type,Env2,Env3). type_check_expression((Exp1 mod Exp2),Type,Env1,Env3) :- !, equate_types(Type,integer), type_check_expression(Exp1,Type,Env1,Env2), type_check_expression(Exp2,Type,Env2,Env3). type_check_expression(min(Exp1,Exp2),Type,Env1,Env3) :- !, type_check_expression(Exp1,Type,Env1,Env2), type_check_expression(Exp2,Type,Env2,Env3). type_check_expression(max(Exp1,Exp2),Type,Env1,Env3) :- !, type_check_expression(Exp1,Type,Env1,Env2), type_check_expression(Exp2,Type,Env2,Env3). type_check_expression((Exp1 >> Exp2),Type,Env1,Env3) :- !, equate_types(Type,integer), type_check_expression(Exp1,Env1,Env2), type_check_expression(Exp2,Env2,Env3). type_check_expression((Exp1 << Exp2),Type,Env1,Env3) :- !, equate_types(Type,integer), type_check_expression(Exp1,Type,Env1,Env2), type_check_expression(Exp2,Type,Env2,Env3). type_check_expression((Exp1 /\ Exp2),Type,Env1,Env3) :- !, equate_types(Type,integer), type_check_expression(Exp1,Type,Env1,Env2), type_check_expression(Exp2,Type,Env2,Env3). type_check_expression((Exp1 \/ Exp2),Type,Env1,Env3) :- !, equate_types(Type,integer), type_check_expression(Exp1,Type,Env1,Env2), type_check_expression(Exp2,Type,Env2,Env3). type_check_expression(Exp,Type,Env1,Env2) :- /* catch all */ type_check_term(Exp,Type,Env1,Env2). % }}} unify_args([],[],Env,Env). unify_args([X|Xs],[Y|Ys],Env1,Env3) :- type_check_goal((X = Y), Env1, Env2,_,[]), unify_args(Xs,Ys,Env2,Env3). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ERROR MESSAGES head_error(Term,ExpType,InfType,Head,Body) :- format('TYPE ERROR: expected type `~w\' for term `~w\'\n',[ExpType,Term]), format(' inferred type `~w\'\n',[InfType]), format('\tin head `~w\' of clause:\n',[Head]), portray_clause((Head :- Body)). less_polymorphic_error(InfSig,DecSig) :- numbervars(InfSig,0,_), numbervars(DecSig,0,_), format('TYPE ERROR: Inferred signature is less polymorphic than declared signature.\n',[]), format(' inferred signature `~p\'\n',[InfSig]), format(' declared signature `~p\'\n',[DecSig]). duplicate_signature_error(Signature) :- format('TYPE ERROR: Predicate already has a signature.\n',[]), format(' duplicate signature `~w\'\n',[Signature]), format(' Ignoring duplicate signature.\n',[]). % control_error(+term,+type,+type,+head,+context) {{{ control_error(Term,ExpType,InfType,Head,context(Source,Context)) :- format('TYPE ERROR: expected type `~w\' for term `~w\'\n',[ExpType,Term]), format(' inferred type `~w\'\n',[InfType]), format('\tin goal:\n\t\t ~w\n\tin clause:\n',[Source]), assemble_marked_body(Context,'HERE'(Source),MarkedBody), portray_clause((Head :- MarkedBody)). control_warning(Context,Warning) :- control_warning_(Warning,Context). control_warning_(unknown_predicate_call(Call),context(Source,Context)) :- format('TYPE WARNING: call to unknown predicate `~w\'\n',[Call]), format(' Possible Fixes: - add type annotation `::\' to call\n',[]), format(' - replace with call to other predicate\n',[]), assemble_marked_body(Context,'HERE'(Source),MarkedBody), portray_clause(('...' :- MarkedBody)). prolog:message(error(type_error(Term,ExpectedType,InferredType))) --> [ '\n\tTYPE ERROR: expected type `~w\' for term `~w\'\n' - [ExpectedType, Term], '\t inferred type `~w\'\n' - [InferredType] ]. % }}} % assemble_marked_body(+context,+goal,-goal) {{{ assemble_marked_body(top,Acc,Body) :- Body = Acc. assemble_marked_body(lconj(Context,Right),Acc,Body) :- assemble_marked_body(Context,(Acc,Right),Body). assemble_marked_body(rconj(Context,Left),Acc,Body) :- assemble_marked_body(Context,(Left,Acc),Body). assemble_marked_body(ldisj(Context,Right),Acc,Body) :- assemble_marked_body(Context,(Acc;Right),Body). assemble_marked_body(rdisj(Context,Left),Acc,Body) :- assemble_marked_body(Context,(Left;Acc),Body). assemble_marked_body(cond(Context,Then),Acc,Body) :- assemble_marked_body(Context,(Acc->Then),Body). assemble_marked_body(then(Context,Cond),Acc,Body) :- assemble_marked_body(Context,(Cond->Acc),Body). assemble_marked_body(once(Context),Acc,Body) :- assemble_marked_body(Context,once(Acc),Body). assemble_marked_body(findall(Context,Pattern,Result),Acc,Body) :- assemble_marked_body(Context,findall(Pattern,Acc,Result),Body). % }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Transform clauses: {{{ % % p(T1,...,Tn) :- B. % % becomes: % % p(X1,...,Xn) :- CHECKS, p'(X1,...,Xn). (* one for each predicate *) % % p'(T1,...,Tn) :- B'. % % where all calls to type safe predicates have been replaced in B to get B' transform_clauses(Clauses,NClauses) :- wrappers(Clauses,NClauses). wrappers(Clauses,NClauses) :- findall(FA,(member(Clause,Clauses), only_check_participating_clauses(Clause,FA)),FAs0), sort(FAs0,FAs), maplist(wrapper_clause,FAs,WrapperClauses), maplist(tc_clause,Clauses,TcClauses), append(WrapperClauses,TcClauses,NClauses). % PORTRAY_CLAUSE bug? % % 6 ?- functor(Head,p,2), Clause = (Head :- signature(Head)), portray_clause(Clause). % p(_, _) :- % signature(p(_, _)). wrapper_clause(F/A,Clause) :- functor(Head,F,A), tc_head(Head,Call), Clause = (Head :- type_check:signature(Head,_,[],_), Call ). tc_clause((Head :- Body),(TcHead :- TcBody)) :- !, tc_head(Head,TcHead), tc_body(Body,TcBody). tc_clause(Head, TcHead) :- tc_head(Head,TcHead). tc_head(Head,TcHead) :- Head =.. [F|Args], atom_concat('$tc_',F,NF), TcHead =.. [NF|Args]. tc_body(Var,TcBody) :- var(Var), !, TcBody = Var. tc_body((G1,G2),TcBody) :- !, TcBody = (TcG1,TcG2), tc_body(G1,TcG1), tc_body(G2,TcG2). tc_body((G1;G2),TcBody) :- !, TcBody = (TcG1;TcG2), tc_body(G1,TcG1), tc_body(G2,TcG2). tc_body((G1->G2),TcBody) :- !, TcBody = (TcG1 -> TcG2), tc_body(G1,TcG1), tc_body(G2,TcG2). tc_body(Body, TcBody) :- participating_predicate(Body), !, tc_head(Body,TcBody). tc_body(Body, TcBody) :- TcBody = Body. % }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% only_check_participating_clauses(_) :- \+ type_checking, !, fail. only_check_participating_clauses(Clause) :- only_check_participating_clauses(Clause,_). only_check_participating_clauses((:- _),_) :- !, fail. only_check_participating_clauses((Head :- _),FA) :- !, participating_predicate(Head), FA = F / A, functor(Head,F,A). only_check_participating_clauses(Head,FA) :- participating_predicate(Head), FA = F / A, functor(Head,F,A). participating_predicate(Head) :- functor(Head,Name,Arity), functor(Test,Name,Arity), signature(Test,_,[],_). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% basic_normalize_clause(Alias,Type,Clause) :- Clause = type_check:basic_normalize(Alias,Type). normalize_type(Type0,Type2) :- ( nonvar(Type0), basic_normalize(Type0,Type1) -> normalize_type(Type1,Type2) ; Type2 = Type0 ). equate_types(Type1,Type2) :- ( nonvar(Type1), nonvar(Type2) -> normalize_type(Type1,NType1), normalize_type(Type2,NType2), functor(NType1,Functor,Arity), functor(NType2,Functor,Arity), NType1 =.. [_|Args1], NType2 =.. [_|Args2], maplist(equate_types,Args1,Args2) ; unify_with_occurs_check(Type1,Type2) ). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Utility {{{ lookup_eq([K - V | KVs],Key,Value) :- ( K == Key -> V = Value ; lookup_eq(KVs,Key,Value) ). snd_of_pairs([],[]). snd_of_pairs([_-Y|XYs],[Y|Ys]) :- snd_of_pairs(XYs,Ys). % }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Goal expansion {{{ user:goal_expansion(UnsafeCall :: Signature, SafeCall) :- !, ( type_checking_runtime -> % Already at end_of_file when this code get executed. % prolog_load_context(file,File), % prolog_load_context(term_position,'$stream_position'(_, LineNumber, _, _, _)), % format('Expanding annotation in ~w at line ~w\n',[File,LineNumber]), functor(UnsafeCall,F,A), functor(Signature,F,A), UnsafeCall =.. [_|Args], Signature =.. [_|Types], args_body(Args,Types,Guard,[],_), SafeCall = ( UnsafeCall, ( Guard -> true ; throw(runtime_type_error(UnsafeCall)) ) ) ; SafeCall = UnsafeCall ). user:goal_expansion(UnsafeCall :< _Signature, Call) :- !, Call = UnsafeCall. user:goal_expansion(type_to_any(X,Y),(X = Y)). user:goal_expansion(any_to_type(X,Y,Type),Goal) :- !, ( type_checking_runtime -> Goal = (type_check:type_check_term(X,Type,[],_), X=Y) ; Goal = (X = Y) ). % }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Term expansion {{{ % goes last % otherwise we end up type checking the type checker... user:term_expansion((:- type_check_options(Options)),[]) :- handle_options(Options). user:term_expansion((:- runtime_type_check(Flag)),[]) :- %writeln(type_checking_runtime(Flag)), handle_option(runtime(Flag)). user:term_expansion((:- type Name ---> Constructors), Clauses ) :- ( \+ \+ ( numbervars(Name, 0, _), ground(Constructors) ) -> phrase(constructor_clauses(Constructors,Name), Clauses) ; format("ERROR: invalid TYPE definition~w\n\tType definitions must be range-restricted!\n", [(:- type Name ---> Constructors)]), Clauses = [] ). user:term_expansion((:- type Alias == Type), [ Clause ]) :- basic_normalize_clause(Alias,Type,Clause). user:term_expansion((:- type _Name),[]). % empty type user:term_expansion((:- pred Signature), [ Clause ]) :- signature_clause(Signature,Clause). user:term_expansion((:- trust_pred Signature), [ SignatureClause , TrustedPredicateClause ]) :- signature_clause(Signature,SignatureClause), functor(Signature,P,N), TrustedPredicateClause = type_check:trusted_predicate(P/N). user:term_expansion(end_of_file,Clauses) :- type_check_file(Clauses). user:term_expansion(Clause, NClause) :- only_check_participating_clauses(Clause), assert(clause_to_check(Clause)), NClause = []. % }}} % {{{ final_message(tc_stats(E,T)) :- ( T > 0, type_checking_verbose -> prolog_load_context(module,Mod), write('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'), nl, format('% Type checking for module `~w\' done:\n%\tfound type errors in ~w out of ~w clauses.\n',[Mod,E,T]), ( E == 0 -> write('%\tWell-typed code can\'t go wrong!'), nl ; true ), write('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'), nl ; true ). init_stats(tc_stats(0,0)). inc_error_stats(tc_stats(E,T),tc_stats(NE,NT)) :- NE is E + 1, NT is T + 1. inc_ok_stats(tc_stats(E,T),tc_stats(E,NT)) :- NT is T + 1. % }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Predefined types: {{{ % % The types list(T), pair(A,B), boolean, integer and float are predefined by the type % checker. :- type list(T) ---> [] ; [T|list(T)]. :- type pair(A,B) ---> A - B. :- type boolean ---> true ; false. :- type cmp ---> (=) ; (>) ; (<). % }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Predefined signatures: {{{ % % :- pred write(_). % :- pred writeln(_). % }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % BUGS FOUND {{{ % ========== % % In rbtrees.pl (Vitor Santos Costa) % % :- pred rb_lookupall(K,V,rbtree(K,V)). % :- pred lookupall(K,V,tree(K,V)). % :- pred lookupall(cmp,K,V,tree(K,V)). % % rb_lookupall(Key, Val, t(_,Tree)) :- % lookupall(Key, Val, Tree). % % lookupall(_, _, black(nil,_,_,nil)) :- !, fail. % lookupall(Key, Val, Tree) :- % getkey(Tree,KA), % arg(2,Tree,KA), % compare(Cmp,KA,Key), % lookupall(Cmp,Key,Val,Tree). % % lookupall(>, K, V, Tree) :- % getright(Tree,NTree), % arg(4,Tree,NTree), % rb_lookupall(K, V, NTree). % BUG !!! % lookupall(=, _, V, Tree) :- % getvalue(Tree,V), % arg(3,Tree,V). % lookupall(=, K, V, Tree) :- % getleft(Tree,NTree), % arg(1,Tree,NTree), % lookupall(K, V, NTree). % lookupall(<, K, V, Tree) :- % getleft(Tree,NTree), % arg(1,Tree,NTree), % lookupall(K, V, NTree). % % }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTES {{{ % ===== % % In rbtrees.pl (Vitor Santos Costa) % * cannot share Nil in old and new tree: % % :- pred rb_clone(rbtree(K,_V1),rbtree(K,V2),list(pair(K,V2))). % rb_clone(t(_Nil1,T),t(Nil2,NT),Ns) :- % new(Nil2), % clone(T,NT,Ns,[]). % % }}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
JoseCSantos/GILPS
source/type_checker/type_check.pl
Perl
mit
36,439
package Paws::SSM::DescribeInstancePatchStatesForPatchGroup; use Moose; has Filters => (is => 'ro', isa => 'ArrayRef[Paws::SSM::InstancePatchStateFilter]'); has MaxResults => (is => 'ro', isa => 'Int'); has NextToken => (is => 'ro', isa => 'Str'); has PatchGroup => (is => 'ro', isa => 'Str', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'DescribeInstancePatchStatesForPatchGroup'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::SSM::DescribeInstancePatchStatesForPatchGroupResult'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::SSM::DescribeInstancePatchStatesForPatchGroup - Arguments for method DescribeInstancePatchStatesForPatchGroup on Paws::SSM =head1 DESCRIPTION This class represents the parameters used for calling the method DescribeInstancePatchStatesForPatchGroup on the Amazon Simple Systems Manager (SSM) service. Use the attributes of this class as arguments to method DescribeInstancePatchStatesForPatchGroup. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DescribeInstancePatchStatesForPatchGroup. As an example: $service_obj->DescribeInstancePatchStatesForPatchGroup(Att1 => $value1, Att2 => $value2, ...); Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object. =head1 ATTRIBUTES =head2 Filters => ArrayRef[L<Paws::SSM::InstancePatchStateFilter>] Each entry in the array is a structure containing: Key (string between 1 and 200 characters) Values (array containing a single string) Type (string "Equal", "NotEqual", "LessThan", "GreaterThan") =head2 MaxResults => Int The maximum number of patches to return (per page). =head2 NextToken => Str The token for the next set of items to return. (You received this token from a previous call.) =head2 B<REQUIRED> PatchGroup => Str The name of the patch group for which the patch state information should be retrieved. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method DescribeInstancePatchStatesForPatchGroup in L<Paws::SSM> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/SSM/DescribeInstancePatchStatesForPatchGroup.pm
Perl
apache-2.0
2,560
package Google::Ads::AdWords::v201402::AdGroupBidModifierService::getResponse; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201402' } __PACKAGE__->__set_name('getResponse'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::SOAP::Typelib::ComplexType ); our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %rval_of :ATTR(:get<rval>); __PACKAGE__->_factory( [ qw( rval ) ], { 'rval' => \%rval_of, }, { 'rval' => 'Google::Ads::AdWords::v201402::AdGroupBidModifierPage', }, { 'rval' => 'rval', } ); } # end BLOCK } # end of BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201402::AdGroupBidModifierService::getResponse =head1 DESCRIPTION Perl data type class for the XML Schema defined element getResponse from the namespace https://adwords.google.com/api/adwords/cm/v201402. =head1 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * rval $element->set_rval($data); $element->get_rval(); =back =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201402::AdGroupBidModifierService::getResponse->new($data); Constructor. The following data structure may be passed to new(): { rval => $a_reference_to, # see Google::Ads::AdWords::v201402::AdGroupBidModifierPage }, =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201402/AdGroupBidModifierService/getResponse.pm
Perl
apache-2.0
1,808
# # Copyright 2021 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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. # package hardware::server::ibm::bladecenter::snmp::mode::components::blower; use strict; use warnings; my %map_blower_state = ( 0 => 'unknown', 1 => 'good', 2 => 'warning', 3 => 'bad', ); my %map_controller_state = ( 0 => 'operational', 1 => 'flashing', 2 => 'notPresent', 3 => 'communicationError', 255 => 'unknown', ); # In MIB 'mmblade.mib' my $oid_blowers = '.1.3.6.1.4.1.2.3.51.2.2.3'; my $entry_blower_state = '10'; my $entry_blower_speed = '1'; my $entry_controller_state = '30'; my $count = 4; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_blowers }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking blowers"); $self->{components}->{blower} = {name => 'blowers', total => 0, skip => 0}; return if ($self->check_filter(section => 'blower')); for (my $i = 0; $i < $count; $i++) { my $instance = $i + 1; next if (!defined($self->{results}->{$oid_blowers}->{$oid_blowers . '.' . ($entry_blower_state + $i) . '.0'})); my $blower_state = $map_blower_state{$self->{results}->{$oid_blowers}->{$oid_blowers . '.' . ($entry_blower_state + $i) . '.0'}}; my $blower_speed = defined($self->{results}->{$oid_blowers}->{$oid_blowers . '.' . ($entry_blower_speed + $i) . '.0'}) ? $self->{results}->{$oid_blowers}->{$oid_blowers . '.' . ($entry_blower_speed + $i) . '.0'} : 'unknown'; my $ctrl_state = defined($self->{results}->{$oid_blowers}->{$oid_blowers . '.' . ($entry_controller_state + $i) . '.0'}) ? $map_controller_state{$self->{results}->{$oid_blowers}->{$oid_blowers . '.' . ($entry_controller_state + $i) . '.0'}} : undef; next if ($self->check_filter(section => 'blower', instance => $instance)); next if ($blower_speed =~ /No Blower/i && $self->absent_problem(section => 'blower', instance => $instance)); $self->{components}->{blower}->{total}++; if ($blower_speed =~ /^(\d+)%/) { $blower_speed = $1; my ($exit2, $warn, $crit, $checked) = $self->get_severity_numeric(section => 'blower', instance => $instance, value => $blower_speed); if (!$self->{output}->is_status(value => $exit2, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit2, short_msg => sprintf("Blower speed '%s' is %s %%", $instance, $blower_speed)); } $self->{output}->perfdata_add( label => "blower_speed", unit => '%', nlabel => 'hardware.blower.speed.percentage', instances => $instance, value => $blower_speed, warning => $warn, critical => $crit, min => 0, max => 100 ); } $self->{output}->output_add(long_msg => sprintf("Blower '%s' state is %s (%d %%).", $instance, $blower_state, $blower_speed)); my $exit = $self->get_severity(section => 'blower', value => $blower_state); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Blower '%s' state is %s", $instance, $blower_state)); } next if (!defined($ctrl_state)); next if ($self->check_filter(section => 'blowerctrl', instance => $instance)); next if ($ctrl_state =~ /notPresent/i && $self->absent_problem(section => 'blowerctrl', instance => $instance)); $self->{output}->output_add(long_msg => sprintf("Blower controller '%s' state is %s.", $instance, $ctrl_state)); $exit = $self->get_severity(section => 'blowerctrl', value => $ctrl_state); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Blower controller '%s' state is %s", $instance, $ctrl_state)); } } } 1;
Tpo76/centreon-plugins
hardware/server/ibm/bladecenter/snmp/mode/components/blower.pm
Perl
apache-2.0
5,081
# # (c) Jan Gehring <jan.gehring@gmail.com> # # vim: set ts=2 sw=2 tw=0: # vim: set expandtab: package Rex::Repositorio::Repository::Docker; use Moose; use Try::Tiny; use File::Basename qw'basename'; use Data::Dumper; use Carp; use Params::Validate qw(:all); use File::Spec; use File::Path; our $VERSION = '0.4.1'; # VERSION extends "Rex::Repositorio::Repository::Base"; sub init { my $self = shift; my $repo_dir = $self->app->get_repo_dir( repo => $self->repo->{name} ); mkpath "$repo_dir"; } 1;
gitpan/Rex-Repositorio
lib/Rex/Repositorio/Repository/Docker.pm
Perl
apache-2.0
510
package Google::Ads::AdWords::v201809::SharedCriterionService::ApiExceptionFault; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809' } __PACKAGE__->__set_name('ApiExceptionFault'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::AdWords::v201809::ApiException ); } 1; =pod =head1 NAME Google::Ads::AdWords::v201809::SharedCriterionService::ApiExceptionFault =head1 DESCRIPTION Perl data type class for the XML Schema defined element ApiExceptionFault from the namespace https://adwords.google.com/api/adwords/cm/v201809. A fault element of type ApiException. =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201809::SharedCriterionService::ApiExceptionFault->new($data); Constructor. The following data structure may be passed to new(): $a_reference_to, # see Google::Ads::AdWords::v201809::ApiException =head1 AUTHOR Generated by SOAP::WSDL =cut
googleads/googleads-perl-lib
lib/Google/Ads/AdWords/v201809/SharedCriterionService/ApiExceptionFault.pm
Perl
apache-2.0
1,103
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2018] EMBL-European Bioinformatics Institute 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. =cut package EnsEMBL::Web::JobDispatcher::VEPRest; use strict; use warnings; use JSON qw(to_json); use LWP::UserAgent; use EnsEMBL::Web::VEPConstants qw(REST_DISPATCHER_SERVER_ENDPOINT); use EnsEMBL::Web::Utils::FileHandler qw(file_get_contents file_put_contents); use parent qw(EnsEMBL::Web::JobDispatcher); sub dispatch_job { ## Abstract method implementation my ($self, $ticket_type, $job_data) = @_; my $species = $job_data->{'config'}{'species'}; my $endpoint = REST_DISPATCHER_SERVER_ENDPOINT =~ s/\:species/$species/r; my $input_file = join '/', $job_data->{'work_dir'}, $job_data->{'config'}{'input_file'}; my $output_file = join '/', $job_data->{'work_dir'}, $job_data->{'config'}{'output_file'}; my $output_json = $output_file =~ s/\.[^\.]+$/.json/r; my $status_file = "$output_json.status"; my @variants = file_get_contents($input_file, sub { s/\R//r }); my $response = $self->_post($endpoint, to_json({'variants' => \@variants})); file_put_contents("$output_json.status", $response->status_line); file_put_contents($output_json, $response->content) if $response->is_success; # this will get saved in dispatcher data column $job_data->{'status_file'} = $status_file; $job_data->{'output_json'} = $output_json; return $job_data->{'job_id'}; } sub delete_jobs { ## Nothing needs to be done here } sub update_jobs { ## Abstract method implementation my ($self, $jobs) = @_; for (@$jobs) { my $job_data = $_->dispatcher_data; my ($status) = $job_data->{'status_file'} && -e $job_data->{'status_file'} ? file_get_contents($job_data->{'status_file'}) : ('Job does not exist'); if ($status =~ /^200/) { # job successful $_->dispatcher_status('done'); $_->status('done'); } else { # job failed $_->dispatcher_status('failed'); $_->status('awaiting_user_response'); $_->job_message([{ 'display_message' => $self->default_error_message, 'exception' => {'exception' => $status}, 'fatal' => 1 }]); } } } sub _post { my ($self, $url, $message) = @_; my $ua = LWP::UserAgent->new; $ua->proxy([qw(http https)], $_) for $self->web_proxy || (); my $request = HTTP::Request->new('POST', $url); $request->header('Content-type' => 'application/json'); $request->header('Cache-control' => 'no-cache'); $request->header('Pragma' => 'no-cache'); $request->content($message); return $ua->request($request); } 1;
muffato/public-plugins
tools/modules/EnsEMBL/Web/JobDispatcher/VEPRest.pm
Perl
apache-2.0
3,229
compile :- print(compiling),nl, fcompile('advisor.pro'), fcompile('applast.pro'), fcompile('contains.pro'), fcompile('depth.pro'), fcompile('doubleapp.pro'), fcompile('ex_depth.pro'), fcompile('flip.pro'), fcompile('grammar.pro'), fcompile('groundunify.pro'), fcompile('imperative-solve.pro'), fcompile('liftsolve.pro'), fcompile('map.pro'), fcompile('match.pro'), fcompile('matchapp.pro'), fcompile('maxlength.pro'), fcompile('model_elim.pro'), fcompile('partialevaluator.pro'), fcompile('regexp.pro'), fcompile('relative.pro'), fcompile('remove.pro'), fcompile('remove2.pro'), fcompile('rev.pro'), fcompile('rev_acc_type.pro'), fcompile('revlast.pro'), fcompile('rotateprune.pro'), fcompile('ssuply.pro'), fcompile('transpose.pro'), fcompile('upto.pro'), fcompile('vanilla.doubleapp.pro'), print(finished),nl. :- compile,halt.
leuschel/ecce
ecce_benchmarks/orig/compile_orig.pl
Perl
apache-2.0
894
=head1 NAME LedgerSMB::Scripts::order - Order search functions for LedgerSMB =head1 SYNPOSIS LedgerSMB::Scripts::order->get_criteria($request); =head1 DESCRIPTION This module contains the routines needed to search for orders, whether for shipping or receiving, merging several orders into one, or the like. =cut package LedgerSMB::Scripts::order; use strict; use warnings; use LedgerSMB::App_State; use LedgerSMB::Scripts::reports; use LedgerSMB::Report::Orders; use LedgerSMB::Form; # for dispatching to old code =head1 ROUTINES =over =item get_criteria Expects "search_type" and "oe_class_id" to be set. Any other properties of LedgerSMB::Report::Orders can be set here and will act as defaults. Search type can be one of =over =item search (valid for all types) =item combine (valid for sales/purchase orders only at this time) =item generate (valid for sales/purchase orders only) =back =cut sub get_criteria { my ($request) = @_; my $locale = $LedgerSMB::App_State::Locale; $request->{entity_class} = $request->{oe_class_id} % 2 + 1; $request->{report_name} = 'orders'; $request->{open} = 1 if $request->{search_type} ne 'search'; if ($request->{oe_class_id} == 1){ if ($request->{search_type} eq 'search'){ $request->{title} = $locale->text('Search Sales Orders'); } elsif ($request->{search_type} eq 'generate'){ $request->{title} = $locale->text('Generate Purchase Orders from Sales Orders'); } elsif ($request->{search_type} eq 'combine'){ $request->{title} = $locale->text('Combine Sales Orders'); } elsif ($request->{search_type} eq 'ship'){ $request->{title} = $locale->text('Ship'); } } elsif ($request->{oe_class_id} == 2){ if ($request->{search_type} eq 'search'){ $request->{title} = $locale->text('Search Purchase Orders'); } elsif ($request->{search_type} eq 'combine'){ $request->{title} = $locale->text('Combine Purchase Orders'); } elsif ($request->{search_type} eq 'generate'){ $request->{title} = $locale->text('Generate Sales Orders from Purchase Orders'); } elsif ($request->{search_type} eq 'ship'){ $request->{title} = $locale->text('Receive'); } } elsif ($request->{oe_class_id} == 3){ if ($request->{search_type} eq 'search'){ $request->{title} = $locale->text('Search Quotations'); } } elsif ($request->{oe_class_id} == 4){ if ($request->{search_type} eq 'search'){ $request->{title} = $locale->text('Search Requests for Quotation'); } } LedgerSMB::Scripts::reports::start_report($request); } =item search =cut sub search { my $request = shift @_; if ($request->{search_type} ne 'search'){ $request->{open} =1; delete $request->{closed}; } if (($request->{search_type} eq 'combine') or ($request->{search_type} eq 'generate') ){ $request->{selectable} = 1; $request->{col_select} = 1; } elsif ($request->{search_type} eq 'ship'){ $request->{href_action}='ship_receive'; } my $report = LedgerSMB::Report::Orders->new(%$request); if ($request->{search_type} eq 'combine'){ $report->buttons([{ text => $LedgerSMB::App_State::Locale->text('Combine'), type => 'submit', class => 'submit', name => 'action', value => 'combine', }]); } elsif ($request->{search_type} eq 'generate'){ $report->buttons([{ text => $LedgerSMB::App_State::Locale->text('Generate'), type => 'submit', class => 'submit', name => 'action', value => 'generate', }]); } $report->render($request); } =item combine This combines sales orders or purchase orders. It could be easily supported for quotations and rfq's but this is not currently allowed. =cut sub combine { my ($request) = @_; my @ids; for (1 .. $request->{rowcount_}){ push @ids, $request->{"selected_$_"} if $request->{"selected_$_"}; } $request->call_procedure(funcname => 'order__combine', args => [\@ids]); $request->{search_type} = 'combine'; get_criteria($request); } =item generate This is just a dispatch handle currently to bin/oe's generate_purchase_orders callback. =cut sub generate { my ($request) = @_; my $form = new Form; for my $k (keys %$request){ $form->{$k} = $request->{$k}; } { no strict; no warnings 'redefine'; do 'bin/oe.pl'; } my $locale = $LedgerSMB::App_State::Locale; lsmb_legacy::generate_purchase_orders($form, $locale); } =back =head1 COPYRIGHT COPYRIGHT (C) 2012 The LedgerSMB Core Team. This file may be re-used under the terms of the LedgerSMB General Public License version 2 or at your option any later version. Please see enclosed LICENSE file for details. =cut 1;
tridentcodesolution/tridentcodesolution.github.io
projects/CRM/LedgerSMB-master/LedgerSMB/Scripts/order.pm
Perl
apache-2.0
5,029
=head1 LICENSE Copyright [1999-2016] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute 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. =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =head1 NAME =head1 SYNOPSIS =head1 DESCRIPTION =cut package Bio::EnsEMBL::Funcgen::PhantomPeak; use strict; use Bio::EnsEMBL::Utils::Exception qw( deprecate ); use Bio::EnsEMBL::Funcgen::GenericGetSetFunctionality qw( _generic_get_or_set ); use Role::Tiny::With; with 'Bio::EnsEMBL::Funcgen::GenericConstructor'; sub _constructor_parameters { return { dbID => 'dbID', adaptor => 'adaptor', analysis_id => 'analysis_id', alignment_id => 'alignment_id', num_reads => 'num_reads', est_frag_len => 'est_frag_len', est_frag_len_2 => 'est_frag_len_2', est_frag_len_3 => 'est_frag_len_3', corr_est_frag_len => 'corr_est_frag_len', corr_est_frag_len_2 => 'corr_est_frag_len_2', corr_est_frag_len_3 => 'corr_est_frag_len_3', phantom_peak => 'phantom_peak', corr_phantom_peak => 'corr_phantom_peak', argmin_corr => 'argmin_corr', min_corr => 'min_corr', nsc => 'nsc', rsc => 'rsc', quality_tag => 'quality_tag', run_failed => 'run_failed', error_message => 'error_message', }; } sub dbID { return shift->_generic_get_or_set('dbID', @_); } sub adaptor {return shift->_generic_get_or_set('adaptor', @_);} sub analysis_id { return shift->_generic_get_or_set('analysis_id', @_); } sub alignment_id { return shift->_generic_get_or_set('alignment_id', @_); } sub num_reads { return shift->_generic_get_or_set('num_reads', @_); } sub est_frag_len { return shift->_generic_get_or_set('est_frag_len', @_); } sub est_frag_len_2 { return shift->_generic_get_or_set('est_frag_len_2', @_); } sub est_frag_len_3 { return shift->_generic_get_or_set('est_frag_len_3', @_); } sub corr_est_frag_len { return shift->_generic_get_or_set('corr_est_frag_len', @_); } sub corr_est_frag_len_2 { return shift->_generic_get_or_set('corr_est_frag_len_2', @_); } sub corr_est_frag_len_3 { return shift->_generic_get_or_set('corr_est_frag_len_3', @_); } sub phantom_peak { return shift->_generic_get_or_set('phantom_peak', @_); } sub corr_phantom_peak { return shift->_generic_get_or_set('corr_phantom_peak', @_); } sub argmin_corr { return shift->_generic_get_or_set('argmin_corr', @_); } sub min_corr { return shift->_generic_get_or_set('min_corr', @_); } sub nsc { return shift->_generic_get_or_set('nsc', @_); } sub rsc { return shift->_generic_get_or_set('rsc', @_); } sub quality_tag { return shift->_generic_get_or_set('quality_tag', @_); } sub run_failed { return shift->_generic_get_or_set('run_failed', @_); } sub error_message { return shift->_generic_get_or_set('error_message', @_); } sub get_Alignment { my $self = shift; my $alignment_adaptor = $self->adaptor->db->get_AlignmentAdaptor; if (! defined $alignment_adaptor) { throw("Couldn't get an AlignmentAdaptor!"); } my $alignment = $alignment_adaptor->fetch_by_dbID($self->alignment_id); return $alignment; } =head2 summary_as_hash Example : $summary = $peak_calling->summary_as_hash; Description : Returns summary in a hash reference. Returns : Hashref of descriptive strings Status : Intended for internal use (REST) =cut sub summary_as_hash { my $self = shift; # Optional parameter to avoid infinite recursions when two objects # reference each other. # my $suppress_link = shift; my $summary = { num_reads => $self->num_reads, quality_tag => $self->quality_tag, rsc => $self->rsc, nsc => $self->nsc, phantom_peak => $self->phantom_peak, est_frag_len => $self->est_frag_len, }; if ($suppress_link ne 'alignment') { my $alignment = $self->get_Alignment; $summary->{'alignment'} = $alignment->summary_as_hash('phantom_peak'); } return $summary; } 1;
Ensembl/ensembl-funcgen
modules/Bio/EnsEMBL/Funcgen/PhantomPeak.pm
Perl
apache-2.0
5,034
package Paws::DynamoDBStreams::AttributeMap; use Moose; with 'Paws::API::StrToObjMapParser'; has Map => (is => 'ro', isa => 'HashRef[Paws::DynamoDBStreams::AttributeValue]'); 1; ### main pod documentation begin ### =head1 NAME Paws::DynamoDBStreams::AttributeMap =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::DynamoDBStreams::AttributeMap object: $service_obj->Method(Att1 => { key1 => $value, ..., keyN => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::DynamoDBStreams::AttributeMap object: $result = $service_obj->Method(...); $result->Att1->Map->{ key1 } =head1 DESCRIPTION This class has no description =head1 ATTRIBUTES =head2 Map => L<Paws::DynamoDBStreams::AttributeValue> Use the Map method to retrieve a HashRef to the map =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::DynamoDBStreams> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/DynamoDBStreams/AttributeMap.pm
Perl
apache-2.0
1,416
package ItemConstants; use warnings; use strict; use UrlConstants; use URI::Escape; use File::Glob ':glob'; use File::Copy 'cp'; use Time::HiRes; use Passage; use REST::Client; BEGIN { use Exporter (); use vars qw(@ISA @EXPORT @EXPORT_OK); @ISA = qw(Exporter); @EXPORT_OK = qw(); @EXPORT = qw($asset_path $assetCreateFramesetUrl $assetCreateUrl $assetInsertUrl $assetUploadUrl $itemCharacterizeUrl $assignStandardUrl $assignPassageUrl $imagesUrl $imagesDir $textogif_dir $itemCreateUrl $itemFindUrl $imageEditUrl $assetBlankUrl $assetFindUrl $findByStandardUrl $USE_ITEM_XML $assignRubricUrl $projectConfigDir $escapeChars $mediaUploadUrl $mediaViewUrl $mediaInsertUrl $mediaDeleteUrl $DS_DEVELOPMENT $DS_REVIEW $DS_TESTING $DS_APPROVED $DS_RELEASED $DS_SUSPENDED $DS_CANCELLED $DS_IMPORTED $DS_REJECTED $DS_PM_FIX $DS_RETIRED $DS_CONTENT_REVIEW $DS_CONTENT_REVIEW_2 $DS_ON_HOLD $DS_SCHEDULED $DS_CONTENT_APPROVED $DS_COPY_REVIEW $DS_COPY_REVIEW_2 $DS_COPY_APPROVED $DS_CLIENT_APPROVED $DS_CLIENT_APPROVED_2 $DS_CLIENT_APPROVED_3 $DS_COPY_TEACHER_REVIEW $DS_COPY_F2F_REVIEW $DS_COPY_FINAL_REVIEW $DS_NEW_ART $DS_FIX_ART $DS_SUPERVISOR_REVIEW $DS_CLIENT_PREVIEW $DS_CUSTOMER_PROOF $DS_READY_FOR_AUDIO $DS_CONTENT_REVIEW_1 $DS_ITEM_UPDATE_1 $DS_COMMITTEE_REVIEW $DS_ITEM_UPDATE_2 $DS_CONTENT_REVIEW_3 $DS_SENSITIVITY_REVIEW $DS_EXTERNAL_EDITOR_REVIEW $DS_CONTENT_REVIEW_4 $DS_ITEM_UPDATE_3 $DS_CONTENT_REVIEW_5 $DS_ART_REQUEST_REVIEW $DS_PENDING_ART $DS_READY_FOR_ART $DS_PROOFREADING $DS_CONTENT_REVIEW_6 $DS_ITEM_UPDATE_4 $DS_CONTENT_REVIEW_7 $DS_QA_REVIEW $DS_PROGRAM_DIRECTOR_REVIEW $DS_ART_REQUEST_REVIEW $DS_BANKED $DS_CONSORTIUM_REVIEW $DS_DNU_ITEM_POOL $DS_FIX_MEDIA $DS_NEW_MEDIA $DS_QUERY_RESOLUTION $DS_DATA_REVIEW $DS_OPERATIONAL_ITEM_POOL $DS_POST_ADMIN_REVIEW $DS_QC_PRESENTATION_REVIEW $DS_POST_COMMITTEE $DS_NEW_ACCESSIBILITY $DS_FIX_ACCESSIBILITY @graphic_extensions @media_extensions @asset_extensions @banned_extensions @choice_chars %reverse_choice_chars $OC_ITEM_STANDARD $OC_CONTENT_AREA $OC_GRADE_LEVEL $OC_PASSAGE $OC_POINTS $OC_DOK $OC_RUBRIC $OC_PROTRACTOR $OC_RULER $OC_CALCULATOR $OC_GRADE_SPAN_START $OC_GRADE_SPAN_END $OC_COMPASS $OC_SCORING_METHOD $OC_ITEM_FORMAT $OC_SCALE_VALUE $OC_MAP_VALUE $OC_MINOR_EDIT $OC_SECONDARY_STANDARD $OC_TERTIARY_STANDARD $OC_BENCHMARK $OC_SECONDARY_BENCHMARK $OC_TERTIARY_BENCHMARK $OC_CONTENT_STANDARD $OC_SECONDARY_CONTENT_STANDARD $OC_TERTIARY_CONTENT_STANDARD $OC_COMP_CURRICULUM $OC_CATEGORY $OC_SECONDARY_CATEGORY $OC_TERTIARY_CATEGORY $OC_DEFAULT_ANSWER $OC_LAYOUT $OC_ANSWER_FORMAT $OC_FORM_GROUP $OC_ACCESSIBILITY_AUDIO $OC_ACCESSIBILITY_LARGE_PRINT $OC_ITEM_ENEMY $OC_CHOICE_SHUFFLE $OT_TEST $OT_SECTION $OT_MODULE $OT_PASSAGE $OT_RUBRIC $OT_ITEM $IT_X_MC $IT_NON_X_MC $IT_SHORT_CR $IT_EXTENDED_CR $IT_BUBBLE $IT_MULTI_SHORT_CR $IT_MULTI_EXTENDED_CR $IT_INTERACTIVE $IT_CHOICE $IT_TEXT_ENTRY $IT_EXTENDED_TEXT $IT_INLINE_CHOICE $IT_MATCH $UP_VIEW_ITEM_BANK $UP_VIEW_TEST_BANK $UP_VIEW_WORKGROUP $RP_EDIT_ITEM $RP_REVIEW_ITEM $RP_COMMENT_ITEM $RP_DATA_REVIEW_ITEM $RP_EDIT_TEST $RP_REVIEW_TEST $RP_COMMENT_TEST $IF_STEM $IF_CHOICE $IF_DISTRACTOR_RATIONALE $IF_PROMPT $IF_CHOICE_MATCH $IF_FEEDBACK_INITIAL $IF_FEEDBACK_FINAL @labels @const @ctypes @tools $HD_STD_HIERARCHY $HD_CONTENT_AREA $HD_STANDARD_STRAND $HD_GRADE_CLUSTER $HD_BENCHMARK $HD_GRADE_LEVEL $HD_GLE $HD_SUBSTRAND $HD_GRADE_LEVEL_COURSE $HD_ROOT $HD_LEAF %standard_types $P_ITEM_EDIT $P_ITEM_REVIEW_CONTENT $P_ITEM_REVIEW_COPY $P_ITEM_AUDIO_SCRIPTOR $P_ITEM_APPROVE $P_ITEM_ART $P_ITEM_ADMIN $P_ITEM_SUPER_ADMIN $P_CONTENT_SPECIALIST $P_COPY_EDITOR $P_GRAPHIC_DESIGNER $P_MEDIA_DESIGNER $P_COMMITTEE_REVIEWER $P_QC_PRESENTATION $P_DATA_MANAGER $P_PSYCHOMETRICIAN $P_COMMITTEE_FACILITATOR $UA_NONE $UA_SUPER $UA_ORG $UA_PROGRAM %admin_type $UR_NONE $UR_ITEM_EDIT $UR_CONTENT_SPECIALIST $UR_COPY_EDITOR $UR_GRAPHIC_DESIGNER $UR_MEDIA_DESIGNER $UR_COMMITTEE_REVIEWER $UR_QC_PRESENTATION $UR_DATA_MANAGER $UR_PSYCHOMETRICIAN $UR_COMMITTEE_FACILITATOR $UR_DATA_REVIEWER $UR_ACCESSIBILITY_SPECIALIST %review_type $UT_ITEM_EDITOR %publication_status %export_ok %read_only %item_types %item_formats @dev_states_workflow_ordered_keys %dev_states %genres %languages %difficulty_levels %defaults %layout_types %asy_colors $rubricUrl $rubricPath %contentStandards $pxn8Url $passageUrl $passagePath $imageSaveUrl %default $textogif_url $chartDisplayUrl %charts $chartsUrl $passageUploadAssetUrl $passageInsertAssetUrl $rubricUploadAssetUrl %itemStandardChar $rubricInsertAssetUrl &setImageSize &sendNewItemNotification $sourcesUrl $sourcesDir &replaceChars &fixHtml &getStandardsUnderRoot &getBubbleHtml $CODED_ERROR_TYPE %error_types &getPassageAssets &getRubricAssets &getItemsByUser &hashToSelect &hashToCheckbox &readOgtFile &getStandard &dbCharUpdate &getEditors &getUsers &print_no_auth &printNoAuthPage &get_ts &getNewItemPrefix &getItemAssets &getSession &setItemReviewState &setPassageReviewState &getNextItemSequence &get_project_config %workStates &getProjects &getPassageList %itemNotesTags $dbDsn $dbUser $dbPass $webPath $orcaPath $orcaUrl $webHost &getItemXml &getItemBanks &getStandards &isHTMLContentEmpty &escapeHTML &unescapeHTML &escapeFlashValue &unescapeFlashValue &setAssetAttributes &getContentStandard &getGLENumber &getUsersWithPermissions &getUsersByItemBank &getWorkgroups &getWorkgroupFilters &getFileContent &getItemArchive &getImageSrcTranslate $USE_FLASH_CHARTS %stringCharacteristics &getActionMap &getWorkListForUserType %action_key_states $commonUrl $commonPath %CDE_CONFIG $instance_name $_config &getContentAssetPair &setContentAssetPair $ITEM_ACTION_MAP $PASSAGE_ACTION_MAP %role_item_permission_types %role_test_permission_types %default_role_permissions @role_types %role_labels &getMediaAssetAttributes &getMediaTableHtml &getMediaHtml &getMediaReadyFunction &addItemComment &addPassageComment %item_rating &getBankMetafilesForItem $IB_METAFILE_ITEM_SPEC $IB_METAFILE_PASSAGE_SPEC $IB_METAFILE_COPYRIGHT $IB_METAFILE_OTHER %ib_metafile_types %mc_answer_choices &getOrganizations %review_type_map &getCurrentItemIdByName &getUsersWithReviewType @review_with_edit @review_per_user %item_interactions $ST_MATCH_RESPONSE $ST_RUBRIC &attributeStringToHash &hashToAttributeString %tags_with_no_id %characterization_view_types &makeQueryWithWorkgroupFilter %review_flags &getMetadataClient $metadataServiceUrl ); push @INC, '/usr/lib/perl5/vendor_perl/5.8.6/'; } our @EXPORT; our $CODED_ERROR_TYPE = 0; our $USE_ITEM_XML = 0; our $USE_FLASH_CHARTS = 1; our $escapeChars = "^A-Za-z0-9"; #my $asset_url = "${orcaUrl}images/"; our $asset_path = "${orcaPath}images/"; our $assetCreateFramesetUrl = "${orcaUrl}cgi-bin/assetCreateFrameset.pl"; our $assetCreateUrl = "${orcaUrl}cgi-bin/assetCreate.pl"; our $assetInsertUrl = "${orcaUrl}cgi-bin/assetInsert.pl"; our $assetUploadUrl = "${orcaUrl}cgi-bin/assetUpload.pl"; our $itemCharacterizeUrl = "${orcaUrl}cgi-bin/itemCharacterize.pl"; our $assignStandardUrl = "${orcaUrl}cgi-bin/itemAssignStandard.pl"; our $assignPassageUrl = "${orcaUrl}cgi-bin/itemAssignPassage.pl"; our $assignRubricUrl = "${orcaUrl}cgi-bin/itemAssignRubric.pl"; our $itemCreateUrl = "${orcaUrl}cgi-bin/itemCreate.pl"; our $itemFindUrl = "${orcaUrl}cgi-bin/itemFind.pl"; our $assetFindUrl = "${orcaUrl}cgi-bin/assetFind.pl"; our $mediaUploadUrl = "${orcaUrl}cgi-bin/mediaUpload.pl"; our $mediaViewUrl = "${orcaUrl}cgi-bin/mediaView.pl"; our $mediaInsertUrl = "${orcaUrl}cgi-bin/mediaInsert.pl"; our $mediaDeleteUrl = "${orcaUrl}cgi-bin/mediaDelete.pl"; our $assetBlankUrl = "${orcaUrl}assetCreateBlank.html"; our $passageUploadAssetUrl = "${orcaUrl}cgi-bin/passageUploadAsset.pl"; our $passageInsertAssetUrl = "${orcaUrl}cgi-bin/passageInsertAsset.pl"; our $rubricUploadAssetUrl = "${orcaUrl}cgi-bin/rubricUploadAsset.pl"; our $rubricInsertAssetUrl = "${orcaUrl}cgi-bin/rubricInsertAsset.pl"; our $imageEditUrl = "${orcaUrl}cgi-bin/editImage.pl"; our $imageSaveUrl = "${orcaUrl}cgi-bin/saveImage.pl"; our $pxn8Url = "${commonUrl}pixenate/"; our $passageUrl = "${orcaUrl}passages/"; our $passagePath = $webPath . $passageUrl; our $rubricUrl = "${orcaUrl}rubrics/"; our $rubricPath = $webPath . $rubricUrl; our $findByStandardUrl = "${orcaUrl}cgi-bin/itemFindByStandard.pl"; our $chartDisplayUrl = "${orcaUrl}cgi-bin/chartDisplay.pl"; our $projectConfigDir = "${webPath}${orcaUrl}project/"; our $metadataServiceUrl = $javaUrl . 'service/import/itemMetadata/'; our $imagesUrl = "${orcaUrl}images/"; our $imagesDir = $webPath . $imagesUrl; our $chartsUrl = "${commonUrl}charts/"; our $sourcesUrl = "${orcaUrl}sources/"; our $sourcesDir = $webPath . $sourcesUrl; our $textogif_dir = $webPath . "/textogif/"; our $textogif_url = "${orcaUrl}cgi-bin/textogif.pl"; our @graphic_extensions = qw/gif png jpg jpeg svg/; our @media_extensions = qw/mp3 m4a m4v swf mp4/; our @banned_extensions = qw/exe EXE dll DLL bat BAT/; our @asset_extensions = (@graphic_extensions, @media_extensions, qw/xml/); our @choice_chars = ( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ); our %reverse_choice_chars = ( 'A' => 0, 'B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6, 'H' => 7, 'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11, 'M' => 12, 'N' => 13, 'O' => 14, 'P' => 15, 'Q' => 16, 'R' => 17, 'S' => 18, 'T' => 19, 'U' => 20, 'V' => 21); our $DS_DEVELOPMENT = 1; our $DS_REVIEW = 2; our $DS_TESTING = 3; our $DS_APPROVED = 4; our $DS_RELEASED = 5; our $DS_SUSPENDED = 6; our $DS_CANCELLED = 7; our $DS_IMPORTED = 8; our $DS_REJECTED = 9; our $DS_PM_FIX = 10; our $DS_RETIRED = 11; our $DS_CONTENT_REVIEW = 12; our $DS_CONTENT_REVIEW_2 = 13; our $DS_ON_HOLD = 14; our $DS_SCHEDULED = 15; our $DS_CONTENT_APPROVED = 16; our $DS_COPY_REVIEW = 17; our $DS_COPY_APPROVED = 18; our $DS_NEW_ART = 19; our $DS_FIX_ART = 20; our $DS_CLIENT_APPROVED = 21; our $DS_CLIENT_APPROVED_2 = 22; our $DS_CLIENT_APPROVED_3 = 23; our $DS_COPY_TEACHER_REVIEW = 24; our $DS_COPY_F2F_REVIEW = 25; our $DS_COPY_FINAL_REVIEW = 26; our $DS_COPY_REVIEW_2 = 27; our $DS_SUPERVISOR_REVIEW = 28; our $DS_CLIENT_PREVIEW = 29; our $DS_CUSTOMER_PROOF = 30; our $DS_READY_FOR_AUDIO = 31; ### New CB Dev States our $DS_CONTENT_REVIEW_1 = 40; our $DS_ITEM_UPDATE_1 = 41; our $DS_COMMITTEE_REVIEW = 42; our $DS_ITEM_UPDATE_2 = 43; our $DS_CONTENT_REVIEW_3 = 44; our $DS_SENSITIVITY_REVIEW = 45; our $DS_EXTERNAL_EDITOR_REVIEW = 46; our $DS_CONTENT_REVIEW_4 = 47; our $DS_ITEM_UPDATE_3 = 48; our $DS_CONTENT_REVIEW_5 = 49; our $DS_ART_REQUEST_REVIEW = 50; our $DS_PENDING_ART = 51; our $DS_READY_FOR_ART = 52; our $DS_PROOFREADING = 53; our $DS_CONTENT_REVIEW_6 = 54; our $DS_ITEM_UPDATE_4 = 55; our $DS_CONTENT_REVIEW_7 = 56; our $DS_QA_REVIEW = 57; our $DS_PROGRAM_DIRECTOR_REVIEW = 58; ### New SBAC Dev States our $DS_BANKED = 60; our $DS_CONSORTIUM_REVIEW = 61; our $DS_DNU_ITEM_POOL = 62; our $DS_FIX_MEDIA = 63; our $DS_NEW_MEDIA = 64; our $DS_QUERY_RESOLUTION = 65; our $DS_DATA_REVIEW = 66; our $DS_OPERATIONAL_ITEM_POOL = 67; our $DS_POST_ADMIN_REVIEW = 68; our $DS_QC_PRESENTATION_REVIEW = 69; our $DS_POST_COMMITTEE = 70; our $DS_NEW_ACCESSIBILITY = 71; our $DS_FIX_ACCESSIBILITY = 72; our $OC_ITEM_STANDARD = 1; our $OC_CONTENT_AREA = 2; our $OC_GRADE_LEVEL = 3; our $OC_PASSAGE = 4; our $OC_GRADE_SPAN_START = 5; our $OC_GRADE_SPAN_END = 6; our $OC_POINTS = 7; our $OC_DOK = 8; our $OC_PROTRACTOR = 9; our $OC_RULER = 10; our $OC_CALCULATOR = 13; our $OC_RUBRIC = 16; our $OC_COMPASS = 18; our $OC_SCORING_METHOD = 28; our $OC_ITEM_FORMAT = 30; our $OC_SCALE_VALUE = 31; our $OC_MAP_VALUE = 32; our $OC_MINOR_EDIT = 33; our $OC_SECONDARY_STANDARD = 34; our $OC_TERTIARY_STANDARD = 35; our $OC_BENCHMARK = 36; our $OC_SECONDARY_BENCHMARK = 37; our $OC_TERTIARY_BENCHMARK = 38; our $OC_CONTENT_STANDARD = 39; our $OC_SECONDARY_CONTENT_STANDARD = 40; our $OC_TERTIARY_CONTENT_STANDARD = 41; our $OC_COMP_CURRICULUM = 42; our $OC_CATEGORY = 43; our $OC_SECONDARY_CATEGORY = 44; our $OC_TERTIARY_CATEGORY = 45; our $OC_DEFAULT_ANSWER = 46; our $OC_LAYOUT = 47; our $OC_ANSWER_FORMAT = 48; our $OC_FORM_GROUP = 49; our $OC_ACCESSIBILITY_AUDIO = 50; our $OC_ACCESSIBILITY_LARGE_PRINT = 51; our $OC_ITEM_ENEMY = 52; our $OC_CHOICE_SHUFFLE = 53; our $OT_TEST = 1; our $OT_MODULE = 2; our $OT_SECTION = 3; our $OT_ITEM = 4; our $OT_PASSAGE = 7; our $OT_RUBRIC = 8; our $IF_STEM = 1; our $IF_CHOICE = 2; our $IF_DISTRACTOR_RATIONALE = 3; our $IF_FEEDBACK_INITIAL = 4; our $IF_FEEDBACK_FINAL = 5; our $IF_PROMPT = 6; our $IF_CHOICE_MATCH = 7; our $IT_X_MC = 1; our $IT_NON_X_MC = 2; our $IT_SHORT_CR = 3; our $IT_EXTENDED_CR = 4; our $IT_BUBBLE = 5; our $IT_INTERACTIVE = 6; our $IT_MULTI_SHORT_CR = 23; our $IT_MULTI_EXTENDED_CR = 24; our $IT_CHOICE = 1; our $IT_TEXT_ENTRY = 2; our $IT_EXTENDED_TEXT = 3; our $IT_INLINE_CHOICE = 4; our $IT_MATCH = 5; our $ST_MATCH_RESPONSE = 1; our $ST_RUBRIC = 2; our $HD_STD_HIERARCHY = 1; our $HD_CONTENT_AREA = 2; our $HD_STANDARD_STRAND = 3; our $HD_GRADE_CLUSTER = 4; our $HD_BENCHMARK = 5; our $HD_GRADE_LEVEL = 6; our $HD_GLE = 7; our $HD_SUBSTRAND = 8; our $HD_GRADE_LEVEL_COURSE = 9; our %standard_types = ( 1 => 'Program', 2 => 'Test Subject', 3 => 'Area', 4 => 'General Content', 5 => 'Specific Content', 6 => 'Sub-Specific Content' ); our $HD_ROOT = 1; our $HD_LEAF = 6; our $IB_METAFILE_ITEM_SPEC = 1; our $IB_METAFILE_PASSAGE_SPEC = 2; our $IB_METAFILE_COPYRIGHT = 3; our $IB_METAFILE_OTHER = 4; our %ib_metafile_types = ( $IB_METAFILE_ITEM_SPEC => 'Item Specification', $IB_METAFILE_PASSAGE_SPEC => 'Passage Specification', $IB_METAFILE_COPYRIGHT => 'Copyright/DRM', $IB_METAFILE_OTHER => 'Other' ); our $P_ITEM_EDIT = 1; our $P_ITEM_REVIEW_CONTENT = 2; our $P_ITEM_REVIEW_COPY = 4; our $P_ITEM_APPROVE = 8; our $P_ITEM_ADMIN = 16; our $P_ITEM_ART = 32; our $P_ITEM_AUDIO_SCRIPTOR = 40; our $P_ITEM_SUPER_ADMIN = 64; our $P_CONTENT_SPECIALIST = 128; our $P_COPY_EDITOR = 256; our $P_GRAPHIC_DESIGNER = 512; our $P_MEDIA_DESIGNER = 1024; our $P_COMMITTEE_REVIEWER = 2048; our $P_QC_PRESENTATION = 4096; our $P_DATA_MANAGER = 8192; our $P_PSYCHOMETRICIAN = 16384; our $P_COMMITTEE_FACILITATOR = 32768; our @role_types = ( $P_ITEM_EDIT, $P_CONTENT_SPECIALIST, $P_COPY_EDITOR, $P_GRAPHIC_DESIGNER, $P_MEDIA_DESIGNER, $P_COMMITTEE_REVIEWER, $P_QC_PRESENTATION, $P_DATA_MANAGER, $P_PSYCHOMETRICIAN, $P_COMMITTEE_FACILITATOR ); my %role_labels = ( $P_ITEM_EDIT => 'Item Writer', $P_CONTENT_SPECIALIST => 'Content Specialist', $P_COPY_EDITOR => 'Copy Editor', $P_GRAPHIC_DESIGNER => 'Graphic Designer', $P_MEDIA_DESIGNER => 'Media Designer', $P_COMMITTEE_REVIEWER => 'Committee Reviewer', $P_QC_PRESENTATION => 'QC Presentation', $P_DATA_MANAGER => 'Data Manager', $P_PSYCHOMETRICIAN => 'Psychmetrician', $P_COMMITTEE_FACILITATOR => 'Committee Facilitator', ); our $UP_VIEW_ITEM_BANK = 1; our $UP_VIEW_TEST_BANK = 2; our $UP_VIEW_WORKGROUP = 3; our $UA_NONE = 0; our $UA_SUPER = 1; our $UA_ORG = 2; our $UA_PROGRAM = 3; our %admin_type = ( $UA_NONE => 'None', $UA_SUPER => 'Super Admin', $UA_ORG => 'Organization Admin', $UA_PROGRAM => 'Program Admin' ); our $UR_NONE = 0; our $UR_ITEM_EDIT = 1; our $UR_CONTENT_SPECIALIST = 2; our $UR_COPY_EDITOR = 3; our $UR_GRAPHIC_DESIGNER = 4; our $UR_MEDIA_DESIGNER = 5; our $UR_COMMITTEE_REVIEWER = 6; our $UR_QC_PRESENTATION = 7; our $UR_DATA_MANAGER = 8; our $UR_PSYCHOMETRICIAN = 9; our $UR_COMMITTEE_FACILITATOR = 10; our $UR_DATA_REVIEWER = 11; our $UR_ACCESSIBILITY_SPECIALIST = 12; our %review_type = ( $UR_NONE => 'None', $UR_ITEM_EDIT => 'Item Writer', $UR_CONTENT_SPECIALIST => 'Content Specialist', $UR_COPY_EDITOR => 'Copy Editor', $UR_GRAPHIC_DESIGNER => 'Graphic Designer', $UR_MEDIA_DESIGNER => 'Media Designer', $UR_ACCESSIBILITY_SPECIALIST => 'Accessibility Specialist', $UR_COMMITTEE_REVIEWER => 'Committee Reviewer', $UR_DATA_REVIEWER => 'Data Reviewer', $UR_QC_PRESENTATION => 'QC Presentation', $UR_DATA_MANAGER => 'Data Manager', $UR_PSYCHOMETRICIAN => 'Psychometrician', $UR_COMMITTEE_FACILITATOR => 'Committee Facilitator' ); our %review_type_map = ( $UR_NONE => '', $UR_ITEM_EDIT => 'editor', $UR_CONTENT_SPECIALIST => 'content_specialist', $UR_COPY_EDITOR => 'copy_editor', $UR_GRAPHIC_DESIGNER => 'graphic_designer', $UR_MEDIA_DESIGNER => 'media_designer', $UR_ACCESSIBILITY_SPECIALIST => 'accessibility_specialist', $UR_COMMITTEE_REVIEWER => 'committee_reviewer', $UR_DATA_REVIEWER => 'data_reviewer', $UR_QC_PRESENTATION => 'qc_presentation', $UR_DATA_MANAGER => 'data_manager', $UR_PSYCHOMETRICIAN => 'psychometrician', $UR_COMMITTEE_FACILITATOR => 'committee_facilitator' ); our @review_with_edit = qw/editor content_specialist copy_editor graphic_designer media_designer qc_presentation/; our @review_per_user = qw/editor graphic_designer media_designer/; # Do away with bit vectors for role permissions, as we would like to phase these out one day our $RP_EDIT_ITEM = 1; our $RP_REVIEW_ITEM = 2; our $RP_COMMENT_ITEM = 5; our $RP_DATA_REVIEW_ITEM = 7; our $RP_EDIT_TEST = 3; our $RP_REVIEW_TEST = 4; our $RP_COMMENT_TEST = 6; our %role_item_permission_types = ( 1 => 'Edit Item', 2 => 'Review Item', 5 => 'Comment Item', 7 => 'Data Review Item' ); our %role_test_permission_types = ( 3 => 'Edit Test', 4 => 'Review Test', 6 => 'Comment Test' ); our %default_role_permissions = ( $P_ITEM_EDIT => { $RP_EDIT_ITEM => 1, $RP_REVIEW_ITEM => 1 }, $P_CONTENT_SPECIALIST => { $RP_EDIT_ITEM => 1, $RP_REVIEW_ITEM => 1 }, $P_COPY_EDITOR => { $RP_EDIT_ITEM => 1, $RP_REVIEW_ITEM => 1 }, $P_GRAPHIC_DESIGNER => { $RP_EDIT_ITEM => 1, $RP_REVIEW_ITEM => 1 }, $P_MEDIA_DESIGNER => { $RP_EDIT_ITEM => 1, $RP_REVIEW_ITEM => 1 }, $P_COMMITTEE_REVIEWER => { $RP_REVIEW_ITEM => 1, $RP_COMMENT_ITEM => 1 }, $P_COMMITTEE_FACILITATOR => { $RP_REVIEW_ITEM => 1, $RP_COMMENT_ITEM => 1 }, $P_QC_PRESENTATION => { $RP_EDIT_ITEM => 1, $RP_REVIEW_ITEM => 1 }, $P_DATA_MANAGER => { $RP_DATA_REVIEW_ITEM => 1, }, $P_PSYCHOMETRICIAN => { $RP_DATA_REVIEW_ITEM => 1 }, ); our $UT_ITEM_EDITOR = 11; our @labels = (); our @const = (); our @ctypes = ( $OC_CONTENT_AREA, $OC_GRADE_LEVEL, $OC_GRADE_SPAN_START, $OC_GRADE_SPAN_END, $OC_DOK, $OC_POINTS ); our @tools = ( $OC_PROTRACTOR, $OC_RULER, $OC_CALCULATOR, $OC_COMPASS ); our %stringCharacteristics = map { $_ => 1 } ( $OC_COMP_CURRICULUM ); $labels[$OC_CONTENT_AREA] = 'Content Area:'; $labels[$OC_GRADE_SPAN_START] = 'Grade Span Start:'; $labels[$OC_GRADE_SPAN_END] = 'Grade Span End:'; $labels[$OC_GRADE_LEVEL] = 'Grade Level:'; $labels[$OC_POINTS] = 'Item Points:'; $labels[$OC_DOK] = 'Depth of Knowledge:'; $labels[$OC_PROTRACTOR] = 'Protractor:'; $labels[$OC_RULER] = 'Ruler:'; $labels[$OC_CALCULATOR] = 'Calculator:'; $labels[$OC_COMPASS] = 'Compass:'; $labels[$OC_SCORING_METHOD] = 'Scoring:'; $labels[$OC_COMP_CURRICULUM] = 'Comprehensive Curriculum:'; $labels[$OC_FORM_GROUP] = 'Form Group:'; $labels[$OC_CHOICE_SHUFFLE] = 'Choice Shuffle? :'; $const[$OC_CONTENT_AREA] = { '1' => 'MATH', '2' => 'ELA' }; $const[$OC_GRADE_LEVEL] = { '0' => 'K', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '10' => '10', '11' => '11', '12' => '12' }; $const[56] = { '0' => 'K', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '10' => '10', '11' => '11', '12' => '12', }; $const[$OC_GRADE_SPAN_START] = { '-1' => '-', '0' => 'K', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '10' => '10', '11' => '11', '12' => '12', }; $const[$OC_GRADE_SPAN_END] = { '-1' => '-', '0' => 'K', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '10' => '10', '11' => '11', '12' => '12', }; $const[$OC_POINTS] = { '0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '10' => '10', '11' => '11', '12' => '12', '13' => '13', '14' => '14', '15' => '15', '16' => '16' }; $const[$OC_DOK] = { '1' => '1', '2' => '2', '3' => '3', '4' => '4' }; $const[$OC_PROTRACTOR] = { '0' => 'NO', '1' => 'YES', '2' => 'MAYBE' }; $const[$OC_RULER] = { '0' => 'NO', '1' => 'YES', '2' => 'MAYBE' }; $const[$OC_CALCULATOR] = { '0' => 'NO', '1' => 'YES', '2' => 'MAYBE' }; $const[$OC_COMPASS] = { '1' => 'YES' }; $const[$OC_SCORING_METHOD] = { '1' => 'Match Response', '2' => 'Rubric' }; $const[$OC_ITEM_FORMAT] = { '1' => 'Selected Response', '2' => 'Constructed Response', '3' => 'Activity Based', '4' => 'Performance Task', '5' => 'Unsupported' }; $const[$OC_CHOICE_SHUFFLE] = { '0' => 'No', '1' => 'Yes', }; $const[$OC_FORM_GROUP] = { '1' => 'Applied Algebra' }; our %mc_answer_choices = ( '0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '10' => '10' ); our %charts = ( '2dline' => 'Line.swf', '2dcolumn' => 'Column2D.swf', '2dpie' => 'Pie2D.swf', 'scatterplot' => 'Scatter.swf' ); our %item_types = ( '1' => 'SR, exclusive', '2' => 'SR, non-exclusive', '3' => 'CR, single-line', '4' => 'CR, multi-line', '5' => 'Bubble/Grid', '6' => 'Interactive', '23' => 'CR, multi-entry, single-line', '24' => 'CR, multi-entry, multi-line', ); our %item_formats = ( '1' => 'Selected Response', '2' => 'Constructed Response', '3' => 'Activity Based', '4' => 'Performance Task', '5' => 'Unsupported' ); our %item_interactions = ( '1' => 'Choice', '2' => 'Text Entry', '3' => 'Extended Text', '4' => 'Inline Choice', '5' => 'Match' ); our @dev_states_workflow_ordered_keys = (1,40,19,20,64,63,71,72,69,42,13,17,65,44,61,60,66,68,4,5,9,11); our %dev_states = ( '1' => 'Development', '2' => 'Review', '3' => 'Testing', '4' => 'Approved', '5' => 'Released', '6' => 'Suspended', '9' => 'Rejected', '11' => 'Retired', '12' => 'Content Review', '13' => 'Content Review 2', '14' => 'On Hold', '15' => 'Scheduled', '16' => 'Query Resolution', '17' => 'Copy Review', '18' => 'Copy/Proof Approval', '19' => 'Create Art', '20' => 'Edit Art', '21' => 'Client Approval', '22' => 'Client Approval 2', '23' => 'Client Approval 3', '24' => 'Copy Teacher Review', '25' => 'Copy F2F Review', '26' => 'Copy Final Review', '27' => '2nd Copy Review', '28' => 'Supervisor Review', '29' => 'Client Preview', '30' => 'Customer Proof', 40 => 'Content Review 1', 41 => 'Item Update 1', 42 => 'Committee Review', 13 => 'Content Review 2', 43 => 'Item Update 2', 44 => 'Content Review 3', 45 => 'Sensitivity Review', 46 => 'External Editor Review', 47 => 'Content Review 4', 48 => 'Item Update 3', 49 => 'Content Review 5', 50 => 'Art Request Review', 51 => 'Pending Art', 52 => 'Ready for Art', 53 => 'Proofreading', 54 => 'Content Review 6', 55 => 'Item Update 4', 56 => 'Content Review 7', 57 => 'QA Review', 58 => 'Program Director Review', 60 => 'Banked', 61 => 'Consortium Review', 62 => 'DNU Item Pool', 63 => 'Edit Media', 64 => 'Create Media', 65 => 'Query Resolution', 66 => 'Data Review', 67 => 'Operational Item Pool', 68 => 'Post Admin Review', 69 => 'QC Presentation Review', 70 => 'Post Committee', 71 => 'Create Accessibility', 72 => 'Edit Accessibility' ); our %publication_status = ( 1 => 'Field Test', 2 => 'Embedded Field Test', 3 => 'Operational', 4 => 'Field Tested', 5 => 'Pilot', 6 => 'Equating', 7 => 'Released', 8 => 'Ready for Operational', 9 => 'Ready for Field Test', 10 => 'Ready for Pilot Test', 11 => 'Pilot Tested', 12 => 'Ready for Field Review', 13 => 'Field Reviewed', 14 => 'Operational Equating', 15 => 'Rejected', ); our %export_ok = ( '0' => 'no', '1' => 'yes' ); our %read_only = ( '0' => 'no', '1' => 'yes' ); our %difficulty_levels = ( '1' => 'easy', '2' => 'medium', '3' => 'hard' ); our %layout_types = ( '1' => 'single column', '2' => '2 columns', '3' => 'single row' ); our %genres = ( '0' => '', '1' => 'Poem', '2' => 'Fiction', '3' => 'Proofreading', '4' => 'Non-Fiction', '5' => 'Biography/Interview', '6' => 'Information Resource', '7' => 'Drama' ); our %languages = ( '1' => 'English', '2' => 'Spanish' ); our %error_types = ( 'c' => 'Concept', 'g' => 'Guess', 'p' => 'Process' ); our %default = ( $OC_POINTS => '1' ); our %asy_colors = ( 'black' => 'Black', 'gray' => 'Gray', 'white' => 'White', 'red' => 'Red', 'green' => 'Green', 'blue' => 'Blue', 'yellow' => 'Yellow', 'magenta' => 'Magenta', 'cyan' => 'Cyan', 'brown' => 'Brown', 'darkgreen' => 'Dark Green', 'darkblue' => 'Dark Blue', 'orange' => 'Orange', 'purple' => 'Purple', 'lightblue' => 'Light Blue', 'pink' => 'Pink', 'lavender' => 'Lavender' ); our %workStates = ( '1' => $DS_DEVELOPMENT, '2' => $DS_CONTENT_REVIEW, '3' => $DS_CONTENT_REVIEW_2, '4' => $DS_COPY_REVIEW, '5' => $DS_CONTENT_APPROVED, '6' => $DS_COPY_APPROVED, '7' => $DS_SUPERVISOR_REVIEW, '8' => $DS_CLIENT_PREVIEW, '9' => $DS_CLIENT_APPROVED, '10' => $DS_READY_FOR_AUDIO, 40 => $DS_CONTENT_REVIEW_1, 41 => $DS_ITEM_UPDATE_1, 42 => $DS_COMMITTEE_REVIEW, 43 => $DS_ITEM_UPDATE_2, 44 => $DS_CONTENT_REVIEW_3, 45 => $DS_SENSITIVITY_REVIEW, 46 => $DS_EXTERNAL_EDITOR_REVIEW, 47 => $DS_CONTENT_REVIEW_4, 48 => $DS_ITEM_UPDATE_3, 49 => $DS_CONTENT_REVIEW_5, 50 => $DS_ART_REQUEST_REVIEW, 51 => $DS_PENDING_ART, 52 => $DS_READY_FOR_ART, 53 => $DS_PROOFREADING, 54 => $DS_CONTENT_REVIEW_6, 55 => $DS_ITEM_UPDATE_4, 56 => $DS_CONTENT_REVIEW_7, 57 => $DS_QA_REVIEW, 58 => $DS_PROGRAM_DIRECTOR_REVIEW, 60 => $DS_BANKED, 61 => $DS_CONSORTIUM_REVIEW, 62 => $DS_DNU_ITEM_POOL, 63 => $DS_FIX_MEDIA, 64 => $DS_NEW_MEDIA, 65 => $DS_QUERY_RESOLUTION, 66 => $DS_DATA_REVIEW, 67 => $DS_OPERATIONAL_ITEM_POOL, 68 => $DS_POST_ADMIN_REVIEW, 69 => $DS_QC_PRESENTATION_REVIEW, 70 => $DS_POST_COMMITTEE, 71 => $DS_NEW_ACCESSIBILITY, 72 => $DS_FIX_ACCESSIBILITY ); our %characterization_view_types = ( $OC_CONTENT_AREA => 'content_area', $OC_GRADE_LEVEL => 'grade_level' ); our %itemNotesTags = ( '1' => { 'accepted all' => 'Accepted all edits.', 'query resolved' => 'Query resolved/additional edits.', 'rewritten' => 'Rewritten.', 'no comments/edits' => 'No comments or edits from Copy.', 'verified' => 'CR verified.', 'art corrections' => 'Art corrections made.', 'fixed eoc view' => 'Fixed EOC view.' } ); our %itemStandardChar = ( '0' => { 'gle' => $OC_ITEM_STANDARD, 'standard' => $OC_CONTENT_STANDARD, 'benchmark' => $OC_BENCHMARK, 'category' => $OC_CATEGORY }, '1' => { 'gle' => $OC_SECONDARY_STANDARD, 'standard' => $OC_SECONDARY_CONTENT_STANDARD, 'benchmark' => $OC_SECONDARY_BENCHMARK, 'category' => $OC_SECONDARY_CATEGORY }, '2' => { 'gle' => $OC_TERTIARY_STANDARD, 'standard' => $OC_TERTIARY_CONTENT_STANDARD, 'benchmark' => $OC_TERTIARY_BENCHMARK, 'category' => $OC_TERTIARY_CATEGORY } ); # # The 1st key references the hd_id of the standards hierarchy root # The 2nd key references the content area (Math, ELA) # our %contentStandards = ( '1' => { '1' => { '1' => 'Number and Number Relations', '2' => 'Algebra', '3' => 'Measurement', '4' => 'Geometry', '5' => 'Data Analysis, Probability, and Discrete Math', '6' => 'Patterns, Relations, and Functions' }, '2' => { '1' => 'Standard 1', '2' => 'Standard 2', '3' => 'Standard 3', '4' => 'Standard 4', '5' => 'Standard 5', '6' => 'Standard 6', '7' => 'Standard 7' } }, '2184' => { '1' => { '1' => 'Number Sense', '2' => 'Algebra and Functions', '3' => 'Measurement and Geometry', '4' => 'Statistics, Data Analysis, and Probability', '5' => 'Mathematical Reasoning' }, '2' => { '1' => 'Word Analysis', '2' => 'Reading Comprehension', '3' => 'Literary Response and Analysis', '4' => 'Writing Strategies', '5' => 'Writing Applications', '6' => 'Writing Conventions' } } ); our %action_key_states = ( development => $DS_DEVELOPMENT, content_review => $DS_CONTENT_REVIEW, content_review_2 => $DS_CONTENT_REVIEW_2, copy_review => $DS_COPY_REVIEW, copy_review_2 => $DS_COPY_REVIEW_2, copy_approve => $DS_COPY_APPROVED, content_approve => $DS_CONTENT_APPROVED, supervisor_review => $DS_SUPERVISOR_REVIEW, client_preview => $DS_CLIENT_PREVIEW, client_approve => $DS_CLIENT_APPROVED, client_approve_2 => $DS_CLIENT_APPROVED_2, client_approve_3 => $DS_CLIENT_APPROVED_3, copy_teacher_review => $DS_COPY_TEACHER_REVIEW, copy_f2f_review => $DS_COPY_F2F_REVIEW, copy_final_review => $DS_COPY_FINAL_REVIEW, customer_proof => $DS_CUSTOMER_PROOF, new_art => $DS_NEW_ART, fix_art => $DS_FIX_ART, reject => $DS_REJECTED, approve => $DS_APPROVED, content_review_1 => $DS_CONTENT_REVIEW_1, item_update_1 => $DS_ITEM_UPDATE_1, committee_review => $DS_COMMITTEE_REVIEW, item_update_2 => $DS_ITEM_UPDATE_2, content_review_3 => $DS_CONTENT_REVIEW_3, sensitivity_review => $DS_SENSITIVITY_REVIEW, external_editor_review => $DS_EXTERNAL_EDITOR_REVIEW, content_review_4 => $DS_CONTENT_REVIEW_4, item_update_3 => $DS_ITEM_UPDATE_3, content_review_5 => $DS_CONTENT_REVIEW_5, art_request_review => $DS_ART_REQUEST_REVIEW, pending_art => $DS_PENDING_ART, ready_for_art => $DS_READY_FOR_ART, proofreading => $DS_PROOFREADING, content_review_6 => $DS_CONTENT_REVIEW_6, item_update_4 => $DS_ITEM_UPDATE_4, content_review_7 => $DS_CONTENT_REVIEW_7, qa_review => $DS_QA_REVIEW, program_director_review => $DS_PROGRAM_DIRECTOR_REVIEW, banked => $DS_BANKED, consortium_review => $DS_CONSORTIUM_REVIEW, dnu_item_pool => $DS_DNU_ITEM_POOL, new_media => $DS_NEW_MEDIA, fix_media => $DS_FIX_MEDIA, new_accessibility => $DS_NEW_ACCESSIBILITY, fix_accessibility => $DS_FIX_ACCESSIBILITY, query_resolution => $DS_QUERY_RESOLUTION, data_review => $DS_DATA_REVIEW, operational_item_pool => $DS_OPERATIONAL_ITEM_POOL, post_admin_review => $DS_POST_ADMIN_REVIEW, qc_presentation => $DS_QC_PRESENTATION_REVIEW, committee_facilitator => $DS_POST_COMMITTEE, last_state => 'last_state', ); our %item_rating = ( 1 => 'Poor', 2 => 'Fair', 3 => 'Good', 4 => 'Very Good', 5 => 'Excellent' ); our %review_flags = ( notes => { 'color' => 'blue', 'tag' => 'N' }, new_media => { 'color' => 'green', 'tag' => 'M' }, edit_media => { 'color' => 'red', 'tag' => 'M' }, new_art => { 'color' => 'green', 'tag' => 'A' }, edit_art => { 'color' => 'red', 'tag' => 'A' }, reject_writer => { 'color' => 'red', 'tag' => 'X' }, resubmit_writer => { 'color' => 'green', 'tag' => 'X' }, minor_edit => { 'color' => 'blue', 'tag' => 'E' }, ); our @tags_with_no_id_list = qw/br hr em b i strong font u maligngroup malignmark menclose merror mfenced mfrac mglyph mi mlabeledtr mlongdiv mmultiscripts mn mo mover mpadded mphantom mroot mrow ms mscarries mscarry msgroup msline mspace msqrt msrow mstack mstyle msub msup msubsup mtable mtd mtext mrt munder munderover /; our %tags_with_no_id = map { $_ => 1 } @tags_with_no_id_list; sub replaceChars { my $source = shift; my @char_array = split //, $source; for(my $i=0; $i < scalar(@char_array); $i++) { my $ascii_num = ord($char_array[$i]); if($ascii_num >= 160) { $char_array[$i] = '&#' . $ascii_num . ';'; } } return join ('', @char_array); } sub getNewItemPrefix { my $dbh = shift; my $contentArea = shift; my $grade = shift; my $hdId = shift; my $year = shift; my $format = shift; my $passage = shift || ''; my $std = &getStandard( $dbh, $hdId ); my $strand = substr( $std->{$HD_STANDARD_STRAND}->{value}, 0, 1 ); my $gle = $std->{$HD_LEAF}->{value}; $gle =~ m/(\d+)/; $gle = $1; $grade = $const[$OC_GRADE_LEVEL]->{$grade}; $format = $const[$OC_ITEM_FORMAT]->{$format}; $contentArea = $const[$OC_CONTENT_AREA]->{$contentArea}; if ( $contentArea eq 'MATH' ) { return "${grade}${strand}${gle}_${year}_${format}"; } elsif ( $contentArea eq 'ELA' ) { my $psg = new Passage( $dbh, $passage ); return "${grade}${strand}${gle}_${year}_${format}_$psg->{code}"; } return ''; } sub getNextItemSequence { my $dbh = shift; my $bank = shift; my $prefix = shift; my $sql = "SELECT i_external_id FROM item WHERE ib_id=${bank} AND i_external_id LIKE '${prefix}%' ORDER BY LENGTH(i_external_id) DESC, i_external_id DESC LIMIT 1"; my $sth = $dbh->prepare($sql); $sth->execute(); if ( my $row = $sth->fetchrow_hashref ) { my $lastId = $row->{i_external_id}; $sth->finish; $lastId =~ m/(\d+)$/; my $seq = $1; $seq =~ s/^0+//; return int($seq) + 1; } else { $sth->finish; return 1; } } sub sendNewItemNotification { use MIME::Lite; my $dbh = shift; my $bankName = shift; my $writerId = shift; return 0 unless $writerId; # by default, assume it doesn't work my $status = 0; my $sql = 'SELECT * FROM user WHERE u_id=' . $writerId; my $sth = $dbh->prepare($sql); $sth->execute(); if(my $row = $sth->fetchrow_hashref) { my $body = <<END_HERE; Hello $row->{u_first_name} $row->{u_last_name}, SBAC IAIP ITEM(s) have been placed in your queue and needs your attention: Program : ${bankName} If you have any questions, please contact customer support. SBAC7PacMetTeam\@pacificmetrics.com Regards, SBAC IAIP Notifier END_HERE eval { my $message = MIME::Lite->new( To => $row->{u_email}, From => '"SBAC IAIP" <SBAC7PacMetTeam@pacificmetrics.com>', Subject => 'SBAC IAIP ITEM Needs Your Attention!', Data => $body, ); $message->send( 'smtp', 'localhost' ); }; if($@) { # problem sending the e-mail } else { $status = 1; } } else { # user not found } $sth->finish; return $status; } sub getFileContent { my $filePath = shift; my $fileString = ''; open FILE, '<', $filePath; while (<FILE>) { $fileString .= $_; } close FILE; return $fileString; } sub getContentStandard { my $dbh = shift; my $hdId = shift; my $contentArea = shift; my $strand = 0; my $parentPath = ''; my $sql = "SELECT hd_parent_path, hd_value FROM hierarchy_definition WHERE hd_id=${hdId}"; my $sth = $dbh->prepare($sql); $sth->execute(); if ( my $row = $sth->fetchrow_hashref ) { $parentPath = $row->{hd_parent_path}; } else { $parentPath = 0; } my @parentList = split /,/, $parentPath; @parentList = reverse @parentList; my $standardsHierarchy = $parentList[0] ? $parentList[0] : $parentList[1]; if ( $standardsHierarchy == 1 && $contentArea == 2 ) { $sql = "SELECT hd_value FROM hierarchy_definition WHERE hd_type=${HD_SUBSTRAND} AND hd_id IN (${parentPath})"; $sth = $dbh->prepare($sql); $sth->execute(); if ( my $row = $sth->fetchrow_hashref ) { if ( $row->{hd_value} =~ /(\d+)/ ) { $strand = $1; } } } else { $sql = "SELECT hd_posn_in_parent FROM hierarchy_definition WHERE hd_type=${HD_STANDARD_STRAND} AND hd_id IN (${parentPath})"; $sth = $dbh->prepare($sql); $sth->execute(); if ( my $row = $sth->fetchrow_hashref ) { $strand = $row->{hd_posn_in_parent}; } } return $strand; } sub getGLENumber { my $dbh = shift; my $gleId = shift; my $gleNumber = 0; my $sql = "SELECT hd_value FROM hierarchy_definition WHERE hd_id=${gleId}"; my $sth = $dbh->prepare($sql); $sth->execute(); if ( my $row = $sth->fetchrow_hashref ) { $row->{hd_value} =~ /(\d+)/; $gleNumber = $1; } return $gleNumber; } sub getStandardsUnderRoot { my $dbh = shift; my $rootId = shift; my %hd = (); # Build data structure from hierarchy_definition my $sql = 'SELECT * FROM hierarchy_definition WHERE hd_parent_path LIKE \'%,' . $rootId . ',%\' OR hd_parent_id = ' . $rootId . ' ORDER BY hd_posn_in_parent'; my $sth = $dbh->prepare($sql); $sth->execute() || print( STDERR "Failed Query:" . $dbh->err . "," . $dbh->errstr ); while ( my $row = $sth->fetchrow_hashref ) { my @hdParentPath = split /,/, $row->{hd_parent_path}; foreach (@hdParentPath) { $hd{$_} = {} unless exists $hd{$_}; } $hd{ $row->{hd_id} } = {} unless exists $hd{ $row->{hd_id} }; $hd{ $row->{hd_id} }->{type} = $row->{hd_type}; $hd{ $row->{hd_id} }->{value} = $row->{hd_value}; $hd{ $row->{hd_id} }->{posn} = $row->{hd_posn_in_parent}; $hd{ $row->{hd_id} }->{parent} = $row->{hd_parent_id}; $hd{ $row->{hd_id} }->{path} = $row->{hd_parent_path}; $hd{ $row->{hd_parent_id} }->{child} = [] unless exists $hd{ $row->{hd_parent_id} }->{child}; push @{ $hd{ $row->{hd_parent_id} }->{child} }, $row->{hd_id}; if ( $row->{hd_std_desc} or $row->{hd_type} == $HD_LEAF ) { $hd{ $row->{hd_id} }->{text} = $row->{hd_std_desc} || ''; } } $sth->finish; return \%hd; } sub getSession { my $dbh = shift; my $sessId = shift; my $user = { writer_code => 'WCNONE', type => 0, id => 0, roles => 0, adminType => 0, reviewType => 0, organizationId => 0, itemBanks => {}, rolePermissions => {}, }; my $sql = 'SELECT user.*, session.ss_id FROM user, session' . ' WHERE user.u_id=session.u_id AND session.ss_id=' . $dbh->quote($sessId) . ' ORDER BY ss_expiration DESC LIMIT 1'; my $sth = $dbh->prepare($sql); $sth->execute(); if ( my $row = $sth->fetchrow_hashref ) { $user->{type} = $row->{u_type}; $user->{id} = $row->{u_id}; $user->{roles} = $row->{u_permissions}; $user->{organizationId} = $row->{o_id}; $user->{adminType} = $row->{u_admin_type}; $user->{reviewType} = $row->{u_review_type}; $user->{writer_code} = $row->{u_writer_code}; $user->{rolePermissions} = {}; $sql = 'SELECT up_value FROM user_permission WHERE u_id=' . $row->{u_id} . ' AND up_type=' . $UP_VIEW_ITEM_BANK; my $sth2 = $dbh->prepare($sql); $sth2->execute(); while ( my $row2 = $sth2->fetchrow_hashref ) { $user->{itemBanks}{ $row2->{up_value} } = 1; } $sth2->finish; foreach my $role (@role_types) { next unless exists $default_role_permissions{$role}; if($role & $user->{roles}) { foreach my $perm (keys %{$default_role_permissions{$role}}) { $user->{rolePermissions}{$perm} = 1; } } } } return $user; } sub setItemReviewState { my $dbh = shift; my $itemId = shift; my $lastDevState = shift; my $newDevState = shift; my $userId = shift; my $acceptedTimestamp = shift || 'NOW()'; if ( $acceptedTimestamp ne 'NOW()' ) { $acceptedTimestamp = "'${acceptedTimestamp}'"; } my $sql = 'SELECT i_xml_data, i_notes, i_qti_xml_data, i_tei_data, ib_id FROM item WHERE i_id=' . $itemId; my $sth = $dbh->prepare($sql); $sth->execute(); my $row = $sth->fetchrow_hashref; $sql = sprintf('INSERT INTO item_status SET i_id=%d, is_last_dev_state=%d, is_new_dev_state=%d,' . ' is_timestamp=NOW(), is_accepted_timestamp=%s, is_u_id=%d, i_xml_data=%s, i_notes=%s,' . 'i_qti_xml_data=%s, i_tei_data=%s, ib_id=%s', $itemId, $lastDevState, $newDevState, $acceptedTimestamp, $userId, $dbh->quote($row->{i_xml_data}), $dbh->quote($row->{i_notes}), $dbh->quote($row->{i_qti_xml_data}), $dbh->quote($row->{i_tei_data}), $row->{ib_id} ); $sth = $dbh->prepare($sql); $sth->execute(); # copy all the item_fragment records to item_status_fragment my $is_id = $dbh->{mysql_insertid}; $sql = sprintf('SELECT * FROM item_fragment WHERE i_id=' . $itemId); $sth = $dbh->prepare($sql); $sth->execute(); $sql = <<SQL; INSERT INTO item_status_fragment SET is_id=?, i_id=?, if_id=?, isf_text=? SQL my $sth2 = $dbh->prepare($sql); while(my $row = $sth->fetchrow_hashref) { $sth2->execute($is_id, $itemId, $row->{if_id}, $row->{if_text}); } $sth->finish; $sth2->finish; my @itemToPDFargs = ( "${orcaPath}cgi-bin/itemToPDF.pl", $instance_name, $itemId ); system(@itemToPDFargs); $sql = "UPDATE item SET i_review_lock=0, i_dev_state=${newDevState}, i_notes='', i_last_save_user_id=0 WHERE i_id=${itemId}"; $sth = $dbh->prepare($sql); $sth->execute(); $sth->finish; } sub attributeStringToHash { my $attString = shift; my %out = (); while($attString =~ /(\w+)\s?=\s?"([^"]+)"/g) { $out{$1} = $2; } return \%out; } sub hashToAttributeString { my $data = shift; return join(' ', map { $_ . '="' . $data->{$_} . '"' } keys %$data); } sub getItemXml { my $dbh = shift; my $itemId = shift; my $itemName = shift || ''; my $xml = ''; my $sql = "SELECT * FROM item WHERE " . ( $itemName eq '' ? "i_id=${itemId}" : "ib_id=${itemId} AND i_external_id='${itemName}' ORDER BY i_version DESC LIMIT 1" ); my $sth = $dbh->prepare($sql); $sth->execute(); if ( my $row = $sth->fetchrow_hashref ) { $xml = $row->{i_xml_data}; $xml =~ s/(<item [^>]+>)/$1 <name>$row->{i_external_id}<\/name> /; } $sth->finish; return $xml; } sub setPassageReviewState { use Passage; my $dbh = shift; my $passageId = shift; my $lastDevState = shift; my $newDevState = shift; my $userId = shift; my $acceptedTimestamp = shift || 'NOW()'; if ( $acceptedTimestamp ne 'NOW()' ) { $acceptedTimestamp = "'${acceptedTimestamp}'"; } my $psg = new Passage( $dbh, $passageId ); my $sql = "INSERT INTO passage_status SET p_id=${passageId}, ps_last_dev_state=${lastDevState}, ps_new_dev_state=${newDevState}, ps_timestamp=NOW(), ps_accepted_timestamp=${acceptedTimestamp}, ps_u_id=${userId}, ib_id=$psg->{bank}, p_notes=(SELECT p_notes FROM passage WHERE p_id=${passageId}), p_content=" . $dbh->quote( $psg->{body} ) . ", ps_footnotes=" . $dbh->quote( $psg->getFootnotesAsString() ); my $sth = $dbh->prepare($sql); $sth->execute(); system( "${orcaPath}cgi-bin/passageToPDF.pl", $passageId ); $sql = "UPDATE passage SET p_review_lock=0, p_dev_state=${newDevState}, p_notes='' WHERE p_id=${passageId}"; $sth = $dbh->prepare($sql); $sth->execute(); $sth->finish; } sub getItemAssets { use ItemAsset; my $bankId = shift; my $itemName = shift; my $itemVersion = shift; my @assets = (); my %asset_ext = map { $_ => 1 } @asset_extensions; my $pathString = $itemVersion == 0 ? "${imagesDir}lib${bankId}/${itemName}/*" : "${imagesDir}lib${bankId}/${itemName}/V${itemVersion}*"; foreach ( bsd_glob($pathString) ) { $_ =~ /\.(\w+)$/; next unless exists $asset_ext{$1}; my $assetName; if ($itemVersion) { $_ =~ /$itemName\/V\d+\.(.*?)$/; $assetName = $1; } else { next if $_ =~ /$itemName\/V\d+\./; $_ =~ /$itemName\/(.*)$/; $assetName = $1; } push @assets, new ItemAsset( $bankId, $itemName, $itemVersion, $assetName ); } return @assets; } sub getPassageAssets { use PassageAsset; my $bankId = shift; my $passageId = shift; my @assets = (); my %asset_ext = map { $_ => 1 } @asset_extensions; warn "Searching ${passagePath}lib${bankId}/images/p${passageId}/*"; foreach ( bsd_glob("${passagePath}lib${bankId}/images/p${passageId}/*") ) { $_ =~ /\.(\w+)$/; next unless exists $asset_ext{$1}; $_ =~ /p$passageId\/(.*)$/; my $assetName = $1; push @assets, new PassageAsset( $bankId, $passageId, $assetName ); } return @assets; } sub getRubricAssets { use RubricAsset; my $bankId = shift; my $rubricId = shift; my @assets = (); my %asset_ext = map { $_ => 1 } @asset_extensions; foreach ( bsd_glob("${rubricPath}lib${bankId}/images/r${rubricId}/*") ) { $_ =~ /\.(\w+)$/; next unless exists $asset_ext{$1}; $_ =~ /r$rubricId\/(.*)$/; my $assetName = $1; push @assets, new RubricAsset( $bankId, $rubricId, $assetName ); } return @assets; } sub setAssetAttributes { my $dbh = shift; my $itemId = shift; my $fileName = shift; my $media_description = shift; my $sourceUrl = shift; my $uId = shift; my $sql = sprintf( 'INSERT INTO item_asset_attribute SET i_id=%d, iaa_filename=%s, iaa_media_description=%s, iaa_source_url=%s, iaa_u_id=%d, iaa_timestamp=NOW()', $itemId, $dbh->quote($fileName), $dbh->quote($media_description), $dbh->quote($sourceUrl), $uId ); my $sth = $dbh->prepare($sql); $sth->execute(); $sth->finish; } # using the database handle get media asset attirbutes for the specified item id # from the database # # returns a reference to an array of hash references containting field name and field # value pairs; NULL field values are returned as undef. # # undef may be returned if the asset is not found or errors occur during query exection. # errors are sent to STDERR. # to do ensure values are set # to do ensure escape itemAssetId (SQL INJECTION) sub getMediaAssetAttributes { my $dbh = shift; my $i_id = shift; my $interaction_id = shift || 0; my $out = []; my $sql = sprintf(q{ SELECT i.i_id, i.ib_id, i.i_external_id, i.i_version, iaa.iaa_id, iaa.iaa_filename, iaa.iaa_source_url, iaa.iaa_media_description FROM item_asset_attribute iaa, item AS i WHERE i.i_id=%d AND i.i_id=iaa.i_id AND iaa.iaa_filename REGEXP "\.mp3$|\.m4a$|\.m4v$|\.mp4$|\.swf$" }, $i_id); my $sth = $dbh->prepare($sql) or warn $dbh->errstr; # return undef; $sth->execute or warn $dbh->errstr; # return undef; while(my $row = $sth->fetchrow_hashref) { my $rec = {}; foreach(qw/i_id ib_id i_external_id i_version iaa_id iaa_filename iaa_source_url iaa_media_description/) { $rec->{$_} = $row->{$_}; } if($interaction_id) { $sql = sprintf(q{ SELECT ifg.* FROM item_fragment AS ifg WHERE ifg.i_id = %d AND ifg.if_type=2 AND ifg.ii_id=%d AND ifg.if_text LIKE CONCAT("%%",%s,"%%") ORDER BY ifg.if_seq; }, $i_id, $interaction_id, $dbh->quote($row->{iaa_filename})); } else { $sql = sprintf(q{ SELECT ifg.* FROM item_fragment AS ifg WHERE ifg.i_id=%d AND ifg.if_type=1 AND ifg.if_text LIKE CONCAT("%%",%s,"%%") }, $i_id, $dbh->quote($row->{iaa_filename})); } my $sth2 = $dbh->prepare($sql) or warn $dbh->errstr; # return undef; $sth2->execute or warn $dbh->errstr; # return undef; while(my $row2 = $sth2->fetchrow_hashref) { if($interaction_id) { $rec->{i_part} = 'Choice ' . $choice_chars[$row2->{if_seq} - 1]; } else { $rec->{i_part} = 'Stem'; } } push @{$out}, $rec; } return $out; } # generate media html table for an item sub getMediaTableHtml { use HTML::Template; my $mediaAssets = shift; my $editMode = shift || 0; my $ib_id = shift; my $i_id = shift; my $i_external_id = shift; my $i_version = shift; my $interaction_id = shift || 0; my $mediaTmplt = HTML::Template->new(scalarref => \ <<TEMPLATE <div> <table id="mediaAssetTable" class="tablesorter" border="1" cellpadding="2" cellspacing="2"> <caption>Media Assets<TMPL_IF NAME=SHOWUPLOAD><span style="float:right;"><input type="button" value="Upload" onClick="myOpen('mediaUpload', '<TMPL_VAR NAME=UPLOADURL>',550,450);"></span></TMPL_IF></caption> <thead> <tr> <th style="padding-right:20px;">Item Part</th> <th style="padding-right:20px;">Filename</th> <th style="padding-right:20px;">Description</th> <th style="padding-right:20px;">File Size</th> <th>Actions</th> </tr> </thead> <tfoot id="noMediaMessage"<TMPL_IF NAME=ASSETS> style="display:none;"</TMPL_IF>> <tr> <td colspan="5"><span style="font-style:italic;">No Media Assets</span></td> </tr> </tfoot> <tbody> <TMPL_LOOP NAME=ASSETS> <tr id="<TMPL_VAR NAME=IAA_FILENAME>"> <td><TMPL_VAR NAME=ITEMPART></td> <td><TMPL_VAR NAME=FILENAME></td> <td><TMPL_VAR NAME=DESCRIPTION></td> <td><TMPL_VAR NAME=FILESIZE></td> <td><TMPL_VAR NAME=VIEWLINK><TMPL_IF NAME=SHOWEDITOPTS>&nbsp;|&nbsp;<TMPL_VAR NAME=INSERTLINK>&nbsp;|&nbsp;<TMPL_VAR NAME=DELETELINK></TMPL_IF></td> </tr> </TMPL_LOOP> </tbody> </table> </div> TEMPLATE ); my $rows = [ map {{ IAA_FILENAME => $_->{iaa_filename}, ITEMPART => (defined $_->{i_part} ? $_->{i_part} : "<span style=\"font-style:italic;\">Unassigned</span>"), FILENAME => $_->{iaa_source_url}, DESCRIPTION => $_->{iaa_media_description}, FILESIZE => sprintf("%.1f", (-s ${orcaPath} . 'images/lib' . $_->{ib_id} . '/' . $_->{i_external_id} . '/' . $_->{iaa_filename})/1024).' kb', VIEWLINK => "<a href=\"#\" onClick=\"myOpen('mediaViewer','${mediaViewUrl}?itemBankId=$_->{ib_id}&itemName=$_->{i_external_id}&version=$_->{i_version}&imageId=$_->{iaa_filename}',700,500);\">View</a>", SHOWEDITOPTS => $editMode, INSERTLINK => "<a href=\"#\" onClick=\"myOpen('mediaInsert','${mediaInsertUrl}?i_id=$_->{i_id}&iaa_id=$_->{iaa_id}&interaction_id=${interaction_id}',400,350);\">Associations</a>", DELETELINK => "<a href=\"#\" onClick=\"myOpen('mediaDelete','${mediaDeleteUrl}?i_id=$_->{i_id}&i_version=$_->{i_version}&iaa_id=$_->{iaa_id}&interaction_id=${interaction_id}',400,350);\">Delete</a>" }} @{$mediaAssets} ]; my $mediaUploadUrlParams = "?itemBankId=$ib_id&itemId=$i_id&itemExternalId=$i_external_id&version=$i_version"; $mediaTmplt->param(ASSETS=>$rows, SHOWUPLOAD=>$editMode, UPLOADURL=>$mediaUploadUrl.$mediaUploadUrlParams); # this block is resulting in error pring() on unopened filehandle # Trick HTML::Template output subroutine into treating $mediaHtml as file #my $mediaHtml = ''; #open(MEMORY, ">", \$mediaHtml) or warn "Could not open string for writing!"; #print MEMORY "test\n"; #$mediaTmplt->output(print_to => \*MEMORY); #return $mediaHtml; $mediaTmplt->output; } sub getMediaHtml { my $playerId = shift; my $ext = shift; my $title = shift; my $path = shift; my $html = ''; my $is_audio = 0; my $is_video = 0; if ($ext eq 'mp3' || $ext eq 'm4a') { $is_audio = 1; } elsif ($ext eq 'm4v') { $is_video = 1; } elsif ($ext eq 'mp4') { use Image::ExifTool qw(:Public); my $mp4_info = ImageInfo($path); $is_audio = $mp4_info->{MIMEType} =~ m/^audio\/mp4/; $is_video = $mp4_info->{MIMEType} =~ m/^video\/mp4/; } if($is_audio) { $html = <<END_HTML; <div id="${playerId}" class="jp-jplayer"></div> <div id="${playerId}_container" class="jp-audio"> <div class="jp-type-single"> <div class="jp-gui jp-interface"> <ul class="jp-controls"> <li><a href="javascript:;" class="jp-play" tabindex="1">play</a></li> <li><a href="javascript:;" class="jp-pause" tabindex="1">pause</a></li> <li><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li> <li><a href="javascript:;" class="jp-mute" tabindex="1" title="mute">mute</a></li> <li><a href="javascript:;" class="jp-unmute" tabindex="1" title="unmute">unmute</a></li> <li><a href="javascript:;" class="jp-volume-max" tabindex="1" title="max volume">max volume</a></li> </ul> <div class="jp-progress"> <div class="jp-seek-bar"> <div class="jp-play-bar"></div> </div> </div> <div class="jp-current-time"></div> <div class="jp-duration"></div> </div> <div class="jp-title"> <ul> <li>${title}</li> </ul> </div> <div class="jp-no-solution"> <span>Update Required</span> To play the media you need to upgrade to a browser that supports HTML5 or Flash </div> </div> </div> END_HTML } elsif ($is_video) { $html = <<END_HTML; <div id="${playerId}_container" class="jp-video jp-video-360p"> <div class="jp-type-single"> <div id="${playerId}" class="jp-jplayer"></div> <div class="jp-gui"> <div class="jp-video-play"> <a href="javascript:;" class="jp-video-play-icon" tabindex="1">play</a> </div> <div class="jp-interface"> <div class="jp-progress"> <div class="jp-seek-bar"> <div class="jp-play-bar"></div> </div> </div> <div class="jp-current-time"></div> <div class="jp-duration"></div> <div class="jp-title"> <ul> <li>${title}</li> </ul> </div> <div class="jp-controls-holder"> <ul class="jp-controls"> <li><a href="javascript:;" class="jp-play" tabindex="1">play</a></li> <li><a href="javascript:;" class="jp-pause" tabindex="1">pause</a></li> <li><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li> <li><a href="javascript:;" class="jp-volume-max" tabindex="1" title="max volume">max volume</a></li> </ul> <div class="jp-volume-bar"> <div class="jp-volume-bar-value"></div> </div> </div> </div> </div> <div class="jp-no-solution"> <span>Update Required</span> To play the media you will need to either update your browser to a recent version or update your <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>. </div> </div> </div> END_HTML } else { $html = <<END_HTML; <div>Media Type ${ext} not recognized.</div> END_HTML } return $html; } sub getMediaReadyFunction { my $playerId = shift; my $ext = shift; my $url = shift; my $path = shift; my $html = ''; my $is_audio = 0; my $is_video = 0; if ($ext eq 'mp3' || $ext eq 'm4a') { $is_audio = 1; } elsif ($ext eq 'm4v') { $is_video = 1; } elsif ($ext eq 'mp4') { use Image::ExifTool qw(:Public); my $mp4_info = ImageInfo($path); $is_audio = $mp4_info->{MIMEType} =~ m/^audio\/mp4/; $is_video = $mp4_info->{MIMEType} =~ m/^video\/mp4/; } if($is_audio) { $html = <<END_HTML; \$("#${playerId}").jPlayer({ ready: function(event) { \$(this).jPlayer("setMedia", { //${ext}: "${url}" m4a: "${url}" }); }, play: function() { \$(this).jPlayer("pauseOthers"); }, swfPath: "/common/js", //supplied: "${ext}", supplied: "m4a", cssSelectorAncestor: "#${playerId}_container", wmode: "window" }); END_HTML } elsif ($is_video) { $html = <<END_HTML; \$("#${playerId}").jPlayer({ ready: function(event) { \$(this).jPlayer("setMedia", { m4v: "${url}" }); }, play: function() { \$(this).jPlayer("pauseOthers"); }, swfPath: "/common/js", supplied: "m4v", size: { cssClass: "jp-video-360p" }, cssSelectorAncestor: "#${playerId}_container" }); END_HTML } else { $html = ''; } return $html; } sub getBankMetafilesForItem { my $dbh = shift; my $itemId = shift; my $type = shift || 0; my %metafiles = (); my $typeSql = ''; if($type) { $typeSql = ' AND ibm.ibm_type_code=' . $type; } my $sql = <<SQL; SELECT ibm.* FROM item_bank_metafiles AS ibm, item_metafile_association AS ima WHERE ima.i_id=${itemId} AND ima.ibm_id=ibm.ibm_id ${typeSql} ORDER BY ibm.ibm_timestamp DESC SQL my $sth = $dbh->prepare($sql); $sth->execute(); while ( my $row = $sth->fetchrow_hashref ) { my $key = $row->{ibm_id}; $metafiles{$key} = {}; $metafiles{$key}{bankId} = $row->{ib_id}; $metafiles{$key}{comment} = $row->{ibm_comment}; $metafiles{$key}{timestamp} = $row->{ibm_timestamp}; $metafiles{$key}{name} = $row->{ibm_orig_name}; $metafiles{$key}{view} = "${orcaUrl}itembank-metafiles/lib$row->{ib_id}/$row->{ibm_id}.$row->{ibm_version}-$row->{ibm_orig_name}"; $metafiles{$key}{view} =~ s/\s/%20/g; } $sth->finish; return \%metafiles; } sub addItemComment { my $dbh = shift; my $itemId = shift; my $userId = shift; my $type = shift; my $devState = shift; my $rating = shift; my $comment = shift || ''; my $sql = sprintf('SELECT ic_id FROM item_comment WHERE i_id=%d AND u_id=%d AND ic_dev_state=%d', $itemId, $userId, $devState); my $sth = $dbh->prepare($sql); $sth->execute(); if(my $row = $sth->fetchrow_hashref) { $sql = sprintf('UPDATE item_comment SET ic_rating=%d, ic_comment=%s, ic_timestamp=NOW() WHERE ic_id=%d', $rating, $dbh->quote($comment), $row->{ic_id}); } else { $sql = sprintf('INSERT INTO item_comment SET i_id=%d, u_id=%d, ic_type=%d, ic_dev_state=%d, ic_rating=%d, ic_comment=%s, ic_timestamp=NOW()', $itemId, $userId, $type, $devState, $rating, $dbh->quote($comment)); } $sth->finish; $sth = $dbh->prepare($sql); $sth->execute(); $sth->finish; } sub addPassageComment { my $dbh = shift; my $passageId = shift; my $userId = shift; my $type = shift; my $devState = shift; my $rating = shift; my $comment = shift || ''; my $sql = sprintf('SELECT pc_id FROM passage_comment WHERE p_id=%d AND u_id=%d AND pc_dev_state=%d', $passageId, $userId, $devState); my $sth = $dbh->prepare($sql); $sth->execute(); if(my $row = $sth->fetchrow_hashref) { $sql = sprintf('UPDATE passage_comment SET pc_rating=%d, pc_comment=%s, pc_timestamp=NOW() WHERE pc_id=%d', $rating, $dbh->quote($comment), $row->{pc_id}); } else { $sql = sprintf('INSERT INTO passage_comment SET p_id=%d, u_id=%d, pc_type=%d, pc_dev_state=%d, pc_rating=%d, pc_comment=%s, pc_timestamp=NOW()', $passageId, $userId, $type, $devState, $rating, $dbh->quote($comment)); } $sth->finish; $sth = $dbh->prepare($sql); $sth->execute(); $sth->finish; } sub getActionMap { my $file = shift; my $start_time = [Time::HiRes::gettimeofday()]; my %map = (); my $xp = new XML::XPath( filename => $file ); foreach my $workNode ( $xp->findnodes('/workflow_set/workflow') ) { my $type = $xp->find( 'user_type', $workNode )->string_value; #print "User ${type}\n"; foreach my $actionNode ( $xp->findnodes( 'actions/action', $workNode ) ) { my $seq = $xp->find( 'sequence', $actionNode )->string_value; my $fromState = $xp->find( 'from_state', $actionNode )->string_value; my $label = $xp->find( 'label', $actionNode )->string_value; print STDERR "Cannot find map for state ${fromState}\n" unless exists $action_key_states{$fromState}; $map{$type}{$seq}{state} = $action_key_states{$fromState}; $map{$type}{$seq}{stateValue} = $fromState; $map{$type}{$seq}{label} = $label; if ( $xp->exists( 'use_compare', $actionNode ) ) { $map{$type}{$seq}{compare} = 1; } # NOTE: This is hard-coding comparison mode to always-on $map{$type}{$seq}{compare} = 1; if ( $xp->exists( 'compare_state', $actionNode ) ) { my $compareState = $xp->find( 'compare_state', $actionNode )->string_value; print STDERR "Cannot find map for compare state ${compareState}\n" unless exists $action_key_states{$compareState}; $map{$type}{$seq}{compareState} = $action_key_states{$compareState}; $map{$type}{$seq}{compareStateValue} = $compareState; } if ( $xp->exists( 'item_notes', $actionNode ) ) { $map{$type}{$seq}{itemNotesTag} = $xp->find( 'item_notes', $actionNode )->string_value; } if ( $xp->exists( 'is_group_review', $actionNode ) ) { $map{$type}{$seq}{isGroupReview} = 1; } if ( $xp->exists( 'is_group_review_lead', $actionNode ) ) { $map{$type}{$seq}{isGroupReviewLead} = 1; } # a group review state won't use normal transitions, there is just a hard-coded accept if($map{$type}{$seq}{isGroupReview}) { my $auto = 'accept'; $map{$type}{$seq}{$auto}{action} = join ('-', $map{$type}{$seq}{stateValue}, $auto); $map{$type}{$seq}{$auto}{label} = 'Accept'; $map{$type}{$seq}{$auto}{state} = $map{$type}{$seq}{state}; $map{$type}{$seq}{$auto}{stateValue} = $map{$type}{$seq}{stateValue}; } else { foreach my $transitionNode ( $xp->findnodes( 'transitions/transition', $actionNode ) ) { my $trans = $xp->find( 'transition_type', $transitionNode )->string_value; my $label = $xp->find( 'label', $transitionNode )->string_value; my $toState = $xp->find( 'to_state', $transitionNode )->string_value; print STDERR "Cannot find map for trans state '$toState'\n" unless exists $action_key_states{$toState}; $map{$type}{$seq}{$trans}{action} = join( '-', $fromState, $trans ); $map{$type}{$seq}{$trans}{label} = $label; $map{$type}{$seq}{$trans}{state} = $action_key_states{$toState}; $map{$type}{$seq}{$trans}{stateValue} = $toState; if ( $xp->exists( 'with_notification', $transitionNode ) ) { $map{$type}{$seq}{$trans}{notify_user} = $xp->find( 'with_notification', $transitionNode )->string_value; } } } } } my $diff = Time::HiRes::tv_interval($start_time); warn "Map loaded in $diff\n"; return \%map; } sub getWorkListForUserType { my $map = shift; my $userType = shift; my %list = (); return %list unless exists $map->{$userType}; foreach ( keys %{ $map->{$userType} } ) { $list{$_} = $map->{$userType}{$_}{label}; } return %list; } sub getCurrentItemIdByName { my $dbh = shift; my $itemBankId = shift; my $itemName = shift; my $itemId = 0; my $sql = sprintf('SELECT i_id FROM item WHERE ib_id=%d AND i_external_id=%s ORDER BY i_version DESC LIMIT 1', $itemBankId, $dbh->quote($itemName)); my $sth = $dbh->prepare($sql); $sth->execute(); if ( my $row = $sth->fetchrow_hashref ) { $itemId = $row->{i_id}; } $sth->finish; return $itemId; } sub getBubbleHtml { my $format = shift; $format =~ m/(\d+)(\.?)(\d*)$/; my $leading = $1; my $trailing = $3; my $decimal = $2; my $lCount = length($leading); my $tCount = length($trailing); my $html = '<table border="1" cellpadding="0" cellspacing="0" style="border-color: #000000;">'; # Build the header row $html .= '<tr style="border-color: #000000;">'; for ( my $i = 0 ; $i < $lCount ; $i++ ) { $html .= '<td style="width: 30px; height: 30px;" class="bubble">&nbsp;</td>'; } if ( $decimal eq '.' ) { $html .= '<td style="width: 30px; height: 30px;" class="bubble">' . '<span style="font-size:28pt; margin-top:8px;">.</span>' . '</td>'; } for ( my $i = 0 ; $i < $tCount ; $i++ ) { $html .= '<td style="width: 30px; height: 30px;" class="bubble">&nbsp;</td>'; } $html .= '</tr>'; # build the rest $html .= '<tr>'; for ( my $i = 0 ; $i < $lCount ; $i++ ) { $html .= '<td style="width: 27px;" class="bubble">'; for ( my $j = 0 ; $j <= substr( $leading, $i, 1 ) ; $j++ ) { $html .= '<input type="button" value="' . $j . '" class="bubble" /><br />'; } $html .= '</td>'; } if ( $decimal eq '.' ) { $html .= '<td style="width: 27px;" class="bubble">&nbsp;</td>'; } for ( my $i = 0 ; $i < $tCount ; $i++ ) { $html .= '<td style="width: 27px;" class="bubble">'; for ( my $j = 0 ; $j <= substr( $trailing, $i, 1 ) ; $j++ ) { $html .= '<input type="button" value="' . $j . '" class="bubble" /><br />'; } $html .= '</td>'; } $html .= '</tr></table>'; return $html; } sub readOgtFile { my $ogtFilePath = shift; my $params = shift; $ogtFilePath =~ tr/ /_/; if ( -e $ogtFilePath ) { open OGTFILE, "<${ogtFilePath}"; my $line = <OGTFILE>; close OGTFILE; $line =~ s/\s+$//; foreach my $namevalue ( split /&/, $line ) { my ( $n, $v ) = split /=/, $namevalue; $params->{ uri_unescape($n) } = uri_unescape($v); } } } sub hashToSelect { my $name = shift; my $hash = shift; my $match = shift; $match = '' unless defined $match; my $change = shift || ''; my $blank = shift || ''; my $sort = shift || ''; my $style = shift || ' '; $match = '' unless defined($match); my $out = '<select name="' . $name . '"' . ( $change eq '' ? '' : ' onChange="' . $change . '"' ) . ( $style eq '' ? '' : ' style="' . $style . '"' ) . '>'; $out .= '<option value=""></option>' unless $change eq ''; if ( $blank ne '' ) { my $blankLabel = ''; if ( $blank =~ m/^(\w+):(.*)$/ ) { $blank = $1; $blankLabel = $2; } if ( $blank eq 'null' ) { $blank = ''; } $out .= '<option value="' . $blank . '">' . $blankLabel . '</option>'; } my $sortSub = sub { $a <=> $b }; # Check for non-numeric keys my $firstVal = (keys %{$hash})[0]; if(defined($firstVal) && $firstVal !~ /^\d+$/) { $sortSub = sub { $a cmp $b }; } # sort by value if preferred, instead of by key if ( $sort eq 'value' ) { $sortSub = sub { $hash->{$a} cmp $hash->{$b} }; } foreach my $key ( sort $sortSub keys %{$hash} ) { $out .= '<option value="' . $key . '"' . ( $key eq $match ? ' SELECTED' : '' ) . '>' . $hash->{$key} . '</option>'; } $out .= '</select>'; return $out; } sub hashToCheckbox { my $name = shift; my $hash = shift; my $breakCount = shift || 20; my $sort = shift || ''; my $fieldCounter = 0; my $sortSub = sub { $a <=> $b }; if ( $sort eq 'value' ) { $sortSub = sub { $hash->{$a} cmp $hash->{$b} }; } my $out = ''; foreach ( sort $sortSub keys %{$hash} ) { $hash->{$_} =~ s/\s/&nbsp;/g; $out .= ( $fieldCounter > 0 and $fieldCounter % $breakCount == 0 ? '<br />' : '' ) . "$hash->{$_}&nbsp;<input type=\"checkbox\" name=\"${name}_$_\" value=\"yes\" />&nbsp;&nbsp;&nbsp;"; $fieldCounter++; } return $out; } sub getItemArchive { my $dbh = shift; my $itemIds = shift; my $debug = 0; my %in = (); my $tmpDir = "/tmp/getItemXml_$$/"; mkdir $tmpDir, 0777; print STDERR "Created tmpDir '$tmpDir'\n" if $debug; my $zipDir = $tmpDir . 'Items/'; my $imgDir = $zipDir . 'images/'; mkdir $zipDir, 0777; mkdir $imgDir, 0777; # The file $zipFile will be moved to $tmpFile just before deleting $tmpDir my $zipFile = "${tmpDir}getItemXml_$$.zip"; my $tmpFile = "/tmp/itemXml_$$.zip"; my $itemRelPath = './images/'; my %standard_labels = (); # get standard labels my $sql = 'SELECT * FROM qualifier_label WHERE sh_id=1'; my $sth = $dbh->prepare($sql); $sth->execute(); while ( my $row = $sth->fetchrow_hashref ) { $row->{ql_label} =~ s/[\s\/]/_/g; $standard_labels{ $row->{ql_type} } = lc( $row->{ql_label} ); } $sth->finish; $sql = "SELECT i.i_id, i.i_external_id, i.i_correct_response FROM item AS i WHERE i.i_id IN (" . join( ',', @{$itemIds} ) . ')' . " ORDER BY i.i_external_id"; $sth = $dbh->prepare($sql); $sth->execute(); print STDERR "Running query: $sql\n" if $debug; while ( my $row = $sth->fetchrow_hashref ) { # Create the item images directory my $itemDir = "${imgDir}$row->{i_external_id}/"; mkdir $itemDir, 0777; print STDERR "Created itemDir '$itemDir'\n" if $debug; # Build the item xml my $itemXml = &getItemXml( $dbh, $row->{i_id} ); # in the expression: # $1 is the <item> tag # $2 is the <item_name> tag # $3 is everything between the <item> tag and the 1st <question> tag # $4 is the 1st <question> tag #$itemXml =~ s/(<item [^>]+>)\s+(<item_name>.*?<\/item_name>)(.*?)(<question [^>]+>)/$1 $2 $3 $4/; # place the <correct> tag inside the corresponding <choice> tag at the end of the content # in this expression: # $1 is the <choice> tag # $2 is the content before the end </span> tag # $3 is the end </span> tag # $4 is the end </choice> tag #$itemXml =~ s/(<choice[^>]+value="$row->{i_correct_response}"[^>]*>)(.*?)(<\/span>)\s*(<\/choice>)/$1$2<correct>*<\/correct>$3$4/; # remove any blank choices #$itemXml =~ s/<choice[^>]+><span>&#160;<\/span><\/choice>//g; # Translate absolute URLs to relative $itemXml =~ s/src="([^"]+)"/&getImageSrcTranslate($1,$row->{i_external_id},${itemDir},${itemRelPath})/eg; open ITEM, '>', $zipDir . "$row->{i_external_id}.xml"; print ITEM $itemXml; close ITEM; } $sth->finish; my $origDir = Cwd::abs_path; chdir $tmpDir; system( "zip", "-r", "getItemXml_$$", "Items" ); chdir $origDir; rename $zipFile, $tmpFile; #system("rm","-rf",$tmpDir); return $tmpFile; } sub getImageSrcTranslate { my $url = shift; my $itemId = shift; my $itemPath = shift; my $relDir = shift; my $itemUrl = "${relDir}${itemId}/"; my $imgUrl = ''; if ( $url =~ m/$itemId\/(.*)/ ) { my $imgPath = $itemPath . $1; $imgUrl = $itemUrl . $1; cp( $webPath . $url, $imgPath ) || print STDERR "Unable to copy ${webPath}${url} to ${imgPath}"; } else { print STDERR "${url} does not contain the string '${itemId}'"; } return 'src="' . $imgUrl . '"'; } sub getStandard { my $dbh = shift; my $hdId = shift || ''; my $sth; $hdId = 0 if $hdId eq ''; my $standard = {}; my $pos = 0; while ( $hdId != 0 ) { my $sql = "SELECT * FROM hierarchy_definition WHERE hd_id=${hdId}"; $sth = $dbh->prepare($sql); $sth->execute() || print( STDERR "Failed Query:" . $dbh->err . "," . $dbh->errstr ); if ( my $row = $sth->fetchrow_hashref ) { $standard->{ $row->{hd_type} } = {}; $standard->{ $row->{hd_type} }->{pos} = $pos++; $standard->{ $row->{hd_type} }->{value} = $row->{hd_value}; $standard->{ $row->{hd_type} }->{sibling_pos} = $row->{hd_posn_in_parent}; $standard->{ $row->{hd_type} }->{id} = $row->{hd_id}; $hdId = $row->{hd_parent_id}; if ( int( $row->{hd_type} ) == $HD_ROOT ) { $hdId = 0; } elsif ( int( $row->{hd_type} ) == $HD_LEAF ) { $standard->{ $row->{hd_type} }->{text} = $row->{hd_std_desc}; } } else { $hdId = 0; } } $sth->finish if defined $sth; return $standard; } sub makeQueryWithWorkgroupFilter { my $sql = shift; my $wg = shift; my $objectType = shift; my $objQueryRef = shift; my $charTable = ($objectType == $OT_ITEM) ? 'item_characterization' : 'object_characterization'; my @wgFilters = (); my %filter_types = (); foreach my $fkey (keys %{$wg->{filters}}) { my @filterParts = (); my $fpart = $wg->{filters}{$fkey}{parts}; foreach my $fpkey (keys %{$fpart}) { my $fptable = 'ocfp' . $fpkey; if($objectType == $OT_ITEM) { push @filterParts, "(${objQueryRef}.i_id=${fptable}.i_id AND ${fptable}.ic_type=${fpkey} AND ${fptable}.ic_value=" . $fpart->{$fpkey} . ')'; } elsif ($objectType == $OT_PASSAGE) { push @filterParts, "(${fptable}.oc_object_type=${OT_PASSAGE} AND ${objQueryRef}.p_id=${fptable}.oc_object_id " . "AND ${fptable}.oc_characteristic=${fpkey} AND ${fptable}.oc_int_value=" . $fpart->{$fpkey} . ')'; } $filter_types{$fpkey} = 1; } push @wgFilters, join (' AND ', @filterParts); } my $wgJoinQuery = ' (' . join (' OR ', map { '(' . $_ . ')' } @wgFilters) . ') AND'; my $wgJoinTable = ''; $wgJoinTable .= $charTable . ' AS ocfp' . $_ . ', ' foreach keys %filter_types; unless(scalar @wgFilters) { $wgJoinTable = ''; $wgJoinQuery = '/*empty-workgroup*/ 1=0 AND'; } $sql =~ s/(FROM \/\*cde\-filter\*\/)/$1 $wgJoinTable/; $sql =~ s/(WHERE \/\*cde\-filter\*\/)/$1 $wgJoinQuery/; return $sql; } sub getMetadataClient { my $restClient = REST::Client->new(); $restClient->setHost('https://' . $webHost); $restClient->setTimeout(5); $restClient->setFollow(1); #$restClient->getUseragent()->credentials("${webHost}:443",'SBAC', # "ws-user-1","ping"); return $restClient; } sub getEditors { my $dbh = shift; my $itemBankId = shift || 0; my %editors = (); my $sql = ''; # set up the query different if we restrict by item bank access if($itemBankId) { $sql = <<SQL; SELECT u.* FROM user AS u, user_permission AS up WHERE u.u_id=up.u_id AND up.up_type=${UP_VIEW_ITEM_BANK} AND up.up_value=${itemBankId} AND u.u_type=11 SQL } else { $sql = 'SELECT u.* FROM user AS u WHERE u.u_type=11'; } # add stuff here to the query that applies either way $sql .= ' AND u.u_deleted=0 AND u.u_review_type=1'; my $sth = $dbh->prepare($sql); $sth->execute(); while ( my $row = $sth->fetchrow_hashref ) { $editors{ $row->{u_id} } = "$row->{u_last_name}, $row->{u_first_name} [$row->{u_username}]"; } $sth->finish; return \%editors; } sub getUsersWithReviewType { my $dbh = shift; my $reviewType = shift || 0; my $itemBankId = shift || 0; my %users = (); return \%users unless $reviewType && $itemBankId; my $sql = ''; # set up the query different if we restrict by item bank access $sql = <<SQL; SELECT u.* FROM user AS u, user_permission AS up WHERE u.u_id=up.u_id AND up.up_type=${UP_VIEW_ITEM_BANK} AND up.up_value=${itemBankId} AND u.u_type=11 AND u.u_deleted=0 AND u.u_review_type=${reviewType} SQL my $sth = $dbh->prepare($sql); $sth->execute(); while ( my $row = $sth->fetchrow_hashref ) { $users{ $row->{u_id} } = "$row->{u_last_name}, $row->{u_first_name} [$row->{u_username}]"; } $sth->finish; return \%users; } sub getUsers { my $dbh = shift; my $organizationId = shift || 0; my %users = (); my $sql = 'SELECT t1.* FROM user AS t1 WHERE' . ' t1.u_type=11 AND t1.u_permissions>0'; if($organizationId) { $sql .= ' AND t1.o_id=' . $organizationId; } my $sth = $dbh->prepare($sql); $sth->execute(); while ( my $row = $sth->fetchrow_hashref ) { $users{ $row->{u_id} } = "$row->{u_last_name}, $row->{u_first_name} [$row->{u_username}]"; } $sth->finish; return \%users; } sub getUsersWithPermissions { my $dbh = shift; my $organizationId = shift || 0; my %users = (); my $sql = 'SELECT u.* FROM user AS u WHERE' . ' u.u_type=11 AND u.u_deleted=0 AND u.u_permissions > 0'; if($organizationId) { $sql .= ' AND u.o_id=' . $organizationId; } my $sth = $dbh->prepare($sql); $sth->execute(); while ( my $row = $sth->fetchrow_hashref ) { my $key = $row->{u_id}; $users{$key} = {}; $users{$key}{name} = "$row->{u_last_name}, $row->{u_first_name} [$row->{u_username}]"; $users{$key}{roles} = $row->{u_permissions}; $users{$key}{itemBanks} = {}; $users{$key}{testBanks} = {}; $users{$key}{reviewType} = $row->{u_review_type}; $users{$key}{adminType} = $row->{u_admin_type}; $users{$key}{organizationId} = $row->{o_id}; $sql = 'SELECT up_value FROM user_permission WHERE u_id=' . $row->{u_id} . ' AND up_type=' . $UP_VIEW_ITEM_BANK; my $sth2 = $dbh->prepare($sql); $sth2->execute(); while ( my $row2 = $sth2->fetchrow_hashref ) { $users{$key}{itemBanks}{ $row2->{up_value} } = 1; } $sth2->finish; $sql = 'SELECT up_value FROM user_permission WHERE u_id=' . $row->{u_id} . ' AND up_type=' . $UP_VIEW_TEST_BANK; $sth2 = $dbh->prepare($sql); $sth2->execute(); while ( my $row2 = $sth2->fetchrow_hashref ) { $users{$key}{testBanks}{ $row2->{up_value} } = 1; } $sth2->finish; } $sth->finish; return \%users; } sub getUsersByItemBank { my $dbh = shift; my $itemBankId = shift || 0; my %users = (); my $sql = <<SQL; SELECT u.* FROM user AS u, user_permission AS up WHERE u.u_type=11 AND u.u_deleted=0 AND u.u_id=up.u_id AND up.up_type=${UP_VIEW_ITEM_BANK} AND up.up_value=${itemBankId} SQL my $sth = $dbh->prepare($sql); $sth->execute(); while ( my $row = $sth->fetchrow_hashref ) { my $user = {}; $user->{name} = "$row->{u_last_name}, $row->{u_first_name} [$row->{u_username}]"; $user->{reviewType} = $row->{u_review_type}; $user->{adminType} = $row->{u_admin_type}; $user->{organizationId} = $row->{o_id}; $users{$row->{u_id}} = $user; } return \%users; } sub getWorkgroups { my $dbh = shift; my $itemBankId = shift; my %out = (); my $sql = sprintf('SELECT * FROM workgroup WHERE ib_id=%d ORDER BY w_name',$itemBankId); my $sth = $dbh->prepare($sql); $sth->execute(); while(my $row = $sth->fetchrow_hashref) { my $wg = {}; $wg->{name} = $row->{w_name}; $wg->{description} = $row->{w_description}; $out{$row->{w_id}} = $wg; } return \%out; } sub getWorkgroupsByUser { my $dbh = shift; my $userId = shift; my %out = (); my $sql = <<SQL; SELECT w.* FROM workgroup AS w, user_permission AS up WHERE up.u_id=${userId} AND up.up_type=${UP_VIEW_WORKGROUP} AND up.up_value=w.w_id SQL my $sth = $dbh->prepare($sql); $sth->execute(); while(my $row = $sth->fetchrow_hashref) { my $wg = {}; $wg->{bank} = $row->{ib_id}; $wg->{name} = $row->{w_name}; $wg->{description} = $row->{w_description}; $wg->{filters} = &getWorkgroupFilters($dbh, $row->{w_id}); $out{$row->{w_id}} = $wg; } return \%out; } sub getWorkgroupFilters { my $dbh = shift; my $workGroupId = shift; my %out = (); my $sql = <<SQL; SELECT wfp.* FROM workgroup_filter_part AS wfp, workgroup_filter AS wf WHERE wf.w_id=${workGroupId} AND wfp.wf_id=wf.wf_id SQL my $sth = $dbh->prepare($sql); $sth->execute(); while(my $row = $sth->fetchrow_hashref) { $out{$row->{wf_id}}{parts}{$row->{wf_type}} = $row->{wf_value}; } return \%out; } sub getItemsByUser { my $dbh = shift; my $user = shift || 0; my $itemBankId = shift || 0; my %items = (); my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime(time); my $today = sprintf( '%04d-%02d-%02d', $year + 1900, $mon + 1, $mday ); my $sql = "SELECT its.*, i.i_external_id FROM item_status AS its, item AS i WHERE its.is_u_id=${user} AND its.is_timestamp >= '${today}' AND its.i_id=i.i_id AND i.ib_id=${itemBankId}"; my $sth = $dbh->prepare($sql); $sth->execute(); print STDERR "getItemsByUser: $sql"; while ( my $row = $sth->fetchrow_hashref ) { my $key = $row->{is_timestamp}; $items{$key} = {}; $items{$key}{id} = $row->{i_id}; $items{$key}{name} = $row->{i_external_id}; $items{$key}{lastDevState} = $dev_states{ $row->{is_last_dev_state} }; $items{$key}{newDevState} = $dev_states{ $row->{is_new_dev_state} }; } $sth->finish; return \%items; } sub getProjects { my $dbh = shift; my $itemBankId = shift || 0; my %projects = (); my $sql = "SELECT * FROM item_project WHERE ib_id=${itemBankId}"; my $sth = $dbh->prepare($sql); $sth->execute(); while ( my $row = $sth->fetchrow_hashref ) { $projects{ $row->{ip_id} } = $row->{ip_name}; } $sth->finish; return \%projects; } sub getOrganizations { my $dbh = shift; my %orgs = (); my $sql = "SELECT * FROM organization"; my $sth = $dbh->prepare($sql); $sth->execute(); while ( my $row = $sth->fetchrow_hashref ) { my $key = $row->{o_id}; $orgs{$key} = {}; $orgs{$key}{name} = $row->{o_name}; $orgs{$key}{description} = $row->{o_description}; $orgs{$key}{name_escaped} = &escapeHTML($row->{o_name}); $orgs{$key}{description_escaped} = &escapeHTML($row->{o_description}); } $sth->finish; return \%orgs; } sub getItemBanks { my $dbh = shift; my $userId = shift || 0; my $organizationId = shift || 0; my %banks = (); my $sql; if ($userId) { $sql = "SELECT ib.* FROM item_bank AS ib, user_permission AS up" . " WHERE up.u_id=${userId} AND up.up_type=${UP_VIEW_ITEM_BANK} AND up.up_value=ib.ib_id"; } else { $sql = "SELECT * FROM item_bank"; if($organizationId) { $sql .= " WHERE o_id=${organizationId}"; } } my $sth = $dbh->prepare($sql); $sth->execute(); while ( my $row = $sth->fetchrow_hashref ) { my $key = $row->{ib_id}; $banks{$key} = {}; $banks{$key}{name} = $row->{ib_external_id}; $banks{$key}{description} = $row->{ib_description}; $banks{$key}{owner} = $row->{ib_owner}; $banks{$key}{hostBase} = $row->{ib_host_base}; $banks{$key}{hasIMS} = $row->{ib_has_ims}; $banks{$key}{assignIMSId} = $row->{ib_assign_ims_id}; $banks{$key}{organization} = $row->{o_id}; $banks{$key}{tb_id} = $row->{tb_id}; $banks{$key}{sh_id} = $row->{sh_id}; } $sth->finish; return \%banks; } sub getStandards { my $dbh = shift; my %tbl = (); my $sql = "SELECT * FROM standard_hierarchy ORDER BY sh_external_id"; my $sth = $dbh->prepare($sql); $sth->execute(); while ( my $row = $sth->fetchrow_hashref ) { $tbl{$row->{sh_id}} = $row->{sh_external_id}; } $sth->finish; return \%tbl; } sub getPassageList { my $dbh = shift; my $itemBankId = shift || 0; my $contentArea = shift || ''; my $gradeLevel = shift || ''; my %passages = (); my $sql = "SELECT p.* FROM passage AS p WHERE p.ib_id=${itemBankId}" . ( $contentArea eq '' ? '' : " AND ${contentArea} = (SELECT oc_int_value FROM object_characterization WHERE oc_object_type=${OT_PASSAGE} AND oc_object_id=p.p_id AND oc_characteristic=${OC_CONTENT_AREA} LIMIT 1)" ) . ( $gradeLevel eq '' ? '' : " AND ${gradeLevel} = (SELECT oc_int_value FROM object_characterization WHERE oc_object_type=${OT_PASSAGE} AND oc_object_id=p.p_id AND oc_characteristic=${OC_GRADE_LEVEL} LIMIT 1)" ); my $sth = $dbh->prepare($sql); $sth->execute(); while ( my $row = $sth->fetchrow_hashref ) { $passages{ $row->{p_id} } = $row->{p_name}; } $sth->finish; return \%passages; } sub dbCharUpdate { my $dbh = shift; my $oType = shift; my $oID = shift; my $cType = shift; my $cValue = shift; my $sql = "SELECT * FROM object_characterization" . " WHERE oc_object_type=${oType}" . " AND oc_object_id=${oID} AND oc_characteristic=${cType}"; my $sth = $dbh->prepare($sql); $sth->execute() || print( STDERR "Failed Query:" . $dbh->err ); if ( my $row = $sth->fetchrow_hashref ) { $sql = "UPDATE object_characterization SET oc_int_value=${cValue}" . " WHERE oc_object_type=${oType}" . " AND oc_object_id=${oID} AND oc_characteristic=${cType}"; } else { $sql = 'INSERT INTO object_characterization' . ' (oc_object_type,oc_object_id,oc_characteristic,oc_int_value)' . " VALUES (${oType},${oID},${cType},${cValue})"; } $sth = $dbh->prepare($sql); $sth->execute() || print( STDERR "Failed Query:" . $dbh->err ); $sth->finish; } sub get_project_config { my $projectId = shift; my %config = (); use XML::XPath; my $xp = XML::XPath->new( 'filename' => "${projectConfigDir}${projectId}.xml" ); $config{startDate} = $xp->getNodeText('/project/@startDate'); $config{endDate} = $xp->getNodeText('/project/@endDate'); $config{writers} = {}; $config{workstates} = {}; foreach ( $xp->find('/project/writers/writer')->get_nodelist ) { $config{writers}->{ $_->getAttribute('id') } = {}; $config{writers}->{ $_->getAttribute('id') }->{rate} = $_->getAttribute('rate'); $config{writers}->{ $_->getAttribute('id') }->{rateType} = $_->getAttribute('rateType'); } foreach ( $xp->find('/project/workstates/state')->get_nodelist ) { $config{workstates}->{ $_->getAttribute('id') } = {}; $config{workstates}->{ $_->getAttribute('id') }->{estimate} = $_->getAttribute('timeEstimate'); } return \%config; } sub fixHtml { my $html = shift; $html =~ s/http:\/\/$ENV{SERVER_NAME}//gs if defined $ENV{SERVER_NAME}; $html =~ s/<\/img (?:style|src)[^>]*>/<\/p>/gs; $html =~ s/<\/span[^>]+>/<\/span>/gs; $html =~ s/<\/td[^>]+>/<\/td>/gs; $html =~ s/<\/li[^>]+>/<\/li>/gs; $html =~ s/<\/p[^>]+>/<\/p>/gs; $html =~ s/<align="\w*"><\/align="\w*">//gs; $html =~ s/<\/?st1:[^>]*>//gs; $html =~ s/<\/?o:[^>]*>//gs; $html =~ s/<\/?v:[^>]*>//gs; $html =~ s/<\/?w:[^>]*>//gs; $html =~ s/<\/>//gs; $html =~ s/classid=''/classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'/gs; $html =~ s/classid=""/classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"/gs; while ( $html =~ m/(?:value|flashvars)="(?:[^"]*)\&amp;amp;/ ) { $html =~ s/(value|flashvars)="([^"]*?)\&(?:amp;){2,}([^"]*)"/$1="$2\&amp;$3"/s; } return $html; } sub setImageSize { my $srcLine = shift; $srcLine =~ /src="([^"]+)"/; #unless($1 =~ /\.gif$/) { return $srcLine; } my $file = $webPath . $1; my $output = `identify $file`; $output =~ /(\d{1,4})x(\d{1,4})/; if ( defined($1) ) { my $width = $1; my $height = $2; if ( $width =~ /^\d+$/ && $width > 0 ) { return $srcLine . ' width="' . int($width) . '" height="' . int($height) . '" '; } else { return $srcLine; } } else { return $srcLine; } } # tests to see if html content is empty, decodes any mutlibyte characters and # strips html, finally checks to see if any spaces (single or multibyte) sub isHTMLContentEmpty { my $html_content = shift; use HTML::Entities; my $html_decoded = decode_entities($html_content); my $plain_content = $html_decoded; return ($plain_content=~/^\p{Zs}*$|^\s*$/); } sub escapeHTML { my $html = shift; return '' unless defined $html; $html =~ s/&/&amp;/g; $html =~ s/(value|flashvars)="([^"]+)"/&escapeFlashValue($1,$2)/eg; $html =~ s/</&lt;/g; $html =~ s/>/&gt;/g; $html =~ s/"/&quot;/g; $html =~ s/'/&apos;/g; return $html; } sub unescapeHTML { my $html = shift; return '' unless defined $html; $html =~ s/(value|flashvars)="([^"]+)"/&unescapeFlashValue($1,$2)/eg; return $html; } sub escapeFlashValue { my $name = shift; my $value = shift; $value =~ s/&/&amp;/g; return $name . '="' . $value . '"'; } sub unescapeFlashValue { my $name = shift; my $value = shift; $value =~ s/&amp;/&/g; return $name . '="' . $value . '"'; } sub print_no_auth { return <<END_HTML; <html> <head> <title>Not Authorized</title> <link rel="stylesheet" href="${UrlConstants::orcaUrl}style/text.css" type="text/css" /> </head> <body> <div class="title">You Are Not Authorized to Access this Application. Click here <a href="#" onClick="parent.document.location.href='${UrlConstants::authUrl}logout';">to Log Out.</a></div> </body> </html> END_HTML } sub printNoAuthPage { my $msg = shift; print <<END_HTML; <html> <head> <title>Not Authorized</title> </head> <body> <h3>You Are Not Authorized to Access this page!</h3> </body> </html> END_HTML } sub get_ts { my $time_shift = shift; my $addSeconds = ( $time_shift ? $time_shift : 0 ); my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime( time + $addSeconds ); return sprintf( "%4d-%02d-%02d %02d:%02d:%02d", $year + 1900, $mon + 1, $mday, $hour, $min, $sec ); } sub getContentAssetPair { my $dbh = shift; my $object_type = shift; my $object_id = shift; my $assetName = shift; my $pairName = ''; $assetName = $dbh->quote($assetName); my $sql = <<SQL; SELECT cap_pair_name FROM content_asset_pair WHERE cap_object_type=${object_type} AND cap_object_id=${object_id} AND cap_asset_name=${assetName} SQL my $sth = $dbh->prepare($sql); $sth->execute(); if(my $row = $sth->fetchrow_hashref) { $pairName = $row->{cap_pair_name}; } $sth->finish; return $pairName; } sub setContentAssetPair { my $dbh = shift; my $object_type = shift; my $object_id = shift; my $assetName = shift; my $pairName = shift; $assetName = $dbh->quote($assetName); $pairName = $dbh->quote($pairName); my $sql = <<SQL; SELECT cap_id FROM content_asset_pair WHERE cap_object_type=${object_type} AND cap_object_id=${object_id} AND cap_asset_name=${assetName} SQL my $sth = $dbh->prepare($sql); $sth->execute(); if(my $row = $sth->fetchrow_hashref) { $sql = "UPDATE content_asset_pair SET cap_pair_name=${pairName} WHERE cap_id=$row->{cap_id}"; } else { $sql = <<SQL; INSERT INTO content_asset_pair SET cap_object_type=${object_type}, cap_object_id=${object_id}, cap_asset_name=${assetName}, cap_pair_name=${pairName} SQL } #print STDERR $sql; $sth = $dbh->prepare($sql); $sth->execute(); $sth->finish; } 1;
SmarterApp/ItemAuthoring
sbac-iaip-rpm-installer/iaip-wwwcde-rpm/src/main/www/cdesbac/cgi-bin/ItemConstants.pm
Perl
apache-2.0
98,359
## OpenXPKI::Server::API.pm ## ## Written 2005, 2006, 2007 by Michael Bell, Martin Bartosch and ## Alexander Klink for the OpenXPKI project ## restructured 2006 by Alexander Klink for the OpenXPKI project ## Copyright (C) 2005-2007 by The OpenXPKI Project package OpenXPKI::Server::API; use strict; use warnings; use utf8; use English; use Benchmark ':hireswallclock'; use Class::Std; use Data::Dumper; use Regexp::Common; use Params::Validate qw( validate :types ); use OpenXPKI::Debug; use OpenXPKI::Exception; use OpenXPKI::Server::Context qw( CTX ); use OpenXPKI::DN; use OpenXPKI::Server::API::Default; use OpenXPKI::Server::API::Object; use OpenXPKI::Server::API::Profile; use OpenXPKI::Server::API::Secret; use OpenXPKI::Server::API::Token; use OpenXPKI::Server::API::Visualization; use OpenXPKI::Server::API::Workflow; use OpenXPKI::Server::API::Smartcard; my %external_of :ATTR; my %method_info_of :ATTR; my %memoization_of :ATTR; our $current_method; sub BUILD { my ($self, $ident, $arg_ref) = @_; Params::Validate::validation_options( # let parameter validation errors throw a proper exception on_fail => sub { my $error = shift; OpenXPKI::Exception->throw ( message => "I18N_OPENXPKI_SERVER_API_INVALID_PARAMETER", params => { ERROR => $error, CALL => $current_method }); }, ); if ($arg_ref->{EXTERNAL}) { # we are called externally, do ACL checks $external_of{$ident} = 1; } my $re_all = qr{ \A .* \z }xms; my $re_alpha_string = qr{ \A [ \w \- \. : \s ]* \z }xms; my $re_integer_string = qr{ \A $RE{num}{int} \z }xms; my $re_boolean = qr{ \A [01] \z }xms; my $re_base64_string = qr{ \A [A-Za-z0-9\+/=_\-]* \z }xms; my $re_cert_string = qr{ \A [A-Za-z0-9\+/=_\-\ \n]+ \z }xms; my $re_filename_string = qr{ \A [A-Za-z0-9\+/=_\-\.]* \z }xms; my $re_image_format = qr{ \A (ps|png|jpg|gif|cmapx|imap|svg|svgz|mif|fig|hpgl|pcl|NULL) \z }xms; my $re_cert_format = qr{ \A (PEM|DER|TXT|PKCS7|HASH) \z }xms; my $re_crl_format = qr{ \A (PEM|DER|TXT|HASH|RAW) \z }xms; my $re_privkey_format = qr{ \A (PKCS8_PEM|PKCS8_DER|OPENSSL_PRIVKEY|PKCS12|JAVA_KEYSTORE) \z }xms; # TODO - consider opening up re_sql_string even more, currently this means # that we can not search for unicode characters in certificate subjects, # for example ... my $re_sql_string = qr{ \A [a-zA-Z0-9\@\-_\.\s\%\*\+\=\,\:\ ]* \z }xms; my $re_approval_msg_type = qr{ \A (CSR|CRR) \z }xms; my $re_approval_lang = qr{ \A (de_DE|en_US|ru_RU) \z }xms; my $re_csr_format = qr{ \A (PEM|DER|TXT) \z }xms; my $re_pkcs10 = qr{ \A [A-za-z0-9\+/=_\-\r\n\ ]+ \z}xms; $method_info_of{$ident} = { ### Default API 'get_cert_identifier' => { class => 'Default', params => { 'CERT' => { type => SCALAR, regex => $re_cert_string, }, }, }, 'count_my_certificates' => { class => 'Default', params => { }, }, 'list_my_certificates' => { class => 'Default', params => { LIMIT => { type => SCALAR, optional => 1, regex => $re_integer_string, }, START => { type => SCALAR, optional => 1, regex => $re_integer_string, }, }, }, 'get_workflow_ids_for_cert' => { class => 'Default', params => { 'CSR_SERIAL' => { type => SCALAR, regex => $re_integer_string, optional => 1, }, IDENTIFIER => { type => SCALAR, regex => $re_base64_string, optional => 1, }, }, }, 'get_default_token' => { class => 'Token', params => { }, }, 'get_token_alias_by_type' => { class => 'Token', params => { 'TYPE' => { type => SCALAR, regex => $re_alpha_string, }, 'VALIDITY' => { type => HASHREF, optional => 1, }, }, }, 'get_token_alias_by_group' => { class => 'Token', params => { 'GROUP' => { type => SCALAR, regex => $re_alpha_string, }, 'VALIDITY' => { type => HASHREF, optional => 1, }, }, }, 'list_active_aliases' => { class => 'Token', params => { 'GROUP' => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, 'TYPE' => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, 'VALIDITY' => { type => HASHREF, optional => 1, }, 'REALM' => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, }, }, 'get_trust_anchors' => { class => 'Token', params => { 'PATH' => { type => SCALAR, regex => $re_alpha_string, }, }, }, 'get_certificate_for_alias' => { class => 'Token', params => { 'ALIAS' => { type => SCALAR, regex => $re_alpha_string, }, }, }, 'get_approval_message' => { class => 'Default', params => { 'TYPE' => { type => SCALAR, regex => $re_approval_msg_type, optional => 1, }, 'WORKFLOW' => { type => SCALAR, regex => $re_alpha_string, }, 'ID' => { type => SCALAR, regex => $re_integer_string, }, 'LANG' => { type => SCALAR, regex => $re_approval_lang, }, }, memoize => 1, }, 'get_head_version_id' => { class => 'Default', params => { }, }, 'get_pki_realm' => { class => 'Default', params => { }, }, 'get_user' => { class => 'Default', params => { }, }, 'get_role' => { class => 'Default', params => { }, }, 'get_session_info' => { class => 'Default', params => { }, }, 'get_alg_names' => { class => 'Default', params => { }, }, 'get_param_names' => { class => 'Default', params => { 'KEYTYPE' => { type => SCALAR, regex => $re_alpha_string, }, }, memoize => 1, }, 'get_param_values' => { class => 'Default', params => { 'KEYTYPE' => { type => SCALAR, regex => $re_alpha_string, }, 'PARAMNAME' => { type => SCALAR, regex => $re_alpha_string, }, }, memoize => 1, }, 'get_chain' => { class => 'Default', params => { START_IDENTIFIER => { type => SCALAR, regex => $re_base64_string, }, OUTFORMAT => { type => SCALAR, optional => 1, regex => $re_cert_format, }, BUNDLE => { type => SCALAR, optional => 1, regex => $re_boolean, }, KEEPROOT => { type => SCALAR, optional => 1, regex => $re_boolean, }, }, }, 'get_ca_list' => { class => 'Token', params => { PKI_REALM => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, }, }, 'get_ca_cert' => { class => 'Object', params => { IDENTIFIER => { type => SCALAR, regex => $re_base64_string, } }, }, 'get_cert' => { class => 'Object', params => { IDENTIFIER => { type => SCALAR, regex => $re_base64_string, }, FORMAT => { type => SCALAR, optional => 1, regex => $re_cert_format, }, }, }, 'private_key_exists_for_cert' => { class => 'Object', params => { IDENTIFIER => { type => SCALAR, regex => $re_base64_string, }, }, }, 'get_private_key_for_cert' => { class => 'Object', params => { IDENTIFIER => { type => SCALAR, regex => $re_base64_string, }, FORMAT => { type => SCALAR, regex => $re_privkey_format, }, PASSWORD => { type => SCALAR, # regex => ??? }, CSP => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, }, }, 'get_crl' => { class => 'Object', params => { SERIAL => { type => SCALAR, regex => $re_integer_string, }, FILENAME => { type => SCALAR, optional => 1, regex => $re_filename_string, }, FORMAT => { type => SCALAR, optional => 1, regex => $re_crl_format, }, PKI_REALM => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, }, }, 'get_crl_list' => { class => 'Object', params => { 'ISSUER' => { type => SCALAR, regex => $re_base64_string, optional => 1, }, 'PKI_REALM' => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, 'FORMAT' => { type => SCALAR, optional => 1, regex => $re_crl_format, }, VALID_AT => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, LIMIT => { type => SCALAR, regex => $re_integer_string, optional => 1, }, }, }, 'get_random' => { class => 'Default', params => { 'LENGTH' => { type => SCALAR, regex => $re_integer_string, }, }, }, 'search_cert_count' => { class => 'Object', params => { IDENTIFIER => { type => SCALAR, optional => 1, regex => $re_base64_string, }, EMAIL => { type => SCALAR, optional => 1, regex => $re_sql_string, }, SUBJECT => { type => SCALAR, optional => 1, regex => $re_sql_string, }, ISSUER => { type => SCALAR, optional => 1, regex => $re_sql_string, }, SUBJECT_KEY_IDENTIFIER => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, AUTHORITY_KEY_IDENTIFIER => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, CSR_SERIAL => { type => SCALAR, optional => 1, regex => $re_integer_string, }, CERT_SERIAL => { type => SCALAR, optional => 1, regex => $re_integer_string, }, 'PKI_REALM' => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, NOTBEFORE => { type => SCALAR, optional => 1, regex => $re_integer_string, }, NOTAFTER => { type => SCALAR, optional => 1, regex => $re_integer_string, }, PROFILE => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, CERT_ATTRIBUTES => { type => ARRAYREF, optional => 1, }, VALID_AT => { type => SCALAR, optional => 1, regex => $re_integer_string, }, STATUS => { type => SCALAR, optional => 1, regex => $re_sql_string, }, }, }, 'search_cert' => { class => 'Object', params => { IDENTIFIER => { type => SCALAR, optional => 1, regex => $re_base64_string, }, EMAIL => { type => SCALAR, optional => 1, regex => $re_sql_string, }, SUBJECT => { type => SCALAR, optional => 1, regex => $re_sql_string, }, ISSUER => { type => SCALAR, optional => 1, regex => $re_sql_string, }, CSR_SERIAL => { type => SCALAR, optional => 1, regex => $re_integer_string, }, CERT_SERIAL => { type => SCALAR, optional => 1, regex => $re_integer_string, }, 'PKI_REALM' => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, SUBJECT_KEY_IDENTIFIER => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, AUTHORITY_KEY_IDENTIFIER => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, NOTBEFORE => { type => SCALAR, optional => 1, regex => $re_integer_string, }, NOTAFTER => { type => SCALAR, optional => 1, regex => $re_integer_string, }, PROFILE => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, CERT_ATTRIBUTES => { type => ARRAYREF, optional => 1, }, LIMIT => { type => SCALAR, optional => 1, regex => $re_integer_string, }, START => { type => SCALAR, optional => 1, regex => $re_integer_string, }, VALID_AT => { type => SCALAR, optional => 1, regex => $re_integer_string, }, STATUS => { type => SCALAR, optional => 1, regex => $re_sql_string, }, }, }, 'get_roles' => { class => 'Default', params => { }, }, 'get_servers' => { class => 'Default', params => { }, memoize => 1, }, 'get_export_destinations' => { class => 'Default', params => { }, memoize => 1, }, 'convert_csr' => { class => 'Default', params => { DATA => { type => SCALAR, }, IN => { type => SCALAR, regex => $re_csr_format, }, OUT => { type => SCALAR, regex => $re_csr_format, }, }, }, 'convert_certificate' => { class => 'Default', params => { DATA => { type => SCALAR, }, IN => { type => SCALAR, regex => $re_csr_format, }, OUT => { type => SCALAR, regex => $re_csr_format, }, }, }, 'send_notification' => { class => 'Default', params => { MESSAGE => { type => SCALAR, regex => $re_alpha_string, }, PARAMS => { type => HASHREF, optional => 1, }, }, }, ## Profile API 'get_possible_profiles_for_role' => { class => 'Profile', params => { 'ROLE' => { type => SCALAR, regex => $re_alpha_string, }, 'NOHIDE' => { type => SCALAR, optional => 1, regex => $re_boolean, }, }, memoize => 1, }, 'get_available_cert_roles' => { class => 'Profile', params => { PROFILES => { type => ARRAYREF, optional => 1, }, }, memoize => 1, }, 'get_cert_profiles' => { class => 'Profile', params => { 'NOHIDE' => { type => SCALAR, optional => 1, regex => $re_boolean, }, }, memoize => 1, }, 'get_cert_subject_profiles' => { class => 'Profile', params => { PROFILE => { type => SCALAR, regex => $re_alpha_string, }, }, memoize => 1, }, 'get_cert_subject_styles' => { class => 'Profile', params => { PROFILE => { type => SCALAR, regex => $re_alpha_string, }, PKCS10 => { type => SCALAR, optional => 1, regex => $re_pkcs10, }, }, memoize => 1, }, 'get_additional_information_fields' => { class => 'Profile', params => { }, memoize => 1, }, 'get_field_definition' => { class => 'Profile', params => { PROFILE => { type => SCALAR, regex => $re_alpha_string }, FIELDS => { type => ARRAYREF, }, }, }, 'render_subject_from_template' => { class => 'Profile', params => { PROFILE => { type => SCALAR, regex => $re_alpha_string }, STYLE => { type => SCALAR, optional => 1, regex => $re_alpha_string, }, VARS => { type => HASHREF, }, }, }, 'render_san_from_template' => { class => 'Profile', params => { PROFILE => { type => SCALAR, regex => $re_alpha_string }, STYLE => { type => SCALAR, optional => 1, regex => $re_alpha_string, }, VARS => { type => HASHREF, }, ADDITIONAL => { type => HASHREF | UNDEF, optional => 1 }, }, }, 'list_supported_san' => { class => 'Profile', params => {} }, 'render_metadata_from_template'=> { class => 'Profile', params => { PROFILE => { type => SCALAR, regex => $re_alpha_string }, STYLE => { type => SCALAR, optional => 1, regex => $re_alpha_string, }, VARS => { type => HASHREF, }, }, }, ### Object API 'get_csr_info_hash_from_data' => { class => 'Object', params => { DATA => { type => SCALAR, # TODO: regexp? }, }, }, 'set_data_pool_entry' => { class => 'Object', params => { 'PKI_REALM' => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, 'NAMESPACE' => { type => SCALAR, regex => $re_alpha_string, }, 'EXPIRATION_DATE' => { type => SCALAR | UNDEF, regex => $re_integer_string, optional => 1, }, 'ENCRYPT' => { type => SCALAR, regex => $re_integer_string, optional => 1, }, 'KEY' => { type => SCALAR, regex => $re_alpha_string, }, 'VALUE' => { type => SCALAR | UNDEF, regex => $re_all, }, 'FORCE' => { type => SCALAR, regex => $re_integer_string, optional => 1, }, 'COMMIT' => { type => SCALAR, regex => $re_integer_string, optional => 1, }, }, }, 'get_data_pool_entry' => { class => 'Object', params => { 'PKI_REALM' => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, 'NAMESPACE' => { type => SCALAR, regex => $re_alpha_string, }, 'KEY' => { type => SCALAR, regex => $re_alpha_string, }, }, }, 'modify_data_pool_entry' => { class => 'Object', params => { 'PKI_REALM' => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, 'NAMESPACE' => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, 'KEY' => { type => SCALAR, regex => qr{ \A \$? [ \w \- \. : \s ]* \z }xms, }, 'NEWKEY' => { type => SCALAR, regex => qr{ \A \$? [ \w \- \. : \s ]* \z }xms, }, 'EXPIRATION_DATE' => { type => SCALAR | UNDEF, # allow integers but also empty string (undef...) regex => qr{ \A $RE{num}{int}* \z }xms, optional => 1, }, }, }, 'list_data_pool_entries' => { class => 'Object', params => { 'PKI_REALM' => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, 'NAMESPACE' => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, 'LIMIT' => { type => SCALAR, regex => $re_integer_string, optional => 1, }, }, }, 'validate_certificate' => { class => 'Object', params => { 'PEM' => { type => SCALAR | ARRAYREF, optional => 1, }, 'PKCS7' => { type => SCALAR, regex => $re_cert_string, optional => 1, }, 'ANCHOR' => { type => ARRAYREF, optional => 1, }, 'NOCRL' => { type => SCALAR, regex => $re_integer_string, optional => 1, }, } }, ### Visualization API 'get_workflow_instance_info' => { class => 'Visualization', params => { ID => { type => SCALAR, regex => $re_integer_string, }, FORMAT => { type => SCALAR, regex => $re_image_format, }, LANGUAGE => { type => SCALAR, # TODO: regexp? }, }, }, ### Workflow API 'get_cert_identifier_by_csr_wf' => { class => 'Workflow', params => { 'WORKFLOW_ID' => { type => SCALAR, regex => $re_integer_string, }, }, }, 'get_number_of_workflow_instances' => { class => 'Workflow', params => { ACTIVE => { type => SCALAR, regex => $re_integer_string, optional => 1, }, }, }, 'list_workflow_instances' => { class => 'Workflow', params => { LIMIT => { type => SCALAR, regex => $re_integer_string, }, START => { type => SCALAR, regex => $re_integer_string, }, ACTIVE => { type => SCALAR, regex => $re_integer_string, optional => 1, }, }, }, 'list_workflow_titles' => { class => 'Workflow', params => { }, memoize => 1, }, 'list_context_keys' => { class => 'Workflow', params => { WORKFLOW_TYPE => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, }, }, 'get_workflow_type_for_id' => { class => 'Workflow', params => { ID => { type => SCALAR, regex => $re_integer_string, }, }, }, 'get_workflow_info' => { class => 'Workflow', params => { WORKFLOW => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, ID => { type => SCALAR, regex => $re_integer_string, }, }, }, 'get_workflow_ui_info' => { class => 'Workflow', params => { WORKFLOW => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, ID => { type => SCALAR, regex => $re_integer_string, optional => 1, }, ACTIVITY => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, }, }, 'get_workflow_history' => { class => 'Workflow', params => { ID => { type => SCALAR, regex => $re_integer_string, }, }, }, 'execute_workflow_activity' => { class => 'Workflow', params => { WORKFLOW => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, ID => { type => SCALAR, regex => $re_integer_string, optional => 1, }, ACTIVITY => { type => SCALAR, regex => $re_alpha_string, }, PARAMS => { type => HASHREF, optional => 1, }, }, }, 'create_workflow_instance' => { class => 'Workflow', params => { WORKFLOW => { type => SCALAR, regex => $re_alpha_string, }, FILTER_PARAMS => { type => SCALAR, regex => $re_alpha_string, default => 0, }, PARAMS => { type => HASHREF, optional => 1, }, }, }, 'get_workflow_activities' => { class => 'Workflow', params => { WORKFLOW => { type => SCALAR, regex => $re_alpha_string, }, ID => { type => SCALAR, regex => $re_integer_string, }, }, }, 'get_workflow_activities_params' => { class => 'Workflow', params => { WORKFLOW => { type => SCALAR, regex => $re_alpha_string, }, ID => { type => SCALAR, regex => $re_integer_string, }, }, }, 'search_workflow_instances' => { class => 'Workflow', params => { CONTEXT => { type => ARRAYREF | UNDEF, optional => 1, }, TYPE => { type => SCALAR | ARRAYREF, # regex => $re_alpha_string, # parameter content is checked in the method itself # because we can't check the array ref entries here optional => 1, }, STATE => { type => SCALAR | ARRAYREF, # regex => $re_alpha_string, # parameter content is checked in the method itself # because we can't check the array ref entries here optional => 1, }, LIMIT => { type => SCALAR, regex => $re_integer_string, optional => 1, }, START => { type => SCALAR, regex => $re_integer_string, optional => 1, }, }, }, 'search_workflow_instances_count' => { class => 'Workflow', params => { CONTEXT => { type => ARRAYREF | UNDEF, optional => 1, }, TYPE => { type => SCALAR | ARRAYREF, # regex => $re_alpha_string, # parameter content is checked in the method itself # because we can't check the array ref entries here optional => 1, }, STATE => { type => SCALAR | ARRAYREF, # regex => $re_alpha_string, # parameter content is checked in the method itself # because we can't check the array ref entries here optional => 1, }, }, }, 'get_secrets' => { class => 'Secret', params => { }, memoize => 1, }, 'is_secret_complete' => { class => 'Secret', params => { SECRET => { type => SCALAR, regex => $re_alpha_string } } }, 'set_secret_part' => { class => 'Secret', params => { SECRET => { type => SCALAR, regex => $re_alpha_string }, PART => { type => SCALAR, optional => 1, regex => $re_integer_string }, VALUE => { type => SCALAR, regex => $re_all } } }, 'clear_secret' => { class => 'Secret', params => { SECRET => { type => SCALAR, regex => $re_alpha_string }, }, }, ### Smartcard API 'sc_analyze_certificate' => { class => 'Smartcard', params => { 'DATA' => { type => SCALAR, regex => $re_cert_string, }, 'CERTFORMAT' => { type => SCALAR, regex => $re_cert_string, }, 'DONTPARSE' => { type => SCALAR, regex => $re_integer_string, }, }, }, 'sc_parse_certificates' => { class => 'Smartcard', params => { 'CERTS' => { type => ARRAYREF, #regex => qr{ \A [A-Za-z0-9\+/=_\-\ \n]+ \z }xms;, }, 'CERTFORMAT' => { type => SCALAR, regex => $re_cert_string, optional => 1, }, }, }, 'sc_analyze_smartcard' => { class => 'Smartcard', params => { 'CERTS' => { type => ARRAYREF, #regex => $re_cert_string, }, 'CERTFORMAT' => { type => SCALAR, regex => $re_cert_string, optional => 1, }, 'SMARTCARDID' => { type => SCALAR, regex => $re_alpha_string, }, 'SMARTCHIPID' => { type => SCALAR, regex => $re_alpha_string, optional => 1, }, 'USERID' => { type => SCALAR, regex => $re_sql_string, optional => 1, }, 'WORKFLOW_TYPES' => { type => ARRAYREF, optional => 1, }, }, }, }; } sub AUTOMETHOD { my ($self, $ident, @args) = @_; my $method_name = $_; ##! 16: 'method name: ' . $method_name return sub { if (!exists $method_info_of{$ident}->{$method_name}) { ##! 16: 'exception' OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVER_API_INVALID_METHOD_CALLED', params => { 'METHOD_NAME' => $method_name, }, log => { logger => CTX('log'), priority => 'info', facility => 'system', }, ); } my $class = $method_info_of{$ident}->{$method_name}->{class}; my $valid_params = $method_info_of{$ident}->{$method_name}->{params}; ##! 16: 'args: ' . Dumper(\@args) # do parameter checking $current_method = $method_name; if (scalar @args > 1 || defined $args[0]) { validate( @args, $valid_params, ); } # ACL checking - FIXME - ACL - need implementation if (0 && $external_of{$ident}) { # do ACL checking my $affected_role = $method_info_of{$ident}->{$method_name}->{affected_role}; my $acl_hashref = { ACTIVITY => "API::" . $class . "::" . $method_name, }; if (defined $affected_role) { # FIXME: optional for now, as we don't have a good way to # figure out which role is affected by a certain API call $acl_hashref->{AFFECTED_ROLE} = $affected_role; } eval { #FIXME - ACL checking is disabled #CTX('acl')->authorize($acl_hashref); # logging is done in ACL class }; if (my $exc = OpenXPKI::Exception->caught()) { OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVER_API_ACL_CHECK_FAILED', params => { 'EXCEPTION' => $exc->message(), 'PARAMS' => $exc->params(), }, ); } elsif ($EVAL_ERROR) { OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVER_API_ACL_CHECK_FAILED', params => { 'EVAL_ERROR' => $EVAL_ERROR, }, log => { logger => CTX('log'), priority => 'error', facility => [ 'system', 'audit' ] }, ); } } CTX('log')->log( MESSAGE => "Method '$method_name' called via API", PRIORITY => 'debug', FACILITY => 'system', ); my $memoization_key; if (exists $method_info_of{$ident}->{$method_name}->{memoize} && $method_info_of{$ident}->{$method_name}->{memoize}) { ##! 128: 'method ' . $method_name . ' may be memoized' $memoization_key = ''; foreach my $key (keys %{ $args[0] }) { $memoization_key .= $key . '=' . $args[0]->{$key}; } ##! 128: 'args: ' . Dumper \@args if ($memoization_key eq '') { # special key is needed if no arguments are passed $memoization_key = 'no_args'; } ##! 128: 'memoization key: ' . $memoization_key if (exists $memoization_of{$ident}->{$method_name}->{$memoization_key}) { ##! 128: 'cache hit for method ' . $method_name . ' / memo key: ' . $memoization_key return $memoization_of{$ident}->{$method_name}->{$memoization_key}; } } ##! 128: 'cache miss for method ' . $method_name . ' / memo key: ' . $memoization_key # call corresponding method my $openxpki_class = "OpenXPKI::Server::API::" . $class; ##! 64: 'Calling ' . $openxpki_class . '->' . $method_name my $t0 = Benchmark->new(); my $result = $openxpki_class->$method_name(@args); my $t1 = Benchmark->new(); ##! 64: 'The call of ' . $openxpki_class . '->' . $method_name . ' took ' . timestr(timediff($t1, $t0)) if (defined $memoization_key) { # if a memoization key is defined, we want to memoize the result return $memoization_of{$ident}->{$method_name}->{$memoization_key} = $result; } return $result; }; } ########################################################################### 1; __END__ =head1 Name OpenXPKI::Server::API =head1 Description This is the interface which should be used by all user interfaces of OpenXPKI. A user interface MUST NOT access the server directly. The only allowed access is via this API. Any function which is not available in this API is not for public use. The API gets access to the server via the 'server' context object. This object must be set before instantiating the API. =head1 Functions =head2 new Default constructor created by Class::Std. The named parameter EXTERNAL should be set to 1 if the API is used from an external source (e.g. within a service). If EXTERNAL is set, in addition to the parameter checks, ACL checks are enabled. =head2 AUTOMETHOD This method is used by Class::Std when a method is called that is undefined in the current class. In our case, this method does the parameter checking for the requested method. If the class has been instantiated with the EXTERNAL parameter, ACL checks are done in addition. Then the class name is constructed from the $method_info hash reference and the corresponding method is called with the given parameters.
durko/openxpki
core/server/OpenXPKI/Server/API.pm
Perl
apache-2.0
46,258
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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. # package cloud::nutanix::snmp::mode::listhypervisors; use base qw(centreon::plugins::mode); use strict; use warnings; use centreon::plugins::misc; my $oid_hypervisorName = '.1.3.6.1.4.1.41263.9.1.3'; sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { 'filter-name:s' => { name => 'filter_name' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } sub manage_selection { my ($self, %options) = @_; my $snmp_result = $self->{snmp}->get_table(oid => $oid_hypervisorName, nothing_quit => 1); $self->{hypervisor} = {}; foreach my $oid (keys %{$snmp_result}) { $snmp_result->{$oid} = centreon::plugins::misc::trim($snmp_result->{$oid}); if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' && $snmp_result->{$oid} !~ /$self->{option_results}->{filter_name}/) { $self->{output}->output_add(long_msg => "skipping hypervisor '" . $snmp_result->{$oid} . "'.", debug => 1); next; } $self->{hypervisor}->{$snmp_result->{$oid}} = { name => $snmp_result->{$oid} }; } } sub run { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; $self->manage_selection(); foreach my $name (sort keys %{$self->{hypervisor}}) { $self->{output}->output_add(long_msg => "'" . $name . "'"); } $self->{output}->output_add(severity => 'OK', short_msg => 'List Hypervisors:'); $self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1); $self->{output}->exit(); } sub disco_format { my ($self, %options) = @_; $self->{output}->add_disco_format(elements => ['name']); } sub disco_show { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; $self->manage_selection(); foreach my $name (sort keys %{$self->{hypervisor}}) { $self->{output}->add_disco_entry(name => $name); } } 1; __END__ =head1 MODE List hypervisors. =over 8 =item B<--filter-name> Filter by hypervisor name. =back =cut
centreon/centreon-plugins
cloud/nutanix/snmp/mode/listhypervisors.pm
Perl
apache-2.0
3,055
package Paws::StorageGateway::VTLDevice; use Moose; has DeviceiSCSIAttributes => (is => 'ro', isa => 'Paws::StorageGateway::DeviceiSCSIAttributes'); has VTLDeviceARN => (is => 'ro', isa => 'Str'); has VTLDeviceProductIdentifier => (is => 'ro', isa => 'Str'); has VTLDeviceType => (is => 'ro', isa => 'Str'); has VTLDeviceVendor => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::StorageGateway::VTLDevice =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::StorageGateway::VTLDevice object: $service_obj->Method(Att1 => { DeviceiSCSIAttributes => $value, ..., VTLDeviceVendor => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::StorageGateway::VTLDevice object: $result = $service_obj->Method(...); $result->Att1->DeviceiSCSIAttributes =head1 DESCRIPTION Represents a device object associated with a tape gateway. =head1 ATTRIBUTES =head2 DeviceiSCSIAttributes => L<Paws::StorageGateway::DeviceiSCSIAttributes> A list of iSCSI information about a VTL device. =head2 VTLDeviceARN => Str Specifies the unique Amazon Resource Name (ARN) of the device (tape drive or media changer). =head2 VTLDeviceProductIdentifier => Str =head2 VTLDeviceType => Str =head2 VTLDeviceVendor => Str =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::StorageGateway> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/StorageGateway/VTLDevice.pm
Perl
apache-2.0
1,924
# # Copyright 2015 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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. # package snmp_standard::mode::numericvalue; use base qw(centreon::plugins::mode); use strict; use warnings; use centreon::plugins::statefile; use Digest::MD5 qw(md5_hex); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; $options{options}->add_options(arguments => { "oid:s" => { name => 'oid' }, "oid-type:s" => { name => 'oid_type', default => 'gauge' }, "counter-per-seconds" => { name => 'counter_per_seconds' }, "warning:s" => { name => 'warning' }, "critical:s" => { name => 'critical' }, "format:s" => { name => 'format', default => 'current value is %s' }, "format-scale" => { name => 'format_scale' }, "format-scale-unit:s" => { name => 'format_scale_unit', default => 'other'}, "perfdata-unit:s" => { name => 'perfdata_unit', default => ''}, "perfdata-name:s" => { name => 'perfdata_name', default => 'value'}, "perfdata-min:s" => { name => 'perfdata_min', default => ''}, "perfdata-max:s" => { name => 'perfdata_max', default => ''}, }); $self->{statefile_cache} = centreon::plugins::statefile->new(%options); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); if (!defined($self->{option_results}->{oid}) || $self->{option_results}->{oid} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify an OID."); $self->{output}->option_exit(); } $self->{option_results}->{oid} = '.' . $self->{option_results}->{oid} if ($self->{option_results}->{oid} !~ /^\./); if ($self->{option_results}->{oid_type} !~ /^gauge|counter$/i) { $self->{output}->add_option_msg(short_msg => "Wrong --oid-type argument '" . $self->{option_results}->{oid_type} . "' ('gauge' or 'counter')."); $self->{output}->option_exit(); } if ($self->{option_results}->{format_scale_unit} !~ /^other|network$/i) { $self->{output}->add_option_msg(short_msg => "Wrong --format-scale-unit argument '" . $self->{option_results}->{format_scale_unit} . "' ('other' or 'network')."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); $self->{output}->option_exit(); } if ($self->{option_results}->{oid_type} =~ /^counter$/i) { $self->{statefile_cache}->check_options(%options); } } sub run { my ($self, %options) = @_; # $options{snmp} = snmp object $self->{snmp} = $options{snmp}; $self->{hostname} = $self->{snmp}->get_hostname(); $self->{snmp_port} = $self->{snmp}->get_port(); my $result = $self->{snmp}->get_leef(oids => [$self->{option_results}->{oid}], nothing_quit => 1); my $value = $result->{$self->{option_results}->{oid}}; if ($self->{option_results}->{oid_type} =~ /^counter$/i) { my $datas = {}; $self->{statefile_cache}->read(statefile => "snmpstandard_" . $self->{hostname} . '_' . $self->{snmp_port} . '_' . $self->{mode} . '_' . md5_hex($self->{option_results}->{oid})); my $old_timestamp = $self->{statefile_cache}->get(name => 'timestamp'); my $old_value = $self->{statefile_cache}->get(name => 'value'); $datas->{timestamp} = time(); $datas->{value} = $value; $self->{statefile_cache}->write(data => $datas); if (!defined($old_timestamp)) { $self->{output}->output_add(severity => 'OK', short_msg => "Buffer creation..."); $self->{output}->display(); $self->{output}->exit(); } # Reboot or counter goes back if ($old_value > $value) { $old_value = 0; } $value = $value - $old_value; if (defined($self->{option_results}->{counter_per_seconds})) { my $delta_time = $datas->{timestamp} - $old_timestamp; $delta_time = 1 if ($delta_time == 0); # at least 1 sec $value = $value / $delta_time; } } my $exit = $self->{perfdata}->threshold_check(value => $value, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); if (defined($self->{option_results}->{format_scale})) { my ($value_mod, $value_unit) = $self->{perfdata}->change_bytes(value => $value); if ($self->{option_results}->{format_scale} =~ /^network$/i) { ($value_mod, $value_unit) = $self->{perfdata}->change_bytes(value => $value, network => 1); } $self->{output}->output_add(severity => $exit, short_msg => sprintf($self->{option_results}->{format}, $value_mod . $value_unit)); } else { $self->{output}->output_add(severity => $exit, short_msg => sprintf($self->{option_results}->{format}, $value)); } $self->{output}->perfdata_add(label => $self->{option_results}->{perfdata_name}, unit => $self->{option_results}->{perfdata_unit}, value => $value, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), min => $self->{option_results}->{perfdata_min}, max => $self->{option_results}->{perfdata_max}); $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check an SNMP numeric value: can be a Counter, Integer, Gauge, TimeTicks. Use 'stringvalue' mode if you want to check: - 'warning' value is 2, 4 and 5. - 'critical' value is 1. - 'ok' value is 10. =over 8 =item B<--oid> OID value to check (numeric format only). =item B<--warning> Threshold warning. =item B<--critical> Threshold critical. =item B<--oid-type> Type of the OID (Default: 'gauge'). Can be 'counter' also. 'counter' will use a retention file. =item B<--counter-per-seconds> Convert counter value on a value per seconds (only with type 'counter'. =item B<--format> Output format (Default: 'current value is %s') =item B<--format-scale> Scale bytes value. We'll display value in output. =item B<--format-scale-type> Could be 'network' (value divide by 1000) or 'other' (divide by 1024) (Default: 'other') Output format (Default: 'current value is %s') =item B<--perfdata-unit> Perfdata unit in perfdata output (Default: '') =item B<--perfdata-name> Perfdata name in perfdata output (Default: 'value') =item B<--perfdata-min> Minimum value to add in perfdata output (Default: '') =item B<--perfdata-max> Maximum value to add in perfdata output (Default: '') =back =cut
s-duret/centreon-plugins
snmp_standard/mode/numericvalue.pm
Perl
apache-2.0
8,640