content
stringlengths 0
894k
| type
stringclasses 2
values |
---|---|
import scapy.all as scapy
import time
from iemlav import logger
class SynFlood(object):
"""SynFlood Class."""
def __init__(self, debug=False):
"""
Initialize SynFlood.
Args:
debug (bool): Log on terminal or not
Raises:
None
Returns:
None
"""
# Initialize logger
self.logger = logger.IemlAVLogger(
__name__,
debug=debug
)
# Initialize SYN dictionary
self.syn_dict = dict()
# Set threshold to 1000 SYN packets / per second
self._THRESHOLD = 1000 # inter = 0.001
def detect_syn_flood(self, pkt):
"""
Detect SYN flood attack.
Args:
pkt (scapy_object): Packet to dissect and observe
Raises:
None
Returns:
None
"""
if (pkt.haslayer(scapy.IP) and
pkt.haslayer(scapy.TCP)):
flag = pkt[scapy.TCP].flags
source_ip = pkt[scapy.IP].src
if flag == "S": # SYN flag
if self.syn_dict.get(source_ip) is None:
# If new IP address
self.syn_dict[source_ip] = {
"start_time": time.time(),
"count": 1
}
else:
count = self.syn_dict[source_ip]["count"]
self.syn_dict[source_ip]["count"] = count + 1
if flag == "A": # ACK flag
if self.syn_dict.get(source_ip) is not None:
# Handshake completed, delete the IP entry (not suspicious)
del self.syn_dict[source_ip]
# Detect intrusion
self.calc_intrusion()
def calc_intrusion(self):
"""
Detect intrusion by comparing threshold
ratios.
Args:
None
Raises:
None
Returns:
None
"""
if len(self.syn_dict) != 0: # If syn dict is not empty
start_ip = [ip for ip in self.syn_dict.keys()][0]
start_time = self.syn_dict[start_ip]["start_time"]
current_time = time.time()
delta_time = int(current_time - start_time)
size_of_syn_dict = len(self.syn_dict)
try:
calc_threshold = int(size_of_syn_dict / delta_time)
except ZeroDivisionError:
calc_threshold = int(size_of_syn_dict)
if (calc_threshold >= self._THRESHOLD):
self.logger.log(
"Possible SYN flood attack detected.",
logtype="warning"
)
|
python
|
# -*- coding: utf8 -*-
# test encoding: à-é-è-ô-ï-€
# Copyright 2021 Adrien Crovato
#
# 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.
## Physical flux
# Adrien Crovato
# Base class
class PFlux:
def __init__(self):
pass
def __str__(self):
raise RuntimeError('Physical flux not implemented!')
# Advection
class Advection(PFlux):
'''Advection flux
'''
def __init__(self, a):
PFlux.__init__(self)
self.a = a # advection (transport) velocity
def __str__(self):
return 'Advection flux (a = ' + str(self.a) + ')'
def eval(self, u):
'''Compute the physical flux vector
f = a*u
'''
return [self.a * u[0]]
def evald(self, u):
'''Compute the physical flux derivative matrix
df = a
'''
return [[self.a]]
class Advection2(PFlux):
'''Advection flux
'''
def __init__(self, a, b):
PFlux.__init__(self)
self.a = a # first advection (transport) velocity
self.b = b # second advection (transport) velocity
def __str__(self):
return 'Advection flux (a = ' + str(self.a) + ', b = ' + str(self.b) + ')'
def eval(self, u):
'''Compute the physical flux vector
f = [a*u, b*v]
'''
f = [0.] * len(u)
f[0] = self.a * u[0]
f[1] = self.b * u[1]
return f
def evald(self, u):
'''Compute the physical flux derivative matrix
df = [a, 0;
0, b]
'''
df = [[0.] * len(u) for _ in range(len(u))]
df[0][0] = self.a
df[1][1] = self.b
return df
# Burger's
class Burger(PFlux):
'''Burger's flux
'''
def __init__(self):
PFlux.__init__(self)
def __str__(self):
return 'Burger\'s flux'
def eval(self, u):
'''Compute the physical flux vector
f = u*u/2
'''
return [0.5 * u[0] * u[0]]
def evald(self, u):
'''Compute the physical flux derivative matrix
df = u
'''
return [[u[0]]]
# Euler
class Euler(PFlux):
'''Euler flux
'''
def __init__(self, gamma):
PFlux.__init__(self)
self.gamma = gamma # heat capacity ratio
def __str__(self):
return 'Euler flux (gamma = ' + str(self.gamma) + ')'
def eval(self, u):
'''Compute the physical flux vector
f = [rho*u, rho*u^2+p, (E+p)*u]
'''
# Pre-pro
v = u[1] / u[0] # u = rho * u / rho
p = (self.gamma - 1) * (u[2] - 0.5 * u[1] * v) # (gamma - 1) * (E - 0.5 * rho*u*u)
# Flux
f = [0.] * len(u)
f[0] = u[1]
f[1] = u[1] * v + p
f[2] = (u[2] + p) * v
return f
def evald(self, u):
'''Compute the physical flux derivative matrix
df = [0, 1, 0;
(gamma-3)/2*u^2, (3-gamma)*u, gamma-1;
-gamma*E*u/rho + (gamma-1)*u^3, gamma*E/rho + 3*(1-gamma)/2*u^2, gamma*u]
'''
# Pre-pro
v = u[1] / u[0] # = rho * u / rho
e = u[2] / u[0] # = E / rho
# Flux
df = [[0.] * len(u) for _ in range(len(u))]
df[0][1] = 1.
df[1][0] = 0.5 * (self.gamma - 3) * v * v
df[1][1] = (3 - self.gamma) * v
df[1][2] = self.gamma - 1
df[2][0] = -self.gamma * e * v + (self.gamma - 1) * v * v * v
df[2][1] = self.gamma * e + 1.5 * (1 - self.gamma) * v * v
df[2][2] = self.gamma * v
return df
class ShallowWater(PFlux):
'''Shallow water flux
'''
def __init__(self, g):
PFlux.__init__(self)
self.g = g # acceleration due to gravity
def __str__(self):
return 'Shallow water flux (g = ' + str(self.g) + ')'
def eval(self, u):
'''Compute the physical flux vector
f = [h*u, gh + u^2/2]
'''
f = [0.] * len(u)
f[0] = u[0] * u[1]
f[1] = self.g * u[0] + 0.5 * u[1] * u[1]
return f
def evald(self, u):
'''Compute the physical flux derivative matrix
df = [u, h;
g, u]
'''
df = [[0.] * len(u) for _ in range(len(u))]
df[0][0] = u[1]
df[0][1] = u[0]
df[1][0] = self.g
df[1][1] = u[1]
return df
|
python
|
# name: person_builder.py
# version: 0.0.1
# date: 20211225
# author: Leam Hall
# desc: Build a person.
from person import Person
class PersonBuilder:
def set_data(self, person, data = {}):
person.idx = data.get('idx', -1)
person.gender = data.get('gender', '')
person.first_name = data.get('first_name', '')
person.last_name = data.get('last_name', '')
person.birthdate = data.get('birthdate', 0)
person.notes = data.get('notes', '')
return person
def gen_data(self, person, data = {}):
person.gender = data.get('gender', self.gen_gender())
person.first_name = data.get('first_name', self.gen_firstname(person.gender))
person.last_name = data.get('last_name', self.gen_lastname())
person.birthdate = data.get('birthdate', self.gen_birthdate())
person.notes = data.get('notes', '')
return person
def gen_firstname(self, gender):
return 'John'
def gen_lastname(self):
return 'Dough'
def gen_birthdate(self):
return 1234056
def gen_gender(self):
return 'm'
def return_person(self):
return self.person
|
python
|
import rasterio
from sklearn.cluster import AgglomerativeClustering
from shapely.geometry import Polygon
from shapely.ops import nearest_points
from math import sqrt
from gisele import initialization
from shapely import geometry
from gisele.functions import *
from math import *
#from gisele import LV_routing_new_strategy as new_strategy
def points_region_to_casestudy(points_region, polygon_casestudy):
points_CaseStudy = points_region.clip(polygon_casestudy)
return points_CaseStudy
def create_polygon_from_clusters(final_clus, clusters_file, substations_file, resolution, crs):
Clusters = gpd.read_file(clusters_file)
Substations = gpd.read_file(substations_file)
Clusters = Clusters[Clusters['final_clus'] == final_clus]
k = 0
for index, row in Clusters.iterrows():
area = row['geometry']
minx = area.bounds[0]
miny = area.bounds[1]
maxx = area.bounds[2]
maxy = area.bounds[3]
if k == 0:
min_x = minx
min_y = miny
max_x = maxx
max_y = maxy
k = 1
else:
if minx < min_x:
min_x = minx
if miny < min_y:
min_y = miny
if maxx > max_x:
max_x = maxx
if maxy > max_y:
max_y = maxy
for index, row in Substations.iterrows():
substation = row['geometry']
if substation.x < min_x:
min_x = substation.x
if substation.y < min_y:
min_y = substation.y
if substation.x > max_x:
max_x = substation.x
if substation.y > max_y:
max_y = substation.y
study_area = Polygon([Point(min_x, min_y), Point(min_x, max_y), Point(max_x, max_y), Point(max_x, min_y)])
study_area_buffered = study_area.buffer(4 * resolution)
polygon = gpd.GeoDataFrame({'ID': [0], 'geometry': study_area_buffered})
polygon.crs = crs
polygon.to_file('area_polygon', index=False)
return polygon # geodataframe with the polygon
''' The goal of this function is to create a polygon starting from a cluster of clusters'''
def create_grid(crs, resolution, study_area):
# crs and resolution should be a numbers, while the study area is a polygon
df = pd.DataFrame(columns=['X', 'Y'])
min_x, min_y, max_x, max_y = study_area.bounds
# create one-dimensional arrays for x and y
lon = np.arange(min_x, max_x, resolution)
lat = np.arange(min_y, max_y, resolution)
lon, lat = np.meshgrid(lon, lat)
df['X'] = lon.reshape((np.prod(lon.shape),))
df['Y'] = lat.reshape((np.prod(lat.shape),))
geo_df = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.X, df.Y),
crs=crs)
geo_df_clipped = gpd.clip(geo_df, study_area)
# geo_df_clipped.to_file(r'Test\grid_of_points.shp')
return geo_df_clipped
def street_to_points(streets):
streets_points = []
for line in streets['geometry']:
# print(line.geometryType)
if line.geometryType() == 'MultiLineString':
for line1 in line:
for x in list(zip(line1.xy[0], line1.xy[1])):
# print(line1)
streets_points.append(x)
else:
for x in list(zip(line.xy[0], line.xy[1])):
# print(line)
streets_points.append(x)
streets_multipoint = MultiPoint(streets_points)
return streets_multipoint
def coincidence_factor(population, pop_per_household):
return 0.35 + 0.65 / sqrt(population / pop_per_household)
def categorize_substation(clusters_list, substations):
values = []
costs = []
substations['Rated_power [kVA]'] = substations['Rated_power [kVA]']
substations1 = substations['Rated_power [kVA]'].to_list()
for index, row in clusters_list.iterrows():
load_kVA = row.loc['Load [kW]'] / 0.9 # considering a power factor of 0.9
substations2 = [i - load_kVA if i - load_kVA > 0 else 10000 for i in substations1]
power = int(min(substations2) + load_kVA)
values.append(power)
locate_cost = substations[substations['Rated_power [kVA]'] == power]['Cost[euro]']
costs.append(locate_cost.values[0])
clusters_list['Transformer_rated_power [kVA]'] = values
clusters_list['Cost[euro]'] = costs
return clusters_list
def locate_secondary_ss(crs, resolution, load_capita, pop_per_household, road_coef,
Clusters, case_study, LV_distance, ss_data,landcover_option,gisele_dir):
dir_input = r'Case studies/' + case_study + '/Input'
dir_output = '/Case studies/' + case_study
grid_500m_weighted = pd.read_csv(dir_input + '/weighted_grid_of_points.csv')
grid_500m_with_ss = grid_500m_weighted.copy()
grid_500m_gdf = gpd.GeoDataFrame(grid_500m_weighted,
geometry=gpd.points_from_xy(grid_500m_weighted.X, grid_500m_weighted.Y), crs=crs)
grid_500m_with_ss = gpd.GeoDataFrame(grid_500m_with_ss,
geometry=gpd.points_from_xy(grid_500m_with_ss.X, grid_500m_with_ss.Y), crs=crs)
# Create a clusters.exe file
LV_resume = pd.DataFrame()
for index, row in Clusters.iterrows():
os.chdir(gisele_dir)
dir = gisele_dir + dir_output + '/Output/Clusters/' + str(row['cluster_ID'])
clus = row['cluster_ID']
if not os.path.exists(dir):
os.makedirs(dir)
os.makedirs(dir + '/grids')
area = row['geometry']
# THIS IS SPECIFIC FOR THE CASE OF THUSO - ISSUE NEEDS TO BE FIXED WITH CLUSTERS THAT ARE TOO NARROW. If in one line
# of the grid points there are no points -> the graph for the steiner tree will not be connected
area_buffered = area
# area_buffered = row['geometry'].buffer((resolution_MV * 0.1 / 11250) / 2)
area_list = [area_buffered]
# Create grid of points with a 30m resolution
grid_of_points = create_grid(crs, resolution, area)
grid_of_points.to_file(dir + '/points.shp')
# Load and clip protected araes and streets
# protected_areas = gpd.read_file(global_dir+db_dir+case_study+'/Protected_areas/Protected_area-Uganda.shp')
# protected_areas = protected_areas.to_crs(crs)
# protected_areas_clipped=gpd.clip(protected_areas,area)
# protected_areas_clipped.to_file(dir + '/protected.shp)
# To make sure the roads are not cut
min_x, min_y, max_x, max_y = area.bounds
area_for_roads = geometry.Polygon(
[geometry.Point(min_x, min_y), geometry.Point(min_x, max_y), geometry.Point(max_x, max_y),
geometry.Point(max_x, min_y)])
streets = gpd.read_file(dir_input + '/Roads.shp')
streets = streets.to_crs(crs)
streets_clipped = gpd.clip(streets, area_for_roads)
if not streets_clipped.empty:
streets_clipped.to_file(dir + '/Roads.shp')
Street_Multipoint = street_to_points(streets_clipped)
# OPEN THE RASTERS FOR THE SPECIFIC REGION WHERE OUR CLUSTER IS
Population = rasterio.open(dir_input + '/Population_' + str(crs) + '.tif')
Elevation = rasterio.open(dir_input + '/Elevation_' + str(crs) + '.tif')
Slope = rasterio.open(dir_input + '/Slope_' + str(crs) + '.tif')
LandCover = rasterio.open(dir_input + '/LandCover_' + str(crs) + '.tif')
# POPULATE THE GRID OF POINTS
coords = [(x, y) for x, y in zip(grid_of_points.X, grid_of_points.Y)]
grid_of_points = grid_of_points.reset_index(drop=True)
grid_of_points['ID'] = grid_of_points.index
grid_of_points['Population'] = [x[0] for x in Population.sample(coords)]
grid_of_points['Elevation'] = [x[0] for x in Elevation.sample(coords)]
grid_of_points['Slope'] = [x[0] for x in Slope.sample(coords)]
grid_of_points['Land_cover'] = [x[0] for x in LandCover.sample(coords)]
# THIS IS JUST A PROXY, NEEDS TO BE PROPERLY SET
grid_of_points['Protected_area'] = ['FALSE' for x in LandCover.sample(coords)]
print('Sampling rasters finished')
grid_of_points.to_file(dir + '/points.shp')
# AGLOMERATIVE CLUSTERING
scale_factor = 10
populated_grid = grid_of_points[grid_of_points['Population'] > 0]
populated_grid['Population'] = populated_grid['Population'].div(scale_factor).round(0) + 0.51
populated_grid['Population'] = populated_grid['Population'].round(0)
populated_grid = populated_grid.loc[populated_grid.index.repeat(populated_grid.Population.astype(int))]
loc = {'x': populated_grid['X'], 'y': populated_grid['Y']}
pop_points = pd.DataFrame(data=loc).values
clustering = AgglomerativeClustering(distance_threshold=LV_distance * 1.8, linkage='complete',
n_clusters=None).fit(pop_points)
geo_df_clustered = gpd.GeoDataFrame(data=pop_points, columns=['X', 'Y'],
geometry=gpd.points_from_xy(populated_grid['X'], populated_grid['Y']))
geo_df_clustered['Cluster'] = clustering.labels_
geo_df_clustered = geo_df_clustered.drop_duplicates()
geo_df_clustered.set_crs(epsg=crs, inplace=True)
geo_df_clustered.to_file(dir + '/pointsCluster.shp')
# number_clusters=max(geo_df_clustered.Cluster)
# calculate the total distances from one point to another inside the clusters
for cluster in range(max(geo_df_clustered['Cluster']) + 1):
total_distances = []
geo_df_clustered_slice = geo_df_clustered[geo_df_clustered['Cluster'] == cluster]
print(cluster)
for index, row2 in geo_df_clustered_slice.iterrows():
tot_dist = 0
for index1, row1 in geo_df_clustered_slice.iterrows():
tot_dist += sqrt((row2.X - row1.X) ** 2 + (row2.Y - row1.Y) ** 2)
total_distances.append(tot_dist)
geo_df_clustered.loc[geo_df_clustered['Cluster'] == cluster, 'tot_distance'] = total_distances
joinDF = gpd.sjoin(grid_of_points, geo_df_clustered, how='left', op="contains")
grid_of_points['Cluster'] = joinDF['Cluster']
grid_of_points['Cluster'] = grid_of_points['Cluster'].fillna(-1)
grid_of_points['tot_distance'] = joinDF['tot_distance']
# ASSIGN ROAD DISTANCE
if not streets_clipped.empty:
road_distances = []
for index, point in grid_of_points.iterrows():
x = point['geometry'].xy[0][0]
y = point['geometry'].xy[1][0]
nearest_geoms = nearest_points(Point(x, y), Street_Multipoint)
road_distance = nearest_geoms[0].distance(nearest_geoms[1])
road_distances.append(road_distance)
grid_of_points['Road_dist'] = road_distances
# CHOOSE A SUBSTATION
number_clusters = max(grid_of_points.Cluster)
substations = []
# Create a clusters.exe file
clusters_list = pd.DataFrame(columns=['Cluster','Sub_cluster', 'Population', 'Load [kW]'])
# ASSIGN MV POWER FOR THE SECONDARY SUBSTATIONS
grid_of_points['MV_Power'] = 0
for i in range(int(number_clusters) + 1):
subset = grid_of_points[grid_of_points['Cluster'] == i]
sum_pop = subset['Population'].sum()
load = sum_pop * load_capita * coincidence_factor(sum_pop, pop_per_household)
data = np.array([[int(row['cluster_ID']),int(i), sum_pop, load]])
df2 = pd.DataFrame(data, columns=['Cluster','Sub_cluster', 'Population', 'Load [kW]'])
clusters_list = clusters_list.append(df2)
average_distance = subset['tot_distance'] / len(subset)
min_weight = 100000
ID = 0
for index, ROW in subset.iterrows():
if not streets_clipped.empty:
weight = ROW['Road_dist'] * road_coef + average_distance[index]
else:
weight = average_distance[index]
if weight < min_weight:
min_weight = weight
ID = index
substations.append(ID)
grid_of_points['Substation'] = 0
for substation in substations:
grid_of_points.loc[grid_of_points['ID'] == substation, 'Substation'] = 1
for i in range(int(number_clusters) + 1):
population = clusters_list.loc[clusters_list['Sub_cluster'] == i, 'Population'][0]
load = clusters_list.loc[clusters_list['Sub_cluster'] == i, 'Load [kW]'][0]
grid_of_points.loc[
(grid_of_points['Substation'] == 1) & (grid_of_points['Cluster'] == i), 'Population'] = population
grid_of_points.loc[
(grid_of_points['Substation'] == 1) & (grid_of_points['Cluster'] == i), 'MV_Power'] = load
substation_data = pd.read_csv(gisele_dir + '/general_input/' + ss_data)
clusters_list = categorize_substation(clusters_list, substation_data)
clusters_list['Population']=[ceil(i) for i in clusters_list['Population']]
clusters_list.to_csv(dir + '/clusters_list.csv',index=False)
LV_resume=LV_resume.append(clusters_list)
weights_grid = initialization.weighting(grid_of_points,resolution,landcover_option)
grid_of_points['Weight'] = weights_grid['Weight']
grid_of_points.crs = crs
grid_of_points.to_csv(dir + '/Input.csv')
grid_of_points.to_file(dir + '/points.shp')
secondary_substations = grid_of_points[grid_of_points['Substation'] == 1]
secondary_substations.to_file(dir + '/substations.shp')
total_costs = sum(clusters_list['Cost[euro]'].to_list())
print('The total costs for substations are ' + str(total_costs / 1000) + ' thousand euros')
# cluster_polygons_gpd.to_file(dir + '/clusters_polygons.shp')
print('The maximum loading of a cluster is ' + str(max(clusters_list['Load [kW]'])))
print('The minimum loading of a cluster is ' + str(min(clusters_list['Load [kW]'])))
# study_area = Clusters.loc[row['cluster_ID']]['geometry']
study_area = area_buffered
area = study_area
area.crs = crs
grid_500m_clip = gpd.clip(grid_500m_gdf, area) # this is our 500m resolution grid of points
substations = grid_of_points[grid_of_points['Substation'] == 1]
number_substations = substations.shape[0]
ss_starting_id = int(grid_500m_with_ss['ID'].max()) + 1
substations['ID'] = [i for i in range(ss_starting_id, ss_starting_id + number_substations)]
# ss_starting_id+=number_substations
substations.to_file(dir + '/substations.shp')
substations['Cluster'] = clus
substations_weighted = initialization.weighting(substations, resolution, landcover_option)
substations['Weight'] = substations_weighted['Weight']
grid_500m_clip = grid_500m_clip.append(substations)
grid_500m_with_ss = grid_500m_with_ss.append(substations)
#geo_df = initialization.weighting(grid_500m_clip, resolution_MV, landcover_option)
grid_500m_clip.to_file(dir + '/points500m.shp')
# geo_df['Substation'] = grid_500m_clip['Substation']
# geo_df['geometry'] = grid_500m_clip['geometry']
clus += 1
grid_500m_with_ss.to_csv(gisele_dir + '/' + dir_input + '/weighted_grid_of_points_with_ss.csv')
LV_resume.to_csv(gisele_dir + '/' + dir_input +'/LV_resume.csv')
|
python
|
from typing import Any, Dict, Optional, Union
import httpx
from ...client import AuthenticatedClient
from ...models.osidb_api_v1_schema_retrieve_format import OsidbApiV1SchemaRetrieveFormat
from ...models.osidb_api_v1_schema_retrieve_lang import OsidbApiV1SchemaRetrieveLang
from ...models.osidb_api_v1_schema_retrieve_response_200 import OsidbApiV1SchemaRetrieveResponse200
from ...types import UNSET, Response, Unset
def _get_kwargs(
*,
client: AuthenticatedClient,
format_: Union[Unset, None, OsidbApiV1SchemaRetrieveFormat] = UNSET,
lang: Union[Unset, None, OsidbApiV1SchemaRetrieveLang] = UNSET,
) -> Dict[str, Any]:
url = "{}/osidb/api/v1/schema/".format(
client.base_url,
)
headers: Dict[str, Any] = client.get_headers()
json_format_: Union[Unset, None, str] = UNSET
if not isinstance(format_, Unset):
json_format_ = OsidbApiV1SchemaRetrieveFormat(format_).value if format_ else None
json_lang: Union[Unset, None, str] = UNSET
if not isinstance(lang, Unset):
json_lang = OsidbApiV1SchemaRetrieveLang(lang).value if lang else None
params: Dict[str, Any] = {
"format": json_format_,
"lang": json_lang,
}
params = {k: v for k, v in params.items() if v is not UNSET and v is not None}
return {
"url": url,
"headers": headers,
"params": params,
}
def _parse_response(*, response: httpx.Response) -> Optional[OsidbApiV1SchemaRetrieveResponse200]:
if response.status_code == 200:
_response_200 = response.json()
response_200: OsidbApiV1SchemaRetrieveResponse200
if isinstance(_response_200, Unset):
response_200 = UNSET
else:
response_200 = OsidbApiV1SchemaRetrieveResponse200.from_dict(_response_200)
return response_200
return None
def _build_response(*, response: httpx.Response) -> Response[OsidbApiV1SchemaRetrieveResponse200]:
return Response(
status_code=response.status_code,
content=response.content,
headers=response.headers,
parsed=_parse_response(response=response),
)
def sync_detailed(
*,
client: AuthenticatedClient,
format_: Union[Unset, None, OsidbApiV1SchemaRetrieveFormat] = UNSET,
lang: Union[Unset, None, OsidbApiV1SchemaRetrieveLang] = UNSET,
) -> Response[OsidbApiV1SchemaRetrieveResponse200]:
kwargs = _get_kwargs(
client=client,
format_=format_,
lang=lang,
)
response = httpx.get(
verify=client.verify_ssl,
auth=client.auth,
timeout=client.timeout,
**kwargs,
)
response.raise_for_status()
return _build_response(response=response)
def sync(
*,
client: AuthenticatedClient,
format_: Union[Unset, None, OsidbApiV1SchemaRetrieveFormat] = UNSET,
lang: Union[Unset, None, OsidbApiV1SchemaRetrieveLang] = UNSET,
) -> Optional[OsidbApiV1SchemaRetrieveResponse200]:
"""OpenApi3 schema for this API. Format can be selected via content negotiation.
- YAML: application/vnd.oai.openapi
- JSON: application/vnd.oai.openapi+json"""
return sync_detailed(
client=client,
format_=format_,
lang=lang,
).parsed
async def asyncio_detailed(
*,
client: AuthenticatedClient,
format_: Union[Unset, None, OsidbApiV1SchemaRetrieveFormat] = UNSET,
lang: Union[Unset, None, OsidbApiV1SchemaRetrieveLang] = UNSET,
) -> Response[OsidbApiV1SchemaRetrieveResponse200]:
kwargs = _get_kwargs(
client=client,
format_=format_,
lang=lang,
)
async with httpx.AsyncClient(verify=client.verify_ssl) as _client:
response = await _client.get(**kwargs)
return _build_response(response=response)
async def asyncio(
*,
client: AuthenticatedClient,
format_: Union[Unset, None, OsidbApiV1SchemaRetrieveFormat] = UNSET,
lang: Union[Unset, None, OsidbApiV1SchemaRetrieveLang] = UNSET,
) -> Optional[OsidbApiV1SchemaRetrieveResponse200]:
"""OpenApi3 schema for this API. Format can be selected via content negotiation.
- YAML: application/vnd.oai.openapi
- JSON: application/vnd.oai.openapi+json"""
return (
await asyncio_detailed(
client=client,
format_=format_,
lang=lang,
)
).parsed
|
python
|
def work_well():
print("ok")
return "ok"
def say_hello():
print("hello")
return "hello"
|
python
|
# uses minimax to look ahead
import sys
from functools import partial
from game import *
import interactive_game
def compute_score(board, res=TURN_OK):
score = board[0]**5 \
+ board[1]**4 + board[4]**4 \
+ board[2]**2 + board[5]**2 + board[8]**2 \
+ board[3] + board[6] + board[9] + board[12]
if res==TURN_GAME_OVER or res==TURN_ILLEGAL:
return -score
return score
def minimax(board, lm=None, depth=5):
if not lm:
lm = legal_moves(board)
if lm == []:
return (compute_score(board,TURN_ILLEGAL), -1)
best_move = None
for move in lm:
new_board, res = perform_turn(board.copy(), move, ins_random=False, skip_check=True)
score = compute_score(new_board)
if depth != 1:
new_board = insert_random(new_board)
next_score, next_move = minimax(new_board.copy(), depth=depth-1)
score += next_score
score_move = (score,move)
if best_move==None:
best_move = score_move
elif best_move<score_move:
best_move = score_move
return best_move
def ai_2_compute_func(board, lm, depth):
next_score, next_move = minimax(board, lm=lm, depth=depth)
return next_move
if __name__=="__main__":
if len(sys.argv)>=2:
depth = int(sys.argv[1])
else:
depth = 3
interactive_game.start(partial(ai_2_compute_func, depth=depth))
|
python
|
"""Module with function to regularize a 2D curve (with uniform resolution)."""
import math
import numpy
def _get_perimeter(x, y):
"""Return the perimeter of the geometry.
Parameters
----------
x : numpy.ndarray
x-coordinate of the points along the curve.
y : numpy.ndarray
y-coordinate of the points along the curve.
Returns
-------
perimeter : float
The perimeter.
"""
# Duplicate point if necessary to get a closed surface.
atol = 1e-6
if abs(x[0] - x[-1]) > atol or abs(y[0] - y[-1]) > atol:
x, y = numpy.append(x, x[0]), numpy.append(y, y[0])
return numpy.sum(numpy.sqrt((x[1:] - x[:-1])**2 + (y[1:] - y[:-1])**2))
def regularize2d(xo, yo, N=None, ds=None, atol=1.0E-06):
"""Regularize the geometry.
Parameters
----------
xo: numpy.ndarray of floats
The x-coordinates of the boundary to regularize.
yo: numpy.ndarray of floats
The y-coordinates of the boundary to regularize.
N: integer, optional
Number of divisions;
default: None.
ds: float, optional
Desired segment-length;
default: None.
atol: float, optional
Desired tolerance for discretization;
default: 1.0E-06.
Returns
-------
x: numpy.ndarray of floats
The x-coordinates of the regularized boundary.
y: numpy.ndarray of floats
The y-coordinates of the regularized boundary.
"""
if not (N or ds):
return xo.copy(), yo.copy()
if not N:
N = int(math.ceil(_get_perimeter(xo, yo) / ds))
ds = _get_perimeter(xo, yo) / N
# Duplicate point if necessary to get a closed surface.
if abs(xo[0] - xo[-1]) > atol or abs(yo[0] - yo[-1]) > atol:
xo, yo = numpy.append(xo, xo[0]), numpy.append(yo, yo[0])
# Regularize the geometry.
next_idx = 1
last_idx = xo.size - 1
x, y = [xo[0]], [yo[0]]
for _ in range(1, N):
xs, ys = x[-1], y[-1] # Start point
xe, ye = xo[next_idx], yo[next_idx] # End point
length = numpy.sqrt((xe - xs)**2 + (ye - ys)**2)
if abs(ds - length) <= atol: # Copy
x.append(xe)
y.append(ye)
next_idx += 1
elif ds < length: # Interpolate between start and end points
length2 = numpy.sqrt((xe - xs)**2 + (ye - ys)**2)
x.append(xs + ds / length2 * (xe - xs))
y.append(ys + ds / length2 * (ye - ys))
else: # Project the new point
# Get segment index.
while length < ds and next_idx < last_idx:
next_idx += 1
length = numpy.sqrt((xo[next_idx] - xs)**2 +
(yo[next_idx] - ys)**2)
xp, yp = xo[next_idx - 1], yo[next_idx - 1]
xe, ye = xo[next_idx], yo[next_idx]
# Interpolate on segment.
precision = 1
coeff = 0.0
while abs(ds - length) > atol and precision < 6:
xn, yn = xp + coeff * (xe - xp), yp + coeff * (ye - yp)
length = numpy.sqrt((xn - xs)**2 + (yn - ys)**2)
if length > ds:
coeff -= 0.1**precision
precision += 1
coeff += 0.1**precision
# Check new point not too close from first point before adding.
length = numpy.sqrt((xn - x[0])**2 + (yn - y[0])**2)
if length > 0.5 * ds:
x.append(xn)
y.append(yn)
x, y = numpy.array(x), numpy.array(y)
return x, y
|
python
|
from bstools import bsSsh
from bstools import bsPrint
from bstools import bsTime
name = "bstools"
__version__ = "0.1.9"
|
python
|
"""
libmonster.py - mixed support library
# TODO: consider replacing pauthor in keyid with _bibtex.names
# TODO: enusure \emph is dropped from titles in keyid calculation
"""
import re
from heapq import nsmallest
from collections import defaultdict
from itertools import groupby
from operator import itemgetter
from csvw.dsv import UnicodeWriter
from ..util import unique, Trigger
from .bibfiles import Entry
from .bibtex_undiacritic import undiacritic
from .roman import roman, romanint
INF = float('inf')
lgcodestr = Entry.lgcodes
def opv(d, func, *args):
"""
Apply func to all values of a dictionary.
:param d: A dictionary.
:param func: Callable accepting a value of `d` as first parameter.
:param args: Additional positional arguments to be passed to `func`.
:return: `dict` mapping the keys of `d` to the return value of the function call.
"""
return {i: func(v, *args) for i, v in d.items()}
def grp2(l):
"""
Turn a list of pairs into a dictionary, mapping first elements to lists of
co-occurring second elements in pairs.
:param l:
:return:
"""
return {a: [pair[1] for pair in pairs] for a, pairs in
groupby(sorted(l, key=itemgetter(0)), itemgetter(0))}
def grp2fd(l):
"""
Turn a list of pairs into a nested dictionary, thus grouping by the first element in
the pair.
:param l:
:return:
"""
return {k: {vv: 1 for vv in v} for k, v in grp2(l).items()}
reauthor = [re.compile(pattern) for pattern in [
"(?P<lastname>[^,]+),\s((?P<jr>[JS]r\.|[I]+),\s)?(?P<firstname>[^,]+)$",
"(?P<firstname>[^{][\S]+(\s[A-Z][\S]+)*)\s"
"(?P<lastname>([a-z]+\s)*[A-Z\\\\][\S]+)(?P<jr>,\s[JS]r\.|[I]+)?$",
"(?P<firstname>\\{[\S]+\\}[\S]+(\s[A-Z][\S]+)*)\s"
"(?P<lastname>([a-z]+\s)*[A-Z\\\\][\S]+)(?P<jr>,\s[JS]r\.|[I]+)?$",
"(?P<firstname>[\s\S]+?)\s\{(?P<lastname>[\s\S]+)\}(?P<jr>,\s[JS]r\.|[I]+)?$",
"\{(?P<firstname>[\s\S]+)\}\s(?P<lastname>[\s\S]+?)(?P<jr>,\s[JS]r\.|[I]+)?$",
"(?P<lastname>[A-Z][\S]+)$",
"\{(?P<lastname>[\s\S]+)\}$",
"(?P<lastname>[aA]nonymous)$",
"(?P<lastname>\?)$",
"(?P<lastname>[\s\S]+)$",
]]
def psingleauthor(n):
if not n:
return
for pattern in reauthor:
o = pattern.match(n)
if o:
return o.groupdict()
print("Couldn't parse name:", n) # pragma: no cover
def pauthor(s):
pas = [psingleauthor(a) for a in s.split(' and ')]
if [a for a in pas if not a]:
if s:
print(s)
return [a for a in pas if a]
relu = re.compile("\s+|(d\')(?=[A-Z])")
recapstart = re.compile("\[?[A-Z]")
def lowerupper(s):
parts, lower, upper = [x for x in relu.split(s) if x], [], []
for i, x in enumerate(parts):
if not recapstart.match(undiacritic(x)):
lower.append(x)
else:
upper = parts[i:]
break
return lower, upper
def lastnamekey(s):
_, upper = lowerupper(s)
return max(upper) if upper else ''
def rangecomplete(incomplete, complete):
"""
>>> rangecomplete('2', '10')
'12'
"""
if len(complete) > len(incomplete):
# if the second number in a range of pages has less digits than the the first,
# we assume it's meant as only the last digits of the bigger number,
# i.e. 10-2 is interpreted as 10-12.
return complete[:len(complete) - len(incomplete)] + incomplete
return incomplete
rebracketyear = re.compile("\[([\d\,\-\/]+)\]")
reyl = re.compile("[\,\-\/\s\[\]]+")
def pyear(s):
if rebracketyear.search(s):
s = rebracketyear.search(s).group(1)
my = [x for x in reyl.split(s) if x.strip()]
if len(my) == 0:
return "[nd]"
if len(my) != 1:
return my[0] + "-" + rangecomplete(my[-1], my[0])
return my[-1]
bibord = {k: i for i, k in enumerate([
'author',
'editor',
'title',
'booktitle',
'journal',
'school',
'publisher',
'address',
'series',
'volume',
'number',
'pages',
'year',
'issn',
'url',
])}
def bibord_iteritems(fields):
for f in sorted(fields, key=lambda f: (bibord.get(f, INF), f)):
yield f, fields[f]
resplittit = re.compile("[\(\)\[\]\:\,\.\s\-\?\!\;\/\~\=]+")
def wrds(txt):
txt = undiacritic(txt.lower())
txt = txt.replace("'", "").replace('"', "")
return [x for x in resplittit.split(txt) if x]
def renfn(e, ups):
for k, field, newvalue in ups:
typ, fields = e[k]
fields[field] = newvalue
e[k] = (typ, fields)
return e
INLG = 'inlg'
def add_inlg_e(e, trigs, verbose=True, return_newtrain=False):
# FIXME: does not honor 'NOT' for now, only maps words to iso codes.
dh = {word: t.type for t in trigs for _, word in t.clauses}
# map record keys to lists of words in titles:
ts = [(k, wrds(fields['title']) + wrds(fields.get('booktitle', '')))
for (k, (typ, fields)) in e.items()
if 'title' in fields and INLG not in fields]
if verbose:
print(len(ts), "without", INLG)
# map record keys to sets of assigned iso codes, based on words in the title
ann = [(k, set(dh[w] for w in tit if w in dh)) for k, tit in ts]
# list of record keys which have been assigned exactly one iso code
unique_ = [(k, lgs.pop()) for (k, lgs) in ann if len(lgs) == 1]
if verbose:
print(len(unique_), "cases of unique hits")
t2 = renfn(e, [(k, INLG, v) for (k, v) in unique_])
if return_newtrain: # pragma: no cover
newtrain = grp2fd([
(lgcodestr(fields[INLG])[0], w) for (k, (typ, fields)) in t2.items()
if 'title' in fields and INLG in fields
if len(lgcodestr(fields[INLG])) == 1 for w in wrds(fields['title'])])
for (lg, wf) in sorted(newtrain.items(), key=lambda x: len(x[1])):
cm = [(1 + f,
float(1 - f + sum(owf.get(w, 0) for owf in newtrain.values())),
w) for (w, f) in wf.items() if f > 9]
cms = [(f / fn, f, fn, w) for (f, fn, w) in cm]
cms.sort(reverse=True)
return t2, newtrain, cms
return t2
rerpgs = re.compile("([xivmcl]+)\-?([xivmcl]*)")
repgs = re.compile("([\d]+)\-?([\d]*)")
def pagecount(pgstr):
rpgs = rerpgs.findall(pgstr)
pgs = repgs.findall(pgstr)
rsump = sum(romanint(b) - romanint(a) + 1 if b else romanint(a) for (a, b) in rpgs)
sump = sum(int(rangecomplete(b, a)) - int(a) + 1 if b else int(a) for (a, b) in pgs)
if rsump != 0 and sump != 0:
return "%s+%s" % (rsump, sump)
if rsump == 0 and sump == 0:
return ''
return '%s' % (rsump + sump)
rewrdtok = re.compile("[a-zA-Z].+")
reokkey = re.compile("[^a-z\d\-\_\[\]]")
def keyid(fields, fd, ti=2, infinity=float('inf')):
if 'author' not in fields:
if 'editor' not in fields:
values = ''.join(
v for f, v in bibord_iteritems(fields) if f != 'glottolog_ref_id')
return '__missingcontrib__' + reokkey.sub('_', values.lower())
else:
astring = fields['editor']
else:
astring = fields['author']
authors = pauthor(astring)
if len(authors) != len(astring.split(' and ')):
print("Unparsed author in", authors)
print(" ", astring, astring.split(' and '))
print(fields.get('title'))
ak = [undiacritic(x) for x in sorted(lastnamekey(a['lastname']) for a in authors)]
yk = pyear(fields.get('year', '[nd]'))[:4]
tks = wrds(fields.get("title", "no.title")) # takeuntil :
# select the (leftmost) two least frequent words from the title
types = list(unique(w for w in tks if rewrdtok.match(w)))
tk = nsmallest(ti, types, key=lambda w: fd.get(w, infinity))
# put them back into the title order (i.e. 'spam eggs' != 'eggs spam')
order = {w: i for i, w in enumerate(types)}
tk.sort(key=lambda w: order[w])
if 'volume' in fields and all(
f not in fields for f in ['journal', 'booktitle', 'series']):
vk = roman(fields['volume'])
else:
vk = ''
if 'extra_hash' in fields:
yk = yk + fields['extra_hash']
key = '-'.join(ak) + "_" + '-'.join(tk) + vk + yk
return reokkey.sub("", key.lower())
def lgcode(arg):
fields = arg[1]
return lgcodestr(fields['lgcode']) if 'lgcode' in fields else []
def sd(es, hht):
# most signficant piece of descriptive material
# hhtype, pages, year
mi = [(k,
(hht.parse(fields.get('hhtype', 'unknown')),
fields.get('pages', ''),
fields.get('year', ''))) for (k, (typ, fields)) in es.items()]
d = accd(mi)
return [sorted(((p, y, k, t.id) for (k, (p, y)) in d[t.id].items()), reverse=True)
for t in hht if t.id in d]
def pcy(pagecountstr):
if not pagecountstr:
return 0
return eval(pagecountstr) # int(takeafter(pagecountstr, "+"))
def accd(mi):
r = defaultdict(dict)
for (k, (hhts, pgs, year)) in mi:
pci = pcy(pagecount(pgs))
for t in hhts:
r[t][k] = (pci / float(len(hhts)), year)
return r
def byid(es):
return grp2([(cfn, k) for (k, tf) in es.items() for cfn in lgcode(tf)])
def sdlgs(e, hht):
eindex = byid(e)
fes = opv(eindex, lambda ks: {k: e[k] for k in ks})
fsd = opv(fes, sd, hht)
return fsd, fes
def lstat(e, hht):
(lsd, lse) = sdlgs(e, hht)
return opv(lsd, lambda xs: (xs + [[[None]]])[0][0][-1])
def lstat_witness(e, hht):
def statwit(xs):
assert xs
[(typ, ks)] = grp2([(t, k) for [p, y, k, t] in xs[0]]).items()
return typ, ks
(lsd, lse) = sdlgs(e, hht)
return opv(lsd, statwit)
def markconservative(m, trigs, ref, hht, outfn, verbose=True, rank=None):
blamefield = "hhtype"
mafter = markall(m, trigs, verbose=verbose, rank=rank)
ls = lstat(ref, hht)
lsafter = lstat_witness(mafter, hht)
log = []
no_status = defaultdict(set)
for (lg, (stat, wits)) in lsafter.items():
if not ls.get(lg):
srctrickles = [mafter[k][1].get('srctrickle') for k in wits]
for t in srctrickles:
if t and not t.startswith('iso6393'):
no_status[lg].add(t)
continue
if hht[stat] > hht[ls[lg]]:
log = log + [
(lg, [(mafter[k][1].get(blamefield, "No %s" % blamefield),
k,
mafter[k][1].get('title', 'no title'),
mafter[k][1].get('srctrickle', 'no srctrickle')) for k in wits], ls[lg])]
for k in wits:
(t, f) = mafter[k]
if blamefield in f:
del f[blamefield]
mafter[k] = (t, f)
for lg in no_status:
print('{0} lacks status'.format(lg))
with UnicodeWriter(outfn, dialect='excel-tab') as writer:
writer.writerows(((lg, was) + mis for (lg, miss, was) in log for mis in miss))
return mafter
def markall(e, trigs, verbose=True, rank=None):
# the set of fields triggers relate to:
clss = set(t.field for t in trigs)
# all bibitems lacking any of the potential triggered fields:
ei = {k: (typ, fields) for k, (typ, fields) in e.items()
if any(c not in fields for c in clss)}
eikeys = set(list(ei.keys()))
# map words in titles to lists of bibitem keys having the word in the title:
wk = defaultdict(set)
for k, (typ, fields) in ei.items():
for w in wrds(fields.get('title', '')):
wk[w].add(k)
u = defaultdict(lambda: defaultdict(list))
for clauses, triggers in Trigger.group(trigs):
for k in triggers[0](eikeys, wk):
for t in triggers:
u[k][t.cls].append(t)
for k, t_by_c in sorted(u.items(), key=lambda i: i[0]):
t, f = e[k]
f2 = {a: b for a, b in f.items()}
for (field, type_), triggers in sorted(t_by_c.items(), key=lambda i: len(i[1])):
# Make sure we handle the trigger class with the biggest number of matching
# triggers last.
if rank and field in f2:
# only update the assigned hhtype if something better comes along:
if rank(f2[field].split(' (comp')[0]) >= rank(type_):
continue
f2[field] = Trigger.format(type_, triggers)
e[k] = (t, f2)
if verbose:
print("trigs", len(trigs))
print("label classes", len(clss))
print("unlabeled refs", len(ei))
print("updates", len(u))
return e
|
python
|
## Code taken from https://github.com/vqdang/hover_net/blob/master/metrics/stats_utils.py
import warnings
import numpy as np
import scipy
from scipy.optimize import linear_sum_assignment
# --------------------------Optimised for Speed
def get_fast_aji(true, pred):
"""AJI version distributed by MoNuSeg, has no permutation problem but suffered from
over-penalisation similar to DICE2.
Fast computation requires instance IDs are in contiguous orderding i.e [1, 2, 3, 4]
not [2, 3, 6, 10]. Please call `remap_label` before hand and `by_size` flag has no
effect on the result.
"""
if true.sum() == 0 and pred.sum() == 0:
return 1.
true = np.copy(true) # ? do we need this
pred = np.copy(pred)
true_id_list = list(np.unique(true))
pred_id_list = list(np.unique(pred))
true_masks = [
None,
]
for t in true_id_list[1:]:
t_mask = np.array(true == t, np.uint8)
true_masks.append(t_mask)
pred_masks = [
None,
]
for p in pred_id_list[1:]:
p_mask = np.array(pred == p, np.uint8)
pred_masks.append(p_mask)
# prefill with value
pairwise_inter = np.zeros(
[len(true_id_list) - 1, len(pred_id_list) - 1], dtype=np.float64
)
pairwise_union = np.zeros(
[len(true_id_list) - 1, len(pred_id_list) - 1], dtype=np.float64
)
# caching pairwise
for true_id in true_id_list[1:]: # 0-th is background
t_mask = true_masks[true_id]
pred_true_overlap = pred[t_mask > 0]
pred_true_overlap_id = np.unique(pred_true_overlap)
pred_true_overlap_id = list(pred_true_overlap_id)
for pred_id in pred_true_overlap_id:
if pred_id == 0: # ignore
continue # overlaping background
p_mask = pred_masks[pred_id]
total = (t_mask + p_mask).sum()
inter = (t_mask * p_mask).sum()
pairwise_inter[true_id - 1, pred_id - 1] = inter
pairwise_union[true_id - 1, pred_id - 1] = total - inter
pairwise_iou = pairwise_inter / (pairwise_union + 1.0e-6)
# pair of pred that give highest iou for each true, dont care
# about reusing pred instance multiple times
paired_pred = np.argmax(pairwise_iou, axis=1)
pairwise_iou = np.max(pairwise_iou, axis=1)
# exlude those dont have intersection
paired_true = np.nonzero(pairwise_iou > 0.0)[0]
paired_pred = paired_pred[paired_true]
# print(paired_true.shape, paired_pred.shape)
overall_inter = (pairwise_inter[paired_true, paired_pred]).sum()
overall_union = (pairwise_union[paired_true, paired_pred]).sum()
paired_true = list(paired_true + 1) # index to instance ID
paired_pred = list(paired_pred + 1)
# add all unpaired GT and Prediction into the union
unpaired_true = np.array(
[idx for idx in true_id_list[1:] if idx not in paired_true]
)
unpaired_pred = np.array(
[idx for idx in pred_id_list[1:] if idx not in paired_pred]
)
for true_id in unpaired_true:
overall_union += true_masks[true_id].sum()
for pred_id in unpaired_pred:
overall_union += pred_masks[pred_id].sum()
if overall_union == 0:
aji_score = 0.
else:
aji_score = overall_inter / overall_union
return aji_score
#####
def get_fast_aji_plus(true, pred):
"""AJI+, an AJI version with maximal unique pairing to obtain overall intersecion.
Every prediction instance is paired with at most 1 GT instance (1 to 1) mapping, unlike AJI
where a prediction instance can be paired against many GT instances (1 to many).
Remaining unpaired GT and Prediction instances will be added to the overall union.
The 1 to 1 mapping prevents AJI's over-penalisation from happening.
Fast computation requires instance IDs are in contiguous orderding i.e [1, 2, 3, 4]
not [2, 3, 6, 10]. Please call `remap_label` before hand and `by_size` flag has no
effect on the result.
"""
if true.sum() == 0 and pred.sum() == 0:
return 1.
true = np.copy(true) # ? do we need this
pred = np.copy(pred)
true_id_list = list(np.unique(true))
pred_id_list = list(np.unique(pred))
true_masks = [
None,
]
for t in true_id_list[1:]:
t_mask = np.array(true == t, np.uint8)
true_masks.append(t_mask)
pred_masks = [
None,
]
for p in pred_id_list[1:]:
p_mask = np.array(pred == p, np.uint8)
pred_masks.append(p_mask)
# prefill with value
pairwise_inter = np.zeros(
[len(true_id_list) - 1, len(pred_id_list) - 1], dtype=np.float64
)
pairwise_union = np.zeros(
[len(true_id_list) - 1, len(pred_id_list) - 1], dtype=np.float64
)
# caching pairwise
for true_id in true_id_list[1:]: # 0-th is background
t_mask = true_masks[true_id]
pred_true_overlap = pred[t_mask > 0]
pred_true_overlap_id = np.unique(pred_true_overlap)
pred_true_overlap_id = list(pred_true_overlap_id)
for pred_id in pred_true_overlap_id:
if pred_id == 0: # ignore
continue # overlaping background
p_mask = pred_masks[pred_id]
total = (t_mask + p_mask).sum()
inter = (t_mask * p_mask).sum()
pairwise_inter[true_id - 1, pred_id - 1] = inter
pairwise_union[true_id - 1, pred_id - 1] = total - inter
#
pairwise_iou = pairwise_inter / (pairwise_union + 1.0e-6)
#### Munkres pairing to find maximal unique pairing
paired_true, paired_pred = linear_sum_assignment(-pairwise_iou)
### extract the paired cost and remove invalid pair
paired_iou = pairwise_iou[paired_true, paired_pred]
# now select all those paired with iou != 0.0 i.e have intersection
paired_true = paired_true[paired_iou > 0.0]
paired_pred = paired_pred[paired_iou > 0.0]
paired_inter = pairwise_inter[paired_true, paired_pred]
paired_union = pairwise_union[paired_true, paired_pred]
paired_true = list(paired_true + 1) # index to instance ID
paired_pred = list(paired_pred + 1)
overall_inter = paired_inter.sum()
overall_union = paired_union.sum()
# add all unpaired GT and Prediction into the union
unpaired_true = np.array(
[idx for idx in true_id_list[1:] if idx not in paired_true]
)
unpaired_pred = np.array(
[idx for idx in pred_id_list[1:] if idx not in paired_pred]
)
for true_id in unpaired_true:
overall_union += true_masks[true_id].sum()
for pred_id in unpaired_pred:
overall_union += pred_masks[pred_id].sum()
#
if overall_union == 0:
aji_score = 0.
else:
aji_score = overall_inter / overall_union
return aji_score
#####
def get_fast_pq(true, pred, match_iou=0.5):
"""`match_iou` is the IoU threshold level to determine the pairing between
GT instances `p` and prediction instances `g`. `p` and `g` is a pair
if IoU > `match_iou`. However, pair of `p` and `g` must be unique
(1 prediction instance to 1 GT instance mapping).
If `match_iou` < 0.5, Munkres assignment (solving minimum weight matching
in bipartite graphs) is caculated to find the maximal amount of unique pairing.
If `match_iou` >= 0.5, all IoU(p,g) > 0.5 pairing is proven to be unique and
the number of pairs is also maximal.
Fast computation requires instance IDs are in contiguous orderding
i.e [1, 2, 3, 4] not [2, 3, 6, 10]. Please call `remap_label` beforehand
and `by_size` flag has no effect on the result.
Returns:
[dq, sq, pq]: measurement statistic
[paired_true, paired_pred, unpaired_true, unpaired_pred]:
pairing information to perform measurement
"""
assert match_iou >= 0.0, "Cant' be negative"
true = np.copy(true)
pred = np.copy(pred)
true_id_list = list(np.unique(true))
pred_id_list = list(np.unique(pred))
true_masks = [
None,
]
for t in true_id_list[1:]:
t_mask = np.array(true == t, np.uint8)
true_masks.append(t_mask)
pred_masks = [
None,
]
for p in pred_id_list[1:]:
p_mask = np.array(pred == p, np.uint8)
pred_masks.append(p_mask)
# prefill with value
pairwise_iou = np.zeros(
[len(true_id_list) - 1, len(pred_id_list) - 1], dtype=np.float64
)
# caching pairwise iou
for true_id in true_id_list[1:]: # 0-th is background
t_mask = true_masks[true_id]
pred_true_overlap = pred[t_mask > 0]
pred_true_overlap_id = np.unique(pred_true_overlap)
pred_true_overlap_id = list(pred_true_overlap_id)
for pred_id in pred_true_overlap_id:
if pred_id == 0: # ignore
continue # overlaping background
p_mask = pred_masks[pred_id]
total = (t_mask + p_mask).sum()
inter = (t_mask * p_mask).sum()
iou = inter / (total - inter)
pairwise_iou[true_id - 1, pred_id - 1] = iou
#
if match_iou >= 0.5:
paired_iou = pairwise_iou[pairwise_iou > match_iou]
pairwise_iou[pairwise_iou <= match_iou] = 0.0
paired_true, paired_pred = np.nonzero(pairwise_iou)
paired_iou = pairwise_iou[paired_true, paired_pred]
paired_true += 1 # index is instance id - 1
paired_pred += 1 # hence return back to original
else: # * Exhaustive maximal unique pairing
#### Munkres pairing with scipy library
# the algorithm return (row indices, matched column indices)
# if there is multiple same cost in a row, index of first occurence
# is return, thus the unique pairing is ensure
# inverse pair to get high IoU as minimum
paired_true, paired_pred = linear_sum_assignment(-pairwise_iou)
### extract the paired cost and remove invalid pair
paired_iou = pairwise_iou[paired_true, paired_pred]
# now select those above threshold level
# paired with iou = 0.0 i.e no intersection => FP or FN
paired_true = list(paired_true[paired_iou > match_iou] + 1)
paired_pred = list(paired_pred[paired_iou > match_iou] + 1)
paired_iou = paired_iou[paired_iou > match_iou]
# get the actual FP and FN
unpaired_true = [idx for idx in true_id_list[1:] if idx not in paired_true]
unpaired_pred = [idx for idx in pred_id_list[1:] if idx not in paired_pred]
# print(paired_iou.shape, paired_true.shape, len(unpaired_true), len(unpaired_pred))
#
tp = len(paired_true)
fp = len(unpaired_pred)
fn = len(unpaired_true)
# get the F1-score i.e DQ
dq = tp / (tp + 0.5 * fp + 0.5 * fn)
# get the SQ, no paired has 0 iou so not impact
sq = paired_iou.sum() / (tp + 1.0e-6)
return [dq, sq, dq * sq], [paired_true, paired_pred, unpaired_true, unpaired_pred]
#####
def get_fast_dice_2(true, pred):
"""Ensemble dice."""
true = np.copy(true)
pred = np.copy(pred)
true_id = list(np.unique(true))
pred_id = list(np.unique(pred))
overall_total = 0
overall_inter = 0
true_masks = [np.zeros(true.shape)]
for t in true_id[1:]:
t_mask = np.array(true == t, np.uint8)
true_masks.append(t_mask)
pred_masks = [np.zeros(true.shape)]
for p in pred_id[1:]:
p_mask = np.array(pred == p, np.uint8)
pred_masks.append(p_mask)
for true_idx in range(1, len(true_id)):
t_mask = true_masks[true_idx]
pred_true_overlap = pred[t_mask > 0]
pred_true_overlap_id = np.unique(pred_true_overlap)
pred_true_overlap_id = list(pred_true_overlap_id)
try: # blinly remove background
pred_true_overlap_id.remove(0)
except ValueError:
pass # just mean no background
for pred_idx in pred_true_overlap_id:
p_mask = pred_masks[pred_idx]
total = (t_mask + p_mask).sum()
inter = (t_mask * p_mask).sum()
overall_total += total
overall_inter += inter
return 2 * overall_inter / overall_total
#####--------------------------As pseudocode
def get_dice_1(true, pred):
"""Traditional dice."""
# cast to binary 1st
true = np.copy(true)
pred = np.copy(pred)
true[true > 0] = 1
pred[pred > 0] = 1
inter = true * pred
denom = true + pred
return 2.0 * np.sum(inter) / np.sum(denom)
####
def get_dice_2(true, pred):
"""Ensemble Dice as used in Computational Precision Medicine Challenge."""
true = np.copy(true)
pred = np.copy(pred)
true_id = list(np.unique(true))
pred_id = list(np.unique(pred))
# remove background aka id 0
true_id.remove(0)
pred_id.remove(0)
total_markup = 0
total_intersect = 0
for t in true_id:
t_mask = np.array(true == t, np.uint8)
for p in pred_id:
p_mask = np.array(pred == p, np.uint8)
intersect = p_mask * t_mask
if intersect.sum() > 0:
total_intersect += intersect.sum()
total_markup += t_mask.sum() + p_mask.sum()
return 2 * total_intersect / total_markup
#####
def remap_label(pred, by_size=False):
"""Rename all instance id so that the id is contiguous i.e [0, 1, 2, 3]
not [0, 2, 4, 6]. The ordering of instances (which one comes first)
is preserved unless by_size=True, then the instances will be reordered
so that bigger nucler has smaller ID.
Args:
pred : the 2d array contain instances where each instances is marked
by non-zero integer
by_size : renaming with larger nuclei has smaller id (on-top)
"""
pred_id = list(np.unique(pred))
pred_id.remove(0)
if len(pred_id) == 0:
return pred # no label
if by_size:
pred_size = []
for inst_id in pred_id:
size = (pred == inst_id).sum()
pred_size.append(size)
# sort the id by size in descending order
pair_list = zip(pred_id, pred_size)
pair_list = sorted(pair_list, key=lambda x: x[1], reverse=True)
pred_id, pred_size = zip(*pair_list)
new_pred = np.zeros(pred.shape, np.int32)
for idx, inst_id in enumerate(pred_id):
new_pred[pred == inst_id] = idx + 1
return new_pred
#####
def pair_coordinates(setA, setB, radius):
"""Use the Munkres or Kuhn-Munkres algorithm to find the most optimal
unique pairing (largest possible match) when pairing points in set B
against points in set A, using distance as cost function.
Args:
setA, setB: np.array (float32) of size Nx2 contains the of XY coordinate
of N different points
radius: valid area around a point in setA to consider
a given coordinate in setB a candidate for match
Return:
pairing: pairing is an array of indices
where point at index pairing[0] in set A paired with point
in set B at index pairing[1]
unparedA, unpairedB: remaining poitn in set A and set B unpaired
"""
# * Euclidean distance as the cost matrix
pair_distance = scipy.spatial.distance.cdist(setA, setB, metric='euclidean')
# * Munkres pairing with scipy library
# the algorithm return (row indices, matched column indices)
# if there is multiple same cost in a row, index of first occurence
# is return, thus the unique pairing is ensured
indicesA, paired_indicesB = linear_sum_assignment(pair_distance)
# extract the paired cost and remove instances
# outside of designated radius
pair_cost = pair_distance[indicesA, paired_indicesB]
pairedA = indicesA[pair_cost <= radius]
pairedB = paired_indicesB[pair_cost <= radius]
pairing = np.concatenate([pairedA[:,None], pairedB[:,None]], axis=-1)
unpairedA = np.delete(np.arange(setA.shape[0]), pairedA)
unpairedB = np.delete(np.arange(setB.shape[0]), pairedB)
return pairing, unpairedA, unpairedB
|
python
|
from ivy import ivy_module as im
from ivy.ivy_compiler import ivy_from_string
from ivy.tk_ui import new_ui
from ivy import ivy_utils as iu
from ivy import ivy_check as ick
from ivy import ivy_logic as il
prog = """#lang ivy1.5
type t
type p
relation sent(X:p,Y:t)
function pid(X:t):p
axiom X:t = X
axiom X:t < Y & Y < Z -> X < Z
axiom X:t = Y + 0
axiom X:t = Y + Z
axiom X = (Y:t + 1) if (Y = Z) else 0
axiom forall X,Y,Z. X:t < Y & Y < Z -> X < Z
axiom forall NO0:t,NO1:t. ~(pid(NO0:t) < pid(NO1:t) & sent(pid(NO0:t),NO0:t))
"""
with im.Module():
iu.set_parameters({'mode':'induction','show_compiled':'true'})
ivy_from_string(prog,create_isolate=False)
for adecl in im.module.labeled_axioms:
f = adecl.args[1]
print
print str(f)
print il.to_str_with_var_sorts(f)
print il.fmla_to_str_ambiguous(f)
# main_ui.answer("OK")
# ui.check_inductiveness()
# # ui = ui.cti
# cg = ui.current_concept_graph
# cg.show_relation(cg.relation('link(X,Y)'),'+')
# cg.gather()
# main_ui.answer("OK")
# cg.strengthen()
# main_ui.answer("OK")
# ui.check_inductiveness()
# # cg.show_relation(cg.relation('semaphore'),'+')
# cg.gather()
# main_ui.answer("View")
# cg.bmc_conjecture(bound=1)
# # main_ui.mainloop()
|
python
|
# -*- coding: utf-8 -*-
# Ambry Bundle Library File
# Use this file for code that may be imported into other bundles
|
python
|
import kydb
from portfolio_management.common.base_item import BaseItem, Factory
from portfolio_management.common.account_container_mixin import AccountContainerMixin
from portfolio_management.common.position_mixin import PositionMixin
from portfolio_management.portfolio.event import Event, EventType
from portfolio_management.portfolio.instrument import Instrument, InstrumentFx
import portfolio_management.utils.func_utils as fu
class Deal(BaseItem, AccountContainerMixin, PositionMixin, kydb.DbObj):
"""
Represents a buy / sell transaction for a financial instrument
"""
@kydb.stored
def state(self) -> str:
return ''
def state_obj(self) -> Event:
return self.db[Factory.get_class_path('Event', self.state())]
def positions(self) -> dict:
return {}
def __str__(self):
return '{0}[{1}]'.format(self.id(), self.state())
def apply_event(self, event_type, price=None, qty=None, ccy=None):
if event_type == EventType.Amend:
if price:
self.price.setvalue(price)
if qty:
self.price.setvalue(qty)
if ccy:
self.ccy.setvalue(ccy)
self.events().add(self.state())
event = Factory.create('Event', db=self.db, event_type=event_type)
self.state.setvalue(event.id())
@kydb.stored
def instrument(self) -> str:
return ''
def instrument_obj(self) -> Instrument:
return self.db[Factory.get_class_path('Instrument', self.instrument())]
@kydb.stored
def direction(self) -> str:
return 'B'
@kydb.stored
def ccy(self) -> str:
return ''
@kydb.stored
def qty(self) -> float:
return 0.00
@kydb.stored
def events(self) -> set:
return set()
@kydb.stored
def events_obj(self) -> list:
return [self.db[Factory.get_class_path('Event', a)] for a in self.events()]
@kydb.stored
def instrument(self) -> str:
return ''
class DealEq(Deal):
"""
Equity type deal
"""
@kydb.stored
def price(self) -> float:
return 0.00
def positions(self) -> dict:
positions = {
self.ccy() : - self.qty() * self.price(),
self.instrument_obj().symbol(): self.qty()
}
return positions
@kydb.stored
def notional(self) -> float:
return self.qty() if self.qty() else 0.00 * self.price() if self.price() else 0.00
class DealFx(Deal):
"""
FX Spot type deal
"""
@kydb.stored
def rate(self) -> float:
return 0.00
@kydb.stored
def ccy1(self) -> str:
return ''
@kydb.stored
def ccy2(self) -> str:
return ''
@kydb.stored
def ccy1_amount(self) -> float:
return 0.00
@kydb.stored
def ccy2_amount(self) -> float:
return 0.00
def positions(self) -> dict:
factor = 1 if self.direction() == 'B' else -1
positions = {self.ccy1(): self.ccy1_amount() * factor, self.ccy2(): self.ccy2_amount() * factor * -1}
return positions
def instrument_obj(self) -> InstrumentFx:
return self.db[Factory.get_class_path('InstrumentFx', self.instrument())]
def main():
pass
if __name__ == '__main__':
main()
|
python
|
uctable = [ [ 48 ],
[ 49 ],
[ 50 ],
[ 51 ],
[ 52 ],
[ 53 ],
[ 54 ],
[ 55 ],
[ 56 ],
[ 57 ],
[ 194, 178 ],
[ 194, 179 ],
[ 194, 185 ],
[ 194, 188 ],
[ 194, 189 ],
[ 194, 190 ],
[ 217, 160 ],
[ 217, 161 ],
[ 217, 162 ],
[ 217, 163 ],
[ 217, 164 ],
[ 217, 165 ],
[ 217, 166 ],
[ 217, 167 ],
[ 217, 168 ],
[ 217, 169 ],
[ 219, 176 ],
[ 219, 177 ],
[ 219, 178 ],
[ 219, 179 ],
[ 219, 180 ],
[ 219, 181 ],
[ 219, 182 ],
[ 219, 183 ],
[ 219, 184 ],
[ 219, 185 ],
[ 223, 128 ],
[ 223, 129 ],
[ 223, 130 ],
[ 223, 131 ],
[ 223, 132 ],
[ 223, 133 ],
[ 223, 134 ],
[ 223, 135 ],
[ 223, 136 ],
[ 223, 137 ],
[ 224, 165, 166 ],
[ 224, 165, 167 ],
[ 224, 165, 168 ],
[ 224, 165, 169 ],
[ 224, 165, 170 ],
[ 224, 165, 171 ],
[ 224, 165, 172 ],
[ 224, 165, 173 ],
[ 224, 165, 174 ],
[ 224, 165, 175 ],
[ 224, 167, 166 ],
[ 224, 167, 167 ],
[ 224, 167, 168 ],
[ 224, 167, 169 ],
[ 224, 167, 170 ],
[ 224, 167, 171 ],
[ 224, 167, 172 ],
[ 224, 167, 173 ],
[ 224, 167, 174 ],
[ 224, 167, 175 ],
[ 224, 167, 180 ],
[ 224, 167, 181 ],
[ 224, 167, 182 ],
[ 224, 167, 183 ],
[ 224, 167, 184 ],
[ 224, 167, 185 ],
[ 224, 169, 166 ],
[ 224, 169, 167 ],
[ 224, 169, 168 ],
[ 224, 169, 169 ],
[ 224, 169, 170 ],
[ 224, 169, 171 ],
[ 224, 169, 172 ],
[ 224, 169, 173 ],
[ 224, 169, 174 ],
[ 224, 169, 175 ],
[ 224, 171, 166 ],
[ 224, 171, 167 ],
[ 224, 171, 168 ],
[ 224, 171, 169 ],
[ 224, 171, 170 ],
[ 224, 171, 171 ],
[ 224, 171, 172 ],
[ 224, 171, 173 ],
[ 224, 171, 174 ],
[ 224, 171, 175 ],
[ 224, 173, 166 ],
[ 224, 173, 167 ],
[ 224, 173, 168 ],
[ 224, 173, 169 ],
[ 224, 173, 170 ],
[ 224, 173, 171 ],
[ 224, 173, 172 ],
[ 224, 173, 173 ],
[ 224, 173, 174 ],
[ 224, 173, 175 ],
[ 224, 173, 178 ],
[ 224, 173, 179 ],
[ 224, 173, 180 ],
[ 224, 173, 181 ],
[ 224, 173, 182 ],
[ 224, 173, 183 ],
[ 224, 175, 166 ],
[ 224, 175, 167 ],
[ 224, 175, 168 ],
[ 224, 175, 169 ],
[ 224, 175, 170 ],
[ 224, 175, 171 ],
[ 224, 175, 172 ],
[ 224, 175, 173 ],
[ 224, 175, 174 ],
[ 224, 175, 175 ],
[ 224, 175, 176 ],
[ 224, 175, 177 ],
[ 224, 175, 178 ],
[ 224, 177, 166 ],
[ 224, 177, 167 ],
[ 224, 177, 168 ],
[ 224, 177, 169 ],
[ 224, 177, 170 ],
[ 224, 177, 171 ],
[ 224, 177, 172 ],
[ 224, 177, 173 ],
[ 224, 177, 174 ],
[ 224, 177, 175 ],
[ 224, 177, 184 ],
[ 224, 177, 185 ],
[ 224, 177, 186 ],
[ 224, 177, 187 ],
[ 224, 177, 188 ],
[ 224, 177, 189 ],
[ 224, 177, 190 ],
[ 224, 179, 166 ],
[ 224, 179, 167 ],
[ 224, 179, 168 ],
[ 224, 179, 169 ],
[ 224, 179, 170 ],
[ 224, 179, 171 ],
[ 224, 179, 172 ],
[ 224, 179, 173 ],
[ 224, 179, 174 ],
[ 224, 179, 175 ],
[ 224, 181, 166 ],
[ 224, 181, 167 ],
[ 224, 181, 168 ],
[ 224, 181, 169 ],
[ 224, 181, 170 ],
[ 224, 181, 171 ],
[ 224, 181, 172 ],
[ 224, 181, 173 ],
[ 224, 181, 174 ],
[ 224, 181, 175 ],
[ 224, 181, 176 ],
[ 224, 181, 177 ],
[ 224, 181, 178 ],
[ 224, 181, 179 ],
[ 224, 181, 180 ],
[ 224, 181, 181 ],
[ 224, 183, 166 ],
[ 224, 183, 167 ],
[ 224, 183, 168 ],
[ 224, 183, 169 ],
[ 224, 183, 170 ],
[ 224, 183, 171 ],
[ 224, 183, 172 ],
[ 224, 183, 173 ],
[ 224, 183, 174 ],
[ 224, 183, 175 ],
[ 224, 185, 144 ],
[ 224, 185, 145 ],
[ 224, 185, 146 ],
[ 224, 185, 147 ],
[ 224, 185, 148 ],
[ 224, 185, 149 ],
[ 224, 185, 150 ],
[ 224, 185, 151 ],
[ 224, 185, 152 ],
[ 224, 185, 153 ],
[ 224, 187, 144 ],
[ 224, 187, 145 ],
[ 224, 187, 146 ],
[ 224, 187, 147 ],
[ 224, 187, 148 ],
[ 224, 187, 149 ],
[ 224, 187, 150 ],
[ 224, 187, 151 ],
[ 224, 187, 152 ],
[ 224, 187, 153 ],
[ 224, 188, 160 ],
[ 224, 188, 161 ],
[ 224, 188, 162 ],
[ 224, 188, 163 ],
[ 224, 188, 164 ],
[ 224, 188, 165 ],
[ 224, 188, 166 ],
[ 224, 188, 167 ],
[ 224, 188, 168 ],
[ 224, 188, 169 ],
[ 224, 188, 170 ],
[ 224, 188, 171 ],
[ 224, 188, 172 ],
[ 224, 188, 173 ],
[ 224, 188, 174 ],
[ 224, 188, 175 ],
[ 224, 188, 176 ],
[ 224, 188, 177 ],
[ 224, 188, 178 ],
[ 224, 188, 179 ],
[ 225, 129, 128 ],
[ 225, 129, 129 ],
[ 225, 129, 130 ],
[ 225, 129, 131 ],
[ 225, 129, 132 ],
[ 225, 129, 133 ],
[ 225, 129, 134 ],
[ 225, 129, 135 ],
[ 225, 129, 136 ],
[ 225, 129, 137 ],
[ 225, 130, 144 ],
[ 225, 130, 145 ],
[ 225, 130, 146 ],
[ 225, 130, 147 ],
[ 225, 130, 148 ],
[ 225, 130, 149 ],
[ 225, 130, 150 ],
[ 225, 130, 151 ],
[ 225, 130, 152 ],
[ 225, 130, 153 ],
[ 225, 141, 169 ],
[ 225, 141, 170 ],
[ 225, 141, 171 ],
[ 225, 141, 172 ],
[ 225, 141, 173 ],
[ 225, 141, 174 ],
[ 225, 141, 175 ],
[ 225, 141, 176 ],
[ 225, 141, 177 ],
[ 225, 141, 178 ],
[ 225, 141, 179 ],
[ 225, 141, 180 ],
[ 225, 141, 181 ],
[ 225, 141, 182 ],
[ 225, 141, 183 ],
[ 225, 141, 184 ],
[ 225, 141, 185 ],
[ 225, 141, 186 ],
[ 225, 141, 187 ],
[ 225, 141, 188 ],
[ 225, 155, 174 ],
[ 225, 155, 175 ],
[ 225, 155, 176 ],
[ 225, 159, 160 ],
[ 225, 159, 161 ],
[ 225, 159, 162 ],
[ 225, 159, 163 ],
[ 225, 159, 164 ],
[ 225, 159, 165 ],
[ 225, 159, 166 ],
[ 225, 159, 167 ],
[ 225, 159, 168 ],
[ 225, 159, 169 ],
[ 225, 159, 176 ],
[ 225, 159, 177 ],
[ 225, 159, 178 ],
[ 225, 159, 179 ],
[ 225, 159, 180 ],
[ 225, 159, 181 ],
[ 225, 159, 182 ],
[ 225, 159, 183 ],
[ 225, 159, 184 ],
[ 225, 159, 185 ],
[ 225, 160, 144 ],
[ 225, 160, 145 ],
[ 225, 160, 146 ],
[ 225, 160, 147 ],
[ 225, 160, 148 ],
[ 225, 160, 149 ],
[ 225, 160, 150 ],
[ 225, 160, 151 ],
[ 225, 160, 152 ],
[ 225, 160, 153 ],
[ 225, 165, 134 ],
[ 225, 165, 135 ],
[ 225, 165, 136 ],
[ 225, 165, 137 ],
[ 225, 165, 138 ],
[ 225, 165, 139 ],
[ 225, 165, 140 ],
[ 225, 165, 141 ],
[ 225, 165, 142 ],
[ 225, 165, 143 ],
[ 225, 167, 144 ],
[ 225, 167, 145 ],
[ 225, 167, 146 ],
[ 225, 167, 147 ],
[ 225, 167, 148 ],
[ 225, 167, 149 ],
[ 225, 167, 150 ],
[ 225, 167, 151 ],
[ 225, 167, 152 ],
[ 225, 167, 153 ],
[ 225, 167, 154 ],
[ 225, 170, 128 ],
[ 225, 170, 129 ],
[ 225, 170, 130 ],
[ 225, 170, 131 ],
[ 225, 170, 132 ],
[ 225, 170, 133 ],
[ 225, 170, 134 ],
[ 225, 170, 135 ],
[ 225, 170, 136 ],
[ 225, 170, 137 ],
[ 225, 170, 144 ],
[ 225, 170, 145 ],
[ 225, 170, 146 ],
[ 225, 170, 147 ],
[ 225, 170, 148 ],
[ 225, 170, 149 ],
[ 225, 170, 150 ],
[ 225, 170, 151 ],
[ 225, 170, 152 ],
[ 225, 170, 153 ],
[ 225, 173, 144 ],
[ 225, 173, 145 ],
[ 225, 173, 146 ],
[ 225, 173, 147 ],
[ 225, 173, 148 ],
[ 225, 173, 149 ],
[ 225, 173, 150 ],
[ 225, 173, 151 ],
[ 225, 173, 152 ],
[ 225, 173, 153 ],
[ 225, 174, 176 ],
[ 225, 174, 177 ],
[ 225, 174, 178 ],
[ 225, 174, 179 ],
[ 225, 174, 180 ],
[ 225, 174, 181 ],
[ 225, 174, 182 ],
[ 225, 174, 183 ],
[ 225, 174, 184 ],
[ 225, 174, 185 ],
[ 225, 177, 128 ],
[ 225, 177, 129 ],
[ 225, 177, 130 ],
[ 225, 177, 131 ],
[ 225, 177, 132 ],
[ 225, 177, 133 ],
[ 225, 177, 134 ],
[ 225, 177, 135 ],
[ 225, 177, 136 ],
[ 225, 177, 137 ],
[ 225, 177, 144 ],
[ 225, 177, 145 ],
[ 225, 177, 146 ],
[ 225, 177, 147 ],
[ 225, 177, 148 ],
[ 225, 177, 149 ],
[ 225, 177, 150 ],
[ 225, 177, 151 ],
[ 225, 177, 152 ],
[ 225, 177, 153 ],
[ 226, 129, 176 ],
[ 226, 129, 180 ],
[ 226, 129, 181 ],
[ 226, 129, 182 ],
[ 226, 129, 183 ],
[ 226, 129, 184 ],
[ 226, 129, 185 ],
[ 226, 130, 128 ],
[ 226, 130, 129 ],
[ 226, 130, 130 ],
[ 226, 130, 131 ],
[ 226, 130, 132 ],
[ 226, 130, 133 ],
[ 226, 130, 134 ],
[ 226, 130, 135 ],
[ 226, 130, 136 ],
[ 226, 130, 137 ],
[ 226, 133, 144 ],
[ 226, 133, 145 ],
[ 226, 133, 146 ],
[ 226, 133, 147 ],
[ 226, 133, 148 ],
[ 226, 133, 149 ],
[ 226, 133, 150 ],
[ 226, 133, 151 ],
[ 226, 133, 152 ],
[ 226, 133, 153 ],
[ 226, 133, 154 ],
[ 226, 133, 155 ],
[ 226, 133, 156 ],
[ 226, 133, 157 ],
[ 226, 133, 158 ],
[ 226, 133, 159 ],
[ 226, 133, 160 ],
[ 226, 133, 161 ],
[ 226, 133, 162 ],
[ 226, 133, 163 ],
[ 226, 133, 164 ],
[ 226, 133, 165 ],
[ 226, 133, 166 ],
[ 226, 133, 167 ],
[ 226, 133, 168 ],
[ 226, 133, 169 ],
[ 226, 133, 170 ],
[ 226, 133, 171 ],
[ 226, 133, 172 ],
[ 226, 133, 173 ],
[ 226, 133, 174 ],
[ 226, 133, 175 ],
[ 226, 133, 176 ],
[ 226, 133, 177 ],
[ 226, 133, 178 ],
[ 226, 133, 179 ],
[ 226, 133, 180 ],
[ 226, 133, 181 ],
[ 226, 133, 182 ],
[ 226, 133, 183 ],
[ 226, 133, 184 ],
[ 226, 133, 185 ],
[ 226, 133, 186 ],
[ 226, 133, 187 ],
[ 226, 133, 188 ],
[ 226, 133, 189 ],
[ 226, 133, 190 ],
[ 226, 133, 191 ],
[ 226, 134, 128 ],
[ 226, 134, 129 ],
[ 226, 134, 130 ],
[ 226, 134, 133 ],
[ 226, 134, 134 ],
[ 226, 134, 135 ],
[ 226, 134, 136 ],
[ 226, 134, 137 ],
[ 226, 145, 160 ],
[ 226, 145, 161 ],
[ 226, 145, 162 ],
[ 226, 145, 163 ],
[ 226, 145, 164 ],
[ 226, 145, 165 ],
[ 226, 145, 166 ],
[ 226, 145, 167 ],
[ 226, 145, 168 ],
[ 226, 145, 169 ],
[ 226, 145, 170 ],
[ 226, 145, 171 ],
[ 226, 145, 172 ],
[ 226, 145, 173 ],
[ 226, 145, 174 ],
[ 226, 145, 175 ],
[ 226, 145, 176 ],
[ 226, 145, 177 ],
[ 226, 145, 178 ],
[ 226, 145, 179 ],
[ 226, 145, 180 ],
[ 226, 145, 181 ],
[ 226, 145, 182 ],
[ 226, 145, 183 ],
[ 226, 145, 184 ],
[ 226, 145, 185 ],
[ 226, 145, 186 ],
[ 226, 145, 187 ],
[ 226, 145, 188 ],
[ 226, 145, 189 ],
[ 226, 145, 190 ],
[ 226, 145, 191 ],
[ 226, 146, 128 ],
[ 226, 146, 129 ],
[ 226, 146, 130 ],
[ 226, 146, 131 ],
[ 226, 146, 132 ],
[ 226, 146, 133 ],
[ 226, 146, 134 ],
[ 226, 146, 135 ],
[ 226, 146, 136 ],
[ 226, 146, 137 ],
[ 226, 146, 138 ],
[ 226, 146, 139 ],
[ 226, 146, 140 ],
[ 226, 146, 141 ],
[ 226, 146, 142 ],
[ 226, 146, 143 ],
[ 226, 146, 144 ],
[ 226, 146, 145 ],
[ 226, 146, 146 ],
[ 226, 146, 147 ],
[ 226, 146, 148 ],
[ 226, 146, 149 ],
[ 226, 146, 150 ],
[ 226, 146, 151 ],
[ 226, 146, 152 ],
[ 226, 146, 153 ],
[ 226, 146, 154 ],
[ 226, 146, 155 ],
[ 226, 147, 170 ],
[ 226, 147, 171 ],
[ 226, 147, 172 ],
[ 226, 147, 173 ],
[ 226, 147, 174 ],
[ 226, 147, 175 ],
[ 226, 147, 176 ],
[ 226, 147, 177 ],
[ 226, 147, 178 ],
[ 226, 147, 179 ],
[ 226, 147, 180 ],
[ 226, 147, 181 ],
[ 226, 147, 182 ],
[ 226, 147, 183 ],
[ 226, 147, 184 ],
[ 226, 147, 185 ],
[ 226, 147, 186 ],
[ 226, 147, 187 ],
[ 226, 147, 188 ],
[ 226, 147, 189 ],
[ 226, 147, 190 ],
[ 226, 147, 191 ],
[ 226, 157, 182 ],
[ 226, 157, 183 ],
[ 226, 157, 184 ],
[ 226, 157, 185 ],
[ 226, 157, 186 ],
[ 226, 157, 187 ],
[ 226, 157, 188 ],
[ 226, 157, 189 ],
[ 226, 157, 190 ],
[ 226, 157, 191 ],
[ 226, 158, 128 ],
[ 226, 158, 129 ],
[ 226, 158, 130 ],
[ 226, 158, 131 ],
[ 226, 158, 132 ],
[ 226, 158, 133 ],
[ 226, 158, 134 ],
[ 226, 158, 135 ],
[ 226, 158, 136 ],
[ 226, 158, 137 ],
[ 226, 158, 138 ],
[ 226, 158, 139 ],
[ 226, 158, 140 ],
[ 226, 158, 141 ],
[ 226, 158, 142 ],
[ 226, 158, 143 ],
[ 226, 158, 144 ],
[ 226, 158, 145 ],
[ 226, 158, 146 ],
[ 226, 158, 147 ],
[ 226, 179, 189 ],
[ 227, 128, 135 ],
[ 227, 128, 161 ],
[ 227, 128, 162 ],
[ 227, 128, 163 ],
[ 227, 128, 164 ],
[ 227, 128, 165 ],
[ 227, 128, 166 ],
[ 227, 128, 167 ],
[ 227, 128, 168 ],
[ 227, 128, 169 ],
[ 227, 128, 184 ],
[ 227, 128, 185 ],
[ 227, 128, 186 ],
[ 227, 134, 146 ],
[ 227, 134, 147 ],
[ 227, 134, 148 ],
[ 227, 134, 149 ],
[ 227, 136, 160 ],
[ 227, 136, 161 ],
[ 227, 136, 162 ],
[ 227, 136, 163 ],
[ 227, 136, 164 ],
[ 227, 136, 165 ],
[ 227, 136, 166 ],
[ 227, 136, 167 ],
[ 227, 136, 168 ],
[ 227, 136, 169 ],
[ 227, 137, 136 ],
[ 227, 137, 137 ],
[ 227, 137, 138 ],
[ 227, 137, 139 ],
[ 227, 137, 140 ],
[ 227, 137, 141 ],
[ 227, 137, 142 ],
[ 227, 137, 143 ],
[ 227, 137, 145 ],
[ 227, 137, 146 ],
[ 227, 137, 147 ],
[ 227, 137, 148 ],
[ 227, 137, 149 ],
[ 227, 137, 150 ],
[ 227, 137, 151 ],
[ 227, 137, 152 ],
[ 227, 137, 153 ],
[ 227, 137, 154 ],
[ 227, 137, 155 ],
[ 227, 137, 156 ],
[ 227, 137, 157 ],
[ 227, 137, 158 ],
[ 227, 137, 159 ],
[ 227, 138, 128 ],
[ 227, 138, 129 ],
[ 227, 138, 130 ],
[ 227, 138, 131 ],
[ 227, 138, 132 ],
[ 227, 138, 133 ],
[ 227, 138, 134 ],
[ 227, 138, 135 ],
[ 227, 138, 136 ],
[ 227, 138, 137 ],
[ 227, 138, 177 ],
[ 227, 138, 178 ],
[ 227, 138, 179 ],
[ 227, 138, 180 ],
[ 227, 138, 181 ],
[ 227, 138, 182 ],
[ 227, 138, 183 ],
[ 227, 138, 184 ],
[ 227, 138, 185 ],
[ 227, 138, 186 ],
[ 227, 138, 187 ],
[ 227, 138, 188 ],
[ 227, 138, 189 ],
[ 227, 138, 190 ],
[ 227, 138, 191 ],
[ 234, 152, 160 ],
[ 234, 152, 161 ],
[ 234, 152, 162 ],
[ 234, 152, 163 ],
[ 234, 152, 164 ],
[ 234, 152, 165 ],
[ 234, 152, 166 ],
[ 234, 152, 167 ],
[ 234, 152, 168 ],
[ 234, 152, 169 ],
[ 234, 155, 166 ],
[ 234, 155, 167 ],
[ 234, 155, 168 ],
[ 234, 155, 169 ],
[ 234, 155, 170 ],
[ 234, 155, 171 ],
[ 234, 155, 172 ],
[ 234, 155, 173 ],
[ 234, 155, 174 ],
[ 234, 155, 175 ],
[ 234, 160, 176 ],
[ 234, 160, 177 ],
[ 234, 160, 178 ],
[ 234, 160, 179 ],
[ 234, 160, 180 ],
[ 234, 160, 181 ],
[ 234, 163, 144 ],
[ 234, 163, 145 ],
[ 234, 163, 146 ],
[ 234, 163, 147 ],
[ 234, 163, 148 ],
[ 234, 163, 149 ],
[ 234, 163, 150 ],
[ 234, 163, 151 ],
[ 234, 163, 152 ],
[ 234, 163, 153 ],
[ 234, 164, 128 ],
[ 234, 164, 129 ],
[ 234, 164, 130 ],
[ 234, 164, 131 ],
[ 234, 164, 132 ],
[ 234, 164, 133 ],
[ 234, 164, 134 ],
[ 234, 164, 135 ],
[ 234, 164, 136 ],
[ 234, 164, 137 ],
[ 234, 167, 144 ],
[ 234, 167, 145 ],
[ 234, 167, 146 ],
[ 234, 167, 147 ],
[ 234, 167, 148 ],
[ 234, 167, 149 ],
[ 234, 167, 150 ],
[ 234, 167, 151 ],
[ 234, 167, 152 ],
[ 234, 167, 153 ],
[ 234, 167, 176 ],
[ 234, 167, 177 ],
[ 234, 167, 178 ],
[ 234, 167, 179 ],
[ 234, 167, 180 ],
[ 234, 167, 181 ],
[ 234, 167, 182 ],
[ 234, 167, 183 ],
[ 234, 167, 184 ],
[ 234, 167, 185 ],
[ 234, 169, 144 ],
[ 234, 169, 145 ],
[ 234, 169, 146 ],
[ 234, 169, 147 ],
[ 234, 169, 148 ],
[ 234, 169, 149 ],
[ 234, 169, 150 ],
[ 234, 169, 151 ],
[ 234, 169, 152 ],
[ 234, 169, 153 ],
[ 234, 175, 176 ],
[ 234, 175, 177 ],
[ 234, 175, 178 ],
[ 234, 175, 179 ],
[ 234, 175, 180 ],
[ 234, 175, 181 ],
[ 234, 175, 182 ],
[ 234, 175, 183 ],
[ 234, 175, 184 ],
[ 234, 175, 185 ],
[ 239, 188, 144 ],
[ 239, 188, 145 ],
[ 239, 188, 146 ],
[ 239, 188, 147 ],
[ 239, 188, 148 ],
[ 239, 188, 149 ],
[ 239, 188, 150 ],
[ 239, 188, 151 ],
[ 239, 188, 152 ],
[ 239, 188, 153 ],
[ 240, 144, 132, 135 ],
[ 240, 144, 132, 136 ],
[ 240, 144, 132, 137 ],
[ 240, 144, 132, 138 ],
[ 240, 144, 132, 139 ],
[ 240, 144, 132, 140 ],
[ 240, 144, 132, 141 ],
[ 240, 144, 132, 142 ],
[ 240, 144, 132, 143 ],
[ 240, 144, 132, 144 ],
[ 240, 144, 132, 145 ],
[ 240, 144, 132, 146 ],
[ 240, 144, 132, 147 ],
[ 240, 144, 132, 148 ],
[ 240, 144, 132, 149 ],
[ 240, 144, 132, 150 ],
[ 240, 144, 132, 151 ],
[ 240, 144, 132, 152 ],
[ 240, 144, 132, 153 ],
[ 240, 144, 132, 154 ],
[ 240, 144, 132, 155 ],
[ 240, 144, 132, 156 ],
[ 240, 144, 132, 157 ],
[ 240, 144, 132, 158 ],
[ 240, 144, 132, 159 ],
[ 240, 144, 132, 160 ],
[ 240, 144, 132, 161 ],
[ 240, 144, 132, 162 ],
[ 240, 144, 132, 163 ],
[ 240, 144, 132, 164 ],
[ 240, 144, 132, 165 ],
[ 240, 144, 132, 166 ],
[ 240, 144, 132, 167 ],
[ 240, 144, 132, 168 ],
[ 240, 144, 132, 169 ],
[ 240, 144, 132, 170 ],
[ 240, 144, 132, 171 ],
[ 240, 144, 132, 172 ],
[ 240, 144, 132, 173 ],
[ 240, 144, 132, 174 ],
[ 240, 144, 132, 175 ],
[ 240, 144, 132, 176 ],
[ 240, 144, 132, 177 ],
[ 240, 144, 132, 178 ],
[ 240, 144, 132, 179 ],
[ 240, 144, 133, 128 ],
[ 240, 144, 133, 129 ],
[ 240, 144, 133, 130 ],
[ 240, 144, 133, 131 ],
[ 240, 144, 133, 132 ],
[ 240, 144, 133, 133 ],
[ 240, 144, 133, 134 ],
[ 240, 144, 133, 135 ],
[ 240, 144, 133, 136 ],
[ 240, 144, 133, 137 ],
[ 240, 144, 133, 138 ],
[ 240, 144, 133, 139 ],
[ 240, 144, 133, 140 ],
[ 240, 144, 133, 141 ],
[ 240, 144, 133, 142 ],
[ 240, 144, 133, 143 ],
[ 240, 144, 133, 144 ],
[ 240, 144, 133, 145 ],
[ 240, 144, 133, 146 ],
[ 240, 144, 133, 147 ],
[ 240, 144, 133, 148 ],
[ 240, 144, 133, 149 ],
[ 240, 144, 133, 150 ],
[ 240, 144, 133, 151 ],
[ 240, 144, 133, 152 ],
[ 240, 144, 133, 153 ],
[ 240, 144, 133, 154 ],
[ 240, 144, 133, 155 ],
[ 240, 144, 133, 156 ],
[ 240, 144, 133, 157 ],
[ 240, 144, 133, 158 ],
[ 240, 144, 133, 159 ],
[ 240, 144, 133, 160 ],
[ 240, 144, 133, 161 ],
[ 240, 144, 133, 162 ],
[ 240, 144, 133, 163 ],
[ 240, 144, 133, 164 ],
[ 240, 144, 133, 165 ],
[ 240, 144, 133, 166 ],
[ 240, 144, 133, 167 ],
[ 240, 144, 133, 168 ],
[ 240, 144, 133, 169 ],
[ 240, 144, 133, 170 ],
[ 240, 144, 133, 171 ],
[ 240, 144, 133, 172 ],
[ 240, 144, 133, 173 ],
[ 240, 144, 133, 174 ],
[ 240, 144, 133, 175 ],
[ 240, 144, 133, 176 ],
[ 240, 144, 133, 177 ],
[ 240, 144, 133, 178 ],
[ 240, 144, 133, 179 ],
[ 240, 144, 133, 180 ],
[ 240, 144, 133, 181 ],
[ 240, 144, 133, 182 ],
[ 240, 144, 133, 183 ],
[ 240, 144, 133, 184 ],
[ 240, 144, 134, 138 ],
[ 240, 144, 134, 139 ],
[ 240, 144, 139, 161 ],
[ 240, 144, 139, 162 ],
[ 240, 144, 139, 163 ],
[ 240, 144, 139, 164 ],
[ 240, 144, 139, 165 ],
[ 240, 144, 139, 166 ],
[ 240, 144, 139, 167 ],
[ 240, 144, 139, 168 ],
[ 240, 144, 139, 169 ],
[ 240, 144, 139, 170 ],
[ 240, 144, 139, 171 ],
[ 240, 144, 139, 172 ],
[ 240, 144, 139, 173 ],
[ 240, 144, 139, 174 ],
[ 240, 144, 139, 175 ],
[ 240, 144, 139, 176 ],
[ 240, 144, 139, 177 ],
[ 240, 144, 139, 178 ],
[ 240, 144, 139, 179 ],
[ 240, 144, 139, 180 ],
[ 240, 144, 139, 181 ],
[ 240, 144, 139, 182 ],
[ 240, 144, 139, 183 ],
[ 240, 144, 139, 184 ],
[ 240, 144, 139, 185 ],
[ 240, 144, 139, 186 ],
[ 240, 144, 139, 187 ],
[ 240, 144, 140, 160 ],
[ 240, 144, 140, 161 ],
[ 240, 144, 140, 162 ],
[ 240, 144, 140, 163 ],
[ 240, 144, 141, 129 ],
[ 240, 144, 141, 138 ],
[ 240, 144, 143, 145 ],
[ 240, 144, 143, 146 ],
[ 240, 144, 143, 147 ],
[ 240, 144, 143, 148 ],
[ 240, 144, 143, 149 ],
[ 240, 144, 146, 160 ],
[ 240, 144, 146, 161 ],
[ 240, 144, 146, 162 ],
[ 240, 144, 146, 163 ],
[ 240, 144, 146, 164 ],
[ 240, 144, 146, 165 ],
[ 240, 144, 146, 166 ],
[ 240, 144, 146, 167 ],
[ 240, 144, 146, 168 ],
[ 240, 144, 146, 169 ],
[ 240, 144, 161, 152 ],
[ 240, 144, 161, 153 ],
[ 240, 144, 161, 154 ],
[ 240, 144, 161, 155 ],
[ 240, 144, 161, 156 ],
[ 240, 144, 161, 157 ],
[ 240, 144, 161, 158 ],
[ 240, 144, 161, 159 ],
[ 240, 144, 161, 185 ],
[ 240, 144, 161, 186 ],
[ 240, 144, 161, 187 ],
[ 240, 144, 161, 188 ],
[ 240, 144, 161, 189 ],
[ 240, 144, 161, 190 ],
[ 240, 144, 161, 191 ],
[ 240, 144, 162, 167 ],
[ 240, 144, 162, 168 ],
[ 240, 144, 162, 169 ],
[ 240, 144, 162, 170 ],
[ 240, 144, 162, 171 ],
[ 240, 144, 162, 172 ],
[ 240, 144, 162, 173 ],
[ 240, 144, 162, 174 ],
[ 240, 144, 162, 175 ],
[ 240, 144, 163, 187 ],
[ 240, 144, 163, 188 ],
[ 240, 144, 163, 189 ],
[ 240, 144, 163, 190 ],
[ 240, 144, 163, 191 ],
[ 240, 144, 164, 150 ],
[ 240, 144, 164, 151 ],
[ 240, 144, 164, 152 ],
[ 240, 144, 164, 153 ],
[ 240, 144, 164, 154 ],
[ 240, 144, 164, 155 ],
[ 240, 144, 166, 188 ],
[ 240, 144, 166, 189 ],
[ 240, 144, 167, 128 ],
[ 240, 144, 167, 129 ],
[ 240, 144, 167, 130 ],
[ 240, 144, 167, 131 ],
[ 240, 144, 167, 132 ],
[ 240, 144, 167, 133 ],
[ 240, 144, 167, 134 ],
[ 240, 144, 167, 135 ],
[ 240, 144, 167, 136 ],
[ 240, 144, 167, 137 ],
[ 240, 144, 167, 138 ],
[ 240, 144, 167, 139 ],
[ 240, 144, 167, 140 ],
[ 240, 144, 167, 141 ],
[ 240, 144, 167, 142 ],
[ 240, 144, 167, 143 ],
[ 240, 144, 167, 146 ],
[ 240, 144, 167, 147 ],
[ 240, 144, 167, 148 ],
[ 240, 144, 167, 149 ],
[ 240, 144, 167, 150 ],
[ 240, 144, 167, 151 ],
[ 240, 144, 167, 152 ],
[ 240, 144, 167, 153 ],
[ 240, 144, 167, 154 ],
[ 240, 144, 167, 155 ],
[ 240, 144, 167, 156 ],
[ 240, 144, 167, 157 ],
[ 240, 144, 167, 158 ],
[ 240, 144, 167, 159 ],
[ 240, 144, 167, 160 ],
[ 240, 144, 167, 161 ],
[ 240, 144, 167, 162 ],
[ 240, 144, 167, 163 ],
[ 240, 144, 167, 164 ],
[ 240, 144, 167, 165 ],
[ 240, 144, 167, 166 ],
[ 240, 144, 167, 167 ],
[ 240, 144, 167, 168 ],
[ 240, 144, 167, 169 ],
[ 240, 144, 167, 170 ],
[ 240, 144, 167, 171 ],
[ 240, 144, 167, 172 ],
[ 240, 144, 167, 173 ],
[ 240, 144, 167, 174 ],
[ 240, 144, 167, 175 ],
[ 240, 144, 167, 176 ],
[ 240, 144, 167, 177 ],
[ 240, 144, 167, 178 ],
[ 240, 144, 167, 179 ],
[ 240, 144, 167, 180 ],
[ 240, 144, 167, 181 ],
[ 240, 144, 167, 182 ],
[ 240, 144, 167, 183 ],
[ 240, 144, 167, 184 ],
[ 240, 144, 167, 185 ],
[ 240, 144, 167, 186 ],
[ 240, 144, 167, 187 ],
[ 240, 144, 167, 188 ],
[ 240, 144, 167, 189 ],
[ 240, 144, 167, 190 ],
[ 240, 144, 167, 191 ],
[ 240, 144, 169, 128 ],
[ 240, 144, 169, 129 ],
[ 240, 144, 169, 130 ],
[ 240, 144, 169, 131 ],
[ 240, 144, 169, 132 ],
[ 240, 144, 169, 133 ],
[ 240, 144, 169, 134 ],
[ 240, 144, 169, 135 ],
[ 240, 144, 169, 189 ],
[ 240, 144, 169, 190 ],
[ 240, 144, 170, 157 ],
[ 240, 144, 170, 158 ],
[ 240, 144, 170, 159 ],
[ 240, 144, 171, 171 ],
[ 240, 144, 171, 172 ],
[ 240, 144, 171, 173 ],
[ 240, 144, 171, 174 ],
[ 240, 144, 171, 175 ],
[ 240, 144, 173, 152 ],
[ 240, 144, 173, 153 ],
[ 240, 144, 173, 154 ],
[ 240, 144, 173, 155 ],
[ 240, 144, 173, 156 ],
[ 240, 144, 173, 157 ],
[ 240, 144, 173, 158 ],
[ 240, 144, 173, 159 ],
[ 240, 144, 173, 184 ],
[ 240, 144, 173, 185 ],
[ 240, 144, 173, 186 ],
[ 240, 144, 173, 187 ],
[ 240, 144, 173, 188 ],
[ 240, 144, 173, 189 ],
[ 240, 144, 173, 190 ],
[ 240, 144, 173, 191 ],
[ 240, 144, 174, 169 ],
[ 240, 144, 174, 170 ],
[ 240, 144, 174, 171 ],
[ 240, 144, 174, 172 ],
[ 240, 144, 174, 173 ],
[ 240, 144, 174, 174 ],
[ 240, 144, 174, 175 ],
[ 240, 144, 179, 186 ],
[ 240, 144, 179, 187 ],
[ 240, 144, 179, 188 ],
[ 240, 144, 179, 189 ],
[ 240, 144, 179, 190 ],
[ 240, 144, 179, 191 ],
[ 240, 144, 185, 160 ],
[ 240, 144, 185, 161 ],
[ 240, 144, 185, 162 ],
[ 240, 144, 185, 163 ],
[ 240, 144, 185, 164 ],
[ 240, 144, 185, 165 ],
[ 240, 144, 185, 166 ],
[ 240, 144, 185, 167 ],
[ 240, 144, 185, 168 ],
[ 240, 144, 185, 169 ],
[ 240, 144, 185, 170 ],
[ 240, 144, 185, 171 ],
[ 240, 144, 185, 172 ],
[ 240, 144, 185, 173 ],
[ 240, 144, 185, 174 ],
[ 240, 144, 185, 175 ],
[ 240, 144, 185, 176 ],
[ 240, 144, 185, 177 ],
[ 240, 144, 185, 178 ],
[ 240, 144, 185, 179 ],
[ 240, 144, 185, 180 ],
[ 240, 144, 185, 181 ],
[ 240, 144, 185, 182 ],
[ 240, 144, 185, 183 ],
[ 240, 144, 185, 184 ],
[ 240, 144, 185, 185 ],
[ 240, 144, 185, 186 ],
[ 240, 144, 185, 187 ],
[ 240, 144, 185, 188 ],
[ 240, 144, 185, 189 ],
[ 240, 144, 185, 190 ],
[ 240, 145, 129, 146 ],
[ 240, 145, 129, 147 ],
[ 240, 145, 129, 148 ],
[ 240, 145, 129, 149 ],
[ 240, 145, 129, 150 ],
[ 240, 145, 129, 151 ],
[ 240, 145, 129, 152 ],
[ 240, 145, 129, 153 ],
[ 240, 145, 129, 154 ],
[ 240, 145, 129, 155 ],
[ 240, 145, 129, 156 ],
[ 240, 145, 129, 157 ],
[ 240, 145, 129, 158 ],
[ 240, 145, 129, 159 ],
[ 240, 145, 129, 160 ],
[ 240, 145, 129, 161 ],
[ 240, 145, 129, 162 ],
[ 240, 145, 129, 163 ],
[ 240, 145, 129, 164 ],
[ 240, 145, 129, 165 ],
[ 240, 145, 129, 166 ],
[ 240, 145, 129, 167 ],
[ 240, 145, 129, 168 ],
[ 240, 145, 129, 169 ],
[ 240, 145, 129, 170 ],
[ 240, 145, 129, 171 ],
[ 240, 145, 129, 172 ],
[ 240, 145, 129, 173 ],
[ 240, 145, 129, 174 ],
[ 240, 145, 129, 175 ],
[ 240, 145, 131, 176 ],
[ 240, 145, 131, 177 ],
[ 240, 145, 131, 178 ],
[ 240, 145, 131, 179 ],
[ 240, 145, 131, 180 ],
[ 240, 145, 131, 181 ],
[ 240, 145, 131, 182 ],
[ 240, 145, 131, 183 ],
[ 240, 145, 131, 184 ],
[ 240, 145, 131, 185 ],
[ 240, 145, 132, 182 ],
[ 240, 145, 132, 183 ],
[ 240, 145, 132, 184 ],
[ 240, 145, 132, 185 ],
[ 240, 145, 132, 186 ],
[ 240, 145, 132, 187 ],
[ 240, 145, 132, 188 ],
[ 240, 145, 132, 189 ],
[ 240, 145, 132, 190 ],
[ 240, 145, 132, 191 ],
[ 240, 145, 135, 144 ],
[ 240, 145, 135, 145 ],
[ 240, 145, 135, 146 ],
[ 240, 145, 135, 147 ],
[ 240, 145, 135, 148 ],
[ 240, 145, 135, 149 ],
[ 240, 145, 135, 150 ],
[ 240, 145, 135, 151 ],
[ 240, 145, 135, 152 ],
[ 240, 145, 135, 153 ],
[ 240, 145, 135, 161 ],
[ 240, 145, 135, 162 ],
[ 240, 145, 135, 163 ],
[ 240, 145, 135, 164 ],
[ 240, 145, 135, 165 ],
[ 240, 145, 135, 166 ],
[ 240, 145, 135, 167 ],
[ 240, 145, 135, 168 ],
[ 240, 145, 135, 169 ],
[ 240, 145, 135, 170 ],
[ 240, 145, 135, 171 ],
[ 240, 145, 135, 172 ],
[ 240, 145, 135, 173 ],
[ 240, 145, 135, 174 ],
[ 240, 145, 135, 175 ],
[ 240, 145, 135, 176 ],
[ 240, 145, 135, 177 ],
[ 240, 145, 135, 178 ],
[ 240, 145, 135, 179 ],
[ 240, 145, 135, 180 ],
[ 240, 145, 139, 176 ],
[ 240, 145, 139, 177 ],
[ 240, 145, 139, 178 ],
[ 240, 145, 139, 179 ],
[ 240, 145, 139, 180 ],
[ 240, 145, 139, 181 ],
[ 240, 145, 139, 182 ],
[ 240, 145, 139, 183 ],
[ 240, 145, 139, 184 ],
[ 240, 145, 139, 185 ],
[ 240, 145, 147, 144 ],
[ 240, 145, 147, 145 ],
[ 240, 145, 147, 146 ],
[ 240, 145, 147, 147 ],
[ 240, 145, 147, 148 ],
[ 240, 145, 147, 149 ],
[ 240, 145, 147, 150 ],
[ 240, 145, 147, 151 ],
[ 240, 145, 147, 152 ],
[ 240, 145, 147, 153 ],
[ 240, 145, 153, 144 ],
[ 240, 145, 153, 145 ],
[ 240, 145, 153, 146 ],
[ 240, 145, 153, 147 ],
[ 240, 145, 153, 148 ],
[ 240, 145, 153, 149 ],
[ 240, 145, 153, 150 ],
[ 240, 145, 153, 151 ],
[ 240, 145, 153, 152 ],
[ 240, 145, 153, 153 ],
[ 240, 145, 155, 128 ],
[ 240, 145, 155, 129 ],
[ 240, 145, 155, 130 ],
[ 240, 145, 155, 131 ],
[ 240, 145, 155, 132 ],
[ 240, 145, 155, 133 ],
[ 240, 145, 155, 134 ],
[ 240, 145, 155, 135 ],
[ 240, 145, 155, 136 ],
[ 240, 145, 155, 137 ],
[ 240, 145, 156, 176 ],
[ 240, 145, 156, 177 ],
[ 240, 145, 156, 178 ],
[ 240, 145, 156, 179 ],
[ 240, 145, 156, 180 ],
[ 240, 145, 156, 181 ],
[ 240, 145, 156, 182 ],
[ 240, 145, 156, 183 ],
[ 240, 145, 156, 184 ],
[ 240, 145, 156, 185 ],
[ 240, 145, 156, 186 ],
[ 240, 145, 156, 187 ],
[ 240, 145, 163, 160 ],
[ 240, 145, 163, 161 ],
[ 240, 145, 163, 162 ],
[ 240, 145, 163, 163 ],
[ 240, 145, 163, 164 ],
[ 240, 145, 163, 165 ],
[ 240, 145, 163, 166 ],
[ 240, 145, 163, 167 ],
[ 240, 145, 163, 168 ],
[ 240, 145, 163, 169 ],
[ 240, 145, 163, 170 ],
[ 240, 145, 163, 171 ],
[ 240, 145, 163, 172 ],
[ 240, 145, 163, 173 ],
[ 240, 145, 163, 174 ],
[ 240, 145, 163, 175 ],
[ 240, 145, 163, 176 ],
[ 240, 145, 163, 177 ],
[ 240, 145, 163, 178 ],
[ 240, 146, 144, 128 ],
[ 240, 146, 144, 129 ],
[ 240, 146, 144, 130 ],
[ 240, 146, 144, 131 ],
[ 240, 146, 144, 132 ],
[ 240, 146, 144, 133 ],
[ 240, 146, 144, 134 ],
[ 240, 146, 144, 135 ],
[ 240, 146, 144, 136 ],
[ 240, 146, 144, 137 ],
[ 240, 146, 144, 138 ],
[ 240, 146, 144, 139 ],
[ 240, 146, 144, 140 ],
[ 240, 146, 144, 141 ],
[ 240, 146, 144, 142 ],
[ 240, 146, 144, 143 ],
[ 240, 146, 144, 144 ],
[ 240, 146, 144, 145 ],
[ 240, 146, 144, 146 ],
[ 240, 146, 144, 147 ],
[ 240, 146, 144, 148 ],
[ 240, 146, 144, 149 ],
[ 240, 146, 144, 150 ],
[ 240, 146, 144, 151 ],
[ 240, 146, 144, 152 ],
[ 240, 146, 144, 153 ],
[ 240, 146, 144, 154 ],
[ 240, 146, 144, 155 ],
[ 240, 146, 144, 156 ],
[ 240, 146, 144, 157 ],
[ 240, 146, 144, 158 ],
[ 240, 146, 144, 159 ],
[ 240, 146, 144, 160 ],
[ 240, 146, 144, 161 ],
[ 240, 146, 144, 162 ],
[ 240, 146, 144, 163 ],
[ 240, 146, 144, 164 ],
[ 240, 146, 144, 165 ],
[ 240, 146, 144, 166 ],
[ 240, 146, 144, 167 ],
[ 240, 146, 144, 168 ],
[ 240, 146, 144, 169 ],
[ 240, 146, 144, 170 ],
[ 240, 146, 144, 171 ],
[ 240, 146, 144, 172 ],
[ 240, 146, 144, 173 ],
[ 240, 146, 144, 174 ],
[ 240, 146, 144, 175 ],
[ 240, 146, 144, 176 ],
[ 240, 146, 144, 177 ],
[ 240, 146, 144, 178 ],
[ 240, 146, 144, 179 ],
[ 240, 146, 144, 180 ],
[ 240, 146, 144, 181 ],
[ 240, 146, 144, 182 ],
[ 240, 146, 144, 183 ],
[ 240, 146, 144, 184 ],
[ 240, 146, 144, 185 ],
[ 240, 146, 144, 186 ],
[ 240, 146, 144, 187 ],
[ 240, 146, 144, 188 ],
[ 240, 146, 144, 189 ],
[ 240, 146, 144, 190 ],
[ 240, 146, 144, 191 ],
[ 240, 146, 145, 128 ],
[ 240, 146, 145, 129 ],
[ 240, 146, 145, 130 ],
[ 240, 146, 145, 131 ],
[ 240, 146, 145, 132 ],
[ 240, 146, 145, 133 ],
[ 240, 146, 145, 134 ],
[ 240, 146, 145, 135 ],
[ 240, 146, 145, 136 ],
[ 240, 146, 145, 137 ],
[ 240, 146, 145, 138 ],
[ 240, 146, 145, 139 ],
[ 240, 146, 145, 140 ],
[ 240, 146, 145, 141 ],
[ 240, 146, 145, 142 ],
[ 240, 146, 145, 143 ],
[ 240, 146, 145, 144 ],
[ 240, 146, 145, 145 ],
[ 240, 146, 145, 146 ],
[ 240, 146, 145, 147 ],
[ 240, 146, 145, 148 ],
[ 240, 146, 145, 149 ],
[ 240, 146, 145, 150 ],
[ 240, 146, 145, 151 ],
[ 240, 146, 145, 152 ],
[ 240, 146, 145, 153 ],
[ 240, 146, 145, 154 ],
[ 240, 146, 145, 155 ],
[ 240, 146, 145, 156 ],
[ 240, 146, 145, 157 ],
[ 240, 146, 145, 158 ],
[ 240, 146, 145, 159 ],
[ 240, 146, 145, 160 ],
[ 240, 146, 145, 161 ],
[ 240, 146, 145, 162 ],
[ 240, 146, 145, 163 ],
[ 240, 146, 145, 164 ],
[ 240, 146, 145, 165 ],
[ 240, 146, 145, 166 ],
[ 240, 146, 145, 167 ],
[ 240, 146, 145, 168 ],
[ 240, 146, 145, 169 ],
[ 240, 146, 145, 170 ],
[ 240, 146, 145, 171 ],
[ 240, 146, 145, 172 ],
[ 240, 146, 145, 173 ],
[ 240, 146, 145, 174 ],
[ 240, 150, 169, 160 ],
[ 240, 150, 169, 161 ],
[ 240, 150, 169, 162 ],
[ 240, 150, 169, 163 ],
[ 240, 150, 169, 164 ],
[ 240, 150, 169, 165 ],
[ 240, 150, 169, 166 ],
[ 240, 150, 169, 167 ],
[ 240, 150, 169, 168 ],
[ 240, 150, 169, 169 ],
[ 240, 150, 173, 144 ],
[ 240, 150, 173, 145 ],
[ 240, 150, 173, 146 ],
[ 240, 150, 173, 147 ],
[ 240, 150, 173, 148 ],
[ 240, 150, 173, 149 ],
[ 240, 150, 173, 150 ],
[ 240, 150, 173, 151 ],
[ 240, 150, 173, 152 ],
[ 240, 150, 173, 153 ],
[ 240, 150, 173, 155 ],
[ 240, 150, 173, 156 ],
[ 240, 150, 173, 157 ],
[ 240, 150, 173, 158 ],
[ 240, 150, 173, 159 ],
[ 240, 150, 173, 160 ],
[ 240, 150, 173, 161 ],
[ 240, 157, 141, 160 ],
[ 240, 157, 141, 161 ],
[ 240, 157, 141, 162 ],
[ 240, 157, 141, 163 ],
[ 240, 157, 141, 164 ],
[ 240, 157, 141, 165 ],
[ 240, 157, 141, 166 ],
[ 240, 157, 141, 167 ],
[ 240, 157, 141, 168 ],
[ 240, 157, 141, 169 ],
[ 240, 157, 141, 170 ],
[ 240, 157, 141, 171 ],
[ 240, 157, 141, 172 ],
[ 240, 157, 141, 173 ],
[ 240, 157, 141, 174 ],
[ 240, 157, 141, 175 ],
[ 240, 157, 141, 176 ],
[ 240, 157, 141, 177 ],
[ 240, 157, 159, 142 ],
[ 240, 157, 159, 143 ],
[ 240, 157, 159, 144 ],
[ 240, 157, 159, 145 ],
[ 240, 157, 159, 146 ],
[ 240, 157, 159, 147 ],
[ 240, 157, 159, 148 ],
[ 240, 157, 159, 149 ],
[ 240, 157, 159, 150 ],
[ 240, 157, 159, 151 ],
[ 240, 157, 159, 152 ],
[ 240, 157, 159, 153 ],
[ 240, 157, 159, 154 ],
[ 240, 157, 159, 155 ],
[ 240, 157, 159, 156 ],
[ 240, 157, 159, 157 ],
[ 240, 157, 159, 158 ],
[ 240, 157, 159, 159 ],
[ 240, 157, 159, 160 ],
[ 240, 157, 159, 161 ],
[ 240, 157, 159, 162 ],
[ 240, 157, 159, 163 ],
[ 240, 157, 159, 164 ],
[ 240, 157, 159, 165 ],
[ 240, 157, 159, 166 ],
[ 240, 157, 159, 167 ],
[ 240, 157, 159, 168 ],
[ 240, 157, 159, 169 ],
[ 240, 157, 159, 170 ],
[ 240, 157, 159, 171 ],
[ 240, 157, 159, 172 ],
[ 240, 157, 159, 173 ],
[ 240, 157, 159, 174 ],
[ 240, 157, 159, 175 ],
[ 240, 157, 159, 176 ],
[ 240, 157, 159, 177 ],
[ 240, 157, 159, 178 ],
[ 240, 157, 159, 179 ],
[ 240, 157, 159, 180 ],
[ 240, 157, 159, 181 ],
[ 240, 157, 159, 182 ],
[ 240, 157, 159, 183 ],
[ 240, 157, 159, 184 ],
[ 240, 157, 159, 185 ],
[ 240, 157, 159, 186 ],
[ 240, 157, 159, 187 ],
[ 240, 157, 159, 188 ],
[ 240, 157, 159, 189 ],
[ 240, 157, 159, 190 ],
[ 240, 157, 159, 191 ],
[ 240, 158, 163, 135 ],
[ 240, 158, 163, 136 ],
[ 240, 158, 163, 137 ],
[ 240, 158, 163, 138 ],
[ 240, 158, 163, 139 ],
[ 240, 158, 163, 140 ],
[ 240, 158, 163, 141 ],
[ 240, 158, 163, 142 ],
[ 240, 158, 163, 143 ],
[ 240, 159, 132, 128 ],
[ 240, 159, 132, 129 ],
[ 240, 159, 132, 130 ],
[ 240, 159, 132, 131 ],
[ 240, 159, 132, 132 ],
[ 240, 159, 132, 133 ],
[ 240, 159, 132, 134 ],
[ 240, 159, 132, 135 ],
[ 240, 159, 132, 136 ],
[ 240, 159, 132, 137 ],
[ 240, 159, 132, 138 ],
[ 240, 159, 132, 139 ],
[ 240, 159, 132, 140 ] ]
|
python
|
import functools
import time
import argparse
import sys
import asyncio
import cocrawler.burner as burner
import cocrawler.config as config
def burn(dt, data):
t0 = time.clock()
end = t0 + dt
while time.clock() < end:
pass
return 1,
async def work():
while True:
dt, data = await queue.get()
partial = functools.partial(burn, dt, data)
await b.burn(partial)
queue.task_done()
async def crawl():
workers = [asyncio.Task(work(), loop=loop) for _ in range(100)]
await queue.join()
for w in workers:
if not w.done():
w.cancel()
ARGS = argparse.ArgumentParser(description='bench_burn benchmark for burner thread overhead')
ARGS.add_argument('--threads', type=int, default=2)
ARGS.add_argument('--workers', type=int, default=100)
ARGS.add_argument('--datasize', type=int, default=10000)
ARGS.add_argument('--affinity', action='store_true')
ARGS.add_argument('--duration', type=float, default=0.010)
ARGS.add_argument('--count', type=int, default=10000)
args = ARGS.parse_args()
c = {'Multiprocess': {'BurnerThreads': args.threads, 'Affinity': args.affinity}}
config.set_config(c)
loop = asyncio.get_event_loop()
b = burner.Burner('parser')
queue = asyncio.Queue()
for _ in range(args.count):
queue.put_nowait((args.duration, 'x' * args.datasize))
print('args are', args)
print('Processing {} items of size {} kbytes and {:.3f} seconds of burn using {} burner threads'.format(
args.count, int(args.datasize/1000), args.duration, args.threads))
t0 = time.time()
c0 = time.clock()
try:
loop.run_until_complete(crawl())
except KeyboardInterrupt:
sys.stderr.flush()
print('\nInterrupt. Exiting.\n')
finally:
loop.stop()
loop.run_forever()
loop.close()
elapsed = time.time() - t0
print('Elapsed time is {:.1f} seconds.'.format(elapsed))
expected = args.count * args.duration / args.threads
print('Expected is {:.1f} seconds.'.format(expected))
print('Burner-side overhead is {}% or {:.4f} seconds per call'.format(
int((elapsed - expected)/expected*100), (elapsed - expected)/args.count))
celapsed = time.clock() - c0
print('Main-thread overhead is {}%, {:.4f} seconds per call, {} calls per cpu-second'.format(
int(celapsed/elapsed*100), celapsed/args.count, int(args.count/celapsed)))
|
python
|
## Script (Python) "updateProductionStage"
##parameters=sci
# Copy the object in development to review and production.
object = sci.object
st = object.portal_staging
st.updateStages(object, 'dev', ['review', 'prod'],
sci.kwargs.get('comment', ''))
|
python
|
"""
Benchmark Sorted Dictionary Datatypes
"""
import warnings
from .benchmark import *
# Tests.
@register_test
def contains(func, size):
for val in lists[size][::100]:
assert func(val)
@register_test
def getitem(func, size):
for val in lists[size][::100]:
assert func(val) == -val
@register_test
def setitem(func, size):
for val in lists[size][::100]:
func(val, -val)
@register_test
def setitem_existing(func, size):
for val in lists[size][::100]:
func(val, -val)
@register_test
def delitem(func, size):
for val in lists[size][::100]:
func(val)
@register_test
def iter(func, size):
assert all(idx == val for idx, val in enumerate(func()))
# Setups.
def do_nothing(obj, size):
pass
def fill_values(obj, size):
if hasattr(obj, 'update'):
obj.update({val: -val for val in range(size)})
else:
for val in range(size):
obj[val] = -val
# Implementation imports.
from .context import sortedcontainers
from sortedcontainers import SortedDict
kinds['SortedDict'] = SortedDict
try:
from rbtree import rbtree
kinds['rbtree'] = rbtree
except ImportError:
warnings.warn('No module named rbtree', ImportWarning)
try:
from blist import sorteddict
kinds['blist.sorteddict'] = sorteddict
except ImportError:
warnings.warn('No module named blist', ImportWarning)
try:
from treap import treap
kinds['treap'] = treap
except ImportError:
warnings.warn('No module named treap', ImportWarning)
try:
from bintrees import FastAVLTree, FastRBTree
kinds['FastAVLTree'] = FastAVLTree
kinds['FastRBTree'] = FastRBTree
except ImportError:
warnings.warn('No module named bintrees', ImportWarning)
try:
from skiplistcollections import SkipListDict
kinds['SkipListDict'] = SkipListDict
except ImportError:
warnings.warn('No module named skiplistcollections', ImportWarning)
try:
from banyan import SortedDict as BanyanSortedDict
kinds['banyan.SortedDict'] = BanyanSortedDict
except ImportError:
warnings.warn('No module named banyan', ImportWarning)
# Implementation configuration.
for name in tests:
impls[name] = OrderedDict()
for name, kind in kinds.items():
impls['contains'][name] = {
'setup': fill_values,
'ctor': kind,
'func': '__contains__',
'limit': 1000000
}
if 'treap' in impls['contains']:
del impls['contains']['treap']
for name, kind in kinds.items():
impls['getitem'][name] = {
'setup': fill_values,
'ctor': kind,
'func': '__getitem__',
'limit': 1000000
}
for name, kind in kinds.items():
impls['setitem'][name] = {
'setup': do_nothing,
'ctor': kind,
'func': '__setitem__',
'limit': 1000000
}
for name, kind in kinds.items():
impls['setitem_existing'][name] = {
'setup': fill_values,
'ctor': kind,
'func': '__setitem__',
'limit': 1000000
}
for name, kind in kinds.items():
impls['delitem'][name] = {
'setup': fill_values,
'ctor': kind,
'func': '__delitem__',
'limit': 1000000
}
for name, kind in kinds.items():
impls['iter'][name] = {
'setup': fill_values,
'ctor': kind,
'func': '__iter__',
'limit': 1000000
}
if __name__ == '__main__':
main('SortedDict')
|
python
|
import sys
import salt.client.ssh
import salt.utils.parsers
class SaltSSH(salt.utils.parsers.SaltSSHOptionParser):
"""
Used to Execute the salt ssh routine
"""
def run(self):
if "-H" in sys.argv or "--hosts" in sys.argv:
sys.argv += ["x", "x"] # Hack: pass a mandatory two options
# that won't be used anyways with -H or --hosts
self.parse_args()
ssh = salt.client.ssh.SSH(self.config)
ssh.run()
|
python
|
import os
import importlib
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ohlc
# from matplotlib.finance import volume_overlay
import matplotlib.ticker as ticker
from catalyst.exchange.exchange_bundle import ExchangeBundle
from catalyst.exchange.exchange_bcolz import BcolzExchangeBarReader
from catalyst.exchange.bundle_utils import get_df_from_arrays, get_bcolz_chunk
from catalyst.exchange.factory import get_exchange
EXCHANGE_NAMES = ['bitfinex', 'bittrex', 'poloniex']
exchanges = dict((e, getattr(importlib.import_module(
'catalyst.exchange.{0}.{0}'.format(e)), e.capitalize()))
for e in EXCHANGE_NAMES)
class ValidateChunks(object):
def __init__(self):
self.columns = ['open', 'high', 'low', 'close', 'volume']
def chunk_to_df(self, exchange_name, symbol, data_frequency, period):
exchange = get_exchange(exchange_name)
asset = exchange.get_asset(symbol)
filename = get_bcolz_chunk(
exchange_name=exchange_name,
symbol=symbol,
data_frequency=data_frequency,
period=period
)
reader = BcolzExchangeBarReader(rootdir=filename,
data_frequency=data_frequency)
# metadata = BcolzMinuteBarMetadata.read(filename)
start = reader.first_trading_day
end = reader.last_available_dt
if data_frequency == 'daily':
end = end - pd.Timedelta(hours=23, minutes=59)
print(start, end, data_frequency)
arrays = reader.load_raw_arrays(self.columns, start, end,
[asset.sid, ])
bundle = ExchangeBundle(exchange_name)
periods = bundle.get_calendar_periods_range(
start, end, data_frequency
)
return get_df_from_arrays(arrays, periods)
def plot_ohlcv(self, df):
fig, ax = plt.subplots()
# Plot the candlestick
candlestick2_ohlc(ax, df['open'], df['high'], df['low'], df['close'],
width=1, colorup='g', colordown='r', alpha=0.5)
# shift y-limits of the candlestick plot so that there is space
# at the bottom for the volume bar chart
pad = 0.25
yl = ax.get_ylim()
ax.set_ylim(yl[0] - (yl[1] - yl[0]) * pad, yl[1])
# Add a seconds axis for the volume overlay
ax2 = ax.twinx()
ax2.set_position(
matplotlib.transforms.Bbox([[0.125, 0.1], [0.9, 0.26]]))
# Plot the volume overlay
# bc = volume_overlay(ax2, df['open'], df['close'], df['volume'],
# colorup='g', alpha=0.5, width=1)
ax.xaxis.set_major_locator(ticker.MaxNLocator(6))
def mydate(x, pos):
try:
return df.index[int(x)]
except IndexError:
return ''
ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
plt.margins(0)
plt.show()
def plot(self, filename):
df = self.chunk_to_df(filename)
self.plot_ohlcv(df)
def to_csv(self, filename):
df = self.chunk_to_df(filename)
df.to_csv(os.path.basename(filename).split('.')[0] + '.csv')
v = ValidateChunks()
df = v.chunk_to_df(
exchange_name='bitfinex',
symbol='eth_btc',
data_frequency='daily',
period='2016'
)
print(df.tail())
v.plot_ohlcv(df)
# v.plot(
# ex
# )
|
python
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Atmosphere container base class definitions
Created on Wed Nov 16 16:37:03 2016
@author: maxwell
"""
from collections import MutableMapping
import numpy as np
from . import constants
from .readprof import readprof, readprof_ozone
class Atmosphere(MutableMapping):
"""
Dict-like container for atmosphere array variables.
Keeps temperature, pressure, height, ozone and humidity.
"""
#minimum allowable water vapor mixing ratio
_qmin = 3.0e-6
#bounds for where to look for tropopause
_ttl_pmax = 400.0
_ttl_pmin = 5.0
_tmin = 100
_tmax = 375
_mcclathcydir = 'atmosphere/profiles/mcclatchy'
def __init__(self, gridstagger=None, plev=None,**kwargs):
"""
Define available keys and set defaults.
Note that we require to know if the grid is staggered, and if we should
treat RH or q as static. None of the other variables will be checked
for consistency, so it is up to the user to make sure that all of the
variables have the right dimensionality and units. It is recommended
that all vectors be numpy arrays.
vars:
plev (hPa) pressure
tlev (K) temperature
qlev (g/g) water vapor mixing ratio
rhlev (0<=x<=1) relative humididty
o3lev (g/g) ozone mass mixing ratio
"""
print("Initializing Atmosphere object")
#check that the grid is well defined
if gridstagger is None:
estr = "{} class requires (bool) gridstagger input."
raise ValueError(estr.format(self.__class__.__name__))
if plev is None:
estr = "{} class requires ndarray plev input."
raise ValueError(estr.format(self.__class__.__name__))
self.gridstagger = gridstagger
self.plev = plev
self.nlev = len(plev)
self.nlay = self.nlev-1
#we need at least some kind of moisture
self.qlev = kwargs.get('qlev', None)
self.rhlev = kwargs.get('rhlev', None)
self.holdrh = kwargs.get('holdrh', None)
#optional, we will provide defaults
self.tlev = kwargs.get('tlev', None)
self.o3lev = kwargs.get('o3lev', None)
#T defaults to isothermal
if (self.tlev is None):
self.tlev = 288.0*np.ones(len(self.plev))
print("WARNING: T not provided, default to mean isothermal value.")
# assign moisture vars with sanity checks
if (self.qlev is None and self.rhlev is None):
self.qlev = np.zeros(len(self.plev))
self.rhlev = np.zeros(len(self.plev))
print("WARNING: moisture not provided, default to 0.")
userh = False
elif (self.qlev is None and self.rhlev is not None):
print("WARNING: q not provided. Setting based on RH.")
self.rhlev = self._enforece_rh_range(self.rhlev)
self.qlev = self._enforce_q_gradient(
self._rh2q(self.plev, self.tlev, self.rhlev)
)
userh = True
elif (self.qlev is not None and self.rhlev is None):
print("WARNING: RH not provided. Seting based on q.")
self.qlev = self._enforce_q_gradient(self.qlev)
self.rhlev = self._q2rh(self.plev, self.tlev, self.qlev)
userh = False
else:
userh = True
self.qlev = self._enforce_q_gradient(self.qlev)
self.rhlev = self._enforce_rh_range(self.rhlev)
if(self.holdrh is None):
self.holdrh = userh
print(
"WARNING: holdrh not provided, setting to {0}".format(userh))
#o3 defaults to 0
if (self.o3lev is None):
self.o3lev = np.zeros(len(self.plev))
print("WARNING: ozone not provided, default to 0.")
#define layer tags
self.play = 0.5*(plev[:-1] + plev[1:])
self.tlay = self._lev2lay(self.plev,self.tlev, self.play)
self.o3lay = self._lev2lay(self.plev, self.o3lev, self.play)
self.qlay = self._lev2lay(self.plev, self.qlev, self.play)
self.rhlay = self._lev2lay(self.plev, self.rhlev, self.play)
tsfc = kwargs.get('tsfc', None)
if (tsfc is None):
print("WARNING: tsfc not provided. Using tlev[-1].")
tsfc = self.tlev[-1]
self.tsfc = tsfc
self._p_z()
self._updatecoldpoint()
self._updatewarmpoint()
self._updatewv()
# %%dict-like behavior
def __setitem__(self, key, value=None,):
if (key == 'plev' or key == 'play' or key == 'p' or
key == 'zlev' or key == 'zlay' or key == 'z'):
err = "{cls} object doesn't support changing value of {key}."
raise TypeError(
err.format(cls=self.__class__.__name__, key=key)
)
if self.__contains__(key):
self.__dict__[key] = value
else:
raise KeyError ("'{0}' not found in collection".format(key))
def __getitem__(self, key):
return self.__dict__[key]
def __delitem__(self,key):
raise TypeError ("{cls} object doesn't support item deletion"
.format(cls=self.__class__.__name__))
def __iter__(self):
return self.__dict__.__iter__()
def __len__(self):
if (self.gridstagger):
return self.nlay
else:
return self.nlev
def __contains__(self,key):
return self.__dict__.__contains__(key)
# %% alternate constructors
@classmethod
def mcclatchy(cls, prof,gridstagger=None,p=None,holdrh=None, **kwargs):
"""
Alternate constructor using a McClatchy standard profile.
"""
keys = ['plev', 'tlev', 'qlev', 'o3lev']
prof = ''.join(['/'.join([cls._mcclathcydir,prof]),'.lay'])
#if any column vars are provided, we will use them as defaults here
t = kwargs.pop('tlev',None)
q = kwargs.pop('qlev', None)
o3 = kwargs.pop('o3lev', None)
print("Initializing {cls} object from file {f}.".format(
cls=cls.__name__, f=prof))
try:
(ps,ts,qs,o3s) = readprof(prof)
except FileNotFoundError:
raise FileNotFoundError(
"File {prof} does not exist".format(prof=prof) )
if (p is None):
print("WARNING:: pressure levels not provided. "
"Using default McClatchy values. ")
p = ps
else:
print("{}: interpolating to provided grid".format(
cls.__name__)
)
if t is None: t = cls.interp(ps,ts,p)
if q is None: q = cls.interp(ps,qs,p)
if o3 is None: o3 = cls.interp(ps,o3s,p)
defaults = dict(zip(keys, [p,t,q,o3]))
if gridstagger is None:
print("WARNING: gridstagger not provided for Atmosphere()."
,"Setting to True"
)
gridstagger = True
return cls(gridstagger=gridstagger,holdrh=holdrh,**defaults,**kwargs)
@classmethod
def fromfile(cls, fname, gridstagger=None, p=None, holdrh=None, **kwargs):
"""
Alternate constructor using any standard profile from file.
"""
keys = ['plev', 'tlev', 'qlev', 'o3lev']
#if any column vars are provided, we will use them as defaults here
t = kwargs.pop('tlev',None)
q = kwargs.pop('qlev', None)
o3 = kwargs.pop('o3lev', None)
print("Initializing {cls} object from file {f}.".format(
cls=cls.__name__, f=fname))
try:
(ps,ts,qs,o3s) = readprof(fname)
except FileNotFoundError:
raise FileNotFoundError(
"File {prof} does not exist".format(prof=fname) )
if (p is None):
print("WARNING:: pressure levels not provided. "
"Using default McClatchy values. ")
p = ps
else:
print("{}: interpolating to provided grid".format(
cls.__name__)
)
if t is None: t = cls.interp(ps,ts,p)
if q is None: q = cls.interp(ps,qs,p)
if o3 is None: o3 = cls.interp(ps,o3s,p)
defaults = dict(zip(keys, [p,t,q,o3]))
if gridstagger is None:
print("WARNING: gridstagger not provided for Atmosphere()."
,"Setting to True"
)
gridstagger = True
return cls(gridstagger=gridstagger,holdrh=holdrh,**defaults,**kwargs)
def ozone_fromfile(self, fname):
"""
setter method to set ozone from a text file directly.
"""
print('Attempt to read ozone profile from file:{f}'.format(
f=fname))
try:
ps, o3s = readprof_ozone(fname)
except FileNotFoundError:
raise FileNotFoundError(
"File {prof} does not exist".format(prof=fname) )
self.o3 = np.maximum(self.interp(ps, o3s, self.p),0)
# %% interpolation
@staticmethod
def _findvalue(x,xq):
"""
Find equal or larger value in array with at least one index to left.
Array lookup should be sorted in ascending order.
"""
L,R = int(1), int(len(x)-1)
while L < R:
M = int((L+R)/2)
if xq > x[M]:
L = M+1
elif xq < x[M]:
R = M
else:
return M
return R
@classmethod
def interp(cls,x,y,xq):
"""
Interpolate linearly with extrapolation when out of range.
Expects xq to be a vector (i.e., numpy 1D array).
"""
yq = np.empty(len(xq)) #yq needs to be same type as xq
for iout,target in enumerate(xq):
idx = cls._findvalue(x,target)
f = (target-x[idx-1])/(x[idx]-x[idx-1])
yq[iout] = (1-f)*y[idx-1] + f*y[idx]
return yq
@classmethod
def _lev2lay(cls,plev,xlev,play):
"""Move Level vars to layers"""
return cls.interp(plev, xlev, play)
@classmethod #remake so that it takes generic arguments and returns a vecotr
def _lay2lev(cls,play,xlay,plev):
"""Move Layer vars to levels"""
return cls.interp(play,xlay,plev)
def updategrid(self):
"""
Interpolate temperature to all levels/layers. Spread WV variables too.
"""
if(self.gridstagger):
self['tlev'] = self._lay2lev(
self['play'], self['tlay'], self['plev']
)
self['qlev'] = self._lay2lev(
self['play'], self['qlay'], self['plev']
)
self['rhlev'] = self._lay2lev(
self['play'], self['rhlay'], self['plev']
)
self['o3lev'] = self._lay2lev(
self['play'], self['o3lay'], self['plev']
)
else:
self['tlay'] = self._lev2lay(
self['plev'], self['tlev'], self['play']
)
self['qlay'] = self._lev2lay(
self['plev'], self['qlev'], self['play']
)
self['rhlay'] = self._lev2lay(
self['plev'], self['rhlev'], self['play']
)
self['o3lay'] = self._lay2lev(
self['plev'], self['o3lev'], self['play']
)
self._updatewv()
self._p_z()
self._updatecoldpoint()
self._updatewarmpoint()
# %% moisture
@staticmethod
def satvap(temp):
"""
Saturation Vapor pressure (Goff and Gratch, 1946)
Temp is the temperature in Kelvins and may be a numpy array
"""
ttrans = 0 #253.15
tsteam = 373.16
tice= 273.16
#choose water or ice saturation
loge = np.where(temp>=ttrans,
(-7.90298*(tsteam/temp-1) + 5.02808*np.log10(tsteam/temp)
-1.3816e-7 * (10**(11.344*(1-temp/tsteam))-1)
+8.1328e-3 * (10**(-3.49149*(tsteam/temp-1))-1)
+np.log10(1013.25)
),
(-9.09718*(tice/temp-1) - 3.56654*np.log10(tice/temp)
-0.876793*(1-temp/tice) + np.log10(6.1173)
) )
return 10**loge
@classmethod
def satmixrat(cls,pres,temp):
"""Saturation mixing ratio"""
return constants.eps*cls.satvap(temp)/pres
@classmethod
def _q2rh(cls, p,t,q):
"""
Convert mixing ratio to relative humidity.
Assumes that the grid pressure is equivalent to the dry pressure.
"""
return q/cls.satmixrat(p,t)
@classmethod
def _rh2q(cls, p,t,rh):
"""
Convert RH to mixing ratio and enforce minimum values for q.
Also enforces the vertical gradient of q such that q can never increase
with height.
"""
return rh*cls.satmixrat(p,t)
@classmethod
def _enforce_q_gradient(cls, q):
"""Ensure q decrease with height"""
q[-1] = np.maximum(q[-1], cls._qmin)
for i in np.arange(len(q)-1,0,-1):
q[i-1] = np.maximum(np.minimum(q[i], q[i-1]), cls._qmin)
return q
@classmethod
def _enforce_rh_range(cls,rh):
rh = np.maximum(0.0, np.minimum(1.0, rh))
return rh
def _updatewv(self):
"""Spread water vapor from rh to q or vice-versa as grid specifies."""
if(self.holdrh):
self.qlev = self._enforce_q_gradient(
self._rh2q(self.plev,self.tlev,self.rhlev)
)
self.qlay = self._enforce_q_gradient(
self._rh2q(self.play,self.tlay,self.rhlay)
)
else:
self.rhlev = self._enforce_rh_range(
self._q2rh(self.plev, self.tlev, self.qlev)
)
self.rhlay = self._enforce_rh_range(
self._q2rh(self.play, self.tlay, self.qlay)
)
# %% height-related methods
def _p_z(self):
tv = self.tlay*(1 + (1-1/constants.eps)*self.qlay)
dz = ( (constants.Rd/constants.grav)
*np.log(self.plev[1:]/self.plev[:-1]) * tv )
zlev = np.zeros(len(self.plev))
zlev[1:] = np.cumsum(dz[::-1])
self.zlev = zlev[::-1]
self.zlay = self._lev2lay(
self.plev, self.zlev, self.play)
#%% get cold point and conv. top
def _updatecoldpoint(self):
mask = np.logical_and(
self.p <= self._ttl_pmax, self.p >= self._ttl_pmin)
icold_point = np.argmin(np.where(mask, self.t, 99999))
self._icold_point = icold_point
def _updatewarmpoint(self):
mask = self.p >= self._ttl_pmax
iwarm_point = np.argmax(np.where(mask, self.t, -99999))
self._iwarm_point = iwarm_point
# %% property variables for more obvious getting and setting
def _checkvar(self, value):
if len(self) != len(value):
raise ValueError(
"Length of array provided does not match the target dimension"
)
@property
def t(self):
if (self.gridstagger):
return self.tlay
else:
return self.tlev
@t.setter
def t(self, value):
self._checkvar(value)
if(self.gridstagger):
self.tlay = np.minimum(np.maximum(value,self._tmin),self._tmax)
else:
self.tlev = np.minimum(np.maximum(value,self._tmin),self._tmax)
self.updategrid()
@property
def tsfc(self):
return self._tsfc
@tsfc.setter
def tsfc(self,value):
self._tsfc = np.minimum(np.maximum(value,self._tmin), self._tmax)
@property
def q(self):
if (self.gridstagger):
return self.qlay
else:
return self.qlev
@q.setter
def q(self,value):
self._checkvar(value)
if (self.holdrh):
print(
"WARNING: holdrh set to True, but setting q directly. "
"Value will be overwritten."
)
if (self.gridstagger):
self.qlay = value
else:
self.qlev = value
self.updategrid()
@property
def rh(self):
if (self.gridstagger):
return self.rhlay
else:
return self.rhlev
@rh.setter
def rh(self,value):
self._checkvar(value)
if (not self.holdrh):
print(
"WARNING: holdrh set to False, but setting RH directly. "
"Value will be overwritten."
)
if(self.gridstagger):
self.rhlay = value
else:
self.rhlev = value
self.updategrid()
@property
def o3(self):
if(self.gridstagger):
return self.o3lay
else:
return self.o3lev
@o3.setter
def o3(self, value):
self._checkvar(value)
if(self.gridstagger):
self.o3lay = value
else:
self.o3lev = value
self.updategrid()
@property
def p(self):
if(self.gridstagger):
return self.play
else:
return self.plev
@property
def z(self):
if(self.gridstagger):
return self.zlay
else:
return self.zlev
@property
def tcold(self):
return self.t[self.icold]
@property
def pcold(self):
return self.p[self.icold]
@property
def zcold(self):
return self.z[self.icold]
@property
def icold(self):
return self._icold_point
@property
def tconv(self):
return self.t[self.iconv]
@property
def pconv(self):
return self.p[self.iconv]
@property
def zconv(self):
return self.z[self.iconv]
#although icold is calculated internally, not all atmospheres will need a
# convective top(iconv). Provide a setter method so that external objects
# can include this functionality if desired.
@property
def iconv(self):
try:
return self._iconv_top
except AttributeError:
msg = ("WARNING: attempt to access undefined _iconv_top. Using "
"cold point 'icold' instead")
print(msg)
return self.icold
@iconv.setter
def iconv(self, value):
self._iconv_top = value
@property
def twarm(self):
return self.t[self.iwarm]
@property
def pwarm(self):
return self.p[self.iwarm]
@property
def iwarm(self):
return self._iwarm_point
|
python
|
# -*- coding:utf-8 -*-
#autor -> manoel vilela
#gerando graficos em relação a eficiencia dos algoritmos de ordenação bubble, merge and personal
import pylab
def extract_data(file_name):
data = open(file_name, "r").read().split()
data = [element.split() for element in data.split("=")]
vector, values = data
|
python
|
import graphene
from django.db.models import F, Q
from tabletop.models import DurationType, Game
from tabletop.schema import GameNode
from tabletop.utils.graphene import optimize_queryset
class Query(object):
games = graphene.List(
GameNode,
id=graphene.UUID(),
query=graphene.String(),
players=graphene.Int(),
entity=graphene.UUID(),
max_duration=graphene.Int(),
parent=graphene.UUID(),
)
def resolve_games(
self,
info,
id: str = None,
query: str = None,
parent: str = None,
players: int = None,
entity: str = None,
max_duration: int = None,
):
# TODO(dcramer): fix optimize_queryset so it handles the OneToOne join automatically
qs = Game.objects.select_related("image").distinct()
if id:
qs = qs.filter(id=id)
if parent:
qs = qs.filter(parent=parent)
if query:
qs = qs.filter(name__istartswith=query)
if entity:
qs = qs.filter(entities=entity)
if players:
qs = qs.filter(min_players__lte=players, max_players__gte=players)
if max_duration:
qs = qs.filter(
Q(duration__lte=max_duration, duration_type=DurationType.total)
| Q(
duration__lte=max_duration
/ (players if players else F("max_players")),
duration_type=DurationType.per_player,
)
)
qs = optimize_queryset(qs, info, "games", GameNode.fix_queryset)
return qs.order_by("name")
|
python
|
#General imports====================================
from html.parser import HTMLParser
from urllib import parse
#Finds all anchor <a> tags in a website============
class LinkFinder(HTMLParser):
def __init__(self, base_url, page_url):
super().__init__()
self.base_url = base_url
self.page_url = page_url
self.links = set()
def handle_starttag(self, tag, attrs):
if tag == 'a':
for (attribute, value) in attrs:
if attribute == 'href':
url = parse.urljoin(self.base_url, value)
self.links.add(url)
def page_links(self):
return self.links
def error(self, message):
pass
|
python
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2017 Ganggao Zhu- Grupo de Sistemas Inteligentes
# gzhu[at]dit.upm.es
# DIT, UPM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from gensim import corpora, models, similarities, matutils
class TextAnalysis:
"""This implements wrapper for gensim lsa and tfidf analysis of text collection"""
def __init__(self, text_process, model, dictionary, tfidf, tfidf_index, lsa, lsa_index):
self._text_process = text_process
self._model = model
self._dictionary = dictionary
self._tfidf = tfidf
self._tfidf_index = tfidf_index
self._lsa = lsa
self._lsa_index = lsa_index
def text2model(self, text):
t = self._text_process(text)
bow = self._dictionary.doc2bow(t)
tfidf = self._tfidf[bow]
if self._model == 'tfidf':
return tfidf
else:
return self._lsa[tfidf]
def text_similarity(self, t1, t2):
if self._model == 'tfidf':
t1_vec = matutils.any2sparse(self.text2model(t1))
t2_vec = matutils.any2sparse(self.text2model(t2))
return matutils.cossim(t1_vec, t2_vec)
else:
t1_vec = matutils.any2sparse(self.text2model(t1))
t2_vec = matutils.any2sparse(self.text2model(t2))
return matutils.cossim(t1_vec, t2_vec)
def search(self, text):
query = self.text2model(text)
if self._model == 'tfidf':
return self._tfidf_index[query]
else:
return self._lsa_index[query]
@classmethod
def load(cls, text_process, model='tfidf', top_N=100, save_dir='data/'):
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
dictionary = corpora.Dictionary.load(save_dir+'dictionary')
tfidf = models.TfidfModel.load(save_dir+'tfidf.model')
tfidf_index = similarities.Similarity.load(save_dir+'tfidf_index/tfidf.index')
tfidf_index.num_best = top_N
if model == 'lsa':
lsa = models.LsiModel.load(save_dir+'lsa.model')
lsa_index = similarities.Similarity.load(save_dir+'lsa_index/lsa.index')
lsa_index.num_best = top_N
return cls(text_process, model, dictionary, tfidf, tfidf_index, lsa, lsa_index)
return cls(text_process, model, dictionary, tfidf, tfidf_index, None, None)
@classmethod
def train(cls, texts, text_process, model='lsa', topic_n=100, top_N=100, save_dir='data/'):
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
corpus = [text_process(t) for t in texts]
dictionary = corpora.Dictionary(corpus)
print(dictionary)
dictionary.save(save_dir+'dictionary')
bow = [dictionary.doc2bow(t) for t in corpus]
corpora.MmCorpus.serialize(save_dir+'bow', bow)
bow_corpus = corpora.MmCorpus(save_dir+'bow')
tfidf = models.TfidfModel(bow_corpus, id2word=dictionary)
corpora.MmCorpus.serialize(save_dir+'tfidf', tfidf[bow_corpus])
tfidf.save(save_dir+'tfidf.model')
tfidf_corpus = corpora.MmCorpus(save_dir+'tfidf')
tfidf_index = similarities.Similarity(save_dir+'tfidf_index/shard', tfidf_corpus, num_features=tfidf_corpus.num_terms)
tfidf_index.num_best = top_N
tfidf_index.save(save_dir+'tfidf_index/tfidf.index')
if model == 'lsa':
lsa = models.LsiModel(tfidf_corpus, id2word=dictionary, num_topics=topic_n)
lsa.save(save_dir+'lsa.model')
lsa_index = similarities.Similarity(save_dir+'lsa_index/shard', lsa[tfidf_corpus], num_features=topic_n)
lsa_index.num_best = top_N
lsa_index.save(save_dir+'lsa_index/lsa.index')
return cls(text_process, model, dictionary, tfidf, tfidf_index, lsa, lsa_index)
return cls(text_process, model, dictionary, tfidf, tfidf_index, None, None)
|
python
|
"""
MIT License
Copyright (c) 2020-2021 Hyeonki Hong <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import numpy as np
import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Input
from tensorflow.keras.optimizers import Adam
from .dataset.keras_sequence import YOLODataset # for exporting
from .model import YOLOv4Model
from .training.callbacks import (
SaveWeightsCallback, # for exporting
YOLOCallbackAtEachStep,
)
from .training.yolo_loss import YOLOv4Loss
from .utils.mAP import create_mAP_input_files # for exporting
from .utils.tflite import save_as_tflite # for expoerting
from .utils.weights import (
load_weights as _load_weights,
save_weights as _save_weights,
)
from ..common.base_class import BaseClass
physical_devices = tf.config.experimental.list_physical_devices("GPU")
if len(physical_devices) > 0:
tf.config.experimental.set_memory_growth(physical_devices[0], True)
print("Call tf.config.experimental.set_memory_growth(GPU0, True)")
class YOLOv4(BaseClass):
@property
def model(self) -> YOLOv4Model:
return self._model
def make_model(self):
K.clear_session()
_input = Input(self.config.net.input_shape)
self._model = YOLOv4Model(config=self.config)
self._model(_input)
def load_weights(self, weights_path: str, weights_type: str = "tf"):
"""
Usage:
yolo.load_weights("checkpoints")
yolo.load_weights("yolov4.weights", weights_type="yolo")
"""
if weights_type == "yolo":
_load_weights(self._model, weights_path)
elif weights_type == "tf":
self._model.load_weights(weights_path)
def save_weights(
self, weights_path: str, weights_type: str = "tf", to: int = 0
):
"""
Usage:
yolo.save_weights("checkpoints")
yolo.save_weights("yolov4.weights", weights_type="yolo")
yolo.save_weights("yolov4.conv.137", weights_type="yolo", to=137)
"""
to_layer = ""
if to > 0:
to_layer = self.config.metalayers[to - 1].name
if weights_type == "yolo":
_save_weights(self._model, weights_path, to=to_layer)
elif weights_type == "tf":
self._model.save_weights(weights_path)
def summary(self, line_length=90, summary_type: str = "tf", **kwargs):
if summary_type == "tf":
self._model.summary(line_length=line_length, **kwargs)
else:
self.config.summary()
#############
# Inference #
#############
@tf.function
def _predict(self, x):
yolos = self._model(x, training=False)
# [yolo0, yolo1, ...]
# yolo == Dim(batch, height, width, channels)
batch = yolos[0].shape[0]
candidates = []
stride = 5 + self.config.yolo_0.classes
for yolo in yolos:
candidates.append(K.reshape(yolo, shape=(batch, -1, stride)))
return K.concatenate(candidates, axis=1)
def predict(self, frame: np.ndarray):
"""
Predict one frame
@param frame: Dim(height, width, channels)
@return pred_bboxes
Dim(-1, (x,y,w,h,o, cls_id0, prob0, cls_id1, prob1))
"""
# image_data == Dim(1, input_size[1], input_size[0], channels)
height, width, _ = frame.shape
image_data = self.resize_image(frame)
image_data = image_data / 255.0
image_data = image_data[np.newaxis, ...].astype(np.float32)
candidates = self._predict(image_data)[0].numpy()
# Select 0
pred_bboxes = self.yolo_diou_nms(
candidates=candidates, beta_nms=self.config.yolo_0.beta_nms
)
self.fit_to_original(pred_bboxes, height, width)
return pred_bboxes
############
# Training #
############
def compile(
self,
optimizer=None,
loss=None,
**kwargs,
):
if optimizer is None:
optimizer = Adam(learning_rate=self.config.net.learning_rate)
if loss is None:
loss = YOLOv4Loss(config=self.config, model=self.model)
return self._model.compile(
optimizer=optimizer,
loss=loss,
**kwargs,
)
def fit(
self,
dataset,
callbacks=None,
validation_data=None,
validation_steps=None,
verbose: int = 3,
**kwargs,
):
"""
verbose=3 is one line per step
"""
callbacks = callbacks or []
callbacks.append(
YOLOCallbackAtEachStep(config=self.config, verbose=verbose)
)
epochs = self.config.net.max_batches // len(dataset) + 1
return self._model.fit(
dataset,
epochs=epochs,
verbose=verbose if verbose < 3 else 0,
callbacks=callbacks,
validation_data=validation_data,
validation_steps=validation_steps,
**kwargs,
)
|
python
|
"""Command line tools for Flask server app."""
from os import environ
from uuid import UUID
from flask_script import Manager
from flask_migrate import MigrateCommand, upgrade
from app import create_app, db
from app.mongo import drop_mongo_collections
from app.authentication.models import User, PasswordAuthentication, OrganizationMembership
from app.samples.sample_models import Sample
from app.sample_groups.sample_group_models import SampleGroup
app = create_app()
manager = Manager(app) # pylint: disable=invalid-name
manager.add_command('db', MigrateCommand)
# These must be imported AFTER Mongo connection has been established during app creation
# pylint: disable=wrong-import-position
from seed import create_abrf_analysis_result as create_abrf_result
from seed.fuzz import generate_metadata, create_saved_group
# pylint: enable=wrong-import-position
@manager.command
def recreate_db():
"""Recreate a database using migrations."""
# We cannot simply use db.drop_all() because it will not drop the alembic_versions table
sql = 'SELECT \
\'drop table if exists "\' || tablename || \'" cascade;\' as pg_drop \
FROM \
pg_tables \
WHERE \
schemaname=\'public\';'
drop_statements = db.engine.execute(sql)
if drop_statements.rowcount > 0:
drop_statement = '\n'.join([x['pg_drop'] for x in drop_statements])
drop_statements.close()
db.engine.execute(drop_statement)
# Run migrations
upgrade()
# Empty Mongo database
drop_mongo_collections()
def get_user():
"""Get the password from env vars or a default."""
username = environ.get('SEED_USER_USERNAME', 'bchrobot')
email = environ.get('SEED_USER_EMAIL', '[email protected]')
password = environ.get('SEED_USER_PASSWORD', 'Foobar22')
new_user = User(
username=username,
email=email,
user_type='user',
)
new_user.password_authentication = PasswordAuthentication(password=password)
return new_user
@manager.command
def seed_users():
"""Seed just the users for the database."""
db.session.add(get_user())
db.session.commit()
@manager.command
def seed_db():
"""Seed the database."""
default_user = get_user()
# Create Mason Lab
mason_lab = User(
username='MasonLab',
email='[email protected]',
user_type='organization',
)
membership = OrganizationMembership(role='admin')
membership.user = default_user
mason_lab.user_memberships.append(membership)
db.session.add_all([mason_lab, membership])
db.session.commit()
# Create ABRF sample group
abrf_uuid = UUID('00000000-0000-4000-8000-000000000000')
abrf_description = 'ABRF San Diego Mar 24th-29th 2017'
abrf_2017_group = SampleGroup(name='ABRF 2017',
owner_uuid=mason_lab.uuid,
owner_name=mason_lab.username,
is_library=True,
analysis_result=create_abrf_result(save=True),
description=abrf_description)
abrf_2017_group.uuid = abrf_uuid
abrf_sample_01 = Sample(name='SomethingUnique_A',
library_uuid=abrf_uuid,
analysis_result=create_abrf_result(save=True),
metadata=generate_metadata()).save()
abrf_sample_02 = Sample(name='SomethingUnique_B',
library_uuid=abrf_uuid,
analysis_result=create_abrf_result(save=True),
metadata=generate_metadata()).save()
abrf_2017_group.samples = [abrf_sample_01, abrf_sample_02]
db.session.add(abrf_2017_group)
db.session.commit()
# Create fuzzed group
fuzz_uuid = UUID('00000000-0000-4000-8000-000000000001')
create_saved_group(owner=mason_lab, uuid=fuzz_uuid)
if __name__ == '__main__':
manager.run()
|
python
|
import torch
from transformers import BertTokenizerFast
from colbert.modeling.tokenization.utils import _split_into_batches, _sort_by_length
class DocTokenizer():
def __init__(self, doc_maxlen):
self.tok = BertTokenizerFast.from_pretrained('bert-base-uncased')
self.doc_maxlen = doc_maxlen
self.D_marker_token, self.D_marker_token_id = '[D]', self.tok.get_vocab()['[unused1]']
self.cls_token, self.cls_token_id = self.tok.cls_token, self.tok.cls_token_id
self.sep_token, self.sep_token_id = self.tok.sep_token, self.tok.sep_token_id
assert self.D_marker_token_id == 2
def tokenize(self, batch_text, add_special_tokens=False):
assert type(batch_text) in [list, tuple], (type(batch_text))
tokens = [self.tok.tokenize(x, add_special_tokens=False) for x in batch_text]
if not add_special_tokens:
return tokens
prefix, suffix = [self.cls_token, self.D_marker_token], [self.sep_token]
tokens = [prefix + lst + suffix for lst in tokens]
return tokens
def encode(self, batch_text, add_special_tokens=False):
assert type(batch_text) in [list, tuple], (type(batch_text))
ids = self.tok(batch_text, add_special_tokens=False)['input_ids']
if not add_special_tokens:
return ids
prefix, suffix = [self.cls_token_id, self.D_marker_token_id], [self.sep_token_id]
ids = [prefix + lst + suffix for lst in ids]
return ids
def tensorize(self, batch_text, bsize=None):
assert type(batch_text) in [list, tuple], (type(batch_text))
# add placehold for the [D] marker
batch_text = ['. ' + x for x in batch_text]
obj = self.tok(batch_text, padding='longest', truncation='longest_first',
return_tensors='pt', max_length=self.doc_maxlen)
ids, mask = obj['input_ids'], obj['attention_mask']
# postprocess for the [D] marker
ids[:, 1] = self.D_marker_token_id
if bsize:
ids, mask, reverse_indices = _sort_by_length(ids, mask, bsize)
batches = _split_into_batches(ids, mask, bsize)
return batches, reverse_indices
return ids, mask
|
python
|
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For further information on the license, see the LICENSE.txt file #
# For further information please visit http://www.aiida.net #
###########################################################################
import numpy
_default_epsilon_length = 1e-5
_default_epsilon_angle = 1e-5
def change_reference(reciprocal_cell, kpoints, to_cartesian=True):
"""
Change reference system, from cartesian to crystal coordinates (units of b1,b2,b3) or viceversa.
:param reciprocal_cell: a 3x3 array representing the cell lattice vectors in reciprocal space
:param kpoints: a list of (3) point coordinates
:return kpoints: a list of (3) point coordinates in the new reference
"""
if not isinstance(kpoints, numpy.ndarray):
raise ValueError('kpoints must be a numpy.array')
transposed_cell = numpy.transpose(numpy.array(reciprocal_cell))
if to_cartesian:
matrix = transposed_cell
else:
matrix = numpy.linalg.inv(transposed_cell)
# note: kpoints is a list Nx3, matrix is 3x3.
# hence, first transpose kpoints, then multiply, finally transpose it back
return numpy.transpose(numpy.dot(matrix, numpy.transpose(kpoints)))
def analyze_cell(cell=None, pbc=None):
"""
A function executed by the __init__ or by set_cell.
If a cell is set, properties like a1, a2, a3, cosalpha, reciprocal_cell are
set as well, although they are not stored in the DB.
:note: units are Angstrom for the cell parameters, 1/Angstrom for the
reciprocal cell parameters.
"""
if pbc is None:
pbc = [True, True, True]
dimension = sum(pbc)
if cell is None:
return {
'reciprocal_cell': None,
'dimension': dimension,
'pbc': pbc
}
the_cell = numpy.array(cell)
reciprocal_cell = 2. * numpy.pi * numpy.linalg.inv(the_cell).transpose()
a1 = numpy.array(the_cell[0, :]) # units = Angstrom
a2 = numpy.array(the_cell[1, :]) # units = Angstrom
a3 = numpy.array(the_cell[2, :]) # units = Angstrom
a = numpy.linalg.norm(a1) # units = Angstrom
b = numpy.linalg.norm(a2) # units = Angstrom
c = numpy.linalg.norm(a3) # units = Angstrom
b1 = reciprocal_cell[0, :] # units = 1/Angstrom
b2 = reciprocal_cell[1, :] # units = 1/Angstrom
b3 = reciprocal_cell[2, :] # units = 1/Angstrom
cosalpha = numpy.dot(a2, a3) / b / c
cosbeta = numpy.dot(a3, a1) / c / a
cosgamma = numpy.dot(a1, a2) / a / b
result = {
'a1': a1,
'a2': a2,
'a3': a3,
'a': a,
'b': b,
'c': c,
'b1': b1,
'b2': b2,
'b3': b3,
'cosalpha': cosalpha,
'cosbeta': cosbeta,
'cosgamma': cosgamma,
'dimension': dimension,
'reciprocal_cell': reciprocal_cell,
'pbc': pbc,
}
return result
def get_explicit_kpoints_path(value=None, cell=None, pbc=None, kpoint_distance=None, cartesian=False,
epsilon_length=_default_epsilon_length,
epsilon_angle=_default_epsilon_angle):
"""
Set a path of kpoints in the Brillouin zone.
:param value: description of the path, in various possible formats.
None: automatically sets all irreducible high symmetry paths.
Requires that a cell was set
or::
[('G','M'), (...), ...]
[('G','M',30), (...), ...]
[('G',(0,0,0),'M',(1,1,1)), (...), ...]
[('G',(0,0,0),'M',(1,1,1),30), (...), ...]
:param cell: 3x3 array representing the structure cell lattice vectors
:param pbc: 3-dimensional array of booleans signifying the periodic boundary
conditions along each lattice vector
:param float kpoint_distance: parameter controlling the distance between
kpoints. Distance is given in crystal coordinates, i.e. the distance
is computed in the space of b1,b2,b3. The distance set will be the
closest possible to this value, compatible with the requirement of
putting equispaced points between two special points (since extrema
are included).
:param bool cartesian: if set to true, reads the coordinates eventually
passed in value as cartesian coordinates. Default: False.
:param float epsilon_length: threshold on lengths comparison, used
to get the bravais lattice info. It has to be used if the
user wants to be sure the right symmetries are recognized.
:param float epsilon_angle: threshold on angles comparison, used
to get the bravais lattice info. It has to be used if the
user wants to be sure the right symmetries are recognized.
:returns: point_coordinates, path, bravais_info, explicit_kpoints, labels
"""
bravais_info = find_bravais_info(
cell=cell, pbc=pbc,
epsilon_length=epsilon_length,
epsilon_angle=epsilon_angle
)
analysis = analyze_cell(cell, pbc)
dimension = analysis['dimension']
reciprocal_cell = analysis['reciprocal_cell']
pbc = list(analysis['pbc'])
if dimension == 0:
# case with zero dimension: only gamma-point is set
return [[0., 0., 0.]], None, bravais_info
def _is_path_1(path):
try:
are_two = all([len(i) == 2 for i in path])
if not are_two:
return False
for i in path:
are_str = all([isinstance(b, str) for b in i])
if not are_str:
return False
except IndexError:
return False
return True
def _is_path_2(path):
try:
are_three = all([len(i) == 3 for i in path])
if not are_three:
return False
are_good = all([all([isinstance(b[0], str),
isinstance(b[1], str),
isinstance(b[2], int)])
for b in path])
if not are_good:
return False
# check that at least two points per segment (beginning and end)
points_num = [int(i[2]) for i in path]
if any([i < 2 for i in points_num]):
raise ValueError('Must set at least two points per path '
'segment')
except IndexError:
return False
return True
def _is_path_3(path):
# [('G',(0,0,0),'M',(1,1,1)), (...), ...]
try:
_ = len(path)
are_four = all([len(i) == 4 for i in path])
if not are_four:
return False
have_labels = all(all([isinstance(i[0], str), isinstance(i[2], str)]) for i in path)
if not have_labels:
return False
for i in path:
coord1 = [float(j) for j in i[1]]
coord2 = [float(j) for j in i[3]]
if len(coord1) != 3 or len(coord2) != 3:
return False
except (TypeError, IndexError):
return False
return True
def _is_path_4(path):
# [('G',(0,0,0),'M',(1,1,1),30), (...), ...]
try:
_ = len(path)
are_five = all([len(i) == 5 for i in path])
if not are_five:
return False
have_labels = all(all([isinstance(i[0], str), isinstance(i[2], str)]) for i in path)
if not have_labels:
return False
have_points_num = all([isinstance(i[4], int) for i in path])
if not have_points_num:
return False
# check that at least two points per segment (beginning and end)
points_num = [int(i[4]) for i in path]
if any([i < 2 for i in points_num]):
raise ValueError('Must set at least two points per path '
'segment')
for i in path:
coord1 = [float(j) for j in i[1]]
coord2 = [float(j) for j in i[3]]
if len(coord1) != 3 or len(coord2) != 3:
return False
except (TypeError, IndexError):
return False
return True
def _num_points_from_coordinates(path, point_coordinates, kpoint_distance=None):
# NOTE: this way of creating intervals ensures equispaced objects
# in crystal coordinates of b1,b2,b3
distances = [numpy.linalg.norm(numpy.array(point_coordinates[i[0]]) -
numpy.array(point_coordinates[i[1]])
) for i in path]
if kpoint_distance is None:
# Use max_points_per_interval as the default guess for automatically
# guessing the number of points
max_point_per_interval = 10
max_interval = max(distances)
try:
points_per_piece = [max(2, max_point_per_interval * i // max_interval) for i in distances]
except ValueError:
raise ValueError('The beginning and end of each segment in the '
'path should be different.')
else:
points_per_piece = [max(2, int(distance // kpoint_distance)) for distance in distances]
return points_per_piece
if cartesian:
if cell is None:
raise ValueError('To use cartesian coordinates, a cell must '
'be provided')
if kpoint_distance is not None:
if kpoint_distance <= 0.:
raise ValueError('kpoints_distance must be a positive float')
if value is None:
if cell is None:
raise ValueError('Cannot set a path not even knowing the '
'kpoints or at least the cell')
point_coordinates, path, bravais_info = get_kpoints_path(
cell=cell, pbc=pbc, cartesian=cartesian,
epsilon_length=epsilon_length,
epsilon_angle=epsilon_angle)
num_points = _num_points_from_coordinates(path, point_coordinates, kpoint_distance)
elif _is_path_1(value):
# in the form [('X','M'),(...),...]
if cell is None:
raise ValueError('Cannot set a path not even knowing the '
'kpoints or at least the cell')
path = value
point_coordinates, _, bravais_info = get_kpoints_path(
cell=cell, pbc=pbc, cartesian=cartesian,
epsilon_length=epsilon_length,
epsilon_angle=epsilon_angle)
num_points = _num_points_from_coordinates(path, point_coordinates, kpoint_distance)
elif _is_path_2(value):
# [('G','M',30), (...), ...]
if cell is None:
raise ValueError('Cannot set a path not even knowing the '
'kpoints or at least the cell')
path = [(i[0], i[1]) for i in value]
point_coordinates, _, bravais_info = get_kpoints_path(
cell=cell, pbc=pbc, cartesian=cartesian,
epsilon_length=epsilon_length,
epsilon_angle=epsilon_angle)
num_points = [i[2] for i in value]
elif _is_path_3(value):
# [('G',(0,0,0),'M',(1,1,1)), (...), ...]
path = [(i[0], i[2]) for i in value]
point_coordinates = {}
for piece in value:
if piece[0] in point_coordinates:
if point_coordinates[piece[0]] != piece[1]:
raise ValueError('Different points cannot have the same label')
else:
if cartesian:
point_coordinates[piece[0]] = change_reference(
reciprocal_cell,
numpy.array([piece[1]]),
to_cartesian=False)[0]
else:
point_coordinates[piece[0]] = piece[1]
if piece[2] in point_coordinates:
if point_coordinates[piece[2]] != piece[3]:
raise ValueError('Different points cannot have the same label')
else:
if cartesian:
point_coordinates[piece[2]] = change_reference(
reciprocal_cell,
numpy.array([piece[3]]),
to_cartesian=False)[0]
else:
point_coordinates[piece[2]] = piece[3]
num_points = _num_points_from_coordinates(path, point_coordinates, kpoint_distance)
elif _is_path_4(value):
# [('G',(0,0,0),'M',(1,1,1),30), (...), ...]
path = [(i[0], i[2]) for i in value]
point_coordinates = {}
for piece in value:
if piece[0] in point_coordinates:
if point_coordinates[piece[0]] != piece[1]:
raise ValueError('Different points cannot have the same label')
else:
if cartesian:
point_coordinates[piece[0]] = change_reference(
reciprocal_cell,
numpy.array([piece[1]]),
to_cartesian=False)[0]
else:
point_coordinates[piece[0]] = piece[1]
if piece[2] in point_coordinates:
if point_coordinates[piece[2]] != piece[3]:
raise ValueError('Different points cannot have the same label')
else:
if cartesian:
point_coordinates[piece[2]] = change_reference(
reciprocal_cell,
numpy.array([piece[3]]),
to_cartesian=False)[0]
else:
point_coordinates[piece[2]] = piece[3]
num_points = [i[4] for i in value]
else:
raise ValueError('Input format not recognized')
explicit_kpoints = [tuple(point_coordinates[path[0][0]])]
labels = [(0, path[0][0])]
for count_piece, i in enumerate(path):
ini_label = i[0]
end_label = i[1]
ini_coord = point_coordinates[ini_label]
end_coord = point_coordinates[end_label]
path_piece = list(zip(numpy.linspace(ini_coord[0], end_coord[0],
num_points[count_piece]),
numpy.linspace(ini_coord[1], end_coord[1],
num_points[count_piece]),
numpy.linspace(ini_coord[2], end_coord[2],
num_points[count_piece]),
))
for count, j in enumerate(path_piece):
if all(numpy.array(explicit_kpoints[-1]) == j):
continue # avoid duplcates
else:
explicit_kpoints.append(j)
# add labels for the first and last point
if count == 0:
labels.append((len(explicit_kpoints) - 1, ini_label))
if count == len(path_piece) - 1:
labels.append((len(explicit_kpoints) - 1, end_label))
# I still have some duplicates in the labels: eliminate them
sorted(set(labels), key=lambda x: x[0])
return point_coordinates, path, bravais_info, explicit_kpoints, labels
def find_bravais_info(cell, pbc, epsilon_length=_default_epsilon_length,
epsilon_angle=_default_epsilon_angle):
"""
Finds the Bravais lattice of the cell passed in input to the Kpoint class
:note: We assume that the cell given by the cell property is the
primitive unit cell.
.. note:: in 3D, this implementation expects
that the structure is already standardized according to the Setyawan
paper. If this is not the case, the kpoints and band structure returned will be incorrect. The only case
that is dealt correctly by the library is the case when axes are swapped, where the library correctly
takes this swapping/rotation into account to assign kpoint labels and coordinates.
:param cell: 3x3 array representing the structure cell lattice vectors
:param pbc: 3-dimensional array of booleans signifying the periodic boundary
conditions along each lattice vector
passed in value as cartesian coordinates. Default: False.
:param float epsilon_length: threshold on lengths comparison, used
to get the bravais lattice info. It has to be used if the
user wants to be sure the right symmetries are recognized.
:param float epsilon_angle: threshold on angles comparison, used
to get the bravais lattice info. It has to be used if the
user wants to be sure the right symmetries are recognized.
:return: a dictionary, with keys short_name, extended_name, index
(index of the Bravais lattice), and sometimes variation (name of
the variation of the Bravais lattice) and extra (a dictionary
with extra parameters used by the get_kpoints_path method)
"""
if cell is None:
return None
analysis = analyze_cell(cell, pbc)
a1 = analysis['a1']
a2 = analysis['a2']
a3 = analysis['a3']
a = analysis['a']
b = analysis['b']
c = analysis['c']
cosa = analysis['cosalpha']
cosb = analysis['cosbeta']
cosc = analysis['cosgamma']
dimension = analysis['dimension']
pbc = list(pbc)
# values of cosines at various angles
_90 = 0.
_60 = 0.5
_30 = numpy.sqrt(3.) / 2.
_120 = -0.5
# NOTE: in what follows, I'm assuming the textbook order of alfa, beta and gamma
# TODO: Maybe additional checks to see if the "correct" primitive
# cell is used ? (there are other equivalent primitive
# unit cells to the one expected here, typically for body-, c-, and
# face-centered lattices)
def l_are_equals(a, b):
# function to compare lengths
return abs(a - b) <= epsilon_length
def a_are_equals(a, b):
# function to compare angles (actually, cosines)
return abs(a - b) <= epsilon_angle
if dimension == 3:
# =========================================#
# 3D case -> 14 possible Bravais lattices #
# =========================================#
comparison_length = [l_are_equals(a, b), l_are_equals(b, c),
l_are_equals(c, a)]
comparison_angles = [a_are_equals(cosa, cosb), a_are_equals(cosb, cosc),
a_are_equals(cosc, cosa)]
if comparison_length.count(True) == 3:
# needed for the body centered orthorhombic:
orci_a = numpy.linalg.norm(a2 + a3)
orci_b = numpy.linalg.norm(a1 + a3)
orci_c = numpy.linalg.norm(a1 + a2)
orci_the_a, orci_the_b, orci_the_c = sorted([orci_a, orci_b, orci_c])
bco1 = - (-orci_the_a ** 2 + orci_the_b ** 2 + orci_the_c ** 2) / (4. * a ** 2)
bco2 = - (orci_the_a ** 2 - orci_the_b ** 2 + orci_the_c ** 2) / (4. * a ** 2)
bco3 = - (orci_the_a ** 2 + orci_the_b ** 2 - orci_the_c ** 2) / (4. * a ** 2)
# ======================#
# simple cubic lattice #
# ======================#
if comparison_angles.count(True) == 3 and a_are_equals(cosa, _90):
bravais_info = {'short_name': 'cub',
'extended_name': 'cubic',
'index': 1,
'permutation': [0, 1, 2]
}
# =====================#
# face centered cubic #
# =====================#
elif comparison_angles.count(True) == 3 and a_are_equals(cosa, _60):
bravais_info = {'short_name': 'fcc',
'extended_name': 'face centered cubic',
'index': 2,
'permutation': [0, 1, 2]
}
# =====================#
# body centered cubic #
# =====================#
elif comparison_angles.count(True) == 3 and a_are_equals(cosa, -1. / 3.):
bravais_info = {'short_name': 'bcc',
'extended_name': 'body centered cubic',
'index': 3,
'permutation': [0, 1, 2]
}
# ==============#
# rhombohedral #
# ==============#
elif comparison_angles.count(True) == 3:
# logical order is important, this check must come after the cubic cases
bravais_info = {'short_name': 'rhl',
'extended_name': 'rhombohedral',
'index': 11,
'permutation': [0, 1, 2]
}
if cosa > 0.:
bravais_info['variation'] = 'rhl1'
eta = (1. + 4. * cosa) / (2. + 4. * cosa)
bravais_info['extra'] = {'eta': eta,
'nu': 0.75 - eta / 2.,
}
else:
bravais_info['variation'] = 'rhl2'
eta = 1. / (2. * (1. - cosa) / (1. + cosa))
bravais_info['extra'] = {'eta': eta,
'nu': 0.75 - eta / 2.,
}
# ==========================#
# body centered tetragonal #
# ==========================#
elif comparison_angles.count(True) == 1: # two angles are the same
bravais_info = {'short_name': 'bct',
'extended_name': 'body centered tetragonal',
'index': 5,
}
if comparison_angles.index(True) == 0: # alfa=beta
ref_ang = cosa
bravais_info['permutation'] = [0, 1, 2]
elif comparison_angles.index(True) == 1: # beta=gamma
ref_ang = cosb
bravais_info['permutation'] = [2, 0, 1]
else: # comparison_angles.index(True)==2: # gamma = alfa
ref_ang = cosc
bravais_info['permutation'] = [1, 2, 0]
if ref_ang >= 0.:
raise ValueError('Problems on the definition of '
'body centered tetragonal lattices')
the_c = numpy.sqrt(-4. * ref_ang * (a ** 2))
the_a = numpy.sqrt(2. * a ** 2 - (the_c ** 2) / 2.)
if the_c < the_a:
bravais_info['variation'] = 'bct1'
bravais_info['extra'] = {'eta': (1. + (the_c / the_a) ** 2) / 4.}
else:
bravais_info['variation'] = 'bct2'
bravais_info['extra'] = {'eta': (1. + (the_a / the_c) ** 2) / 4.,
'csi': ((the_a / the_c) ** 2) / 2.,
}
# ============================#
# body centered orthorhombic #
# ============================#
elif (any([a_are_equals(cosa, bco1), a_are_equals(cosb, bco1), a_are_equals(cosc, bco1)]) and
any([a_are_equals(cosa, bco2), a_are_equals(cosb, bco2), a_are_equals(cosc, bco2)]) and
any([a_are_equals(cosa, bco3), a_are_equals(cosb, bco3), a_are_equals(cosc, bco3)])
):
bravais_info = {'short_name': 'orci',
'extended_name': 'body centered orthorhombic',
'index': 8,
}
if a_are_equals(cosa, bco1) and a_are_equals(cosc, bco3):
bravais_info['permutation'] = [0, 1, 2]
if a_are_equals(cosa, bco1) and a_are_equals(cosc, bco2):
bravais_info['permutation'] = [0, 2, 1]
if a_are_equals(cosa, bco3) and a_are_equals(cosc, bco2):
bravais_info['permutation'] = [1, 2, 0]
if a_are_equals(cosa, bco2) and a_are_equals(cosc, bco3):
bravais_info['permutation'] = [1, 0, 2]
if a_are_equals(cosa, bco2) and a_are_equals(cosc, bco1):
bravais_info['permutation'] = [2, 0, 1]
if a_are_equals(cosa, bco3) and a_are_equals(cosc, bco1):
bravais_info['permutation'] = [2, 1, 0]
bravais_info['extra'] = {'csi': (1. + (orci_the_a / orci_the_c) ** 2) / 4.,
'eta': (1. + (orci_the_b / orci_the_c) ** 2) / 4.,
'dlt': (orci_the_b ** 2 - orci_the_a ** 2) / (4. * orci_the_c ** 2),
'mu': (orci_the_a ** 2 + orci_the_b ** 2) / (4. * orci_the_c ** 2),
}
# if it doesn't fall in the above, is triclinic
else:
bravais_info = {'short_name': 'tri',
'extended_name': 'triclinic',
'index': 14,
}
# the check for triclinic variations is at the end of the method
elif comparison_length.count(True) == 1:
# ============#
# tetragonal #
# ============#
if comparison_angles.count(True) == 3 and a_are_equals(cosa, _90):
bravais_info = {'short_name': 'tet',
'extended_name': 'tetragonal',
'index': 4,
}
if comparison_length[0] == True:
bravais_info['permutation'] = [0, 1, 2]
if comparison_length[1] == True:
bravais_info['permutation'] = [2, 0, 1]
if comparison_length[2] == True:
bravais_info['permutation'] = [1, 2, 0]
# ====================================#
# c-centered orthorombic + hexagonal #
# ====================================#
# alpha/=beta=gamma=pi/2
elif (comparison_angles.count(True) == 1 and
any([a_are_equals(cosa, _90), a_are_equals(cosb, _90), a_are_equals(cosc, _90)])
):
if any([a_are_equals(cosa, _120), a_are_equals(cosb, _120), a_are_equals(cosc, _120)]):
bravais_info = {'short_name': 'hex',
'extended_name': 'hexagonal',
'index': 10,
}
else:
bravais_info = {'short_name': 'orcc',
'extended_name': 'c-centered orthorhombic',
'index': 9,
}
if comparison_length[0] == True:
the_a1 = a1
the_a2 = a2
elif comparison_length[1] == True:
the_a1 = a2
the_a2 = a3
else: # comparison_length[2]==True:
the_a1 = a3
the_a2 = a1
the_a = numpy.linalg.norm(the_a1 + the_a2)
the_b = numpy.linalg.norm(the_a1 - the_a2)
bravais_info['extra'] = {'csi': (1. + (the_a / the_b) ** 2) / 4.,
}
# TODO : re-check this case, permutations look weird
if comparison_length[0] == True:
bravais_info['permutation'] = [0, 1, 2]
if comparison_length[1] == True:
bravais_info['permutation'] = [2, 0, 1]
if comparison_length[2] == True:
bravais_info['permutation'] = [1, 2, 0]
# =======================#
# c-centered monoclinic #
# =======================#
elif comparison_angles.count(True) == 1:
bravais_info = {'short_name': 'mclc',
'extended_name': 'c-centered monoclinic',
'index': 13,
}
# TODO : re-check this case, permutations look weird
if comparison_length[0] == True:
bravais_info['permutation'] = [0, 1, 2]
the_ka = cosa
the_a1 = a1
the_a2 = a2
the_c = c
if comparison_length[1] == True:
bravais_info['permutation'] = [2, 0, 1]
the_ka = cosb
the_a1 = a2
the_a2 = a3
the_c = a
if comparison_length[2] == True:
bravais_info['permutation'] = [1, 2, 0]
the_ka = cosc
the_a1 = a3
the_a2 = a1
the_c = b
the_b = numpy.linalg.norm(the_a1 + the_a2)
the_a = numpy.linalg.norm(the_a1 - the_a2)
the_cosa = 2. * numpy.linalg.norm(the_a1) / the_b * the_ka
if a_are_equals(the_ka, _90): # order matters: has to be before the check on mclc1
bravais_info['variation'] = 'mclc2'
csi = (2. - the_b * the_cosa / the_c) / (4. * (1. - the_cosa ** 2))
psi = 0.75 - the_a ** 2 / (4. * the_b * (1. - the_cosa ** 2))
bravais_info['extra'] = {'csi': csi,
'eta': 0.5 + 2. * csi * the_c * the_cosa / the_b,
'psi': psi,
'phi': psi + (0.75 - psi) * the_b * the_cosa / the_c,
}
elif the_ka < 0.:
bravais_info['variation'] = 'mclc1'
csi = (2. - the_b * the_cosa / the_c) / (4. * (1. - the_cosa ** 2))
psi = 0.75 - the_a ** 2 / (4. * the_b * (1. - the_cosa ** 2))
bravais_info['extra'] = {'csi': csi,
'eta': 0.5 + 2. * csi * the_c * the_cosa / the_b,
'psi': psi,
'phi': psi + (0.75 - psi) * the_b * the_cosa / the_c,
}
else: # if the_ka>0.:
x = the_b * the_cosa / the_c + the_b ** 2 * (1. - the_cosa ** 2) / the_a ** 2
if a_are_equals(x, 1.):
bravais_info['variation'] = 'mclc4' # order matters here too
mu = (1. + (the_b / the_a) ** 2) / 4.
dlt = the_b * the_c * the_cosa / (2. * the_a ** 2)
csi = mu - 0.25 + (1. - the_b * the_cosa / the_c) / (4. * (1. - the_cosa ** 2))
eta = 0.5 + 2. * csi * the_c * the_cosa / the_b
phi = 1. + eta - 2. * mu
psi = eta - 2. * dlt
bravais_info['extra'] = {'mu': mu,
'dlt': dlt,
'csi': csi,
'eta': eta,
'phi': phi,
'psi': psi,
}
elif x < 1.:
bravais_info['variation'] = 'mclc3'
mu = (1. + (the_b / the_a) ** 2) / 4.
dlt = the_b * the_c * the_cosa / (2. * the_a ** 2)
csi = mu - 0.25 + (1. - the_b * the_cosa / the_c) / (4. * (1. - the_cosa ** 2))
eta = 0.5 + 2. * csi * the_c * the_cosa / the_b
phi = 1. + eta - 2. * mu
psi = eta - 2. * dlt
bravais_info['extra'] = {'mu': mu,
'dlt': dlt,
'csi': csi,
'eta': eta,
'phi': phi,
'psi': psi,
}
elif x > 1.:
bravais_info['variation'] = 'mclc5'
csi = ((the_b / the_a) ** 2 + (1. - the_b * the_cosa / the_c) / (1. - the_cosa ** 2)) / 4.
eta = 0.5 + 2. * csi * the_c * the_cosa / the_b
mu = eta / 2. + the_b ** 2 / 4. / the_a ** 2 - the_b * the_c * the_cosa / 2. / the_a ** 2
nu = 2. * mu - csi
omg = (4. * nu - 1. - the_b ** 2 * (1. - the_cosa ** 2) / the_a ** 2) * the_c / (
2. * the_b * the_cosa)
dlt = csi * the_c * the_cosa / the_b + omg / 2. - 0.25
rho = 1. - csi * the_a ** 2 / the_b ** 2
bravais_info['extra'] = {'mu': mu,
'dlt': dlt,
'csi': csi,
'eta': eta,
'rho': rho,
}
# if it doesn't fall in the above, is triclinic
else:
bravais_info = {'short_name': 'tri',
'extended_name': 'triclinic',
'index': 14,
}
# the check for triclinic variations is at the end of the method
else: # if comparison_length.count(True)==0:
fco1 = c ** 2 / numpy.sqrt((a ** 2 + c ** 2) * (b ** 2 + c ** 2))
fco2 = a ** 2 / numpy.sqrt((a ** 2 + b ** 2) * (a ** 2 + c ** 2))
fco3 = b ** 2 / numpy.sqrt((a ** 2 + b ** 2) * (b ** 2 + c ** 2))
# ==============#
# orthorhombic #
# ==============#
if comparison_angles.count(True) == 3:
bravais_info = {'short_name': 'orc',
'extended_name': 'orthorhombic',
'index': 6,
}
lens = [a, b, c]
ind_a = lens.index(min(lens))
ind_c = lens.index(max(lens))
if ind_a == 0 and ind_c == 1:
bravais_info['permutation'] = [0, 2, 1]
if ind_a == 0 and ind_c == 2:
bravais_info['permutation'] = [0, 1, 2]
if ind_a == 1 and ind_c == 0:
bravais_info['permutation'] = [1, 2, 0]
if ind_a == 1 and ind_c == 2:
bravais_info['permutation'] = [1, 0, 2]
if ind_a == 2 and ind_c == 0:
bravais_info['permutation'] = [2, 1, 0]
if ind_a == 2 and ind_c == 1:
bravais_info['permutation'] = [2, 0, 1]
# ============#
# monoclinic #
# ============#
elif (comparison_angles.count(True) == 1 and
any([a_are_equals(cosa, _90), a_are_equals(cosb, _90), a_are_equals(cosc, _90)])):
bravais_info = {'short_name': 'mcl',
'extended_name': 'monoclinic',
'index': 12,
}
lens = [a, b, c]
# find the angle different from 90
# then order (if possible) a<b<c
if not a_are_equals(cosa, _90):
the_cosa = cosa
the_a = min(a, b)
the_b = max(a, b)
the_c = c
if lens.index(the_a) == 0:
bravais_info['permutation'] = [0, 1, 2]
else:
bravais_info['permutation'] = [1, 0, 2]
elif not a_are_equals(cosb, _90):
the_cosa = cosb
the_a = min(a, c)
the_b = max(a, c)
the_c = b
if lens.index(the_a) == 0:
bravais_info['permutation'] = [0, 2, 1]
else:
bravais_info['permutation'] = [1, 2, 0]
else: # if not _are_equals(cosc,_90):
the_cosa = cosc
the_a = min(b, c)
the_b = max(b, c)
the_c = a
if lens.index(the_a) == 1:
bravais_info['permutation'] = [2, 0, 1]
else:
bravais_info['permutation'] = [2, 1, 0]
eta = (1. - the_b * the_cosa / the_c) / (2. * (1. - the_cosa ** 2))
bravais_info['extra'] = {'eta': eta,
'nu': 0.5 - eta * the_c * the_cosa / the_b,
}
# ============================#
# face centered orthorhombic #
# ============================#
elif (any([a_are_equals(cosa, fco1), a_are_equals(cosb, fco1), a_are_equals(cosc, fco1)]) and
any([a_are_equals(cosa, fco2), a_are_equals(cosb, fco2), a_are_equals(cosc, fco2)]) and
any([a_are_equals(cosa, fco3), a_are_equals(cosb, fco3), a_are_equals(cosc, fco3)])
):
bravais_info = {'short_name': 'orcf',
'extended_name': 'face centered orthorhombic',
'index': 7,
}
lens = [a, b, c]
ind_a1 = lens.index(max(lens))
ind_a3 = lens.index(min(lens))
if ind_a1 == 0 and ind_a3 == 2:
bravais_info['permutation'] = [0, 1, 2]
the_a1 = a1
the_a2 = a2
the_a3 = a3
elif ind_a1 == 0 and ind_a3 == 1:
bravais_info['permutation'] = [0, 2, 1]
the_a1 = a1
the_a2 = a3
the_a3 = a2
elif ind_a1 == 1 and ind_a3 == 2:
bravais_info['permutation'] = [1, 0, 2]
the_a1 = a2
the_a2 = a1
the_a3 = a3
elif ind_a1 == 1 and ind_a3 == 0:
bravais_info['permutation'] = [2, 0, 1]
the_a1 = a3
the_a2 = a1
the_a3 = a2
elif ind_a1 == 2 and ind_a3 == 1:
bravais_info['permutation'] = [1, 2, 0]
the_a1 = a2
the_a2 = a3
the_a3 = a1
else: # ind_a1 == 2 and ind_a3 == 0:
bravais_info['permutation'] = [2, 1, 0]
the_a1 = a3
the_a2 = a2
the_a3 = a1
the_a = numpy.linalg.norm(- the_a1 + the_a2 + the_a3)
the_b = numpy.linalg.norm(+ the_a1 - the_a2 + the_a3)
the_c = numpy.linalg.norm(+ the_a1 + the_a2 - the_a3)
fco4 = 1. / the_a ** 2 - 1. / the_b ** 2 - 1. / the_c ** 2
# orcf3
if a_are_equals(fco4, 0.):
bravais_info['variation'] = 'orcf3' # order matters
bravais_info['extra'] = {'csi': (1. + (the_a / the_b) ** 2 - (the_a / the_c) ** 2) / 4.,
'eta': (1. + (the_a / the_b) ** 2 + (the_a / the_c) ** 2) / 4.,
}
# orcf1
elif fco4 > 0.:
bravais_info['variation'] = 'orcf1'
bravais_info['extra'] = {'csi': (1. + (the_a / the_b) ** 2 - (the_a / the_c) ** 2) / 4.,
'eta': (1. + (the_a / the_b) ** 2 + (the_a / the_c) ** 2) / 4.,
}
# orcf2
else:
bravais_info['variation'] = 'orcf2'
bravais_info['extra'] = {'eta': (1. + (the_a / the_b) ** 2 - (the_a / the_c) ** 2) / 4.,
'dlt': (1. + (the_b / the_a) ** 2 + (the_b / the_c) ** 2) / 4.,
'phi': (1. + (the_c / the_b) ** 2 - (the_c / the_a) ** 2) / 4.,
}
else:
bravais_info = {'short_name': 'tri',
'extended_name': 'triclinic',
'index': 14,
}
# ===========#
# triclinic #
# ===========#
# still miss the variations of triclinic
if bravais_info['short_name'] == 'tri':
lens = [a, b, c]
ind_a = lens.index(min(lens))
ind_c = lens.index(max(lens))
if ind_a == 0 and ind_c == 1:
the_a = a
the_b = c
the_c = b
the_cosa = cosa
the_cosb = cosc
the_cosc = cosb
bravais_info['permutation'] = [0, 2, 1]
if ind_a == 0 and ind_c == 2:
the_a = a
the_b = b
the_c = c
the_cosa = cosa
the_cosb = cosb
the_cosc = cosc
bravais_info['permutation'] = [0, 1, 2]
if ind_a == 1 and ind_c == 0:
the_a = b
the_b = c
the_c = a
the_cosa = cosb
the_cosb = cosc
the_cosc = cosa
bravais_info['permutation'] = [1, 0, 2]
if ind_a == 1 and ind_c == 2:
the_a = b
the_b = a
the_c = c
the_cosa = cosb
the_cosb = cosa
the_cosc = cosc
bravais_info['permutation'] = [1, 0, 2]
if ind_a == 2 and ind_c == 0:
the_a = c
the_b = b
the_c = a
the_cosa = cosc
the_cosb = cosb
the_cosc = cosa
bravais_info['permutation'] = [2, 1, 0]
if ind_a == 2 and ind_c == 1:
the_a = c
the_b = a
the_c = b
the_cosa = cosc
the_cosb = cosa
the_cosc = cosb
bravais_info['permutation'] = [2, 0, 1]
if the_cosa < 0. and the_cosb < 0.:
if a_are_equals(the_cosc, 0.):
bravais_info['variation'] = 'tri2a'
elif the_cosc < 0.:
bravais_info['variation'] = 'tri1a'
else:
raise ValueError('Structure erroneously fell into the triclinic (a) case')
elif the_cosa > 0. and the_cosb > 0.:
if a_are_equals(the_cosc, 0.):
bravais_info['variation'] = 'tri2b'
elif the_cosc > 0.:
bravais_info['variation'] = 'tri1b'
else:
raise ValueError('Structure erroneously fell into the triclinic (b) case')
else:
raise ValueError('Structure erroneously fell into the triclinic case')
elif dimension == 2:
# ========================================#
# 2D case -> 5 possible Bravais lattices #
# ========================================#
# find the two in-plane lattice vectors
out_of_plane_index = pbc.index(False) # the non-periodic dimension
in_plane_indexes = list(set(range(3)) - set([out_of_plane_index]))
# in_plane_indexes are the indexes of the two dimensions (e.g. [0,1])
# build a length-2 list with the 2D cell lattice vectors
list_vectors = ['a1', 'a2', 'a3']
vectors = [eval(list_vectors[i]) for i in in_plane_indexes]
# build a length-2 list with the norms of the 2D cell lattice vectors
lens = [numpy.linalg.norm(v) for v in vectors]
# cosine of the angle between the two primitive vectors
list_angles = ['cosa', 'cosb', 'cosc']
cosphi = eval(list_angles[out_of_plane_index])
comparison_length = l_are_equals(lens[0], lens[1])
comparison_angle_90 = a_are_equals(cosphi, _90)
# ================#
# square lattice #
# ================#
if comparison_angle_90 and comparison_length:
bravais_info = {'short_name': 'sq',
'extended_name': 'square',
'index': 1,
}
# =========================#
# (primitive) rectangular #
# =========================#
elif comparison_angle_90:
bravais_info = {'short_name': 'rec',
'extended_name': 'rectangular',
'index': 2,
}
# set the order such that first_vector < second_vector in norm
if lens[0] > lens[1]:
in_plane_indexes.reverse()
# ===========#
# hexagonal #
# ===========#
# this has to be put before the centered-rectangular case
elif (l_are_equals(lens[0], lens[1]) and a_are_equals(cosphi, _120)):
bravais_info = {'short_name': 'hex',
'extended_name': 'hexagonal',
'index': 4,
}
# ======================#
# centered rectangular #
# ======================#
elif (comparison_length and
l_are_equals(numpy.dot(vectors[0] + vectors[1],
vectors[0] - vectors[1]), 0.)):
bravais_info = {'short_name': 'recc',
'extended_name': 'centered rectangular',
'index': 3,
}
# =========#
# oblique #
# =========#
else:
bravais_info = {'short_name': 'obl',
'extended_name': 'oblique',
'index': 5,
}
# set the order such that first_vector < second_vector in norm
if lens[0] > lens[1]:
in_plane_indexes.reverse()
# the permutation is set such that p[2]=out_of_plane_index (third
# new axis is always the non-periodic out-of-plane axis)
# TODO: check that this (and the special points permutation of
# coordinates) works also when the out-of-plane axis is not aligned
# with one of the cartesian axis (I suspect that it doesn't...)
permutation = in_plane_indexes + [out_of_plane_index]
bravais_info['permutation'] = permutation
elif dimension <= 1:
# ====================================================#
# 0D & 1D cases -> only one possible Bravais lattice #
# ====================================================#
if dimension == 1:
# TODO: check that this (and the special points permutation of
# coordinates) works also when the 1D axis is not aligned
# with one of the cartesian axis (I suspect that it doesn't...)
in_line_index = pbc.index(True) # the only periodic dimension
# the permutation is set such that p[0]=in_line_index (the 2 last
# axes are always the non-periodic ones)
permutation = [in_line_index] + list(set(range(3)) - set([in_line_index]))
else:
permutation = [0, 1, 2]
bravais_info = {
'short_name': '{}D'.format(dimension),
'extended_name': '{}D'.format(dimension),
'index': 1,
'permutation': permutation,
}
return bravais_info
def get_kpoints_path(cell, pbc=None, cartesian=False,
epsilon_length=_default_epsilon_length,
epsilon_angle=_default_epsilon_angle):
"""
Get the special point and path of a given structure.
.. note:: in 3D, this implementation expects
that the structure is already standardized according to the Setyawan
paper. If this is not the case, the kpoints and band structure returned will be incorrect. The only case
that is dealt correctly by the library is the case when axes are swapped, where the library correctly
takes this swapping/rotation into account to assign kpoint labels and coordinates.
- In 2D, coordinates are based on the paper:
R. Ramirez and M. C. Bohm, Int. J. Quant. Chem., XXX, pp. 391-411 (1986)
- In 3D, coordinates are based on the paper:
W. Setyawan, S. Curtarolo, Comp. Mat. Sci. 49, 299 (2010)
:param cell: 3x3 array representing the structure cell lattice vectors
:param pbc: 3-dimensional array of booleans signifying the periodic boundary
conditions along each lattice vector
:param cartesian: If true, returns points in cartesian coordinates.
Crystal coordinates otherwise. Default=False
:param epsilon_length: threshold on lengths comparison, used
to get the bravais lattice info
:param epsilon_angle: threshold on angles comparison, used
to get the bravais lattice info
:return special_points,path: special_points: a dictionary of
point_name:point_coords key,values.
path: the suggested path which goes through all high symmetry
lines. A list of lists for all path segments.
e.g. ``[('G','X'),('X','M'),...]``
It's not necessarily a continuous line.
:note: We assume that the cell given by the cell property is the
primitive unit cell
"""
# recognize which bravais lattice we are dealing with
bravais_info = find_bravais_info(
cell=cell, pbc=pbc,
epsilon_length=epsilon_length,
epsilon_angle=epsilon_angle
)
analysis = analyze_cell(cell, pbc)
dimension = analysis['dimension']
reciprocal_cell = analysis['reciprocal_cell']
# pick the information about the special k-points.
# it depends on the dimensionality and the Bravais lattice number.
if dimension == 3:
# 3D case: 14 Bravais lattices
# simple cubic
if bravais_info['index'] == 1:
special_points = {'G': [0., 0., 0.],
'M': [0.5, 0.5, 0.],
'R': [0.5, 0.5, 0.5],
'X': [0., 0.5, 0.],
}
path = [('G', 'X'),
('X', 'M'),
('M', 'G'),
('G', 'R'),
('R', 'X'),
('M', 'R'),
]
# face centered cubic
elif bravais_info['index'] == 2:
special_points = {'G': [0., 0., 0.],
'K': [3. / 8., 3. / 8., 0.75],
'L': [0.5, 0.5, 0.5],
'U': [5. / 8., 0.25, 5. / 8.],
'W': [0.5, 0.25, 0.75],
'X': [0.5, 0., 0.5],
}
path = [('G', 'X'),
('X', 'W'),
('W', 'K'),
('K', 'G'),
('G', 'L'),
('L', 'U'),
('U', 'W'),
('W', 'L'),
('L', 'K'),
('U', 'X'),
]
# body centered cubic
elif bravais_info['index'] == 3:
special_points = {'G': [0., 0., 0.],
'H': [0.5, -0.5, 0.5],
'P': [0.25, 0.25, 0.25],
'N': [0., 0., 0.5],
}
path = [('G', 'H'),
('H', 'N'),
('N', 'G'),
('G', 'P'),
('P', 'H'),
('P', 'N'),
]
# Tetragonal
elif bravais_info['index'] == 4:
special_points = {'G': [0., 0., 0.],
'A': [0.5, 0.5, 0.5],
'M': [0.5, 0.5, 0.],
'R': [0., 0.5, 0.5],
'X': [0., 0.5, 0.],
'Z': [0., 0., 0.5],
}
path = [('G', 'X'),
('X', 'M'),
('M', 'G'),
('G', 'Z'),
('Z', 'R'),
('R', 'A'),
('A', 'Z'),
('X', 'R'),
('M', 'A'),
]
# body centered tetragonal
elif bravais_info['index'] == 5:
if bravais_info['variation'] == 'bct1':
# Body centered tetragonal bct1
eta = bravais_info['extra']['eta']
special_points = {'G': [0., 0., 0.],
'M': [-0.5, 0.5, 0.5],
'N': [0., 0.5, 0.],
'P': [0.25, 0.25, 0.25],
'X': [0., 0., 0.5],
'Z': [eta, eta, -eta],
'Z1': [-eta, 1. - eta, eta],
}
path = [('G', 'X'),
('X', 'M'),
('M', 'G'),
('G', 'Z'),
('Z', 'P'),
('P', 'N'),
('N', 'Z1'),
('Z1', 'M'),
('X', 'P'),
]
else: # bct2
# Body centered tetragonal bct2
eta = bravais_info['extra']['eta']
csi = bravais_info['extra']['csi']
special_points = {
'G': [0., 0., 0.],
'N': [0., 0.5, 0.],
'P': [0.25, 0.25, 0.25],
'S': [-eta, eta, eta],
'S1': [eta, 1 - eta, -eta],
'X': [0., 0., 0.5],
'Y': [-csi, csi, 0.5],
'Y1': [0.5, 0.5, -csi],
'Z': [0.5, 0.5, -0.5],
}
path = [('G', 'X'),
('X', 'Y'),
('Y', 'S'),
('S', 'G'),
('G', 'Z'),
('Z', 'S1'),
('S1', 'N'),
('N', 'P'),
('P', 'Y1'),
('Y1', 'Z'),
('X', 'P'),
]
# orthorhombic
elif bravais_info['index'] == 6:
special_points = {'G': [0., 0., 0.],
'R': [0.5, 0.5, 0.5],
'S': [0.5, 0.5, 0.],
'T': [0., 0.5, 0.5],
'U': [0.5, 0., 0.5],
'X': [0.5, 0., 0.],
'Y': [0., 0.5, 0.],
'Z': [0., 0., 0.5],
}
path = [('G', 'X'),
('X', 'S'),
('S', 'Y'),
('Y', 'G'),
('G', 'Z'),
('Z', 'U'),
('U', 'R'),
('R', 'T'),
('T', 'Z'),
('Y', 'T'),
('U', 'X'),
('S', 'R'),
]
# face centered orthorhombic
elif bravais_info['index'] == 7:
if bravais_info['variation'] == 'orcf1':
csi = bravais_info['extra']['csi']
eta = bravais_info['extra']['eta']
special_points = {'G': [0., 0., 0.],
'A': [0.5, 0.5 + csi, csi],
'A1': [0.5, 0.5 - csi, 1. - csi],
'L': [0.5, 0.5, 0.5],
'T': [1., 0.5, 0.5],
'X': [0., eta, eta],
'X1': [1., 1. - eta, 1. - eta],
'Y': [0.5, 0., 0.5],
'Z': [0.5, 0.5, 0.],
}
path = [('G', 'Y'),
('Y', 'T'),
('T', 'Z'),
('Z', 'G'),
('G', 'X'),
('X', 'A1'),
('A1', 'Y'),
('T', 'X1'),
('X', 'A'),
('A', 'Z'),
('L', 'G'),
]
elif bravais_info['variation'] == 'orcf2':
eta = bravais_info['extra']['eta']
dlt = bravais_info['extra']['dlt']
phi = bravais_info['extra']['phi']
special_points = {'G': [0., 0., 0.],
'C': [0.5, 0.5 - eta, 1. - eta],
'C1': [0.5, 0.5 + eta, eta],
'D': [0.5 - dlt, 0.5, 1. - dlt],
'D1': [0.5 + dlt, 0.5, dlt],
'L': [0.5, 0.5, 0.5],
'H': [1. - phi, 0.5 - phi, 0.5],
'H1': [phi, 0.5 + phi, 0.5],
'X': [0., 0.5, 0.5],
'Y': [0.5, 0., 0.5],
'Z': [0.5, 0.5, 0.],
}
path = [('G', 'Y'),
('Y', 'C'),
('C', 'D'),
('D', 'X'),
('X', 'G'),
('G', 'Z'),
('Z', 'D1'),
('D1', 'H'),
('H', 'C'),
('C1', 'Z'),
('X', 'H1'),
('H', 'Y'),
('L', 'G'),
]
else:
csi = bravais_info['extra']['csi']
eta = bravais_info['extra']['eta']
special_points = {'G': [0., 0., 0.],
'A': [0.5, 0.5 + csi, csi],
'A1': [0.5, 0.5 - csi, 1. - csi],
'L': [0.5, 0.5, 0.5],
'T': [1., 0.5, 0.5],
'X': [0., eta, eta],
'X1': [1., 1. - eta, 1. - eta],
'Y': [0.5, 0., 0.5],
'Z': [0.5, 0.5, 0.],
}
path = [('G', 'Y'),
('Y', 'T'),
('T', 'Z'),
('Z', 'G'),
('G', 'X'),
('X', 'A1'),
('A1', 'Y'),
('X', 'A'),
('A', 'Z'),
('L', 'G'),
]
# Body centered orthorhombic
elif bravais_info['index'] == 8:
csi = bravais_info['extra']['csi']
dlt = bravais_info['extra']['dlt']
eta = bravais_info['extra']['eta']
mu = bravais_info['extra']['mu']
special_points = {'G': [0., 0., 0.],
'L': [-mu, mu, 0.5 - dlt],
'L1': [mu, -mu, 0.5 + dlt],
'L2': [0.5 - dlt, 0.5 + dlt, -mu],
'R': [0., 0.5, 0.],
'S': [0.5, 0., 0.],
'T': [0., 0., 0.5],
'W': [0.25, 0.25, 0.25],
'X': [-csi, csi, csi],
'X1': [csi, 1. - csi, -csi],
'Y': [eta, -eta, eta],
'Y1': [1. - eta, eta, -eta],
'Z': [0.5, 0.5, -0.5],
}
path = [('G', 'X'),
('X', 'L'),
('L', 'T'),
('T', 'W'),
('W', 'R'),
('R', 'X1'),
('X1', 'Z'),
('Z', 'G'),
('G', 'Y'),
('Y', 'S'),
('S', 'W'),
('L1', 'Y'),
('Y1', 'Z'),
]
# C-centered orthorhombic
elif bravais_info['index'] == 9:
csi = bravais_info['extra']['csi']
special_points = {'G': [0., 0., 0.],
'A': [csi, csi, 0.5],
'A1': [-csi, 1. - csi, 0.5],
'R': [0., 0.5, 0.5],
'S': [0., 0.5, 0.],
'T': [-0.5, 0.5, 0.5],
'X': [csi, csi, 0.],
'X1': [-csi, 1. - csi, 0.],
'Y': [-0.5, 0.5, 0.],
'Z': [0., 0., 0.5],
}
path = [('G', 'X'),
('X', 'S'),
('S', 'R'),
('R', 'A'),
('A', 'Z'),
('Z', 'G'),
('G', 'Y'),
('Y', 'X1'),
('X1', 'A1'),
('A1', 'T'),
('T', 'Y'),
('Z', 'T'),
]
# Hexagonal
elif bravais_info['index'] == 10:
special_points = {'G': [0., 0., 0.],
'A': [0., 0., 0.5],
'H': [1. / 3., 1. / 3., 0.5],
'K': [1. / 3., 1. / 3., 0.],
'L': [0.5, 0., 0.5],
'M': [0.5, 0., 0.],
}
path = [('G', 'M'),
('M', 'K'),
('K', 'G'),
('G', 'A'),
('A', 'L'),
('L', 'H'),
('H', 'A'),
('L', 'M'),
('K', 'H'),
]
# rhombohedral
elif bravais_info['index'] == 11:
if bravais_info['variation'] == 'rhl1':
eta = bravais_info['extra']['eta']
nu = bravais_info['extra']['nu']
special_points = {'G': [0., 0., 0.],
'B': [eta, 0.5, 1. - eta],
'B1': [0.5, 1. - eta, eta - 1.],
'F': [0.5, 0.5, 0.],
'L': [0.5, 0., 0.],
'L1': [0., 0., -0.5],
'P': [eta, nu, nu],
'P1': [1. - nu, 1. - nu, 1. - eta],
'P2': [nu, nu, eta - 1.],
'Q': [1. - nu, nu, 0.],
'X': [nu, 0., -nu],
'Z': [0.5, 0.5, 0.5],
}
path = [('G', 'L'),
('L', 'B1'),
('B', 'Z'),
('Z', 'G'),
('G', 'X'),
('Q', 'F'),
('F', 'P1'),
('P1', 'Z'),
('L', 'P'),
]
else: # Rhombohedral rhl2
eta = bravais_info['extra']['eta']
nu = bravais_info['extra']['nu']
special_points = {'G': [0., 0., 0.],
'F': [0.5, -0.5, 0.],
'L': [0.5, 0., 0.],
'P': [1. - nu, -nu, 1. - nu],
'P1': [nu, nu - 1., nu - 1.],
'Q': [eta, eta, eta],
'Q1': [1. - eta, -eta, -eta],
'Z': [0.5, -0.5, 0.5],
}
path = [('G', 'P'),
('P', 'Z'),
('Z', 'Q'),
('Q', 'G'),
('G', 'F'),
('F', 'P1'),
('P1', 'Q1'),
('Q1', 'L'),
('L', 'Z'),
]
# monoclinic
elif bravais_info['index'] == 12:
eta = bravais_info['extra']['eta']
nu = bravais_info['extra']['nu']
special_points = {'G': [0., 0., 0.],
'A': [0.5, 0.5, 0.],
'C': [0., 0.5, 0.5],
'D': [0.5, 0., 0.5],
'D1': [0.5, 0., -0.5],
'E': [0.5, 0.5, 0.5],
'H': [0., eta, 1. - nu],
'H1': [0., 1. - eta, nu],
'H2': [0., eta, -nu],
'M': [0.5, eta, 1. - nu],
'M1': [0.5, 1. - eta, nu],
'M2': [0.5, eta, -nu],
'X': [0., 0.5, 0.],
'Y': [0., 0., 0.5],
'Y1': [0., 0., -0.5],
'Z': [0.5, 0., 0.],
}
path = [('G', 'Y'),
('Y', 'H'),
('H', 'C'),
('C', 'E'),
('E', 'M1'),
('M1', 'A'),
('A', 'X'),
('X', 'H1'),
('M', 'D'),
('D', 'Z'),
('Y', 'D'),
]
elif bravais_info['index'] == 13:
if bravais_info['variation'] == 'mclc1':
csi = bravais_info['extra']['csi']
eta = bravais_info['extra']['eta']
psi = bravais_info['extra']['psi']
phi = bravais_info['extra']['phi']
special_points = {'G': [0., 0., 0.],
'N': [0.5, 0., 0.],
'N1': [0., -0.5, 0.],
'F': [1. - csi, 1. - csi, 1. - eta],
'F1': [csi, csi, eta],
'F2': [csi, -csi, 1. - eta],
'F3': [1. - csi, -csi, 1. - eta],
'I': [phi, 1. - phi, 0.5],
'I1': [1. - phi, phi - 1., 0.5],
'L': [0.5, 0.5, 0.5],
'M': [0.5, 0., 0.5],
'X': [1. - psi, psi - 1., 0.],
'X1': [psi, 1. - psi, 0.],
'X2': [psi - 1., -psi, 0.],
'Y': [0.5, 0.5, 0.],
'Y1': [-0.5, -0.5, 0.],
'Z': [0., 0., 0.5],
}
path = [('G', 'Y'),
('Y', 'F'),
('F', 'L'),
('L', 'I'),
('I1', 'Z'),
('Z', 'F1'),
('Y', 'X1'),
('X', 'G'),
('G', 'N'),
('M', 'G'),
]
elif bravais_info['variation'] == 'mclc2':
csi = bravais_info['extra']['csi']
eta = bravais_info['extra']['eta']
psi = bravais_info['extra']['psi']
phi = bravais_info['extra']['phi']
special_points = {'G': [0., 0., 0.],
'N': [0.5, 0., 0.],
'N1': [0., -0.5, 0.],
'F': [1. - csi, 1. - csi, 1. - eta],
'F1': [csi, csi, eta],
'F2': [csi, -csi, 1. - eta],
'F3': [1. - csi, -csi, 1. - eta],
'I': [phi, 1. - phi, 0.5],
'I1': [1. - phi, phi - 1., 0.5],
'L': [0.5, 0.5, 0.5],
'M': [0.5, 0., 0.5],
'X': [1. - psi, psi - 1., 0.],
'X1': [psi, 1. - psi, 0.],
'X2': [psi - 1., -psi, 0.],
'Y': [0.5, 0.5, 0.],
'Y1': [-0.5, -0.5, 0.],
'Z': [0., 0., 0.5],
}
path = [('G', 'Y'),
('Y', 'F'),
('F', 'L'),
('L', 'I'),
('I1', 'Z'),
('Z', 'F1'),
('N', 'G'),
('G', 'M'),
]
elif bravais_info['variation'] == 'mclc3':
mu = bravais_info['extra']['mu']
dlt = bravais_info['extra']['dlt']
csi = bravais_info['extra']['csi']
eta = bravais_info['extra']['eta']
phi = bravais_info['extra']['phi']
psi = bravais_info['extra']['psi']
special_points = {
'G': [0., 0., 0.],
'F': [1. - phi, 1 - phi, 1. - psi],
'F1': [phi, phi - 1., psi],
'F2': [1. - phi, -phi, 1. - psi],
'H': [csi, csi, eta],
'H1': [1. - csi, -csi, 1. - eta],
'H2': [-csi, -csi, 1. - eta],
'I': [0.5, -0.5, 0.5],
'M': [0.5, 0., 0.5],
'N': [0.5, 0., 0.],
'N1': [0., -0.5, 0.],
'X': [0.5, -0.5, 0.],
'Y': [mu, mu, dlt],
'Y1': [1. - mu, -mu, -dlt],
'Y2': [-mu, -mu, -dlt],
'Y3': [mu, mu - 1., dlt],
'Z': [0., 0., 0.5],
}
path = [('G', 'Y'),
('Y', 'F'),
('F', 'H'),
('H', 'Z'),
('Z', 'I'),
('I', 'F1'),
('H1', 'Y1'),
('Y1', 'X'),
('X', 'F'),
('G', 'N'),
('M', 'G'),
]
elif bravais_info['variation'] == 'mclc4':
mu = bravais_info['extra']['mu']
dlt = bravais_info['extra']['dlt']
csi = bravais_info['extra']['csi']
eta = bravais_info['extra']['eta']
phi = bravais_info['extra']['phi']
psi = bravais_info['extra']['psi']
special_points = {'G': [0., 0., 0.],
'F': [1. - phi, 1 - phi, 1. - psi],
'F1': [phi, phi - 1., psi],
'F2': [1. - phi, -phi, 1. - psi],
'H': [csi, csi, eta],
'H1': [1. - csi, -csi, 1. - eta],
'H2': [-csi, -csi, 1. - eta],
'I': [0.5, -0.5, 0.5],
'M': [0.5, 0., 0.5],
'N': [0.5, 0., 0.],
'N1': [0., -0.5, 0.],
'X': [0.5, -0.5, 0.],
'Y': [mu, mu, dlt],
'Y1': [1. - mu, -mu, -dlt],
'Y2': [-mu, -mu, -dlt],
'Y3': [mu, mu - 1., dlt],
'Z': [0., 0., 0.5],
}
path = [('G', 'Y'),
('Y', 'F'),
('F', 'H'),
('H', 'Z'),
('Z', 'I'),
('H1', 'Y1'),
('Y1', 'X'),
('X', 'G'),
('G', 'N'),
('M', 'G'),
]
else:
csi = bravais_info['extra']['csi']
mu = bravais_info['extra']['mu']
omg = bravais_info['extra']['omg']
eta = bravais_info['extra']['eta']
nu = bravais_info['extra']['nu']
dlt = bravais_info['extra']['dlt']
rho = bravais_info['extra']['rho']
special_points = {
'G': [0., 0., 0.],
'F': [nu, nu, omg],
'F1': [1. - nu, 1. - nu, 1. - omg],
'F2': [nu, nu - 1., omg],
'H': [csi, csi, eta],
'H1': [1. - csi, -csi, 1. - eta],
'H2': [-csi, -csi, 1. - eta],
'I': [rho, 1. - rho, 0.5],
'I1': [1. - rho, rho - 1., 0.5],
'L': [0.5, 0.5, 0.5],
'M': [0.5, 0., 0.5],
'N': [0.5, 0., 0.],
'N1': [0., -0.5, 0.],
'X': [0.5, -0.5, 0.],
'Y': [mu, mu, dlt],
'Y1': [1. - mu, -mu, -dlt],
'Y2': [-mu, -mu, -dlt],
'Y3': [mu, mu - 1., dlt],
'Z': [0., 0., 0.5],
}
path = [('G', 'Y'),
('Y', 'F'),
('F', 'L'),
('L', 'I'),
('I1', 'Z'),
('Z', 'H'),
('H', 'F1'),
('H1', 'Y1'),
('Y1', 'X'),
('X', 'G'),
('G', 'N'),
('M', 'G'),
]
# triclinic
elif bravais_info['index'] == 14:
if bravais_info['variation'] == 'tri1a' or bravais_info['variation'] == 'tri2a':
special_points = {'G': [0.0, 0.0, 0.0],
'L': [0.5, 0.5, 0.0],
'M': [0.0, 0.5, 0.5],
'N': [0.5, 0.0, 0.5],
'R': [0.5, 0.5, 0.5],
'X': [0.5, 0.0, 0.0],
'Y': [0.0, 0.5, 0.0],
'Z': [0.0, 0.0, 0.5],
}
path = [('X', 'G'),
('G', 'Y'),
('L', 'G'),
('G', 'Z'),
('N', 'G'),
('G', 'M'),
('R', 'G'),
]
else:
special_points = {'G': [0.0, 0.0, 0.0],
'L': [0.5, -0.5, 0.0],
'M': [0.0, 0.0, 0.5],
'N': [-0.5, -0.5, 0.5],
'R': [0.0, -0.5, 0.5],
'X': [0.0, -0.5, 0.0],
'Y': [0.5, 0.0, 0.0],
'Z': [-0.5, 0.0, 0.5],
}
path = [('X', 'G'),
('G', 'Y'),
('L', 'G'),
('G', 'Z'),
('N', 'G'),
('G', 'M'),
('R', 'G'),
]
elif dimension == 2:
# 2D case: 5 Bravais lattices
if bravais_info['index'] == 1:
# square
special_points = {'G': [0., 0., 0.],
'M': [0.5, 0.5, 0.],
'X': [0.5, 0., 0.],
}
path = [('G', 'X'),
('X', 'M'),
('M', 'G'),
]
elif bravais_info['index'] == 2:
# (primitive) rectangular
special_points = {'G': [0., 0., 0.],
'X': [0.5, 0., 0.],
'Y': [0., 0.5, 0.],
'S': [0.5, 0.5, 0.],
}
path = [('G', 'X'),
('X', 'S'),
('S', 'Y'),
('Y', 'G'),
]
elif bravais_info['index'] == 3:
# centered rectangular (rhombic)
# TODO: this looks quite different from the in-plane part of the
# 3D C-centered orthorhombic lattice, which is strange...
# NOTE: special points below are in (b1, b2) fractional
# coordinates (primitive reciprocal cell) as for the rest.
# Ramirez & Bohn gave them initially in (s1=b1+b2, s2=-b1+b2)
# coordinates, i.e. using the conventional reciprocal cell.
special_points = {'G': [0., 0., 0.],
'X': [0.5, 0.5, 0.],
'Y1': [0.25, 0.75, 0.],
'Y': [-0.25, 0.25, 0.], # typo in p. 404 of Ramirez & Bohm (should be Y=(0,1/4))
'C': [0., 0.5, 0.],
}
path = [('Y1', 'X'),
('X', 'G'),
('G', 'Y'),
('Y', 'C'),
]
elif bravais_info['index'] == 4:
# hexagonal
special_points = {'G': [0., 0., 0.],
'M': [0.5, 0., 0.],
'K': [1. / 3., 1. / 3., 0.],
}
path = [('G', 'M'),
('M', 'K'),
('K', 'G'),
]
elif bravais_info['index'] == 5:
# oblique
# NOTE: only end-points are high-symmetry points (not the path
# in-between)
special_points = {'G': [0., 0., 0.],
'X': [0.5, 0., 0.],
'Y': [0., 0.5, 0.],
'A': [0.5, 0.5, 0.],
}
path = [('X', 'G'),
('G', 'Y'),
('A', 'G'),
]
elif dimension == 1:
# 1D case: 1 Bravais lattice
special_points = {'G': [0., 0., 0.],
'X': [0.5, 0., 0.],
}
path = [('G', 'X'),
]
elif dimension == 0:
# 0D case: 1 Bravais lattice, only Gamma point, no path
special_points = {'G': [0., 0., 0.],
}
path = [('G', 'G'),
]
permutation = bravais_info['permutation']
def permute(x, permutation):
# return new_x such that new_x[i]=x[permutation[i]]
return [x[int(p)] for p in permutation]
def invpermute(permutation):
# return the inverse of permutation
return [permutation.index(i) for i in range(3)]
the_special_points = {}
for k in special_points.keys():
# NOTE: this originally returned the inverse of the permutation, but was later changed to permutation
the_special_points[k] = permute(special_points[k], permutation)
# output crystal or cartesian
if cartesian:
the_abs_special_points = {}
for k in the_special_points.keys():
the_abs_special_points[k] = change_reference(
reciprocal_cell, numpy.array(the_special_points[k]), to_cartesian=True
)
return the_abs_special_points, path, bravais_info
else:
return the_special_points, path, bravais_info
|
python
|
import signal
import argparse
import logging as log
import os
from pathlib import Path
import errno
from alive_progress import alive_bar
from backupdef import BackupDef
from entries import FolderEntry
from diskspacereserver import DiskSpaceReserver
from util import sanitizeFilename
def backup(source: str, destination: str):
# Create current backup definition from source folder
print("Indexing current folder state...")
with alive_bar(monitor="{count} files", receipt=False) as bar:
folder = FolderEntry.fromFolder(source, bar)
folder.name = sanitizeFilename(folder.name)
new_backupdef = BackupDef(folder)
# Initialize old backup definition
backupdef_path = os.path.join(destination, f"{folder.name}.cbdef")
if Path(backupdef_path).is_file():
print("Loading old backup definition...")
current_backupdef = BackupDef.loadFromFile(backupdef_path)
else:
current_backupdef = BackupDef(FolderEntry(folder.name))
# Initialize delta backup definition
print("Creating delta backup definition...")
delta_backupdef = BackupDef.delta(new_backupdef, current_backupdef)
# Initialize disk space reservation
reserver_path = os.path.join(destination, f"{folder.name}.reserved")
reserver = DiskSpaceReserver(reserver_path, new_backupdef.fileSize * 3)
# Copy over files until the disk is filled up
print("Copying files...")
with alive_bar(delta_backupdef.folder.size,
monitor="{count:,} / {total:,} bytes [{percent:.2%}]",
stats="({rate:,.0f}b/s, eta: {eta}s)") as bar:
while delta_backupdef.folder.contents or delta_backupdef.folder.deleted:
try:
# Before starting to copy over files, reserve space for the eventual backupdef
reserver.reserve()
# Copy the files
delta_backupdef.processDelta(current_backupdef, source, destination, bar)
except KeyboardInterrupt:
# Script was ended by ctrl-c, save backupdef and exit
reserver.release()
current_backupdef.saveToFile(backupdef_path)
print("The copying was interrupted, the progress has been saved.")
exit()
except Exception as e:
if e.errno == errno.ENOSPC:
# Disk full, save backupdef of files copied up to this point and ask for new destination
with bar.pause():
reserver.release()
current_backupdef.saveToFile(backupdef_path)
dest_input = input(f"\aCartridge full, insert next one and enter new path ({destination}): ")
if dest_input != "":
destination = dest_input
backupdef_path = os.path.join(destination, f"{folder.name}.cbdef")
reserver.path = os.path.join(destination, f"{folder.name}.reserved")
else:
# Copying error, save backupdef, print exception message, continue copying next file
reserver.release()
current_backupdef.saveToFile(backupdef_path)
log.warning("The copying was interrupted by an error. "
"The progress has been saved, the details are below:")
log.warning(e)
# Save backupdef of (presumably all) files copied up to this point
reserver.release()
current_backupdef.saveToFile(backupdef_path)
if __name__ == '__main__':
signal.signal(signal.SIGINT, signal.default_int_handler)
parser = argparse.ArgumentParser(description="Perform an incremental backup to"
"multiple, smaller destination drives(cartridges).")
parser.add_argument("source", help="The source directory")
parser.add_argument("destination", help="The destination directory")
parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
args = parser.parse_args()
if args.verbose:
log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG)
else:
log.basicConfig(format="%(levelname)s: %(message)s")
log.info(f"Running with source {args.source} and destination {args.destination}")
backup(args.source, args.destination)
|
python
|
import redis
def handler(message):
print("New message recieved:", message['data'].decode('utf-8'))
r = redis.Redis('10.14.156.254')
p = r.pubsub()
p.subscribe(**{'chat': handler})
thread = p.run_in_thread(sleep_time=0.5) # Создание потока для получения сообщий
print("Press Ctrl+C to stop")
while True:
try:
new_message = input()
r.publish('chat', new_message)
except KeyboardInterrupt:
break
print("Stopped")
thread.stop()
|
python
|
#!/usr/bin/env python
"""
methrafo.train <reference genomes><input MeDIP-Seq bigWig> <input Bisulfite-Seq bigWig> <output model prefix>
e.g.
methrafo.train hg19 example_MeDIP.bw example_Bisulfite.bw output_trained_model_prefix
"""
import pdb,sys,os
import gzip
from File import *
import re
import pyBigWig
from scipy.stats import pearsonr
from sklearn.ensemble import RandomForestRegressor
import math
import cPickle as pickle
#-----------------------------------------------------------------------
def fetchGenome(chrom_id,gref):
with gzip.open(gref+'/'+chrom_id+'.fa.gz','rb') as f:
lf=f.read()
lf=lf.split("\n")
chrom_id=lf[0].split('>')[1]
chrom_seq="".join(lf[1:])
chrom_seq=chrom_seq.upper()
return [chrom_id,chrom_seq]
def cgVector(chrom):
chrom_seq=chrom[1]
cgV=[m.start() for m in re.finditer('CG',chrom_seq)]
return cgV
def scoreVector1(chrom,cgv,bwFile):
bw=pyBigWig.open(bwFile)
chrom_name=chrom[0]
sv=[]
for i in cgv:
si=bw.stats(chrom_name,i,i+1)[0]
si=0 if si==None else si
sv.append(si)
return sv
def scoreVector(chrom,cgv,bwFile):
bw=pyBigWig.open(bwFile)
chrom_name=chrom[0]
sc=bw.values(chrom_name,0,len(chrom[1]))
sv=[0 if math.isnan(sc[item]) else sc[item] for item in cgv ]
return sv
def nearbyCGVector(cgv,nearbycut):
nearcgs=[]
for i in range(len(cgv)):
j=i-1
leftcgs=[]
rightcgs=[]
while (j>0):
if abs(cgv[j]-cgv[i])>nearbycut:
break
else:
leftcgs.append(j)
j=j-1
j=i+1
while (j<len(cgv)):
if abs(cgv[j]-cgv[i])>nearbycut:
break
else:
rightcgs.append(j)
j=j+1
inearcgs=leftcgs+rightcgs
nearcgs.append(inearcgs)
return nearcgs
def nearbyCGScoreVector(chrom,bwFile,cgv,nearcgs):
# the contribution of nearby CGs on current CG
nearcgsS=[]
bw=pyBigWig.open(bwFile)
chrom_name=chrom[0]
k=5 # distance weight parameter
for i in range(len(nearcgs)):
cgi=nearcgs[i]
si=0
for j in cgi:
dij=abs(cgv[j]-cgv[i])
sj=bw.stats(chrom_name,cgv[j],cgv[j]+1)[0]
sj=0 if sj==None else sj
si+=(sj/dij)*k
nearcgsS.append(si)
return nearcgsS
#----------------------------------------------------------------------
def main():
if len(sys.argv[1:])!=4:
print(__doc__)
sys.exit(0)
# reference genomes
gref=sys.argv[1]
# bigwig file-MeDIP-seq
bwFile=sys.argv[2]
# bigwig file bisulfite
bwBSFile=sys.argv[3]
output=sys.argv[4]
rfregressor=RandomForestRegressor(random_state=0)
chroms=os.listdir(gref)
dchrom={}
nearbycut=90
rfregressor=RandomForestRegressor(random_state=0)
#----------------------------------------------------------------------
F=[]
T=[]
print("training...")
cut=0.5
for i in chroms:
if i[0:3]=='chr':
iid=i.split('.')[0]
try:
chromi=fetchGenome(iid,gref)
cgv=cgVector(chromi)
sv=scoreVector(chromi,cgv,bwFile)
#pdb.set_trace()
nearcgs=nearbyCGVector(cgv,nearbycut) # number of cgs nearby
tsv=scoreVector(chromi,cgv,bwBSFile)
FI=[]
for j in range(len(cgv)):
fij=[sv[j],len(nearcgs[j])]
FI.append(fij)
FIX=FI[:int(len(FI)*cut)]
tsvX=tsv[:int(len(tsv)*cut)]
F+=FIX
T+=tsvX
print(iid)
except:
pass
rfregressor.fit(F,T)
with open(output+'.pkl','w') as f:
pickle.dump(rfregressor,f)
if __name__=="__main__":
main()
|
python
|
# -*- coding: utf-8 -*-
"""
Initialize the Hanabi PyQT5 Interface.
"""
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import QPalette
from PyQt5.QtWidgets import QMainWindow, QDesktopWidget, QApplication
from py_hanabi.interface.hanabi_window import HanabiWindow
from py_hanabi.interface.window import Window
__author__ = "Jakrin Juangbhanich"
__email__ = "[email protected]"
class HanabiInterface(QMainWindow):
def __init__(self):
app = QApplication([])
app.setStyle('Fusion')
palette = QPalette()
palette.setColor(QPalette.Window, QtGui.QColor(53, 53, 53))
palette.setColor(QPalette.WindowText, QtCore.Qt.white)
palette.setColor(QPalette.Base, QtGui.QColor(15, 15, 15))
palette.setColor(QPalette.AlternateBase, QtGui.QColor(53, 53, 53))
palette.setColor(QPalette.ToolTipBase, QtCore.Qt.white)
palette.setColor(QPalette.ToolTipText, QtCore.Qt.white)
palette.setColor(QPalette.Text, QtCore.Qt.white)
palette.setColor(QPalette.Button, QtGui.QColor(53, 53, 53))
palette.setColor(QPalette.ButtonText, QtCore.Qt.white)
palette.setColor(QPalette.BrightText, QtCore.Qt.red)
palette.setColor(QPalette.Highlight, QtGui.QColor(0, 110, 200))
palette.setColor(QPalette.HighlightedText, QtGui.QColor(255, 255, 255))
app.setPalette(palette)
super().__init__()
self.setWindowTitle("Hanabi Visualizer")
self.current_window: Window = None
self.window_game: HanabiWindow = HanabiWindow()
self.show_window(self.window_game)
# Force a resize update.
t = QtCore.QTimer()
t.singleShot(0, self.resizeEvent)
app.exec()
def show_window(self, window: Window):
self.current_window = window
window.render(self)
self.center_screen()
def center_screen(self):
qt_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
qt_rectangle.moveCenter(center_point)
self.move(qt_rectangle.topLeft())
def resizeEvent(self, event=None):
self.current_window.on_resize(event)
|
python
|
# Reference: https://github.com/zhangchuheng123/Reinforcement-Implementation/blob/master/code/ppo.py
import torch
def ppo_step(
policy_net,
value_net,
optimizer_policy,
optimizer_value,
optim_value_iter_num,
states,
actions,
returns,
advantages,
fixed_log_probs,
clip_epsilon,
l2_reg,
):
"""Updates Critic network and Policy network with first order optimization
Args:
policy_net: Policy network
value_net: Critic value network
optimizer_policy: optimizer or policy network - Adam
optimizer_value: optimizer or critic network - Adam
optim_value_iter_num: optimizer value iteration number
states: states array
actions: action array
returns: returns values
advantages: estimated advantage values
fixed_log_probs: fixed log probabilities
clip_epsilon: clip epsilon to avoid overfit or underfit
l2_reg: L2 Regularization
"""
# update Critic value network
for _ in range(optim_value_iter_num):
values_pred = value_net(states)
value_loss = (values_pred - returns).pow(2).mean() # MSE for critic network
# weight decays with L2 Regularization
for param in value_net.parameters():
value_loss += param.pow(2).sum() * l2_reg
optimizer_value.zero_grad() # initialize gradients to 0s
# update Critic parameters with Adam optimizer using back propagation
value_loss.backward()
optimizer_value.step()
# update Policy network
log_probs = policy_net.get_log_prob(states, actions) # get log probabilities
# calculate the clipped surrogate objective function
ratio = torch.exp(log_probs - fixed_log_probs)
surr1 = ratio * advantages
surr2 = torch.clamp(ratio, 1.0 - clip_epsilon, 1.0 + clip_epsilon) * advantages
policy_surr = -torch.min(surr1, surr2).mean() # policy net loss
optimizer_policy.zero_grad() # initialize gradients to 0s
# update Actor parameters with Adam optimizer using back propagation
policy_surr.backward()
torch.nn.utils.clip_grad_norm_(
policy_net.parameters(), 40
) # clip the gradient to avoid overfit of under fit
optimizer_policy.step() # update gradients
|
python
|
#
# PySNMP MIB module SL81-STD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SL81-STD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:57:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
ObjectIdentity, IpAddress, NotificationType, iso, ModuleIdentity, enterprises, Gauge32, TimeTicks, Counter32, MibIdentifier, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, Bits, ObjectName, NotificationType, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "IpAddress", "NotificationType", "iso", "ModuleIdentity", "enterprises", "Gauge32", "TimeTicks", "Counter32", "MibIdentifier", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "Bits", "ObjectName", "NotificationType", "Integer32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
omnitronix = MibIdentifier((1, 3, 6, 1, 4, 1, 3052))
sl81 = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5))
status = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 1))
config = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 2))
productIds = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 3))
techSupport = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 99))
eventSensorStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 1, 1))
dataEventStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 1, 2))
eventSensorBasics = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1))
dataEventConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2))
serialPorts = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 2, 3))
network = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 2, 4))
modem = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 2, 5))
snmp = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 2, 6))
pagers = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 2, 7))
time = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 2, 8))
timeouts = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 2, 9))
esPointTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 5, 1, 1, 1), )
if mibBuilder.loadTexts: esPointTable.setStatus('mandatory')
esPointEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 5, 1, 1, 1, 1), ).setIndexNames((0, "SL81-STD-MIB", "esIndexES"), (0, "SL81-STD-MIB", "esIndexPC"), (0, "SL81-STD-MIB", "esIndexPoint"))
if mibBuilder.loadTexts: esPointEntry.setStatus('mandatory')
esIndexES = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esIndexES.setStatus('mandatory')
esIndexPC = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 1, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esIndexPC.setStatus('mandatory')
esIndexPoint = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 1, 1, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esIndexPoint.setStatus('mandatory')
esPointName = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 1, 1, 1, 4), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: esPointName.setStatus('mandatory')
esPointInEventState = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 1, 1, 1, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: esPointInEventState.setStatus('mandatory')
esPointValueInt = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-32768, 32767))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: esPointValueInt.setStatus('mandatory')
esPointValueStr = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 1, 1, 1, 7), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esPointValueStr.setStatus('mandatory')
esPointTimeLastChange = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 1, 1, 1, 8), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esPointTimeLastChange.setStatus('mandatory')
esPointTimetickLastChange = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 1, 1, 1, 9), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esPointTimetickLastChange.setStatus('mandatory')
deStatusTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 5, 1, 2, 1), )
if mibBuilder.loadTexts: deStatusTable.setStatus('mandatory')
deStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 5, 1, 2, 1, 1), ).setIndexNames((0, "SL81-STD-MIB", "deStatusIndex"))
if mibBuilder.loadTexts: deStatusEntry.setStatus('mandatory')
deStatusIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 2, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: deStatusIndex.setStatus('mandatory')
deStatusName = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 2, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: deStatusName.setStatus('mandatory')
deStatusCounter = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 2, 1, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: deStatusCounter.setStatus('mandatory')
deStatusThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 2, 1, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: deStatusThreshold.setStatus('mandatory')
deStatusLastTriggerTime = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 2, 1, 1, 5), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: deStatusLastTriggerTime.setStatus('mandatory')
deStatusLastTriggerData = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 1, 2, 1, 1, 6), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: deStatusLastTriggerData.setStatus('mandatory')
esNumberEventSensors = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esNumberEventSensors.setStatus('mandatory')
esTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2), )
if mibBuilder.loadTexts: esTable.setStatus('mandatory')
esEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1), ).setIndexNames((0, "SL81-STD-MIB", "esIndex"))
if mibBuilder.loadTexts: esEntry.setStatus('mandatory')
esIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esIndex.setStatus('mandatory')
esName = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esName.setStatus('mandatory')
esID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esID.setStatus('mandatory')
esNumberTempSensors = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esNumberTempSensors.setStatus('mandatory')
esTempReportingMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 5), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esTempReportingMode.setStatus('mandatory')
esNumberCCs = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esNumberCCs.setStatus('mandatory')
esCCReportingMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 7), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esCCReportingMode.setStatus('mandatory')
esNumberHumidSensors = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esNumberHumidSensors.setStatus('mandatory')
esHumidReportingMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 9), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esHumidReportingMode.setStatus('mandatory')
esNumberNoiseSensors = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esNumberNoiseSensors.setStatus('mandatory')
esNoiseReportingMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 11), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esNoiseReportingMode.setStatus('mandatory')
esNumberAirflowSensors = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 12), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esNumberAirflowSensors.setStatus('mandatory')
esAirflowReportingMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 13), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esAirflowReportingMode.setStatus('mandatory')
esNumberAnalog = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 14), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esNumberAnalog.setStatus('mandatory')
esAnalogReportingMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 15), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esAnalogReportingMode.setStatus('mandatory')
esNumberRelayOutputs = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 16), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esNumberRelayOutputs.setStatus('mandatory')
esRelayReportingMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 1, 2, 1, 17), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: esRelayReportingMode.setStatus('mandatory')
deFieldTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 1), )
if mibBuilder.loadTexts: deFieldTable.setStatus('mandatory')
deFieldEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 1, 1), ).setIndexNames((0, "SL81-STD-MIB", "deFieldIndex"))
if mibBuilder.loadTexts: deFieldEntry.setStatus('mandatory')
deFieldIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: deFieldIndex.setStatus('mandatory')
deFieldStart = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 1, 1, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: deFieldStart.setStatus('mandatory')
deFieldLength = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 1, 1, 3), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: deFieldLength.setStatus('mandatory')
deFieldName = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 1, 1, 4), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: deFieldName.setStatus('mandatory')
deConfigTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 2), )
if mibBuilder.loadTexts: deConfigTable.setStatus('mandatory')
deConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 2, 1), ).setIndexNames((0, "SL81-STD-MIB", "deConfigIndex"))
if mibBuilder.loadTexts: deConfigEntry.setStatus('mandatory')
deConfigIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: deConfigIndex.setStatus('mandatory')
deConfigEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 2, 1, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: deConfigEnabled.setStatus('mandatory')
deConfigName = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 2, 1, 3), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: deConfigName.setStatus('mandatory')
deConfigEquation = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 2, 1, 4), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: deConfigEquation.setStatus('mandatory')
deConfigThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 2, 1, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: deConfigThreshold.setStatus('mandatory')
deConfigClearMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 2, 1, 6), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: deConfigClearMode.setStatus('mandatory')
deConfigClearTime = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 2, 1, 7), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: deConfigClearTime.setStatus('mandatory')
deConfigAutoClear = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 2, 1, 8), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: deConfigAutoClear.setStatus('mandatory')
deConfigActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 2, 1, 9), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: deConfigActions.setStatus('mandatory')
deConfigTrapNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 2, 1, 10), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: deConfigTrapNumber.setStatus('mandatory')
deConfigClass = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 2, 2, 1, 11), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: deConfigClass.setStatus('mandatory')
numberPorts = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 3, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: numberPorts.setStatus('mandatory')
portConfigTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 5, 2, 3, 2), )
if mibBuilder.loadTexts: portConfigTable.setStatus('mandatory')
portConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 5, 2, 3, 2, 1), ).setIndexNames((0, "SL81-STD-MIB", "portConfigIndex"))
if mibBuilder.loadTexts: portConfigEntry.setStatus('mandatory')
portConfigIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 3, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: portConfigIndex.setStatus('mandatory')
portConfigBaud = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 3, 2, 1, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portConfigBaud.setStatus('mandatory')
portConfigDataFormat = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 3, 2, 1, 3), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portConfigDataFormat.setStatus('mandatory')
portConfigStripPtOutputLfs = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 3, 2, 1, 4), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portConfigStripPtOutputLfs.setStatus('mandatory')
portConfigStripPtInputLfs = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 3, 2, 1, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portConfigStripPtInputLfs.setStatus('mandatory')
portConfigDTRLowIdle = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 3, 2, 1, 6), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portConfigDTRLowIdle.setStatus('mandatory')
portConfigMaskEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 3, 2, 1, 7), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portConfigMaskEnable.setStatus('mandatory')
portConfigDAEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 3, 2, 1, 8), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portConfigDAEnable.setStatus('mandatory')
ipConfigStatic = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 4, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipConfigStatic.setStatus('mandatory')
ipConfigAddress = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 4, 2), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ipConfigAddress.setStatus('mandatory')
ipConfigSubnetMask = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 4, 3), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ipConfigSubnetMask.setStatus('mandatory')
ipConfigDefaultRouter = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 4, 4), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ipConfigDefaultRouter.setStatus('mandatory')
ipConfigEngage = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 4, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ipConfigEngage.setStatus('mandatory')
telnetDuplex = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 4, 6), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: telnetDuplex.setStatus('mandatory')
modemDataFormat = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 5, 1), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: modemDataFormat.setStatus('mandatory')
modemUserSetup = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 5, 2), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: modemUserSetup.setStatus('mandatory')
modemTAPSetup = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 5, 3), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: modemTAPSetup.setStatus('mandatory')
modemTimeBetweenOutbound = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 5, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: modemTimeBetweenOutbound.setStatus('mandatory')
smTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 5, 2, 6, 1), )
if mibBuilder.loadTexts: smTable.setStatus('mandatory')
smEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 5, 2, 6, 1, 1), ).setIndexNames((0, "SL81-STD-MIB", "smIndex"))
if mibBuilder.loadTexts: smEntry.setStatus('mandatory')
smIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 6, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: smIndex.setStatus('mandatory')
smAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 6, 1, 1, 2), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: smAddress.setStatus('mandatory')
pagerRetries = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 7, 1), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pagerRetries.setStatus('mandatory')
pagerTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 5, 2, 7, 2), )
if mibBuilder.loadTexts: pagerTable.setStatus('mandatory')
pagerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 5, 2, 7, 2, 1), ).setIndexNames((0, "SL81-STD-MIB", "pagerIndex"))
if mibBuilder.loadTexts: pagerEntry.setStatus('mandatory')
pagerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 7, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: pagerIndex.setStatus('mandatory')
pagerType = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 7, 2, 1, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pagerType.setStatus('mandatory')
pagerPhoneNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 7, 2, 1, 3), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pagerPhoneNumber.setStatus('mandatory')
pagerID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 7, 2, 1, 4), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pagerID.setStatus('mandatory')
pagerPostCalloutDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 7, 2, 1, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pagerPostCalloutDelay.setStatus('mandatory')
pagerIDDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 2, 7, 2, 1, 6), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pagerIDDelay.setStatus('mandatory')
clock = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 8, 1), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: clock.setStatus('mandatory')
autoDSTAdjust = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 8, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: autoDSTAdjust.setStatus('mandatory')
commandTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 9, 1), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: commandTimeout.setStatus('mandatory')
passthroughTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 2, 9, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: passthroughTimeout.setStatus('mandatory')
siteID = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 3, 1), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: siteID.setStatus('mandatory')
thisProduct = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 3, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: thisProduct.setStatus('mandatory')
stockTrapString = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 3, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: stockTrapString.setStatus('mandatory')
trapEventTypeNumber = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 3, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: trapEventTypeNumber.setStatus('mandatory')
trapEventTypeName = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 3, 5), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: trapEventTypeName.setStatus('mandatory')
trapIncludedValue = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 3, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-32768, 32767))).setMaxAccess("readonly")
if mibBuilder.loadTexts: trapIncludedValue.setStatus('mandatory')
trapIncludedString = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 3, 7), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: trapIncludedString.setStatus('mandatory')
trapEventClassNumber = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 3, 9), Integer32())
if mibBuilder.loadTexts: trapEventClassNumber.setStatus('mandatory')
trapEventClassName = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 3, 10), Integer32())
if mibBuilder.loadTexts: trapEventClassName.setStatus('mandatory')
techSupport1 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 1), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport1.setStatus('mandatory')
techSupport2 = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 99, 2))
techSupport2n1 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 2, 1), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport2n1.setStatus('mandatory')
techSupport2n2 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 2, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport2n2.setStatus('mandatory')
techSupport3 = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 5, 99, 3))
techSupport3n1 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 3, 1), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport3n1.setStatus('mandatory')
techSupport3n2 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 3, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport3n2.setStatus('mandatory')
techSupport3n3 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 3, 3), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport3n3.setStatus('mandatory')
techSupport3n4 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 3, 4), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport3n4.setStatus('mandatory')
techSupport3n5 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 3, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport3n5.setStatus('mandatory')
techSupport4 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 4), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport4.setStatus('mandatory')
techSupport7 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 7), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport7.setStatus('mandatory')
techSupport9 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 9), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport9.setStatus('mandatory')
techSupport10 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 10), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport10.setStatus('mandatory')
techSupport11 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 11), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport11.setStatus('mandatory')
techSupport16 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 16), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport16.setStatus('mandatory')
techSupport17 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 17), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport17.setStatus('mandatory')
techSupport18 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 18), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport18.setStatus('mandatory')
techSupport19 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 19), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport19.setStatus('mandatory')
techSupport20Table = MibTable((1, 3, 6, 1, 4, 1, 3052, 5, 99, 20), )
if mibBuilder.loadTexts: techSupport20Table.setStatus('mandatory')
techSupport20Entry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 5, 99, 20, 1), ).setIndexNames((0, "SL81-STD-MIB", "techSupport20Index"))
if mibBuilder.loadTexts: techSupport20Entry.setStatus('mandatory')
techSupport20Index = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 99, 20, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: techSupport20Index.setStatus('mandatory')
techSupport20 = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 99, 20, 1, 2), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport20.setStatus('mandatory')
techSupport21Table = MibTable((1, 3, 6, 1, 4, 1, 3052, 5, 99, 21), )
if mibBuilder.loadTexts: techSupport21Table.setStatus('mandatory')
techSupport21Entry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 5, 99, 21, 1), ).setIndexNames((0, "SL81-STD-MIB", "techSupport21Index"))
if mibBuilder.loadTexts: techSupport21Entry.setStatus('mandatory')
techSupport21Index = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 99, 21, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: techSupport21Index.setStatus('mandatory')
techSupport21 = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 5, 99, 21, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: techSupport21.setStatus('mandatory')
techSupport22 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 22), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport22.setStatus('mandatory')
techSupport24 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 24), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport24.setStatus('mandatory')
techSupport25 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 25), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport25.setStatus('mandatory')
techSupport26 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 5, 99, 26), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: techSupport26.setStatus('mandatory')
sl81TestTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "stockTrapString"))
sl81StockESDisconnectTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,50)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "stockTrapString"))
sl81StockDataEventTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,100)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "stockTrapString"))
sl81StockContactClosureTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,110)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "stockTrapString"))
sl81StockTempTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,120)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "stockTrapString"))
sl81StockHumidityTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,130)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "stockTrapString"))
sl81StockAnalogTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,140)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "stockTrapString"))
sl81StockCTSTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,160)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "stockTrapString"))
sl81StockSchedTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,170)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "stockTrapString"))
sl81UserTrap1000 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1000)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1001 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1001)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1002 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1002)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1003 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1003)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1004 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1004)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1005 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1005)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1006 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1006)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1007 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1007)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1008 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1008)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1009 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1009)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1010 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1010)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1011 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1011)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1012 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1012)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1013 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1013)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1014 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1014)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1015 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1015)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1016 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1016)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1017 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1017)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1018 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1018)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1019 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1019)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1020 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1020)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1021 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1021)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1022 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1022)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1023 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1023)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1024 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1024)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1025 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1025)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1026 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1026)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1027 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1027)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1028 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1028)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1029 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1029)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1030 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1030)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1031 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1031)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1032 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1032)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1033 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1033)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1034 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1034)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1035 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1035)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1036 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1036)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1037 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1037)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1038 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1038)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1039 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1039)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1040 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1040)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1041 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1041)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1042 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1042)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1043 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1043)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1044 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1044)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1045 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1045)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1046 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1046)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1047 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1047)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1048 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1048)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1049 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1049)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1050 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1050)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1051 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1051)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1052 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1052)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1053 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1053)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1054 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1054)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1055 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1055)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1056 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1056)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1057 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1057)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1058 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1058)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1059 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1059)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1060 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1060)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1061 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1061)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1062 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1062)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1063 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1063)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1064 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1064)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1065 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1065)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1066 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1066)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1067 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1067)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1068 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1068)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1069 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1069)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1070 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1070)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1071 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1071)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1072 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1072)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1073 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1073)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1074 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1074)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1075 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1075)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1076 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1076)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1077 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1077)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1078 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1078)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1079 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1079)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1080 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1080)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1081 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1081)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1082 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1082)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1083 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1083)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1084 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1084)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1085 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1085)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1086 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1086)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1087 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1087)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1088 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1088)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1089 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1089)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1090 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1090)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1091 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1091)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1092 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1092)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1093 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1093)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1094 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1094)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1095 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1095)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1096 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1096)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1097 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1097)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1098 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1098)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1099 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1099)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1100 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1100)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1101 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1101)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1102 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1102)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1103 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1103)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1104 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1104)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1105 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1105)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1106 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1106)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1107 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1107)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1108 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1108)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1109 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1109)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1110 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1110)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1111 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1111)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1112 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1112)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1113 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1113)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1114 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1114)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1115 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1115)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1116 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1116)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1117 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1117)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1118 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1118)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1119 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1119)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1120 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1120)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1121 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1121)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1122 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1122)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1123 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1123)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1124 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1124)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1125 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1125)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1126 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1126)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1127 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1127)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1128 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1128)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1129 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1129)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1130 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1130)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1131 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1131)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1132 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1132)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1133 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1133)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1134 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1134)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1135 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1135)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1136 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1136)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1137 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1137)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1138 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1138)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1139 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1139)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1140 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1140)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1141 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1141)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1142 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1142)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1143 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1143)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1144 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1144)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1145 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1145)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1146 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1146)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1147 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1147)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1148 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1148)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1149 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1149)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1150 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1150)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1151 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1151)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1152 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1152)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1153 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1153)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1154 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1154)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1155 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1155)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1156 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1156)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1157 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1157)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1158 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1158)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1159 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1159)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1160 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1160)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1161 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1161)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1162 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1162)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1163 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1163)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1164 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1164)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1165 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1165)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1166 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1166)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1167 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1167)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1168 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1168)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1169 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1169)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1170 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1170)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1171 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1171)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1172 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1172)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1173 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1173)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1174 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1174)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1175 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1175)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1176 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1176)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1177 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1177)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1178 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1178)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1179 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1179)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1180 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1180)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1181 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1181)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1182 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1182)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1183 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1183)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1184 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1184)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1185 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1185)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1186 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1186)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1187 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1187)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1188 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1188)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1189 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1189)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1190 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1190)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1191 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1191)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1192 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1192)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1193 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1193)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1194 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1194)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1195 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1195)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1196 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1196)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1197 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1197)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1198 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1198)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
sl81UserTrap1199 = NotificationType((1, 3, 6, 1, 4, 1, 3052, 5) + (0,1199)).setObjects(("SL81-STD-MIB", "siteID"), ("SL81-STD-MIB", "esIndex"), ("SL81-STD-MIB", "esName"), ("SL81-STD-MIB", "trapEventTypeNumber"), ("SL81-STD-MIB", "trapEventTypeName"), ("SL81-STD-MIB", "esIndexPoint"), ("SL81-STD-MIB", "esPointName"), ("SL81-STD-MIB", "esID"), ("SL81-STD-MIB", "clock"), ("SL81-STD-MIB", "trapIncludedValue"), ("SL81-STD-MIB", "trapIncludedString"), ("SL81-STD-MIB", "trapEventClassNumber"), ("SL81-STD-MIB", "trapEventClassName"))
mibBuilder.exportSymbols("SL81-STD-MIB", sl81UserTrap1121=sl81UserTrap1121, sl81UserTrap1140=sl81UserTrap1140, sl81UserTrap1171=sl81UserTrap1171, sl81UserTrap1192=sl81UserTrap1192, techSupport3=techSupport3, trapIncludedValue=trapIncludedValue, sl81UserTrap1191=sl81UserTrap1191, smTable=smTable, trapEventTypeName=trapEventTypeName, sl81UserTrap1024=sl81UserTrap1024, ipConfigAddress=ipConfigAddress, sl81StockContactClosureTrap=sl81StockContactClosureTrap, clock=clock, sl81UserTrap1103=sl81UserTrap1103, sl81UserTrap1048=sl81UserTrap1048, sl81UserTrap1097=sl81UserTrap1097, sl81UserTrap1059=sl81UserTrap1059, sl81UserTrap1198=sl81UserTrap1198, sl81UserTrap1100=sl81UserTrap1100, smEntry=smEntry, sl81UserTrap1039=sl81UserTrap1039, deConfigTrapNumber=deConfigTrapNumber, sl81UserTrap1108=sl81UserTrap1108, sl81UserTrap1117=sl81UserTrap1117, techSupport11=techSupport11, techSupport4=techSupport4, modemTimeBetweenOutbound=modemTimeBetweenOutbound, sl81UserTrap1138=sl81UserTrap1138, sl81UserTrap1170=sl81UserTrap1170, sl81UserTrap1023=sl81UserTrap1023, sl81UserTrap1007=sl81UserTrap1007, deConfigClearTime=deConfigClearTime, esCCReportingMode=esCCReportingMode, techSupport21Table=techSupport21Table, sl81UserTrap1053=sl81UserTrap1053, esNumberRelayOutputs=esNumberRelayOutputs, portConfigStripPtInputLfs=portConfigStripPtInputLfs, sl81UserTrap1173=sl81UserTrap1173, sl81UserTrap1081=sl81UserTrap1081, sl81UserTrap1144=sl81UserTrap1144, sl81UserTrap1185=sl81UserTrap1185, trapEventClassName=trapEventClassName, deConfigName=deConfigName, techSupport3n4=techSupport3n4, productIds=productIds, portConfigTable=portConfigTable, techSupport26=techSupport26, sl81UserTrap1153=sl81UserTrap1153, sl81UserTrap1042=sl81UserTrap1042, pagerType=pagerType, sl81UserTrap1037=sl81UserTrap1037, sl81UserTrap1118=sl81UserTrap1118, techSupport9=techSupport9, sl81UserTrap1186=sl81UserTrap1186, numberPorts=numberPorts, sl81UserTrap1182=sl81UserTrap1182, modemDataFormat=modemDataFormat, esNoiseReportingMode=esNoiseReportingMode, techSupport3n2=techSupport3n2, modemTAPSetup=modemTAPSetup, sl81UserTrap1113=sl81UserTrap1113, sl81UserTrap1165=sl81UserTrap1165, sl81UserTrap1107=sl81UserTrap1107, sl81StockCTSTrap=sl81StockCTSTrap, techSupport=techSupport, sl81UserTrap1096=sl81UserTrap1096, sl81UserTrap1004=sl81UserTrap1004, sl81UserTrap1065=sl81UserTrap1065, deConfigEnabled=deConfigEnabled, sl81UserTrap1000=sl81UserTrap1000, sl81UserTrap1141=sl81UserTrap1141, sl81UserTrap1102=sl81UserTrap1102, stockTrapString=stockTrapString, techSupport20Table=techSupport20Table, sl81UserTrap1074=sl81UserTrap1074, sl81UserTrap1086=sl81UserTrap1086, esTable=esTable, portConfigDAEnable=portConfigDAEnable, deFieldTable=deFieldTable, telnetDuplex=telnetDuplex, techSupport10=techSupport10, sl81UserTrap1050=sl81UserTrap1050, smAddress=smAddress, sl81UserTrap1146=sl81UserTrap1146, sl81UserTrap1106=sl81UserTrap1106, sl81UserTrap1062=sl81UserTrap1062, portConfigMaskEnable=portConfigMaskEnable, techSupport21=techSupport21, deFieldLength=deFieldLength, sl81UserTrap1087=sl81UserTrap1087, sl81UserTrap1003=sl81UserTrap1003, esPointName=esPointName, sl81UserTrap1045=sl81UserTrap1045, deFieldEntry=deFieldEntry, techSupport20Entry=techSupport20Entry, sl81UserTrap1012=sl81UserTrap1012, eventSensorStatus=eventSensorStatus, esIndexPoint=esIndexPoint, sl81StockTempTrap=sl81StockTempTrap, sl81UserTrap1068=sl81UserTrap1068, deConfigAutoClear=deConfigAutoClear, esPointTimetickLastChange=esPointTimetickLastChange, sl81UserTrap1030=sl81UserTrap1030, sl81UserTrap1047=sl81UserTrap1047, deStatusTable=deStatusTable, sl81UserTrap1018=sl81UserTrap1018, sl81UserTrap1126=sl81UserTrap1126, sl81UserTrap1008=sl81UserTrap1008, esNumberAirflowSensors=esNumberAirflowSensors, sl81UserTrap1026=sl81UserTrap1026, deConfigClass=deConfigClass, techSupport20=techSupport20, sl81UserTrap1070=sl81UserTrap1070, sl81UserTrap1163=sl81UserTrap1163, sl81UserTrap1172=sl81UserTrap1172, esAnalogReportingMode=esAnalogReportingMode, sl81UserTrap1021=sl81UserTrap1021, esNumberCCs=esNumberCCs, sl81StockSchedTrap=sl81StockSchedTrap, sl81UserTrap1084=sl81UserTrap1084, sl81UserTrap1199=sl81UserTrap1199, sl81UserTrap1079=sl81UserTrap1079, sl81UserTrap1178=sl81UserTrap1178, deConfigThreshold=deConfigThreshold, deConfigActions=deConfigActions, sl81UserTrap1005=sl81UserTrap1005, sl81UserTrap1128=sl81UserTrap1128, sl81UserTrap1032=sl81UserTrap1032, sl81UserTrap1188=sl81UserTrap1188, sl81UserTrap1058=sl81UserTrap1058, sl81UserTrap1089=sl81UserTrap1089, sl81UserTrap1035=sl81UserTrap1035, deStatusName=deStatusName, sl81=sl81, esIndexPC=esIndexPC, sl81UserTrap1054=sl81UserTrap1054, sl81UserTrap1161=sl81UserTrap1161, ipConfigEngage=ipConfigEngage, sl81StockHumidityTrap=sl81StockHumidityTrap, sl81UserTrap1189=sl81UserTrap1189, sl81UserTrap1130=sl81UserTrap1130, sl81UserTrap1181=sl81UserTrap1181, sl81UserTrap1093=sl81UserTrap1093, sl81UserTrap1190=sl81UserTrap1190, portConfigEntry=portConfigEntry, sl81UserTrap1111=sl81UserTrap1111, sl81UserTrap1052=sl81UserTrap1052, timeouts=timeouts, esNumberAnalog=esNumberAnalog, sl81UserTrap1112=sl81UserTrap1112, esPointValueStr=esPointValueStr, sl81UserTrap1043=sl81UserTrap1043, sl81UserTrap1080=sl81UserTrap1080, sl81UserTrap1193=sl81UserTrap1193, esName=esName, sl81UserTrap1049=sl81UserTrap1049, sl81UserTrap1099=sl81UserTrap1099, sl81UserTrap1197=sl81UserTrap1197, sl81UserTrap1028=sl81UserTrap1028, sl81UserTrap1041=sl81UserTrap1041, sl81UserTrap1092=sl81UserTrap1092, techSupport3n5=techSupport3n5, sl81UserTrap1009=sl81UserTrap1009, sl81UserTrap1011=sl81UserTrap1011, sl81UserTrap1044=sl81UserTrap1044, sl81UserTrap1077=sl81UserTrap1077, sl81UserTrap1157=sl81UserTrap1157, deFieldIndex=deFieldIndex, esPointEntry=esPointEntry, sl81UserTrap1110=sl81UserTrap1110, sl81UserTrap1057=sl81UserTrap1057, sl81UserTrap1162=sl81UserTrap1162, sl81UserTrap1147=sl81UserTrap1147, techSupport25=techSupport25, trapEventTypeNumber=trapEventTypeNumber, sl81UserTrap1027=sl81UserTrap1027, sl81UserTrap1114=sl81UserTrap1114, sl81UserTrap1169=sl81UserTrap1169, sl81UserTrap1071=sl81UserTrap1071, autoDSTAdjust=autoDSTAdjust, sl81UserTrap1015=sl81UserTrap1015, techSupport19=techSupport19, sl81UserTrap1075=sl81UserTrap1075, sl81UserTrap1179=sl81UserTrap1179, sl81UserTrap1139=sl81UserTrap1139, sl81UserTrap1196=sl81UserTrap1196, esIndex=esIndex, sl81StockDataEventTrap=sl81StockDataEventTrap, pagerIndex=pagerIndex, sl81UserTrap1167=sl81UserTrap1167, pagerID=pagerID, sl81UserTrap1104=sl81UserTrap1104, sl81StockESDisconnectTrap=sl81StockESDisconnectTrap, sl81UserTrap1175=sl81UserTrap1175, esNumberNoiseSensors=esNumberNoiseSensors, time=time, thisProduct=thisProduct, sl81UserTrap1133=sl81UserTrap1133, dataEventStatus=dataEventStatus, sl81UserTrap1014=sl81UserTrap1014, sl81UserTrap1055=sl81UserTrap1055, deStatusLastTriggerTime=deStatusLastTriggerTime, sl81UserTrap1115=sl81UserTrap1115, deConfigTable=deConfigTable, passthroughTimeout=passthroughTimeout, sl81UserTrap1046=sl81UserTrap1046, sl81UserTrap1040=sl81UserTrap1040, sl81UserTrap1051=sl81UserTrap1051, sl81UserTrap1083=sl81UserTrap1083, sl81UserTrap1152=sl81UserTrap1152, sl81UserTrap1116=sl81UserTrap1116, esIndexES=esIndexES, sl81UserTrap1119=sl81UserTrap1119, dataEventConfig=dataEventConfig, portConfigIndex=portConfigIndex, pagerEntry=pagerEntry, sl81UserTrap1149=sl81UserTrap1149, sl81UserTrap1038=sl81UserTrap1038, techSupport17=techSupport17, sl81UserTrap1176=sl81UserTrap1176, techSupport21Entry=techSupport21Entry, sl81UserTrap1131=sl81UserTrap1131, sl81UserTrap1061=sl81UserTrap1061, sl81UserTrap1002=sl81UserTrap1002, sl81UserTrap1124=sl81UserTrap1124, techSupport16=techSupport16, portConfigStripPtOutputLfs=portConfigStripPtOutputLfs, sl81UserTrap1109=sl81UserTrap1109, esPointTable=esPointTable, siteID=siteID, sl81UserTrap1166=sl81UserTrap1166, sl81UserTrap1064=sl81UserTrap1064, techSupport3n1=techSupport3n1, sl81UserTrap1136=sl81UserTrap1136, sl81UserTrap1125=sl81UserTrap1125, sl81UserTrap1066=sl81UserTrap1066, esAirflowReportingMode=esAirflowReportingMode, sl81UserTrap1019=sl81UserTrap1019, sl81UserTrap1036=sl81UserTrap1036, techSupport18=techSupport18, sl81UserTrap1127=sl81UserTrap1127, portConfigDataFormat=portConfigDataFormat, trapEventClassNumber=trapEventClassNumber, sl81UserTrap1184=sl81UserTrap1184, esHumidReportingMode=esHumidReportingMode, pagerPostCalloutDelay=pagerPostCalloutDelay, sl81UserTrap1159=sl81UserTrap1159, sl81UserTrap1123=sl81UserTrap1123, smIndex=smIndex, techSupport20Index=techSupport20Index, techSupport7=techSupport7, deStatusThreshold=deStatusThreshold, techSupport22=techSupport22, sl81UserTrap1158=sl81UserTrap1158)
mibBuilder.exportSymbols("SL81-STD-MIB", sl81UserTrap1073=sl81UserTrap1073, portConfigBaud=portConfigBaud, sl81UserTrap1120=sl81UserTrap1120, ipConfigSubnetMask=ipConfigSubnetMask, deFieldName=deFieldName, sl81UserTrap1164=sl81UserTrap1164, sl81UserTrap1006=sl81UserTrap1006, sl81UserTrap1017=sl81UserTrap1017, sl81TestTrap=sl81TestTrap, sl81UserTrap1105=sl81UserTrap1105, sl81UserTrap1088=sl81UserTrap1088, sl81UserTrap1098=sl81UserTrap1098, ipConfigStatic=ipConfigStatic, pagerRetries=pagerRetries, sl81UserTrap1129=sl81UserTrap1129, sl81StockAnalogTrap=sl81StockAnalogTrap, techSupport2n2=techSupport2n2, sl81UserTrap1063=sl81UserTrap1063, deConfigEquation=deConfigEquation, sl81UserTrap1091=sl81UserTrap1091, sl81UserTrap1187=sl81UserTrap1187, sl81UserTrap1025=sl81UserTrap1025, sl81UserTrap1010=sl81UserTrap1010, config=config, sl81UserTrap1067=sl81UserTrap1067, deConfigEntry=deConfigEntry, portConfigDTRLowIdle=portConfigDTRLowIdle, sl81UserTrap1160=sl81UserTrap1160, pagerIDDelay=pagerIDDelay, sl81UserTrap1132=sl81UserTrap1132, modem=modem, sl81UserTrap1033=sl81UserTrap1033, sl81UserTrap1148=sl81UserTrap1148, techSupport3n3=techSupport3n3, sl81UserTrap1029=sl81UserTrap1029, sl81UserTrap1150=sl81UserTrap1150, sl81UserTrap1069=sl81UserTrap1069, sl81UserTrap1194=sl81UserTrap1194, sl81UserTrap1134=sl81UserTrap1134, sl81UserTrap1122=sl81UserTrap1122, techSupport24=techSupport24, sl81UserTrap1056=sl81UserTrap1056, esID=esID, sl81UserTrap1151=sl81UserTrap1151, sl81UserTrap1082=sl81UserTrap1082, techSupport1=techSupport1, snmp=snmp, deConfigClearMode=deConfigClearMode, sl81UserTrap1143=sl81UserTrap1143, sl81UserTrap1078=sl81UserTrap1078, pagers=pagers, network=network, ipConfigDefaultRouter=ipConfigDefaultRouter, sl81UserTrap1177=sl81UserTrap1177, sl81UserTrap1174=sl81UserTrap1174, sl81UserTrap1060=sl81UserTrap1060, deStatusIndex=deStatusIndex, sl81UserTrap1156=sl81UserTrap1156, commandTimeout=commandTimeout, deStatusEntry=deStatusEntry, sl81UserTrap1031=sl81UserTrap1031, sl81UserTrap1142=sl81UserTrap1142, serialPorts=serialPorts, sl81UserTrap1101=sl81UserTrap1101, status=status, sl81UserTrap1013=sl81UserTrap1013, deStatusCounter=deStatusCounter, esNumberTempSensors=esNumberTempSensors, pagerPhoneNumber=pagerPhoneNumber, sl81UserTrap1137=sl81UserTrap1137, deFieldStart=deFieldStart, trapIncludedString=trapIncludedString, esNumberEventSensors=esNumberEventSensors, esPointValueInt=esPointValueInt, modemUserSetup=modemUserSetup, sl81UserTrap1145=sl81UserTrap1145, sl81UserTrap1095=sl81UserTrap1095, esPointInEventState=esPointInEventState, techSupport2n1=techSupport2n1, sl81UserTrap1085=sl81UserTrap1085, esRelayReportingMode=esRelayReportingMode, sl81UserTrap1154=sl81UserTrap1154, pagerTable=pagerTable, sl81UserTrap1168=sl81UserTrap1168, sl81UserTrap1090=sl81UserTrap1090, deConfigIndex=deConfigIndex, deStatusLastTriggerData=deStatusLastTriggerData, sl81UserTrap1001=sl81UserTrap1001, eventSensorBasics=eventSensorBasics, esNumberHumidSensors=esNumberHumidSensors, sl81UserTrap1016=sl81UserTrap1016, sl81UserTrap1135=sl81UserTrap1135, sl81UserTrap1094=sl81UserTrap1094, sl81UserTrap1180=sl81UserTrap1180, esEntry=esEntry, sl81UserTrap1155=sl81UserTrap1155, sl81UserTrap1195=sl81UserTrap1195, techSupport21Index=techSupport21Index, sl81UserTrap1072=sl81UserTrap1072, sl81UserTrap1034=sl81UserTrap1034, sl81UserTrap1020=sl81UserTrap1020, esTempReportingMode=esTempReportingMode, sl81UserTrap1076=sl81UserTrap1076, techSupport2=techSupport2, sl81UserTrap1183=sl81UserTrap1183, sl81UserTrap1022=sl81UserTrap1022, omnitronix=omnitronix, esPointTimeLastChange=esPointTimeLastChange)
|
python
|
from allauth.account.forms import ChangePasswordForm as AllauthChangePasswordForm
class ChangePasswordForm(AllauthChangePasswordForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
del self.fields["oldpassword"].widget.attrs["placeholder"]
del self.fields["password1"].widget.attrs["placeholder"]
del self.fields["password2"].widget.attrs["placeholder"]
|
python
|
"""Tests for the convention subsections."""
import re
import pytest
from tests.test_convention_doc import doctypes
@pytest.fixture(
scope="module",
params=[
pytest.param((index, subsection), id=subsection.identifier)
for section in doctypes.SECTIONS
for index, subsection in enumerate(section.subsections)
],
)
def enumerated_subsections(request):
"""Parametrized fixture of each subsection along with its index in the parent section."""
return request.param
def test_subsection_identifier_valid(subsection):
"""Test that the section's identifier is a valid section identifier and matches expectations."""
assert re.match(r"[A-Z]+\.[1-9][0-9]*", subsection.identifier)
assert subsection.identifier.startswith(subsection.parent.identifier)
def test_subsection_identifiers_strictly_increasing(enumerated_subsections):
"""Test that the subsections in a section use strictly incrementing identifiers."""
index, subsection = enumerated_subsections
assert subsection.identifier.split(".")[-1] == str(index + 1)
def test_subsection_isnt_rule(subsection):
"""Test that we don't use subsections for rules."""
assert not (
subsection.header_text.startswith(" ✔️ **DO**")
or subsection.header_text.startswith(" ✔️ **CONSIDER**")
or subsection.header_text.startswith(" ❌ **AVOID**")
or subsection.header_text.startswith(" ❌ **DO NOT**")
)
def test_subsection_identifier_follows_case_convention(subsection):
"""Test that the subsection header starts with an uppercase letter."""
header_text = subsection.header_text.lstrip()
assert header_text[0].isupper(), "header should start with an uppercase letter"
|
python
|
from PKG.models import ResnetV2
import tensorflow as tf
class Classifier(tf.keras.models.Model):
def __init__(self, nclasses, weights=None):
super(Classifier, self).__init__()
self.nn = ResnetV2()
self.classifier = tf.keras.layers.Dense(nclasses)
self.activation = tf.keras.layers.Activation("softmax")
self.dropout = tf.keras.layers.Dropout(0.3)
def call(self, X, training=False):
Y = self.nn(X)
Y = self.classifier(Y)
Y = self.activation(Y)
Y = self.dropout(Y, training=training)
return Y
|
python
|
from helpers.observerpattern import Observable
from HTMLParser import HTMLParser
class DomBuilder(Observable, HTMLParser):
"""
This class is on charge of parse the plainHTML provided via a Reader and construct
a dom representation with it. DOM structure is decoupled from this class and need
to be passed at the time of construction.
"""
# Some elements don't have a closing tag ( https://www.w3.org/TR/html51/syntax.html#void-elements )
voidTags = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen",
"link", "menuitem", "meta", "param", "source", "track", "wbr"] # const
def __init__(self, dom):
HTMLParser.__init__(self)
self.dom = dom
self.actualParent = [None,]
def _finishParsing(self):
self._trigger("ParsingFinished", { 'dom': self.dom })
def handle_starttag(self, tag, attrs):
element = (tag, attrs, self.actualParent[-1])
nodeIndex = self.dom.addNode( element )
if tag not in self.voidTags:
self.actualParent.append( nodeIndex )
def handle_endtag(self, tag):
if tag in self.voidTags:
return # We already did the job
actualParent = self.actualParent.pop()
if self.dom.getNode( actualParent )[0] != tag:
raise Exception("DomBuilder - Closing tag is missing") # TODO: Custom error object. (ParseEror ?)
if self.actualParent[-1] == None:
self._finishParsing()
|
python
|
class Eventseverity(basestring):
"""
EMERGENCY|ALERT|CRITICAL|ERROR|WARNING|NOTICE|INFORMATIONAL|DEBUG
Possible values:
<ul>
<li> "emergency" - System is unusable,
<li> "alert" - Action must be taken immediately,
<li> "critical" - Critical condition,
<li> "error" - Error condition,
<li> "warning" - Warning condition,
<li> "notice" - Normal but significant condition,
<li> "informational" - Information message,
<li> "debug" - A debugging message
</ul>
"""
@staticmethod
def get_api_name():
return "eventseverity"
|
python
|
from .attachment import Attachment
from .integration import Integration
from .message import Message
from .field import Field
|
python
|
""" 152. Maximum Product Subarray
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
"""
class Solution:
def maxProduct(self, nums: List[int]) -> int:
if len(nums) == 0: return 0
if len(nums) == 1: return nums[0]
leftIndex, totalProd = 0,1
prodArray = [0]
for i in range(len(nums)):
if nums[i] == 0:
prodArray.append(Solution.nonNegProd(self, nums[leftIndex:i]))
leftIndex = i+1
prodArray.append(Solution.nonNegProd(self, nums[leftIndex:len(nums)]))
return max(prodArray)
def nonNegProd(self, nums: List[int]) -> int:
if len(nums) == 0: return 0
if len(nums) == 1: return nums[0]
numNeg, totalProd = 0, 1
for i in range(len(nums)):
totalProd*=nums[i]
if nums[i] < 0: numNeg+=1
if numNeg % 2 ==0: return totalProd
leftProd, rightProd = totalProd, totalProd
for i in range(len(nums)-1,-1,-1):
leftProd/=nums[i]
if nums[i] < 0: break
for i in range(len(nums)):
rightProd/=nums[i]
if nums[i] < 0: break
return int(leftProd) if leftProd > rightProd else int(rightProd)
|
python
|
import numpy as np
import math
import matplotlib.pyplot as plt
from bandit import Bandit
from explore_then_exploit_agent import ExploreThenExploit
from MC_simulator import *
from epsilon_greedy_agent import EpsilonGreedy
from ubc1_agent import UBC1Agent
from report import plot
|
python
|
# -*- coding: utf-8 -*-
# import the necessary packages
from tnmlearn.nn.conv import MiniVGGNet
from keras.optimizers import SGD
from tnmlearn.examples import BaseLearningModel
from tnmlearn.datasets import load_cifar10
# %%
class MiniVggNetCifar10(BaseLearningModel):
def __init__(self):
super(MiniVggNetCifar10, self).__init__()
def getData(self):
((self.trainX, self.trainY),
(self.testX, self.testY),
self.classNames) = load_cifar10()
def build(self):
# initialize the optimizer and model
print("[INFO] compiling model...")
opt = SGD(lr=0.01, decay=0.01 / 40, momentum=0.9, nesterov=True)
self.model = MiniVGGNet.build(width=32, height=32, depth=3, classes=10)
self.model.compile(loss="categorical_crossentropy", optimizer=opt,
metrics=["accuracy"])
def fit(self):
return self.fit_(40, 64)
def evaluate(self):
self.evaluate_(64)
|
python
|
from app.order.domain.order import Order
from app.order.domain.order_repository import OrderRepository
class SqlOrderRepository(OrderRepository):
def __init__(self, session):
self.session = session
def save(self, order: Order):
self.session.add(order)
self.session.commit()
def find_all(self):
return self.session.query(Order).all()
def find_by_id(self, id: int):
return self.session.query(Order).filter(Order.id == id).first()
|
python
|
import os
import numpy as np
from copy import copy
from easyric.io import pix4d, geotiff, shp, plot
from easyric.calculate import geo2raw, geo2tiff, raw2raw
####################
# Software wrapper #
####################
class Pix4D:
def __init__(self, project_path, raw_img_path=None, project_name=None,
param_folder=None, dom_path=None, dsm_path=None, ply_path=None):
######################
# Project Attributes #
######################
self.project_path = self._get_full_path(project_path)
sub_folder = os.listdir(self.project_path)
if project_name is None:
self.project_name = os.path.basename(self.project_path)
else:
self.project_name = project_name
if raw_img_path is not None:
self.raw_img_path = os.path.normpath(raw_img_path)
else:
self.raw_img_path = None
#################
# Project Files #
#################
self.xyz_file = None
self.pmat_file = None
self.cicp_file = None
self.ccp_file = None
self.campos_file = None
self.ply_file = None
self.dom_file = None
self.dsm_file = None
self.dom_header = None
self.dsm_header = None
if '1_initial' in sub_folder:
self._original_specify()
else:
if param_folder is None:
raise FileNotFoundError(f'[Wrapper][Pix4D] Current folder |{self.project_path}| is not a standard '
f'pix4d default projects, "1_initial" folder not found and `param_folder` not specified')
else:
self._manual_specify(param_folder, dom_path, dsm_path, ply_path)
if self.dom_file is not None:
self.dom_header = geotiff.get_header(self.dom_file)
if self.dsm_file is not None:
self.dsm_header = geotiff.get_header(self.dsm_file)
###############
# Init Params #
###############
# --------------------
# >>> p4d.offset.x
# 368109.00
# >>> p4d.Py
# 3.9716578516421746
# >>> p4d.img[0].name
# ''DJI_0172.JPG''
# >>> p4d.img['DJI_0172.JPG']
# <class Image>
# >>> p4d.img[0].pmat
# pmat_ndarray
# --------------------
self.offset = None
self.img = None
# from cicp file
self.F = None
self.Px = None
self.Py = None
self.K1 = None
self.K2 = None
self.K3 = None
self.T1 = None
self.T2 = None
self.offset = OffSet(self._get_offsets())
self.img_pos = self._get_campos_df()
vars(self).update(self._get_cicp_dict())
self.img = ImageSet(img_path=self.raw_img_path,
pmat_dict=self._get_pmat_dict(),
ccp_dict=self._get_ccp_dict(),
img_pos=self.img_pos)
def _original_specify(self):
sub_folder = os.listdir(self.project_path)
self.xyz_file = f"{self.project_path}/1_initial/params/{self.project_name}_offset.xyz"
self.pmat_file = f"{self.project_path}/1_initial/params/{self.project_name}_pmatrix.txt"
self.cicp_file = f"{self.project_path}/1_initial/params/{self.project_name}_pix4d_calibrated_internal_camera_parameters.cam"
self.ccp_file = f"{self.project_path}/1_initial/params/{self.project_name}_calibrated_camera_parameters.txt"
self.campos_file = f"{self.project_path}/1_initial/params/{self.project_name}_calibrated_images_position.txt"
if self.raw_img_path is None:
undistorted_path = f"{self.project_path}/1_initial/images/undistorted_images"
if os.path.exists(undistorted_path):
self.raw_img_path = undistorted_path
else:
raise FileNotFoundError("raw image file not given, and could not find undistorted images outputs in Pix4D project")
self.ply_file = None
if '2_densification' in sub_folder:
dens_folder = f"{self.project_path}/2_densification/point_cloud"
self.ply_file = self._check_end(dens_folder, '.ply')
self.dom_file = None
self.dsm_file = None
if '3_dsm_ortho' in sub_folder:
dsm_folder = f"{self.project_path}/3_dsm_ortho/1_dsm"
dom_folder = f"{self.project_path}/3_dsm_ortho/2_mosaic"
self.dsm_file = self._check_end(dsm_folder, '.tif')
self.dom_file = self._check_end(dom_folder, '.tif')
def _manual_specify(self, param_folder, dom_path=None, dsm_path=None, ply_path=None):
self.xyz_file = self._get_full_path(f"{param_folder}/{self.project_name}_offset.xyz")
self.pmat_file = self._get_full_path(f"{param_folder}/{self.project_name}_pmatrix.txt")
self.cicp_file = self._get_full_path(f"{param_folder}/{self.project_name}_pix4d_calibrated_internal_camera_parameters.cam")
self.ccp_file = self._get_full_path(f"{param_folder}/{self.project_name}_calibrated_camera_parameters.txt")
self.campos_file = self._get_full_path(f"{param_folder}/{self.project_name}_calibrated_images_position.txt")
if ply_path is None:
try_ply = f"{self.project_name}_group1_densified_point_cloud.ply"
self.ply_file = self._get_full_path(f"{self.project_path}/{try_ply}")
if self.ply_file is not None:
print(f"[Init][Pix4D] No ply given, however find '{try_ply}' at current project folder")
else:
self.ply_file = self._get_full_path(ply_path)
if dom_path is None:
try_dom = f"{self.project_name}_transparent_mosaic_group1.tif"
self.dom_file = self._get_full_path(f"{self.project_path}/{try_dom}")
if self.dom_file is not None:
print(f"[Init][Pix4D] No dom given, however find '{try_dom}' at current project folder")
else:
self.dom_file = self._get_full_path(dom_path)
if dsm_path is None:
try_dsm = f"{self.project_name}_dsm.tif"
self.dsm_file = self._get_full_path(f"{self.project_path}/{try_dsm}")
if self.dsm_file is not None:
print(f"[Init][Pix4D] No dsm given, however find '{try_dsm}' at current project folder")
else:
self.dsm_file = self._get_full_path(dsm_path)
@staticmethod
def _check_end(folder, ext):
find_path = None
if os.path.exists(folder):
# find the first ply file as output (may cause problem)
for file in os.listdir(folder):
if file.endswith(ext):
find_path = f"{folder}/{file}"
break
return find_path
@staticmethod
def _get_full_path(short_path):
if isinstance(short_path, str):
return os.path.abspath(os.path.normpath(short_path)).replace('\\', '/')
else:
return None
def _get_offsets(self):
return pix4d.read_xyz(self.xyz_file)
def _get_pmat_dict(self):
return pix4d.read_pmat(self.pmat_file)
def _get_ccp_dict(self):
return pix4d.read_ccp(self.ccp_file)
def _get_cicp_dict(self):
return pix4d.read_cicp(self.cicp_file)
def _get_campos_df(self):
return pix4d.read_cam_pos(self.campos_file)
#################
# Easy use apis #
#################
# ======== io.shp =========
def read_shp2d(self, shp_path, shp_proj=None, geotiff_proj=None):
if geotiff_proj is None:
proj = self.dsm_header['proj']
elif geotiff_proj == 'Null': # the special params to do noting transfrom
proj = None
else:
proj = geotiff_proj
shp_dict = shp.read_shp2d(shp_path, shp_proj=shp_proj, geotiff_proj=proj)
return shp_dict
def read_shp3d(self, shp_path, get_z_by='mean', get_z_buffer=0, shp_proj=None, geotiff_proj=None):
shp_dict = shp.read_shp3d(shp_path, self.dsm_file, get_z_by, get_z_buffer, shp_proj, geotiff_proj, geo_head=self.dsm_header)
return shp_dict
# ======== io.geotiff =========
# ======== io.plot =========
# ======== calculate.geo2raw =========
# ======== calculate.geo2tiff =========
# ======== calculate.raw2raw =========
class PhotoScan:
pass
class OpenSfM:
pass
#################
# Used Objects #
#################
class OffSet:
def __init__(self, offsets):
self.x = offsets[0]
self.y = offsets[1]
self.z = offsets[2]
self.np = np.asarray(offsets)
class ImageSet:
def __init__(self, img_path, pmat_dict, ccp_dict, img_pos):
# container for external camera parameters for all raw images
pix4d_used = list(ccp_dict.keys())
self.names = []
self.img = []
# in case the img_path has subfolders
for fpathe, dirs, fs in os.walk(img_path):
for f in fs:
full_path = os.path.join(fpathe,f)
if f in pix4d_used:
# f is img_name
temp = copy(ccp_dict[f])
temp['name'] = f
temp['pmat'] = pmat_dict[f]
temp['path'] = full_path
temp["cam_pos"] = img_pos.loc[f, :].values
self.img.append(Image(**temp))
self.names.append(f)
def __getitem__(self, key):
if isinstance(key, int): # index by photo name
return self.img[key]
elif isinstance(key, str): # index by photo order
return self.img[self.names.index(key)]
elif isinstance(key, slice):
return self.img[key]
else:
print(key)
return None
class Image:
def __init__(self, name, path, w, h, pmat, cam_matrix, rad_distort, tan_distort, cam_pos, cam_rot):
# external parameters
self.name = name
self.path = path
self.w = w
self.h = h
self.pmat = pmat
self.cam_matrix = cam_matrix
self.rad_distort = rad_distort
self.tan_distort = tan_distort
self.cam_pos = cam_pos
self.cam_rot = cam_rot
|
python
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 8 14:38:17 2018
@author: jgoldstein
"""
# try to get some simulated PTA data like in Jeff Hazboun's github https://github.com/Hazboun6/pta_simulations
import numpy as np
import glob, os
import matplotlib.pyplot as plt
plt.rcParams['figure.dpi'] = 2.5 * 72
import astropy
from astropy.time import Time
import enterprise
from enterprise.pulsar import Pulsar
import enterprise_extensions
from enterprise_extensions import models, model_utils
import libstempo as T2, libstempo.toasim as LT, libstempo.plot as LP
from ephem import Ecliptic, Equatorial
# can use LT.fakepulsar to create a fake libstempo tempopulsar
# LT.fakepulsar(parfile, obstimes, toaerr, [optional params])
# first need to get par files
# downloaded IPTA DR2 in /Documents/data/DR2
# maybe try to use .par files from DR2/release/VersionB/... for a bunch of pulsars?
SOURCE = '/home/jgoldstein/Documents/data/DR2/release/VersionB'
def fake_obs_times(source, cadence=20):
"""
For all pulsars in source, generate some fake observation times
Read start and finish from the pulsar .par file. Then pick random times
with a given average cadence (in days).
Parameters
----------
source: str
path to pulsars with .par files in 'pulsar'/'pulsar'.IPTADR2.par
cadence: scalar
default = 20
average cadence (in days) for fake observations
Returns
-------
list:
pulsar names
NumPy array:
observation times in MJD for each pulsar
"""
pulsars = os.listdir(source)
observation_times = []
for p in pulsars:
parfile = os.path.join(source, p, '{}.IPTADR2.par'.format(p))
# read start and end of the observation from parfile, then get some random obs times
with open(parfile) as parf:
for line in parf:
if 'START' in line:
start = float(line.split()[1])
elif 'FINISH' in line:
finish = float(line.split()[1])
break
# pick n random observation times so that total time / n = cadence
num_obs = int((finish - start) / cadence)
obs = np.sort(np.random.randint(start, high=finish, size=num_obs))
observation_times.append(obs)
return pulsars, observation_times
def make_fake_pulsar(source, pulsar_name, obs_times, toa_err=1e-6):
"""
Make an LT fakepulsar
Parameters
----------
source: str
path to pulsars with .par files in 'pulsar'/'pulsar'.IPTADR2.pa
pulsar_name: str
name of the pulsar (is also the directory with files in source)
obs_times: array-like
times of observation in MJD
toa_err: float
toa error in us
Returns
-------
LT.fakepulsar object
"""
par_path = os.path.join(source, pulsar_name, pulsar_name+'.IPTADR2.par')
return LT.fakepulsar(par_path, obs_times, toa_err)
|
python
|
N = int(input())
ans = 0
if N % 100 == 0:
ans = N // 100
else:
ans = (N // 100) + 1
print(ans)
|
python
|
#_*_ coding: utf-8 -*-
{
'name': "Carlosma7",
'summary': """
This is the summary of the addon, second try.""",
'description': """
This is the description of the addon.
""",
'author': "Carlos Morales Aguilera",
'website': "http://www.carlosma7.com",
'category': 'Personal project',
'version':'0.1',
'application': True,
'depends': ['base','sale','mail'],
'data': [
'data/data.xml',
'security/ir.model.access.csv',
'views/patient.xml',
'views/kids.xml',
'views/patient_gender.xml',
'views/appointment.xml',
'views/sale.xml',
'views/doctor.xml',
'wizard/create_appointment.xml'],
'installable': True,
'auto_install': True,
}
|
python
|
#
# PySNMP MIB module BENU-HTTP-CLIENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BENU-HTTP-CLIENT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:37:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint")
benuWAG, = mibBuilder.importSymbols("BENU-WAG-MIB", "benuWAG")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
ObjectIdentity, Counter64, TimeTicks, Gauge32, iso, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, NotificationType, Integer32, ModuleIdentity, Bits, Unsigned32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "Counter64", "TimeTicks", "Gauge32", "iso", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "NotificationType", "Integer32", "ModuleIdentity", "Bits", "Unsigned32", "MibIdentifier")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
benuHttpClientMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11))
benuHttpClientMIB.setRevisions(('2015-10-21 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: benuHttpClientMIB.setRevisionsDescriptions(('Initial Version',))
if mibBuilder.loadTexts: benuHttpClientMIB.setLastUpdated('201510210000Z')
if mibBuilder.loadTexts: benuHttpClientMIB.setOrganization('Benu Networks,Inc')
if mibBuilder.loadTexts: benuHttpClientMIB.setContactInfo('Benu Networks,Inc Corporate Headquarters 300 Concord Road, Suite 110 Billerica, MA 01821 USA Tel: +1 978-223-4700 Fax: +1 978-362-1908 Email: [email protected]')
if mibBuilder.loadTexts: benuHttpClientMIB.setDescription('This MIB module defines management information related to the HTTP client. Copyright (C) 2013 by Benu Networks, Inc. All rights reserved.')
bHttpClientObjects = ObjectIdentity((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1))
if mibBuilder.loadTexts: bHttpClientObjects.setStatus('current')
if mibBuilder.loadTexts: bHttpClientObjects.setDescription('HTTP client information is defined in this branch.')
bHttpClientLatencyTable = MibTable((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1), )
if mibBuilder.loadTexts: bHttpClientLatencyTable.setStatus('current')
if mibBuilder.loadTexts: bHttpClientLatencyTable.setDescription('Latency information list for HTTP client.')
bHttpClientLatencyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1), ).setIndexNames((0, "BENU-HTTP-CLIENT-MIB", "bHttpClientLatencyStatsInterval"))
if mibBuilder.loadTexts: bHttpClientLatencyEntry.setStatus('current')
if mibBuilder.loadTexts: bHttpClientLatencyEntry.setDescription('A logical row in the bHttpClientLatencyTable.')
bHttpClientLatencyStatsInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 1), Integer32())
if mibBuilder.loadTexts: bHttpClientLatencyStatsInterval.setStatus('current')
if mibBuilder.loadTexts: bHttpClientLatencyStatsInterval.setDescription('The interval during which the measurements were accumulated. The interval index one indicates the latest interval for which statistics accumulation was completed. Older the statistics data, greater the interval index value. In a system supporting a history of n intervals with IntervalCount(1) and IntervalCount(n), the most and least recent intervals respectively, the following applies at the end of an interval: - discard the value of IntervalCount(n) - the value of IntervalCount(i) becomes that of IntervalCount(i+1) for 1 <= i < n - the value of IntervalCount(1) becomes that of CurrentCount.')
bHttpClientLatencyStatsIntervalDuration = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientLatencyStatsIntervalDuration.setStatus('current')
if mibBuilder.loadTexts: bHttpClientLatencyStatsIntervalDuration.setDescription('Http client latency stats interval duration.')
bHttpClientLatencyTotalPktCount = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientLatencyTotalPktCount.setStatus('current')
if mibBuilder.loadTexts: bHttpClientLatencyTotalPktCount.setDescription('The count of the total number of packets handled by http client.')
bHttpClientLatencyMaxProcessingTime = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientLatencyMaxProcessingTime.setStatus('current')
if mibBuilder.loadTexts: bHttpClientLatencyMaxProcessingTime.setDescription('Maximum packet processing time handled by http client in micro seconds.')
bHttpClientLatencyMinProcessingTime = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientLatencyMinProcessingTime.setStatus('current')
if mibBuilder.loadTexts: bHttpClientLatencyMinProcessingTime.setDescription('Minimum packet processing time handled by http client in micro seconds.')
bHttpClientLatencyAvgProcessingTime = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 6), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientLatencyAvgProcessingTime.setStatus('current')
if mibBuilder.loadTexts: bHttpClientLatencyAvgProcessingTime.setDescription('Average packet processing time handled by http client in micro seconds.')
bHttpClientLatencyProcessTimeMorethan10MSPktCount = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 7), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientLatencyProcessTimeMorethan10MSPktCount.setStatus('current')
if mibBuilder.loadTexts: bHttpClientLatencyProcessTimeMorethan10MSPktCount.setDescription('Number of packets took more than 10 milli second processing time handled by http client.')
bHttpClientServReqLatencyTotalPktCount = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 8), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientServReqLatencyTotalPktCount.setStatus('current')
if mibBuilder.loadTexts: bHttpClientServReqLatencyTotalPktCount.setDescription('Total number of http server request packets handled by http client.')
bHttpClientServReqLatencyMaxProcessingTime = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 9), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientServReqLatencyMaxProcessingTime.setStatus('current')
if mibBuilder.loadTexts: bHttpClientServReqLatencyMaxProcessingTime.setDescription('Http server request handled by http client maximum packet processing time in micro seconds.')
bHttpClientServReqLatencyMinProcessingTime = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 10), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientServReqLatencyMinProcessingTime.setStatus('current')
if mibBuilder.loadTexts: bHttpClientServReqLatencyMinProcessingTime.setDescription('Http server request handled by http client minimum packet processing time in micro seconds.')
bHttpClientServReqLatencyAvgProcessingTime = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 11), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientServReqLatencyAvgProcessingTime.setStatus('current')
if mibBuilder.loadTexts: bHttpClientServReqLatencyAvgProcessingTime.setDescription('Http server request handled by http client average packet processing time in micro seconds.')
bHttpClientServReqLatencyProcessTimeMorethan10MSPktCount = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 12), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientServReqLatencyProcessTimeMorethan10MSPktCount.setStatus('current')
if mibBuilder.loadTexts: bHttpClientServReqLatencyProcessTimeMorethan10MSPktCount.setDescription('Number of http server request packets handled by http client took more than 10 milli second processing time.')
bHttpClientJsonParsingLatencyTotalPktCount = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 13), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientJsonParsingLatencyTotalPktCount.setStatus('current')
if mibBuilder.loadTexts: bHttpClientJsonParsingLatencyTotalPktCount.setDescription('Total number of packets handled by http client - JSON parsing.')
bHttpClientJsonParsingLatencyMaxProcessingTime = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 14), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientJsonParsingLatencyMaxProcessingTime.setStatus('current')
if mibBuilder.loadTexts: bHttpClientJsonParsingLatencyMaxProcessingTime.setDescription('Maximum packet processing time for JSON parsing handled by httpclient in micro seconds.')
bHttpClientJsonParsingLatencyMinProcessingTime = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 15), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientJsonParsingLatencyMinProcessingTime.setStatus('current')
if mibBuilder.loadTexts: bHttpClientJsonParsingLatencyMinProcessingTime.setDescription('Minimum packet processing time for JSON parsing handled by httpclient in micro seconds.')
bHttpClientJsonParsingLatencyAvgProcessingTime = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 16), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientJsonParsingLatencyAvgProcessingTime.setStatus('current')
if mibBuilder.loadTexts: bHttpClientJsonParsingLatencyAvgProcessingTime.setDescription('Average packet processing time for JSON parsing handled by httpclient in micro seconds.')
bHttpClientJsonParsingLatencyProcessTimeMorethan10MS = MibTableColumn((1, 3, 6, 1, 4, 1, 39406, 2, 1, 11, 1, 1, 1, 17), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bHttpClientJsonParsingLatencyProcessTimeMorethan10MS.setStatus('current')
if mibBuilder.loadTexts: bHttpClientJsonParsingLatencyProcessTimeMorethan10MS.setDescription('Number of packets handled by http client for JSON parsing took more than 10 milli second processing time.')
mibBuilder.exportSymbols("BENU-HTTP-CLIENT-MIB", bHttpClientJsonParsingLatencyAvgProcessingTime=bHttpClientJsonParsingLatencyAvgProcessingTime, bHttpClientLatencyProcessTimeMorethan10MSPktCount=bHttpClientLatencyProcessTimeMorethan10MSPktCount, bHttpClientServReqLatencyMinProcessingTime=bHttpClientServReqLatencyMinProcessingTime, bHttpClientJsonParsingLatencyMaxProcessingTime=bHttpClientJsonParsingLatencyMaxProcessingTime, PYSNMP_MODULE_ID=benuHttpClientMIB, bHttpClientObjects=bHttpClientObjects, benuHttpClientMIB=benuHttpClientMIB, bHttpClientLatencyTable=bHttpClientLatencyTable, bHttpClientLatencyMaxProcessingTime=bHttpClientLatencyMaxProcessingTime, bHttpClientLatencyAvgProcessingTime=bHttpClientLatencyAvgProcessingTime, bHttpClientJsonParsingLatencyMinProcessingTime=bHttpClientJsonParsingLatencyMinProcessingTime, bHttpClientServReqLatencyMaxProcessingTime=bHttpClientServReqLatencyMaxProcessingTime, bHttpClientServReqLatencyProcessTimeMorethan10MSPktCount=bHttpClientServReqLatencyProcessTimeMorethan10MSPktCount, bHttpClientJsonParsingLatencyProcessTimeMorethan10MS=bHttpClientJsonParsingLatencyProcessTimeMorethan10MS, bHttpClientLatencyStatsInterval=bHttpClientLatencyStatsInterval, bHttpClientLatencyStatsIntervalDuration=bHttpClientLatencyStatsIntervalDuration, bHttpClientJsonParsingLatencyTotalPktCount=bHttpClientJsonParsingLatencyTotalPktCount, bHttpClientServReqLatencyAvgProcessingTime=bHttpClientServReqLatencyAvgProcessingTime, bHttpClientLatencyEntry=bHttpClientLatencyEntry, bHttpClientLatencyMinProcessingTime=bHttpClientLatencyMinProcessingTime, bHttpClientServReqLatencyTotalPktCount=bHttpClientServReqLatencyTotalPktCount, bHttpClientLatencyTotalPktCount=bHttpClientLatencyTotalPktCount)
|
python
|
"""
.. module:: __init__
:synopsis: This is where all our global variables and instantiation
happens. If there is simple app setup to do, it can be done here, but
more complex work should be farmed off elsewhere, in order to keep
this file readable.
.. moduleauthor:: Dan Schlosser <dan@[email protected]>
"""
import json
import logging
from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flask.ext.assets import Environment, Bundle
db = MongoEngine()
app = None
adi = dict()
assets = None
gcal_client = None
def create_app(**config_overrides):
"""This is normal setup code for a Flask app, but we give the option
to provide override configurations so that in testing, a different
database can be used.
"""
from app.routes.base import register_error_handlers
# we want to modify the global app, not a local copy
global app
global adi
global assets
global gcal_client
app = Flask(__name__)
# Load config then apply overrides
app.config.from_object('config.flask_config')
app.config.update(config_overrides)
# Initialize assets
assets = Environment(app)
register_scss()
# Setup the database.
db.init_app(app)
# Attach Blueprints (routing) to the app
register_blueprints(app)
# Attache error handling functions to the app
register_error_handlers(app)
# Register the logger.
register_logger(app)
return app
def register_logger(app):
"""Create an error logger and attach it to ``app``."""
max_bytes = int(app.config["LOG_FILE_MAX_SIZE"]) * 1024 * 1024 # MB to B
# Use "# noqa" to silence flake8 warnings for creating a variable that is
# uppercase. (Here, we make a class, so uppercase is correct.)
Handler = logging.handlers.RotatingFileHandler # noqa
f_str = ('%(levelname)s @ %(asctime)s @ %(filename)s '
'%(funcName)s %(lineno)d: %(message)s')
access_handler = Handler(app.config["WERKZEUG_LOG_NAME"],
maxBytes=max_bytes)
access_handler.setLevel(logging.INFO)
logging.getLogger("werkzeug").addHandler(access_handler)
app_handler = Handler(app.config["APP_LOG_NAME"], maxBytes=max_bytes)
formatter = logging.Formatter(f_str)
app_handler.setLevel(logging.INFO)
app_handler.setFormatter(formatter)
app.logger.addHandler(app_handler)
def register_blueprints(app):
"""Registers all the Blueprints (modules) in a function, to avoid
circular dependancies.
Be careful rearranging the order of the app.register_blueprint()
calls, as it can also result in circular dependancies.
"""
from app.routes import client
app.register_blueprint(client)
def register_scss():
"""Registers the Flask-Assets rules for scss compilation. This reads from
``config/scss.json`` to make these rules.
"""
assets.url = app.static_url_path
with open(app.config['SCSS_CONFIG_FILE']) as f:
bundle_set = json.loads(f.read())
output_folder = bundle_set['output_folder']
depends = bundle_set['depends']
for bundle_name, instructions in bundle_set['rules'].iteritems():
bundle = Bundle(*instructions['inputs'],
output=output_folder + instructions['output'],
depends=depends,
filters='scss')
assets.register(bundle_name, bundle)
def run():
"""Runs the app."""
app.run(host=app.config.get('HOST'), port=app.config.get('PORT'))
|
python
|
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. 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.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python 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
# 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.
###############################################################################
"""
This module includes a collection of testing functions for the QuTiP scattering
module. Tests are approximate with low resolution to minimize runtime.
"""
# Author: Ben Bartlett
# Contact: [email protected]
import numpy as np
from numpy.testing import assert_, run_module_suite
from qutip.operators import create, destroy
from qutip.states import basis
from qutip.scattering import *
class TestScattering:
"""
A test class for the QuTiP quantum optical scattering module. These tests
only use the two-level system for comparison, since larger systems can
take a long time to run.
"""
def testScatteringProbability(self):
"""
Asserts that pi pulse in TLS has P0 ~ 0 and P0+P1+P2 ~ 1
"""
w0 = 1.0 * 2 * np.pi
gamma = 1.0
sm = np.sqrt(gamma) * destroy(2)
pulseArea = np.pi
pulseLength = 0.2 / gamma
RabiFreq = pulseArea / (2 * pulseLength)
psi0 = basis(2, 0)
tlist = np.geomspace(gamma, 10 * gamma, 40) - gamma
# Define TLS Hamiltonian
H0S = w0 * create(2) * destroy(2)
H1S1 = lambda t, args: \
RabiFreq * 1j * np.exp(-1j * w0 * t) * (t < pulseLength)
H1S2 = lambda t, args: \
RabiFreq * -1j * np.exp(1j * w0 * t) * (t < pulseLength)
Htls = [H0S, [sm.dag(), H1S1], [sm, H1S2]]
# Run the test
P0 = scattering_probability(Htls, psi0, 0, [sm], tlist)
P1 = scattering_probability(Htls, psi0, 1, [sm], tlist)
P2 = scattering_probability(Htls, psi0, 2, [sm], tlist)
assert_(P0 < 1e-3)
assert_(np.abs(P0 + P1 + P2 - 1) < 1e-3)
def testScatteringAmplitude(self):
"""
Asserts that a 2pi pulse in TLS has ~0 amplitude after pulse
"""
w0 = 1.0 * 2 * np.pi
gamma = 1.0
sm = np.sqrt(gamma) * destroy(2)
pulseArea = 2 * np.pi
pulseLength = 0.2 / gamma
RabiFreq = pulseArea / (2 * pulseLength)
psi0 = basis(2, 0)
T = 50
tlist = np.linspace(0, 1 / gamma, T)
# Define TLS Hamiltonian
H0S = w0 * create(2) * destroy(2)
H1S1 = lambda t, args: \
RabiFreq * 1j * np.exp(-1j * w0 * t) * (t < pulseLength)
H1S2 = lambda t, args: \
RabiFreq * -1j * np.exp(1j * w0 * t) * (t < pulseLength)
Htls = [H0S, [sm.dag(), H1S1], [sm, H1S2]]
# Run the test
state = temporal_scattered_state(Htls, psi0, 1, [sm], tlist)
basisVec = temporal_basis_vector([[40]], T)
amplitude = np.abs((basisVec.dag() * state).full().item())
assert_(amplitude < 1e-3)
def testWaveguideSplit(self):
"""
Checks that a trivial splitting of a waveguide collapse operator like
[sm] -> [sm/sqrt2, sm/sqrt2] doesn't affect the normalization or result
"""
gamma = 1.0
sm = np.sqrt(gamma) * destroy(2)
pulseArea = np.pi
pulseLength = 0.2 / gamma
RabiFreq = pulseArea / (2 * pulseLength)
psi0 = basis(2, 0)
tlist = np.geomspace(gamma, 10 * gamma, 40) - gamma
# Define TLS Hamiltonian with rotating frame transformation
Htls = [[sm.dag() + sm, lambda t, args: RabiFreq * (t < pulseLength)]]
# Run the test
c_ops = [sm]
c_ops_split = [sm / np.sqrt(2), sm / np.sqrt(2)]
P1 = scattering_probability(Htls, psi0, 1, c_ops, tlist)
P1_split = scattering_probability(Htls, psi0, 1, c_ops_split, tlist)
tolerance = 1e-7
assert_(1 - tolerance < P1 / P1_split < 1 + tolerance)
if __name__ == "__main__":
run_module_suite()
|
python
|
""" Unit test for re module"""
import unittest
import re
class ReTests(unittest.TestCase):
def test_findall(self):
#Skulpt is failing all the commented out tests in test_findall and it shouldn't be
val = re.findall("From","dlkjdsljkdlkdsjlk")
self.assertEqual(len(val), 0)
val = re.findall("From","dlkjd From kdsjlk")
self.assertEqual(len(val), 1)
val = re.findall("From","From dlkjd From kdsjlk")
self.assertEqual(len(val), 2)
val = re.findall("[0-9]+/[0-9]+","1/2 1/3 3/4 1/8 fred 10/0")
self.assertEqual(len(val), 5)
a = re.findall(string="A stitch in time saves nine.", flags=re.IGNORECASE, pattern="a")
self.assertEqual(a, ['A', 'a'])
a = re.findall("[a-z]*ei[a-z]*", "Is Dr. Greiner your friend, Julie?", re.IGNORECASE)
self.assertEqual(a, ['Greiner'])
b = re.findall("[a-z]*(ei|ie)[a-z]*", "Is Dr. Greiner your friend, Julie?", re.IGNORECASE)
self.assertEqual(b, ['ei', 'ie', 'ie'])
c = re.findall("[a-z]*(ei|ie)([a-z]*)", "Is Dr. Greiner your friend, Julie?", re.IGNORECASE)
self.assertEqual(c, [('ei', 'ner'), ('ie', 'nd'), ('ie', '')])
d = re.findall("[a-z]*(?:ei|ie)[a-z]*", "Is Dr. Greiner your friend, Julie?", re.IGNORECASE)
self.assertEqual(d, ['Greiner', 'friend', 'Julie'])
self.assertEqual(re.findall('\w+', "Words, words, words."), ['Words', 'words', 'words'])
self.assertEqual(re.findall('(abc)(def)', 'abcdef'), [('abc', 'def')])
self.assertEqual(re.findall('(abc)(def)', 'abcdefabcdefjaabcdef3sabc'), [('abc', 'def'), ('abc', 'def'), ('abc', 'def')])
self.assertEqual(re.findall('(abc)', 'abcdef'), ['abc'])
self.assertEqual(re.findall('(abc)|(def)', 'abcdefabcdefjaabcdef3sabc'), [('abc', ''), ('', 'def'), ('abc', ''), ('', 'def'), ('abc', ''), ('', 'def'), ('abc', '')])
self.assertEqual(re.findall("^\s*$", ""), [''])
#self.assertEqual(re.findall("\s*|a", " a b"), [' ', '', 'a', ' ', '', ''])
self.assertEqual(re.findall("a|\s*", " a b"), [' ', 'a', ' ', '', ''])
#self.assertEqual(re.findall("\s*|a", " ba b"), [' ', '', '', 'a', ' ', '', ''])
self.assertEqual(re.findall("a|\s*", " ba b"), [' ', '', 'a', ' ', '', ''])
self.assertEqual(re.findall(".",""), [])
self.assertEqual(re.findall(".","a"), ['a'])
self.assertEqual(re.findall(".a","a"), [])
self.assertEqual(re.findall("a","a"), ['a'])
self.assertEqual(re.findall("a.","a\n"), [])
self.assertEqual(re.findall(".a","ba"), ['ba'])
self.assertEqual(re.findall("^",""), [''])
self.assertEqual(re.findall("a^",""), [])
self.assertEqual(re.findall("^a","ba"), [])
self.assertEqual(re.findall("^a","ab"), ['a'])
self.assertEqual(re.findall("^a","\na"), [])
self.assertEqual(re.findall("a^","a"), [])
self.assertEqual(re.findall("$",""), [''])
self.assertEqual(re.findall("$a","a"), [])
self.assertEqual(re.findall("a$","a"), ['a'])
self.assertEqual(re.findall("a$","ab"), [])
self.assertEqual(re.findall("a$","a\nb"), [])
self.assertEqual(re.findall("a$","a\n"), ['a'])
self.assertEqual(re.findall("a*",""), [''])
self.assertEqual(re.findall("ab*","a"), ['a'])
self.assertEqual(re.findall("ab*","ab"), ['ab'])
self.assertEqual(re.findall("ab*","abbbbb"), ['abbbbb'])
self.assertEqual(re.findall("ab*","ba"), ['a'])
self.assertEqual(re.findall("ab*","bbbb"), [])
self.assertEqual(re.findall("a+",""), [])
self.assertEqual(re.findall("ab+","a"), [])
self.assertEqual(re.findall("ab+","ab"), ['ab'])
self.assertEqual(re.findall("ab+","abbbbb"), ['abbbbb'])
self.assertEqual(re.findall("ab+","ba"), [])
self.assertEqual(re.findall("ab+","bbbb"), [])
self.assertEqual(re.findall("a?",""), [''])
self.assertEqual(re.findall("ab?","a"), ['a'])
self.assertEqual(re.findall("ab?","ab"), ['ab'])
self.assertEqual(re.findall("ab?","abbbbb"), ['ab'])
self.assertEqual(re.findall("ab?","ba"), ['a'])
self.assertEqual(re.findall("ab?","bbbb"), [])
#self.assertEqual(re.findall("a*?","a"), ['', 'a', ''])
self.assertEqual(re.findall("ab*?","abbbb"), ['a'])
self.assertEqual(re.findall("ab*?","a"), ['a'])
self.assertEqual(re.findall("ab*?",""), [])
self.assertEqual(re.findall("a+?","a"), ['a'])
self.assertEqual(re.findall("ab+?","abbbb"), ['ab'])
self.assertEqual(re.findall("ab+?","a"), [])
self.assertEqual(re.findall("ab+?",""), [])
#self.assertEqual(re.findall("a??","a"), ['', 'a', ''])
self.assertEqual(re.findall("ab??","abbbb"), ['a'])
self.assertEqual(re.findall("ab??","a"), ['a'])
self.assertEqual(re.findall("ab??",""), [])
self.assertEqual(re.findall("a{2}","a"), [])
self.assertEqual(re.findall("a{2}","aa"), ['aa'])
self.assertEqual(re.findall("a{2}","aaa"), ['aa'])
self.assertEqual(re.findall("a{1,2}b","b"), [])
self.assertEqual(re.findall("a{1,2}b","ab"), ['ab'])
self.assertEqual(re.findall("a{1,2}b","aab"), ['aab'])
self.assertEqual(re.findall("a{1,2}b","aaab"), ['aab'])
self.assertEqual(re.findall("a{,2}b","b"), ['b'])
self.assertEqual(re.findall("a{,2}b","ab"), ['ab'])
self.assertEqual(re.findall("a{,2}b","aab"), ['aab'])
self.assertEqual(re.findall("a{,2}b","aaab"), ['aab'])
self.assertEqual(re.findall("a{2,}b","b"), [])
self.assertEqual(re.findall("a{2,}b","ab"), [])
self.assertEqual(re.findall("a{2,}b","aab"), ['aab'])
self.assertEqual(re.findall("a{2,}b","aaab"), ['aaab'])
self.assertEqual(re.findall("a{3,5}","aaaaaaaaaa"), ['aaaaa', 'aaaaa'])
self.assertEqual(re.findall("a{,5}","aaaaaaaaaa"), ['aaaaa', 'aaaaa', ''])
self.assertEqual(re.findall("a{3,}","aaaaaaaaaa"), ['aaaaaaaaaa'])
self.assertEqual(re.findall("a{1,2}?b","b"), [])
self.assertEqual(re.findall("a{1,2}?b","ab"), ['ab'])
self.assertEqual(re.findall("a{1,2}?b","aab"), ['aab'])
self.assertEqual(re.findall("a{1,2}?b","aaab"), ['aab'])
self.assertEqual(re.findall("a{,2}?b","b"), ['b'])
self.assertEqual(re.findall("a{,2}?b","ab"), ['ab'])
self.assertEqual(re.findall("a{,2}?b","aab"), ['aab'])
self.assertEqual(re.findall("a{,2}?b","aaab"), ['aab'])
self.assertEqual(re.findall("a{2,}?b","b"), [])
self.assertEqual(re.findall("a{2,}?b","ab"), [])
self.assertEqual(re.findall("a{2,}?b","aab"), ['aab'])
self.assertEqual(re.findall("a{2,}?b","aaab"), ['aaab'])
self.assertEqual(re.findall("a{3,5}?","aaaaaaaaaa"), ['aaa', 'aaa', 'aaa'])
#self.assertEqual(re.findall("a{,5}?","aaaaaaaaaa"), ['', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '', 'a', ''])
self.assertEqual(re.findall("a{3,}?","aaaaaaaaaa"), ['aaa', 'aaa', 'aaa'])
self.assertEqual(re.findall("[a,b,c]","abc"), ['a', 'b', 'c'])
self.assertEqual(re.findall("[a-z]","bc"), ['b', 'c'])
self.assertEqual(re.findall("[A-Z,0-9]","abcdefg"), [])
self.assertEqual(re.findall("[^A-Z]","ABCDEFGaHIJKL"), ['a'])
self.assertEqual(re.findall("[a*bc]","*"), ['*'])
self.assertEqual(re.findall("|",""), [''])
self.assertEqual(re.findall("|a",""), [''])
self.assertEqual(re.findall("a|b","ba"), ['b', 'a'])
self.assertEqual(re.findall("h|ello","hello"), ['h', 'ello'])
self.assertEqual(re.findall("(b*)","bbbba"), ['bbbb', '', ''])
self.assertEqual(re.findall("(?:b*)","bbbba"), ['bbbb', '', ''])
self.assertEqual(re.findall("a(?=b)","a"), [])
self.assertEqual(re.findall("a(?=b)","ab"), ['a'])
self.assertEqual(re.findall("a(?!b)","a"), ['a'])
self.assertEqual(re.findall("a(?!b)","ab"), [])
pattern = r"\n"
self.assertEqual(re.findall(pattern, "\n"), ['\n'])
self.assertEqual(re.findall(pattern, "\n\n"), ['\n', '\n'])
self.assertEqual(re.findall(pattern, "x\nx"), ['\n'])
self.assertEqual(re.findall(pattern, "x\nx\n"), ['\n', '\n'])
pattern = r"\t"
self.assertEqual(re.findall(pattern, "\t"), ['\t'])
self.assertEqual(re.findall(pattern, "\t\t"), ['\t', '\t'])
self.assertEqual(re.findall(pattern, "x\tx"), ['\t'])
self.assertEqual(re.findall(pattern, "x\tx\t"), ['\t', '\t'])
# issue1148
self.assertEqual(re.findall(r"[^c|p]at", r"mat cat hat pat"), ['mat', 'hat'])
def test_search(self):
val = re.search("From","dlkjdsljkdlkdsjlk")
self.assertEqual(val, None)
val = re.search("From","dlkjd From kdsjlk")
self.assertTrue(val is not None)
val = re.search("From","From dlkjd From kdsjlk")
self.assertTrue(val is not None)
def helper(match,expected):
if type(expected) == str:
if match:
if match.group(0)==expected: return True
else: return False
else: return False
else:
if match: return True == expected
else: return False == expected
self.assertTrue(helper(re.search(".",""),False))
self.assertTrue(helper(re.search(".","a"),True))
self.assertTrue(helper(re.search(".a","a"),False))
self.assertTrue(helper(re.search("a","a"),True))
self.assertTrue(helper(re.search("a.","a\n"),False))
self.assertTrue(helper(re.search(".a","ba"),True))
self.assertTrue(helper(re.search("^",""),True))
self.assertTrue(helper(re.search("a^",""),False))
self.assertTrue(helper(re.search("^a","ba"),False))
self.assertTrue(helper(re.search("^a","ab"),True))
self.assertTrue(helper(re.search("^a","\na"),False))
self.assertTrue(helper(re.search("a^","a"),False))
self.assertTrue(helper(re.search("$",""),True))
self.assertTrue(helper(re.search("$a","a"),False))
self.assertTrue(helper(re.search("a$","a"),True))
self.assertTrue(helper(re.search("a$","ab"),False))
self.assertTrue(helper(re.search("a$","a\nb"),False))
self.assertTrue(helper(re.search("a$","a\n"),True))
self.assertTrue(helper(re.search("a*",""),""))
self.assertTrue(helper(re.search("ab*","a"),"a"))
self.assertTrue(helper(re.search("ab*","ab"),"ab"))
self.assertTrue(helper(re.search("ab*","abbbbb"),"abbbbb"))
self.assertTrue(helper(re.search("ab*","ba"),"a"))
self.assertTrue(helper(re.search("ab*","bbbb"),False))
self.assertTrue(helper(re.search("a+",""),False))
self.assertTrue(helper(re.search("ab+","a"),False))
self.assertTrue(helper(re.search("ab+","ab"),"ab"))
self.assertTrue(helper(re.search("ab+","abbbbb"),"abbbbb"))
self.assertTrue(helper(re.search("ab+","ba"),False))
self.assertTrue(helper(re.search("ab+","bbbb"),False))
self.assertTrue(helper(re.search("a?",""),""))
self.assertTrue(helper(re.search("ab?","a"),"a"))
self.assertTrue(helper(re.search("ab?","ab"),"ab"))
self.assertTrue(helper(re.search("ab?","abbbbb"),"ab"))
self.assertTrue(helper(re.search("ab?","ba"),"a"))
self.assertTrue(helper(re.search("ab?","bbbb"),False))
self.assertTrue(helper(re.search("a*?","a"),""))
self.assertTrue(helper(re.search("ab*?","abbbb"),"a"))
self.assertTrue(helper(re.search("ab*?","a"),"a"))
self.assertTrue(helper(re.search("ab*?",""),False))
self.assertTrue(helper(re.search("a+?","a"),"a"))
self.assertTrue(helper(re.search("ab+?","abbbb"),"ab"))
self.assertTrue(helper(re.search("ab+?","a"),False))
self.assertTrue(helper(re.search("ab+?",""),False))
self.assertTrue(helper(re.search("a??","a"),""))
self.assertTrue(helper(re.search("ab??","abbbb"),"a"))
self.assertTrue(helper(re.search("ab??","a"),"a"))
self.assertTrue(helper(re.search("ab??",""),False))
self.assertTrue(helper(re.search("a{2}","a"),False))
self.assertTrue(helper(re.search("a{2}","aa"),"aa"))
self.assertTrue(helper(re.search("a{2}","aaa"),"aa"))
self.assertTrue(helper(re.search("a{1,2}b","b"),False))
self.assertTrue(helper(re.search("a{1,2}b","ab"),"ab"))
self.assertTrue(helper(re.search("a{1,2}b","aab"),"aab"))
self.assertTrue(helper(re.search("a{1,2}b","aaab"),"aab"))
self.assertTrue(helper(re.search("a{,2}b","b"),"b"))
self.assertTrue(helper(re.search("a{,2}b","ab"),"ab"))
self.assertTrue(helper(re.search("a{,2}b","aab"),"aab"))
self.assertTrue(helper(re.search("a{,2}b","aaab"),"aab"))
self.assertTrue(helper(re.search("a{2,}b","b"),False))
self.assertTrue(helper(re.search("a{2,}b","ab"),False))
self.assertTrue(helper(re.search("a{2,}b","aab"),"aab"))
self.assertTrue(helper(re.search("a{2,}b","aaab"),"aaab"))
self.assertTrue(helper(re.search("a{3,5}","aaaaaaaaaa"),"aaaaa"))
self.assertTrue(helper(re.search("a{,5}","aaaaaaaaaa"),"aaaaa"))
self.assertTrue(helper(re.search("a{3,}","aaaaaaaaaa"),"aaaaaaaaaa"))
self.assertTrue(helper(re.search("[a,b,c]","abc"),"a"))
self.assertTrue(helper(re.search("[a-z]","bc"),"b"))
self.assertTrue(helper(re.search("[A-Z,0-9]","abcdefg"),False))
self.assertTrue(helper(re.search("[^A-Z]","ABCDEFGaHIJKL"),"a"))
self.assertTrue(helper(re.search("[a*bc]","*"),"*"))
self.assertTrue(helper(re.search("|",""),""))
self.assertTrue(helper(re.search("|a",""),""))
self.assertTrue(helper(re.search("a|b","ba"),"b"))
self.assertTrue(helper(re.search("h|ello","hello"),"h"))
self.assertTrue(helper(re.search("(?:b*)","bbbba"),'bbbb'))
self.assertTrue(helper(re.search("a(?=b)","a"),False))
self.assertTrue(helper(re.search("a(?=b)","ab"),"a"))
self.assertTrue(helper(re.search("a(?!b)","a"),"a"))
self.assertTrue(helper(re.search("a(?!b)","ab"),False))
def test_match(self):
val = re.match("From","dlkjdsljkdlkdsjlk")
self.assertEqual(val, None)
val = re.match("From","dlkjd From kdsjlk")
self.assertTrue(val is None)
val = re.match("From","From dlkjd From kdsjlk")
self.assertTrue(val is not None)
def test_groups(self):
m = re.match('([0-9]+)([a-z]+)','345abu')
self.assertEqual(m.groups(), ('345', 'abu'))
self.assertEqual(m.group(0), "345abu")
self.assertEqual(m.group(1), "345")
self.assertEqual(m.group(2), "abu")
m = re.match('([0-9]+)([a-z]+)([A-Z]*)','345abu')
self.assertEqual(m.groups('default'), tuple(['345','abu','']))
def test_split(self):
a = re.split("a", "A stitch in time saves nine.", flags=re.IGNORECASE)
self.assertEqual(a, ['', ' stitch in time s', 'ves nine.'])
self.assertEqual(re.split("\W+", "Words, words, words."), ['Words', 'words', 'words', ''])
self.assertEqual(re.split("(\W+)", "Words, words, words."), ['Words', ', ', 'words', ', ', 'words', '.', ''])
self.assertEqual(re.split("\W+", "Words, words, words.", 1), ['Words', 'words, words.'])
self.assertEqual(re.split('[a-f]+', '0a3B9', 0, re.IGNORECASE), ['0', '3', '9'])
self.assertEqual(re.split("(\W+)", '...words, words...'), ['', '...', 'words', ', ', 'words', '...', ''])
#Skulpt fails the test below and it shouldn't
#self.assertEqual(re.split('x*', 'foo'), ['', 'f', 'o', 'o', ''])
if __name__ == '__main__':
unittest.main()
|
python
|
import os
from setuptools import setup
def package_files(directory):
paths = []
for (path, directories, filenames) in os.walk(directory):
for filename in filenames:
paths.append(os.path.join('..', path, filename))
return paths
extra_files = package_files('sejits4fpgas/hw')
extra_files.append('*.config')
setup(
name='Sejits4Fpgas',
version='0.1',
packages=['sejits4fpgas', 'sejits4fpgas.src'],
package_dir={'sejits4fpgas': 'sejits4fpgas'},
package_data={
'sejits4fpgas':extra_files
},
url='',
license='',
author='Philipp Ebensberger',
author_email='[email protected]',
description='',
install_requires=["numpy", "scikit-image", "scipy", "pytest"],
)
|
python
|
# ======================================================================================================================
# Fakulta informacnich technologii VUT v Brne
# Bachelor thesis
# Author: Filip Bali (xbalif00)
# License: MIT
# ======================================================================================================================
from django.contrib import admin
from .models import Profile
# Register your models here.
admin.site.register(Profile)
|
python
|
import numpy as np
import math
def nanRound(vs, *args, **kw):
def fun(v):
if math.isnan(v): return(v)
return np.around(v, *args, **kw)
return [fun(i) for i in vs]
|
python
|
import os
import sys
import pprint
from PIL import Image
from av import open
video = open(sys.argv[1])
stream = next(s for s in video.streams if s.type == b'video')
for packet in video.demux(stream):
for frame in packet.decode():
frame.to_image().save('sandbox/%04d.jpg' % frame.index)
if frame_count > 5:
break
|
python
|
from markdownify import markdownify as md, ATX, ATX_CLOSED, BACKSLASH, UNDERSCORE
import re
nested_uls = """
<ul>
<li>1
<ul>
<li>a
<ul>
<li>I</li>
<li>II</li>
<li>III</li>
</ul>
</li>
<li>b</li>
<li>c</li>
</ul>
</li>
<li>2</li>
<li>3</li>
</ul>"""
nested_ols = """
<ol>
<li>1
<ol>
<li>a
<ol>
<li>I</li>
<li>II</li>
<li>III</li>
</ol>
</li>
<li>b</li>
<li>c</li>
</ol>
</li>
<li>2</li>
<li>3</li>
</ul>"""
table = re.sub(r'\s+', '', """
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
""")
table_head_body = re.sub(r'\s+', '', """
<table>
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</tbody>
</table>
""")
table_missing_text = re.sub(r'\s+', '', """
<table>
<thead>
<tr>
<th></th>
<th>Lastname</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jill</td>
<td></td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</tbody>
</table>
""")
def test_chomp():
assert md(' <b></b> ') == ' '
assert md(' <b> </b> ') == ' '
assert md(' <b> </b> ') == ' '
assert md(' <b> </b> ') == ' '
assert md(' <b>s </b> ') == ' **s** '
assert md(' <b> s</b> ') == ' **s** '
assert md(' <b> s </b> ') == ' **s** '
assert md(' <b> s </b> ') == ' **s** '
def test_a():
assert md('<a href="https://google.com">Google</a>') == '[Google](https://google.com)'
assert md('<a href="https://google.com">https://google.com</a>', autolinks=False) == '[https://google.com](https://google.com)'
assert md('<a href="https://google.com">https://google.com</a>') == '<https://google.com>'
assert md('<a href="https://community.kde.org/Get_Involved">https://community.kde.org/Get_Involved</a>') == '<https://community.kde.org/Get_Involved>'
assert md('<a href="https://community.kde.org/Get_Involved">https://community.kde.org/Get_Involved</a>', autolinks=False) == '[https://community.kde.org/Get\\_Involved](https://community.kde.org/Get_Involved)'
def test_a_spaces():
assert md('foo <a href="http://google.com">Google</a> bar') == 'foo [Google](http://google.com) bar'
assert md('foo<a href="http://google.com"> Google</a> bar') == 'foo [Google](http://google.com) bar'
assert md('foo <a href="http://google.com">Google </a>bar') == 'foo [Google](http://google.com) bar'
assert md('foo <a href="http://google.com"></a> bar') == 'foo bar'
def test_a_with_title():
text = md('<a href="http://google.com" title="The "Goog"">Google</a>')
assert text == r'[Google](http://google.com "The \"Goog\"")'
def test_a_shortcut():
text = md('<a href="http://google.com">http://google.com</a>')
assert text == '<http://google.com>'
def test_a_no_autolinks():
text = md('<a href="http://google.com">http://google.com</a>', autolinks=False)
assert text == '[http://google.com](http://google.com)'
def test_b():
assert md('<b>Hello</b>') == '**Hello**'
def test_b_spaces():
assert md('foo <b>Hello</b> bar') == 'foo **Hello** bar'
assert md('foo<b> Hello</b> bar') == 'foo **Hello** bar'
assert md('foo <b>Hello </b>bar') == 'foo **Hello** bar'
assert md('foo <b></b> bar') == 'foo bar'
def test_blockquote():
assert md('<blockquote>Hello</blockquote>') == '\n> Hello\n\n'
def test_blockquote_with_paragraph():
assert md('<blockquote>Hello</blockquote><p>handsome</p>') == '\n> Hello\n\nhandsome\n\n'
def test_nested_blockquote():
text = md('<blockquote>And she was like <blockquote>Hello</blockquote></blockquote>')
assert text == '\n> And she was like \n> > Hello\n> \n> \n\n'
def test_br():
assert md('a<br />b<br />c') == 'a \nb \nc'
def test_em():
assert md('<em>Hello</em>') == '*Hello*'
def test_em_spaces():
assert md('foo <em>Hello</em> bar') == 'foo *Hello* bar'
assert md('foo<em> Hello</em> bar') == 'foo *Hello* bar'
assert md('foo <em>Hello </em>bar') == 'foo *Hello* bar'
assert md('foo <em></em> bar') == 'foo bar'
def test_h1():
assert md('<h1>Hello</h1>') == 'Hello\n=====\n\n'
def test_h2():
assert md('<h2>Hello</h2>') == 'Hello\n-----\n\n'
def test_hn():
assert md('<h3>Hello</h3>') == '### Hello\n\n'
assert md('<h6>Hello</h6>') == '###### Hello\n\n'
def test_hn_chained():
assert md('<h1>First</h1>\n<h2>Second</h2>\n<h3>Third</h3>', heading_style=ATX) == '# First\n\n\n## Second\n\n\n### Third\n\n'
assert md('X<h1>First</h1>', heading_style=ATX) == 'X# First\n\n'
def test_hn_nested_tag_heading_style():
assert md('<h1>A <p>P</p> C </h1>', heading_style=ATX_CLOSED) == '# A P C #\n\n'
assert md('<h1>A <p>P</p> C </h1>', heading_style=ATX) == '# A P C\n\n'
def test_hn_nested_simple_tag():
tag_to_markdown = [
("strong", "**strong**"),
("b", "**b**"),
("em", "*em*"),
("i", "*i*"),
("p", "p"),
("a", "a"),
("div", "div"),
("blockquote", "blockquote"),
]
for tag, markdown in tag_to_markdown:
assert md('<h3>A <' + tag + '>' + tag + '</' + tag + '> B</h3>') == '### A ' + markdown + ' B\n\n'
assert md('<h3>A <br>B</h3>', heading_style=ATX) == '### A B\n\n'
# Nested lists not supported
# assert md('<h3>A <ul><li>li1</i><li>l2</li></ul></h3>', heading_style=ATX) == '### A li1 li2 B\n\n'
def test_hn_nested_img():
assert md('<img src="/path/to/img.jpg" alt="Alt text" title="Optional title" />') == ''
assert md('<img src="/path/to/img.jpg" alt="Alt text" />') == ''
image_attributes_to_markdown = [
("", ""),
("alt='Alt Text'", "Alt Text"),
("alt='Alt Text' title='Optional title'", "Alt Text"),
]
for image_attributes, markdown in image_attributes_to_markdown:
assert md('<h3>A <img src="/path/to/img.jpg " ' + image_attributes + '/> B</h3>') == '### A ' + markdown + ' B\n\n'
def test_hr():
assert md('Hello<hr>World') == 'Hello\n\n---\n\nWorld'
assert md('Hello<hr />World') == 'Hello\n\n---\n\nWorld'
assert md('<p>Hello</p>\n<hr>\n<p>World</p>') == 'Hello\n\n\n\n\n---\n\n\nWorld\n\n'
def test_head():
assert md('<head>head</head>') == 'head'
def test_atx_headings():
assert md('<h1>Hello</h1>', heading_style=ATX) == '# Hello\n\n'
assert md('<h2>Hello</h2>', heading_style=ATX) == '## Hello\n\n'
def test_atx_closed_headings():
assert md('<h1>Hello</h1>', heading_style=ATX_CLOSED) == '# Hello #\n\n'
assert md('<h2>Hello</h2>', heading_style=ATX_CLOSED) == '## Hello ##\n\n'
def test_i():
assert md('<i>Hello</i>') == '*Hello*'
def test_ol():
assert md('<ol><li>a</li><li>b</li></ol>') == '1. a\n2. b\n'
assert md('<ol start="3"><li>a</li><li>b</li></ol>') == '3. a\n4. b\n'
def test_p():
assert md('<p>hello</p>') == 'hello\n\n'
def test_strong():
assert md('<strong>Hello</strong>') == '**Hello**'
def test_ul():
assert md('<ul><li>a</li><li>b</li></ul>') == '* a\n* b\n'
def test_nested_ols():
assert md(nested_ols) == '\n1. 1\n\t1. a\n\t\t1. I\n\t\t2. II\n\t\t3. III\n\t2. b\n\t3. c\n2. 2\n3. 3\n'
def test_inline_ul():
assert md('<p>foo</p><ul><li>a</li><li>b</li></ul><p>bar</p>') == 'foo\n\n* a\n* b\n\nbar\n\n'
def test_nested_uls():
"""
Nested ULs should alternate bullet characters.
"""
assert md(nested_uls) == '\n* 1\n\t+ a\n\t\t- I\n\t\t- II\n\t\t- III\n\t+ b\n\t+ c\n* 2\n* 3\n'
def test_bullets():
assert md(nested_uls, bullets='-') == '\n- 1\n\t- a\n\t\t- I\n\t\t- II\n\t\t- III\n\t- b\n\t- c\n- 2\n- 3\n'
def test_li_text():
assert md('<ul><li>foo <a href="#">bar</a></li><li>foo bar </li><li>foo <b>bar</b> <i>space</i>.</ul>') == '* foo [bar](#)\n* foo bar\n* foo **bar** *space*.\n'
def test_img():
assert md('<img src="/path/to/img.jpg" alt="Alt text" title="Optional title" />') == ''
assert md('<img src="/path/to/img.jpg" alt="Alt text" />') == ''
def test_div():
assert md('Hello</div> World') == 'Hello World'
def test_table():
assert md(table) == '| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |'
assert md(table_head_body) == '| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |'
assert md(table_missing_text) == '| | Lastname | Age |\n| --- | --- | --- |\n| Jill | | 50 |\n| Eve | Jackson | 94 |'
def test_strong_em_symbol():
assert md('<strong>Hello</strong>', strong_em_symbol=UNDERSCORE) == '__Hello__'
assert md('<b>Hello</b>', strong_em_symbol=UNDERSCORE) == '__Hello__'
assert md('<em>Hello</em>', strong_em_symbol=UNDERSCORE) == '_Hello_'
assert md('<i>Hello</i>', strong_em_symbol=UNDERSCORE) == '_Hello_'
def test_newline_style():
assert md('a<br />b<br />c', newline_style=BACKSLASH) == 'a\\\nb\\\nc'
|
python
|
from Assignment2 import *
def test_case1():
cost = [[0,0,0,0],
[0,0,5,10],
[0,-1,0,5],
[0,-1,-1,0]
]
print(UCS_Traversal(cost,1,[3]))
def test_case2():
cost = [[0,0,0,0,0],
[0,0,0,10,5],
[0,-1,0,5,0],
[0,-1,-1,0,0],
[0,-1,-1,5,0]
]
print(UCS_Traversal(cost,1,[3]))
def test_case3():
cost = [[0,0,0,0,0,0,0],
[0,0,2,0,0,10,7],
[0,0,0,3,0,0,0],
[0,0,0,0,0,0,2],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,3,0],
]
print(UCS_Traversal(cost,1,[5]))
def test_case4():
cost = [[0,0,0,0,0,0,0],
[0,0,2,0,0,10,7],
[0,0,0,3,0,0,0],
[0,0,0,0,2,0,2],
[0,0,0,0,0,3,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,3,0],
]
print(UCS_Traversal(cost,1,[5]))
def test_case5():
cost = [[0,0,0,0,0,0,0],
[0,0,2,-1,-1,10,-1],
[0,-1,0,2,-1,-1,-1],
[0,-1,-1,0,2,-1,-1],
[0,-1,-1,-1,0,-1,2],
[0,-1,-1,-1,-1,0,-1],
[0,-1,-1,-1,-1,2,0]
]
print(UCS_Traversal(cost,1,[5]))
test_case1()
test_case2()
test_case3()
test_case4()
test_case5()
|
python
|
import numpy as np
import sys, time, glob
#caffe_root = "/home/vagrant/caffe/"
#sys.path.insert(0, caffe_root + 'python')
import caffe
from sklearn.metrics import accuracy_score
from random import shuffle
from sklearn import svm
def init_net():
net = caffe.Classifier(caffe_root + 'models/bvlc_reference_caffenet/deploy.prototxt',
caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel')
net.set_phase_test()
net.set_mode_cpu()
# input preprocessing: 'data' is the name of the input blob == net.inputs[0]
net.set_mean('data', np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy')) # ImageNet mean
net.set_raw_scale('data', 255) # the reference model operates on images in [0,255] range instead of [0,1]
net.set_channel_swap('data', (2,1,0)) # the reference model has channels in BGR order instead of RGB
return net
def get_features(file, net):
#print "getting features for", file
scores = net.predict([caffe.io.load_image(file)])
feat = net.blobs['fc7'].data[4][:,0, 0]
return feat
def shuffle_data(features, labels):
new_features, new_labels = [], []
index_shuf = range(len(features))
shuffle(index_shuf)
for i in index_shuf:
new_features.append(features[i])
new_labels.append(labels[i])
return new_features, new_labels
def get_dataset(net, A_DIR, B_DIR):
CLASS_A_IMAGES = glob.glob(A_DIR + "/*.jpg")
CLASS_B_IMAGES = glob.glob(B_DIR + "/*.jpg")
CLASS_A_FEATURES = map(lambda f: get_features(f, net), CLASS_A_IMAGES)
CLASS_B_FEATURES = map(lambda f: get_features(f, net), CLASS_B_IMAGES)
features = CLASS_A_FEATURES + CLASS_B_FEATURES
labels = [0] * len(CLASS_A_FEATURES) + [1] * len(CLASS_B_FEATURES)
return shuffle_data(features, labels)
net = init_net()
x, y = get_dataset(net, sys.argv[1], sys.argv[2])
l = int(len(y) * 0.4)
x_train, y_train = x[: l], y[: l]
x_test, y_test = x[l : ], y[l : ]
clf = svm.SVC()
clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)
print "Accuracy: %.3f" % accuracy_score(y_test, y_pred)
|
python
|
import numpy as np
import py2neo as pn
import random
import math
import copy
def create_ba_subgraph(M, m_0, n, relation):
# Generate Users-Friends un-directed subgraph
# Generate Users-Follower directed subgraph
node_list = []
for i in range(m_0):
node_list.append(pn.Node('User', name='user' + str(i)))
rel_list = []
for i in range(len(node_list)):
for j in range((i+1),len(node_list)):
rel_list.append(pn.Relationship(node_list[i], relation, node_list[j]))
# 1. Creat node list by node function
# 2. Creat relation list by Relation function
# 3. Creat subgraph by Subgraph function
t = M - m_0 # number of iteration
k = [] # save nodes degree
k_0 = m_0 - 1
p_k = [] # save nodes priority probability
p_0 = 1/m_0
k_all = 0
for i in range(m_0):
p_k.append(p_0)
k.append(k_0)
k_all += k_0
for i in range(t):
m_0_t = m_0 + i # number of nodes at time t
m_0_1 = m_0 + i - 1 # number of nodes at time t-1
node_list.append(pn.Node('User', name='user' + str(m_0_t))) # add one node
add_edge = 1
j_choose = -1
while(add_edge <= n):
for j in range(m_0_t):
if j != j_choose: # to ensure no repeated edges
p_random = random.random()
if p_random <= p_k[j] and add_edge <= n:
j_choose = j
k_j = k[j]
p_k_j = p_k[j]
r_random = random.random()
if r_random > 0.5:
rel_list.append(pn.Relationship(node_list[j], relation, node_list[-1]))
else:
rel_list.append(pn.Relationship(node_list[-1], relation, node_list[j]))
add_edge += 1
k[j] = k_j + 1
k_all += 2
p_k[j] = (k_j + 1)/k_all
k.append(n)
p_k.append(n/k_all)
s = pn.Subgraph(node_list,rel_list)
return s
def create_pp_ba_subgraph(M, m_0, n, post_u0, N, graph):
post_u0_list = np.random.choice(N,m_0)
post_0_list = list(range(m_0))
user_list = [pn.Node('User', name='user' + str(i)) for i in N]
k = [0] * len(N) # list save the number of posts by users
node_list = []
for i in post_0_list:
node_list.append(pn.Node('Post', name='post' + str(i)))
rel_list = []
for i in range(len(node_list)):
p_u = np.random.choice(post_u0_list,1)[0]
k[p_u] += 1
rel_list.append(pn.Relationship(user_list[p_u], 'published', node_list[i]))
# 1. Creat node list by Node function
# 2. Creat relation list by Relation function
# 3. Creat subgraph by Subgraph function
t = M - m_0 # number of iteration
k_all_friends = 0
for i in N:
friends = list(graph.run('MATCH (n:User {name:"user' + str(i) + '"})-[:friends]-(a) return count(a)').data()[0].values())[0]
k_all_friends += friends
k_all_follow = 0
for i in N:
follow = list(graph.run('MATCH (n:User {name:"user' + str(i) + '"})<-[:follow]-(a) return count(a)').data()[0].values())[0]
k_all_follow += follow
for i in range(t):
m_0_t = m_0 + i # number of nodes at time t
node_list.append(pn.Node('Post', name='post' + str(m_0_t))) # add one node
p_j = [0] * len(N) # save list of probability
for j in N:
p_j_friends = list(graph.run('MATCH (n:User {name:"user' + str(j) + '"})-[:friends]-(a) return count(a)').data()[0].values())[0]
p_j_follow = list(graph.run('MATCH (n:User {name:"user' + str(j) + '"})<-[:follow]-(a) return count(a)').data()[0].values())[0]
p_j[j] = (p_j_friends + p_j_follow + k[j]) / (k_all_follow + k_all_friends + sum(k))
user = np.random.choice(user_list,1, p=p_j)[0] # roulette wheel selection
rel_list.append(pn.Relationship(user, 'published', node_list[-1]))
k[user_list.index(user)] += 1
s = pn.Subgraph(node_list,rel_list)
return s
def create_pv_ba_subgraph(P,N,graph):
# depends on friends/followers/reads
user_list = [pn.Node('User', name='user' + str(i)) for i in N]
post_list = [pn.Node('Post', name='post' + str(i)) for i in P]
view_list = [0] * len(P)
rel_list = []
k_all_friends = 0
k_all_follow = 0
for i in P:
user = list(graph.run('match (n:Post{name:"post' + str(i) + '"})<-[:published]-(a) return a').data()[0].values())[0].nodes[0]['name']
friends = list(graph.run('MATCH (n:User {name:"' + user + '"})-[:friends]-(a) return count(a)').data()[0].values())[0]
k_all_friends += friends
follow = list(graph.run('MATCH (n:User {name:"' + user + '"})<-[:follow]-(a) return count(a)').data()[0].values())[0]
k_all_follow += follow
for i in P:
user = list(graph.run('match (n:Post{name:"post' + str(i) + '"})<-[:published]-(a) return a').data()[0].values())[0].nodes[0]['name']
user_list_m = copy.deepcopy(user_list)
for n in user_list_m:
if n['name'] == user:
user_list_m.remove(n)
friends = list(graph.run('MATCH (n:User {name:"' + user + '"})-[:friends]-(a) return count(a)').data()[0].values())[0]
follow = list(graph.run('MATCH (n:User {name:"' + user + '"})<-[:follow]-(a) return count(a)').data()[0].values())[0]
p = (friends + follow + view_list[i]) / (k_all_friends + k_all_follow + sum(view_list))
p_random = random.random()
if p_random <= p:
user_choice = np.random.choice(user_list_m,1)[0]
rel_list.append(pn.Relationship(user_choice,'viewed',post_list[i]))
view_list[i] += 1
s = pn.Subgraph(post_list,rel_list)
return s
def create_pl_ba_subgraph(P,N,graph):
user_list = [pn.Node('User', name='user' + str(i)) for i in N]
post_list = [pn.Node('Post', name='post' + str(i)) for i in P]
liked_list = [0] * len(P)
rel_list = []
k_all_friends = 0
k_all_follow = 0
k_all_posted = 0
for i in P:
user = list(graph.run('match (n:Post{name:"post' + str(i) + '"})<-[:published]-(a) return a').data()[0].values())[0].nodes[0]['name']
friends = list(graph.run('MATCH (n:User {name:"' + user + '"})-[:friends]-(a) return count(a)').data()[0].values())[0]
k_all_friends += friends
follow = list(graph.run('MATCH (n:User {name:"' + user + '"})<-[:follow]-(a) return count(a)').data()[0].values())[0]
k_all_follow += follow
post = list(graph.run('MATCH (n:User {name:"' + user + '"})-[:published]->(a) return count(a)').data()[0].values())[0]
k_all_posted += post
for i in P:
user = list(graph.run('match (n:Post{name:"post' + str(i) + '"})<-[:published]-(a) return a').data()[0].values())[0].nodes[0]['name']
user_list_m = copy.deepcopy(user_list)
for n in user_list_m:
if n['name'] == user:
user_list_m.remove(n)
friends = list(graph.run('MATCH (n:User {name:"' + user + '"})-[:friends]-(a) return count(a)').data()[0].values())[0]
follow = list(graph.run('MATCH (n:User {name:"' + user + '"})<-[:follow]-(a) return count(a)').data()[0].values())[0]
post = list(graph.run('MATCH (n:User {name:"' + user + '"})-[:published]->(a) return count(a)').data()[0].values())[0]
for j in N:
p = (friends + follow + post + liked_list[i]) / (k_all_friends + k_all_follow + k_all_posted + sum(liked_list))
p_random = random.random()
if p_random <= p:
user_choice = np.random.choice(user_list_m,1)[0]
rel_list.append(pn.Relationship(user_choice,'liked',post_list[i]))
liked_list[i] += 1
s = pn.Subgraph(post_list,rel_list)
return s
if __name__ == '__main__':
users = 20 # users nodes
posts = 30 # posts
post_0, post_u0 = 3,3
m_0 = 3 # initial nodes
n = 2 # every time the new node connect to n known nodes, n<=n_user0
N = list(range(users))
P = list(range(posts))
# start a new project in Neo4j and set connections
graph = pn.Graph(
host = 'localhost',
http_port = '7474',
user = 'neo4j',
password = '2500'
)
# stage 1
s_user_friend = create_ba_subgraph(users, m_0, n, relation='friends')
# stage 2
s_user_follow = create_ba_subgraph(users, m_0, n, relation='follow')
graph.run('match (n:User) detach delete n')
graph.create(s_user_friend)
# stage 3
graph.merge(s_user_follow,'User','name')
# stage 4
s_posts_publish = create_pp_ba_subgraph(posts, post_0, n, post_u0, N, graph)
# stage 5
graph.merge(s_posts_publish,'User','name')
# stage 6
s_posts_viewed = create_pv_ba_subgraph(P,N,graph)
# stage 7
graph.merge(s_posts_viewed,'User','name')
# stage 8
s_posts_liked = create_pl_ba_subgraph(P,N,graph)
# stage 9
graph.merge(s_posts_liked,'User','name')
|
python
|
# coding=utf-8
from __future__ import print_function
import authcode
from sqlalchemy_wrapper import SQLAlchemy
from helpers import SECRET_KEY
def test_user_model():
db = SQLAlchemy('sqlite:///:memory:')
auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
assert auth.users_model_name == 'User'
assert auth.roles_model_name == 'Role'
User = auth.User
db.create_all()
user = User(login=u'meh', password='foobar')
db.session.add(user)
db.commit()
assert user.login == u'meh'
assert user.email == user.login
assert hasattr(user, 'password')
assert hasattr(user, 'last_sign_in')
assert repr(user) == '<User meh>'
def test_user_model_to_dict():
db = SQLAlchemy('sqlite:///:memory:')
auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
User = auth.User
db.create_all()
user = User(login=u'meh', password='foobar')
db.session.add(user)
db.commit()
user_dict = user.to_dict()
assert user_dict
def test_backwards_compatibility():
db = SQLAlchemy('sqlite:///:memory:')
auth = authcode.Auth(SECRET_KEY, db=db)
User = auth.User
db.create_all()
user = User(login=u'meh', password='foobar')
db.session.add(user)
db.commit()
assert user._password == user.password
user._password = 'raw'
assert user.password == 'raw'
def test_user_model_methods():
db = SQLAlchemy('sqlite:///:memory:')
auth = authcode.Auth(SECRET_KEY, db=db)
User = auth.User
db.create_all()
user = User(login=u'meh', password='foobar')
db.session.add(user)
db.commit()
assert User.by_id(user.id) == user
assert User.by_id(33) is None
assert User.by_login(u'meh') == user
assert User.by_login(u'foobar') is None
assert user.has_password('foobar')
assert not user.has_password('abracadabra')
assert user.get_token()
assert user.get_uhmac()
def test_set_raw_password():
db = SQLAlchemy('sqlite:///:memory:')
auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
User = auth.User
db.create_all()
user = User(login=u'meh', password='foobar')
db.session.add(user)
db.session.commit()
assert user.password != 'foobar'
user.set_raw_password('foobar')
assert user.password == 'foobar'
def test_role_model():
db = SQLAlchemy('sqlite:///:memory:')
auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
Role = auth.Role
db.create_all()
role = Role(name=u'admin')
db.session.add(role)
db.commit()
assert role.name == u'admin'
assert repr(role) == '<Role admin>'
def test_role_model_to_dict():
db = SQLAlchemy('sqlite:///:memory:')
auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
Role = auth.Role
db.create_all()
role = Role(name=u'admin')
db.session.add(role)
db.commit()
role_dict = role.to_dict()
assert role_dict
def test_role_model_methods():
db = SQLAlchemy('sqlite:///:memory:')
auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
Role = auth.Role
db.create_all()
role = Role(name=u'admin')
db.session.add(role)
db.commit()
assert Role.by_id(role.id) == role
assert Role.by_id(33) is None
assert Role.by_name(u'admin') == role
assert Role.by_name(u'foobar') is None
assert Role.get_or_create(u'admin') == role
role2 = Role.get_or_create(u'owner')
db.commit()
assert role2 != role
assert db.query(Role).count() == 2
assert list(role.users) == []
assert list(role2.users) == []
def test_add_role():
db = SQLAlchemy('sqlite:///:memory:')
auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
User = auth.User
Role = auth.Role
db.create_all()
user = User(login=u'meh', password='foobar')
db.session.add(user)
role = Role(name=u'loremipsum')
db.session.add(role)
db.session.commit()
assert hasattr(auth, 'Role')
assert hasattr(User, 'roles')
# Add nonexistant role creates it
user.add_role('admin')
db.session.commit()
assert user.has_role('admin')
assert db.query(Role).count() == 2
assert list(user.roles) == [Role.by_name('admin')]
# Adding the same role does nothing
user.add_role('admin')
db.session.commit()
assert user.has_role('admin')
assert db.query(Role).count() == 2
assert list(user.roles) == [Role.by_name('admin')]
# Adding an existent role does not create a new one
user.add_role('loremipsum')
db.session.commit()
assert user.has_role('loremipsum')
result = sorted([role.name for role in user.roles])
assert result == ['admin', 'loremipsum']
assert db.query(Role).count() == 2
def test_remove_role():
db = SQLAlchemy('sqlite:///:memory:')
auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
User = auth.User
Role = auth.Role
db.create_all()
user = User(login=u'meh', password='foobar')
db.session.add(user)
db.session.commit()
assert hasattr(auth, 'Role')
assert hasattr(User, 'roles')
user.add_role('admin')
db.session.commit()
assert user.has_role('admin')
assert db.query(Role).count() == 1
# Removed from user but not deleted
user.remove_role('admin')
db.session.commit()
assert not user.has_role('admin')
assert list(user.roles) == []
assert db.query(Role).count() == 1
# Removing a role it doesn't have does nothing
user.remove_role('admin')
db.session.commit()
assert not user.has_role('admin')
assert list(user.roles) == []
assert db.query(Role).count() == 1
# Removing a nonexistant role does nothing
user.remove_role('foobar')
db.session.commit()
assert db.query(Role).count() == 1
def test_models_mixins():
db = SQLAlchemy('sqlite:///:memory:')
class UserMixin(object):
email = db.Column(db.Unicode(300))
def __repr__(self):
return 'overwrited'
class RoleMixin(object):
description = db.Column(db.UnicodeText)
auth = authcode.Auth(SECRET_KEY, db=db, UserMixin=UserMixin, RoleMixin=RoleMixin)
User = auth.User
Role = auth.Role
db.create_all()
user = User(login=u'meh', password='foobar', email=u'[email protected]')
db.session.add(user)
db.flush()
assert User.__tablename__ == 'users'
assert user.login == u'meh'
assert user.email == u'[email protected]'
assert hasattr(user, 'password')
assert hasattr(user, 'last_sign_in')
assert repr(user) == 'overwrited'
assert hasattr(Role, 'description')
def test_naked_sqlalchemy():
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine('sqlite://')
class DB(object):
Session = scoped_session(sessionmaker(bind=engine))
Model = declarative_base()
@property
def session(self):
return self.Session()
db = DB()
auth = authcode.Auth(SECRET_KEY, db=db)
User = auth.User
db.Model.metadata.create_all(bind=engine)
user = User(login=u'meh', password='foobar')
db.session.add(user)
db.session.commit()
assert User.by_id(user.id) == user
assert User.by_id(33) is None
assert User.by_login(u'meh') == user
assert User.by_login(u'foobar') is None
assert user.has_password('foobar')
assert not user.has_password('abracadabra')
assert user.get_token()
assert user.get_uhmac()
|
python
|
# -*- coding: utf-8 -*-
def fluxo_caixa():
fluxo = db(MovimentoCaixa).select()
return locals()
def entradas():
entradas = db(Entradas).select()
return locals()
def n_entrada():
entrada_id = request.vars.entrada
if entrada_id is None:
form = SQLFORM(Entradas, fields=['descricao', 'valor', 'obs', 'created_on'])
else:
form = SQLFORM(Entradas, entrada_id, showid=False, deletable=True,
fields=['descricao', 'valor', 'obs', 'created_on'])
if form.process().accepted:
valor = float(request.vars.valor)
saldo = soma_saldo(valor)
MovimentoCaixa.insert(saldo_inicial=saldo[0], entrada=valor,
saida=0, saldo_final=saldo[1])
redirect(URL('financeiro', 'entradas'))
elif form.errors:
response.flash = 'Ops, confira os campos!'
return locals()
def saidas():
saidas = db(Saidas).select()
return locals()
def n_saida():
saida_id = request.vars.saida_id
if saida_id is None:
form = SQLFORM(Saidas, fields=['descricao', 'valor', 'obs', 'created_on'])
else:
form = SQLFORM(Saidas, saida_id, showid=False, deletable=True,
fields=['descricao', 'valor', 'obs', 'created_on'])
if form.process().accepted:
redirect(URL('financeiro', 'saidas'))
elif form.errors:
response.flash = 'Ops, confira os campos!'
return locals()
|
python
|
# (C) British Crown Copyright 2013 - 2018, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cartopy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with cartopy. If not, see <https://www.gnu.org/licenses/>.
"""
Tests for the Geostationary projection.
"""
from __future__ import (absolute_import, division, print_function)
from numpy.testing import assert_almost_equal
import cartopy.crs as ccrs
def check_proj4_params(name, crs, other_args):
expected = other_args | {'proj={}'.format(name), 'units=m', 'no_defs'}
pro4_params = set(crs.proj4_init.lstrip('+').split(' +'))
assert expected == pro4_params
class TestGeostationary(object):
test_class = ccrs.Geostationary
expected_proj_name = 'geos'
def adjust_expected_params(self, expected):
# Only for Geostationary do we expect the sweep parameter
if self.expected_proj_name == 'geos':
expected.add('sweep=y')
def test_default(self):
geos = self.test_class()
other_args = {'ellps=WGS84', 'h=35785831', 'lat_0=0.0', 'lon_0=0.0',
'x_0=0', 'y_0=0'}
self.adjust_expected_params(other_args)
check_proj4_params(self.expected_proj_name, geos, other_args)
assert_almost_equal(geos.boundary.bounds,
(-5434177.81588539, -5434177.81588539,
5434177.81588539, 5434177.81588539),
decimal=4)
def test_eccentric_globe(self):
globe = ccrs.Globe(semimajor_axis=10000, semiminor_axis=5000,
ellipse=None)
geos = self.test_class(satellite_height=50000,
globe=globe)
other_args = {'a=10000', 'b=5000', 'h=50000', 'lat_0=0.0', 'lon_0=0.0',
'x_0=0', 'y_0=0'}
self.adjust_expected_params(other_args)
check_proj4_params(self.expected_proj_name, geos, other_args)
assert_almost_equal(geos.boundary.bounds,
(-8372.4040, -4171.5043, 8372.4040, 4171.5043),
decimal=4)
def test_eastings(self):
geos = self.test_class(false_easting=5000000,
false_northing=-125000,)
other_args = {'ellps=WGS84', 'h=35785831', 'lat_0=0.0', 'lon_0=0.0',
'x_0=5000000', 'y_0=-125000'}
self.adjust_expected_params(other_args)
check_proj4_params(self.expected_proj_name, geos, other_args)
assert_almost_equal(geos.boundary.bounds,
(-434177.81588539, -5559177.81588539,
10434177.81588539, 5309177.81588539),
decimal=4)
def test_sweep(self):
geos = ccrs.Geostationary(sweep_axis='x')
other_args = {'ellps=WGS84', 'h=35785831', 'lat_0=0.0', 'lon_0=0.0',
'sweep=x', 'x_0=0', 'y_0=0'}
check_proj4_params(self.expected_proj_name, geos, other_args)
pt = geos.transform_point(-60, 25, ccrs.PlateCarree())
assert_almost_equal(pt,
(-4529521.6442, 2437479.4195),
decimal=4)
|
python
|
import sys, os, Jati
class Serve:
def run(self, host, port, sites, log_file, isSSL):
current_dir = os.getcwd()
if current_dir not in sys.path:
sys.path.insert(1, current_dir)
try:
jati = Jati.Jati(host=host, port=port, isSSL=None, log_file=log_file)
jati.addVHost(sites)
jati.start()
except KeyboardInterrupt:
print("closing")
jati.close()
|
python
|
from django.contrib import admin
from .models import Classifier
admin.site.register(Classifier)
|
python
|
def cgi_content(type="text/html"):
return('Content type: ' + type + '\n\n')
def webpage_start():
return('<html>')
def web_title(title):
return('<head><title>' + title + '</title></head>')
def body_start(h1_message):
return('<h1 align="center">' + h1_message + '</h1><p align="center">')
def body_end():
return("</p><br><p align='center'><a href='../index.html'>HOME</a></p></body>")
def webpage_end():
return('</html>')
|
python
|
"""Class to host an MlModel object."""
import logging
import json
from aiokafka import AIOKafkaProducer, AIOKafkaConsumer
from model_stream_processor import __name__
from model_stream_processor.model_manager import ModelManager
logger = logging.getLogger(__name__)
class MLModelStreamProcessor(object):
"""Processor class for MLModel stream processors."""
def __init__(self, model_qualified_name, loop, bootstrap_servers):
"""Create an agent for a model.
:param model_qualified_name: The qualified name of the model that will be hosted in this stream processor.
:type model: str
:param loop: The asyncio event loop to be used by the stream processor.
:type loop: _UnixSelectorEventLoop
:param bootstrap_servers: The kafka brokers to connect to.
:type bootstrap_servers: str
:returns: An instance of MLModelStreamProcessor.
:rtype: MLModelStreamProcessor
"""
model_manager = ModelManager()
self._model = model_manager.get_model(model_qualified_name)
logger.info("Initializing stream processor for model: {}".format(self._model.qualified_name))
if self._model is None:
raise ValueError("'{}' not found in ModelManager instance.".format(model_qualified_name))
base_topic_name = "model_stream_processor.{}.{}.{}".format(model_qualified_name,
self._model.major_version,
self._model.minor_version)
# the topic from which the model will receive prediction inputs
self.consumer_topic = "{}.inputs".format(base_topic_name)
# the topic to which the model will send prediction outputs
self.producer_topic = "{}.outputs".format(base_topic_name)
# the topic to which the model will send prediction errors
self.error_producer_topic = "{}.errors".format(base_topic_name)
logger.info("{} stream processor: Consuming messages from topic {}.".format(self._model.qualified_name,
self.consumer_topic))
logger.info("{} stream processor: Producing messages to topics {} and {}.".format(self._model.qualified_name,
self.producer_topic,
self.error_producer_topic))
self._consumer = AIOKafkaConsumer(self.consumer_topic, loop=loop, bootstrap_servers=bootstrap_servers,
group_id=__name__)
self._producer = AIOKafkaProducer(loop=loop, bootstrap_servers=bootstrap_servers)
def __repr__(self):
"""Return string representation of stream processor."""
return "{} model: {} version: {}".format(super().__repr__(), self._model.qualified_name,
str(self._model.major_version) + "." + str(self._model.minor_version))
async def start(self):
"""Start the consumers and producers."""
logger.info("{} stream processor: Starting consumer and producer.".format(self._model.qualified_name))
await self._consumer.start()
await self._producer.start()
async def process(self):
"""Make predictions on records in a stream."""
async for message in self._consumer:
try:
data = json.loads(message.value)
prediction = self._model.predict(data=data)
serialized_prediction = json.dumps(prediction).encode()
await self._producer.send_and_wait(self.producer_topic, serialized_prediction)
except Exception as e:
logger.error("{} stream processor: Exception: {}".format(self._model.qualified_name, str(e)))
await self._producer.send_and_wait(self.error_producer_topic, message.value)
async def stop(self):
"""Stop the streaming processor."""
logger.info("{} stream processor: Stopping consumer and producer.".format(self._model.qualified_name))
await self._consumer.stop()
await self._producer.stop()
|
python
|
# -*- coding:utf-8 -*-
from __future__ import print_function
import zipfile
import os
import shutil
import time
import property
import shutil
print('====================================\n\nThis Software Only For Android Studio Language Package Replace\nDevelop By Wellchang\n2019/03/20\n\n====================================\n\n')
print('please input the absolute path of new resource_en.jar file',end=':')
filename = input()
print('please input the absolute path of old resource_en.jar file',end=':')
filename_cn = input()
splitNew = filename.split('.')
splitLen = len(splitNew)
prefix = splitNew[splitLen-1]
prefixWithDot = '.' + splitNew[splitLen-1]
path2 = filename.replace(prefixWithDot,'')
path2_cn = filename_cn.replace(prefixWithDot,'')
print('Decompression new resource_en.jar file...',end='',flush=True)
fz = zipfile.ZipFile(filename, 'r')
for file in fz.namelist():
# print(file)
fz.extract(file, path2)
print('Done')
print('Decompression old resource_en.jar file...',end='',flush=True)
fzo = zipfile.ZipFile(filename_cn, 'r')
for file in fzo.namelist():
# print(file)
fzo.extract(file, path2_cn)
print('Done')
print('translate new resource_en.jar file...',end='',flush=True)
for file in fz.namelist():
if(file.endswith(".properties")):
props = property.parse(path2 + '\\' + file)
keys = props.keys
for fileCN in fzo.namelist():
if(fileCN == file):
propsCN = property.parse(path2_cn + '\\' + file)
keysCN = propsCN.keys
for key in keys:
# print(len(keys))
# print(file + "=======>" + key + "=" + props.get(key))
if(propsCN.has_key(key)):
props.set(key,propsCN.get(key))
props.save()
keys.clear()
print('Done')
print('Packing Translated file...',end='',flush=True)
file_new = path2 + "_new.jar"
zNew = zipfile.ZipFile(file_new, 'w', zipfile.ZIP_DEFLATED)
for dirpath, dirnames, filenames in os.walk(path2): # os.walk 遍历目录
fpath = dirpath.replace(path2, '') # 这一句很重要,不replace的话,就从根目录开始复制
fpath = fpath and fpath + os.sep or '' # os.sep路径分隔符
for filename in filenames:
zNew.write(os.path.join(dirpath, filename), fpath+filename)
# os.path.join()函数用于路径拼接文件路径。
# os.path.split(path)把path分为目录和文件两个部分,以列表返回
print('Done')
zNew.close()
print('Delete the extracted file...',end='',flush=True)
shutil.rmtree(path2)
shutil.rmtree(path2_cn)
print('Done')
print('Translation completed!!!')
|
python
|
from collections import Iterable
from iterable_collections.factory import DefaultMethodStrategyFactory
class Collection:
def __init__(self, iterable, strategies):
self._iterable = None
self.iterable = iterable
self._strategies = strategies
def __getattr__(self, item):
if item not in self._strategies:
raise AttributeError('Unknown attribute {}'.format(item))
return self._strategies[item].make_method(self)
def __iter__(self):
return iter(self.iterable)
def __next__(self):
return next(self.iterable)
def __repr__(self):
return 'Collection({})'.format(self.iterable)
@property
def iterable(self):
return self._iterable
@iterable.setter
def iterable(self, iterable):
if not isinstance(iterable, Iterable):
ValueError('Must be an Iterable type.')
self._iterable = iterable
def collect(iterable):
return Collection(iterable, DefaultMethodStrategyFactory().create())
|
python
|
#!/usr/bin/env python2
import os
import sys
# add the current dir to python path
CURRENT_DIR = os.path.expanduser(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, CURRENT_DIR)
os.system('cd %s ;git pull' % CURRENT_DIR)
from app import app
if 'SERVER_SOFTWARE' in os.environ:
import sae
application = sae.create_wsgi_app(app)
else:
app.run(host='0.0.0.0')
|
python
|
# MIT License
#
# Copyright (c) 2021 Douglas Davis
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import functools
import contextlib
import sys
from typing import Iterator, Optional
import pygram11.config
from pygram11._backend import _omp_get_max_threads
def omp_get_max_threads() -> int:
"""Get the number of threads available to OpenMP.
This returns the result of calling the OpenMP C API function `of
the same name
<https://www.openmp.org/spec-html/5.0/openmpsu112.html>`_.
Returns
-------
int
the maximum number of available threads
"""
return _omp_get_max_threads()
def default_omp() -> None:
"""Set OpenMP acceleration thresholds to the default values."""
pygram11.config.set("thresholds.fix1d", 10_000)
pygram11.config.set("thresholds.fix1dmw", 10_000)
pygram11.config.set("thresholds.fix2d", 10_000)
pygram11.config.set("thresholds.var1d", 5_000)
pygram11.config.set("thresholds.var1dmw", 5_000)
pygram11.config.set("thresholds.var2d", 5_000)
def disable_omp() -> None:
"""Disable OpenMP acceleration by maximizing all thresholds."""
for k in pygram11.config.threshold_keys():
pygram11.config.set(k, sys.maxsize)
def force_omp() -> None:
"""Force OpenMP acceleration by nullifying all thresholds."""
for k in pygram11.config.threshold_keys():
pygram11.config.set(k, 0)
def without_omp(*args, **kwargs):
"""Wrap a function to disable OpenMP while it's called.
If a specific key is defined, only that threshold will be modified
to turn OpenMP off.
The settings of the pygram11 OpenMP threshold configurations will
be restored to their previous values at the end of the function
that is being wrapped.
Parameters
----------
key : str, optional
Specific threshold key to turn off.
Examples
--------
Writing a function with this decorator:
>>> import numpy as np
>>> from pygram11 import histogram, without_omp
>>> @without_omp
... def single_threaded_histogram():
... data = np.random.standard_normal(size=(1000,))
... return pygram11.histogram(data, bins=10, range=(-5, 5), flow=True)
Defining a specific `key`:
>>> import pygram11.config
>>> previous = pygram11.config.get("thresholds.var1d")
>>> @without_omp(key="thresholds.var1d")
... def single_threaded_histogram2():
... print(f"in function threshold: {pygram11.config.get('thresholds.var1d')}")
... data = np.random.standard_normal(size=(1000,))
... return pygram11.histogram(data, bins=[-2, -1, 1.5, 3.2])
>>> result = single_threaded_histogram2()
in function threshold: 9223372036854775807
>>> previous
5000
>>> previous == pygram11.config.get("thresholds.var1d")
True
>>> result[0].shape
(3,)
"""
func = None
if len(args) == 1 and callable(args[0]):
func = args[0]
if func:
key = None
if not func:
key = kwargs.get("key")
def cable(func):
@functools.wraps(func)
def decorator(*args, **kwargs):
with omp_disabled(key=key):
res = func(*args, **kwargs)
return res
return decorator
return cable(func) if func else cable
def with_omp(*args, **kwargs):
"""Wrap a function to always enable OpenMP while it's called.
If a specific key is defined, only that threshold will be modified
to turn OpenMP on.
The settings of the pygram11 OpenMP threshold configurations will
be restored to their previous values at the end of the function
that is being wrapped.
Parameters
----------
key : str, optional
Specific threshold key to turn on.
Examples
--------
Writing a function with this decorator:
>>> import numpy as np
>>> from pygram11 import histogram, with_omp
>>> @with_omp
... def multi_threaded_histogram():
... data = np.random.standard_normal(size=(1000,))
... return pygram11.histogram(data, bins=10, range=(-5, 5), flow=True)
Defining a specific `key`:
>>> import pygram11.config
>>> previous = pygram11.config.get("thresholds.var1d")
>>> @with_omp(key="thresholds.var1d")
... def multi_threaded_histogram2():
... print(f"in function threshold: {pygram11.config.get('thresholds.var1d')}")
... data = np.random.standard_normal(size=(1000,))
... return pygram11.histogram(data, bins=[-2, -1, 1.5, 3.2])
>>> result = multi_threaded_histogram2()
in function threshold: 0
>>> previous
5000
>>> previous == pygram11.config.get("thresholds.var1d")
True
>>> result[0].shape
(3,)
"""
func = None
if len(args) == 1 and callable(args[0]):
func = args[0]
if func:
key = None
if not func:
key = kwargs.get("key")
def cable(func):
@functools.wraps(func)
def decorator(*args, **kwargs):
with omp_forced(key=key):
res = func(*args, **kwargs)
return res
return decorator
return cable(func) if func else cable
@contextlib.contextmanager
def omp_disabled(*, key: Optional[str] = None) -> Iterator[None]:
"""Context manager to disable OpenMP.
Parameters
----------
key : str, optional
Specific threshold key to turn off.
Examples
--------
Using a specific key:
>>> import pygram11
>>> import numpy as np
>>> with pygram11.omp_disabled(key="thresholds.var1d"):
... data = np.random.standard_normal(size=(200,))
... result = pygram11.histogram(data, bins=[-2, -1, 1.5, 3.2])
>>> result[0].shape
(3,)
Disable all thresholds:
>>> import pygram11
>>> import numpy as np
>>> with pygram11.omp_disabled():
... data = np.random.standard_normal(size=(200,))
... result = pygram11.histogram(data, bins=12, range=(-3, 3))
>>> result[0].shape
(12,)
"""
if key is not None:
try:
prev = pygram11.config.get(key)
pygram11.config.set(key, sys.maxsize)
yield
finally:
pygram11.config.set(key, prev)
else:
previous = {k: pygram11.config.get(k) for k in pygram11.config.threshold_keys()}
try:
disable_omp()
yield
finally:
for k, v in previous.items():
pygram11.config.set(k, v)
@contextlib.contextmanager
def omp_forced(*, key: Optional[str] = None) -> Iterator[None]:
"""Context manager to force enable OpenMP.
Parameters
----------
key : str, optional
Specific threshold key to turn on.
Examples
--------
Using a specific key:
>>> import pygram11
>>> import numpy as np
>>> with pygram11.omp_forced(key="thresholds.var1d"):
... data = np.random.standard_normal(size=(200,))
... result = pygram11.histogram(data, bins=[-2, -1, 1.5, 3.2])
>>> result[0].shape
(3,)
Enable all thresholds:
>>> import pygram11
>>> import numpy as np
>>> with pygram11.omp_forced():
... data = np.random.standard_normal(size=(200,))
... result = pygram11.histogram(data, bins=10, range=(-3, 3))
>>> result[0].shape
(10,)
"""
if key is not None:
try:
prev = pygram11.config.get(key)
pygram11.config.set(key, 0)
yield
finally:
pygram11.config.set(key, prev)
else:
previous = {k: pygram11.config.get(k) for k in pygram11.config.threshold_keys()}
try:
force_omp()
yield
finally:
for k, v in previous.items():
pygram11.config.set(k, v)
|
python
|
import numpy as np
import pandas as pd
import joblib
dataset = pd.read_csv("datasets/cleaned_cleveland.csv")
X = dataset.iloc[:, :-1]
y = dataset.iloc[:, -1]
from sklearn.neighbors import KNeighborsClassifier
regressor = KNeighborsClassifier(n_neighbors=21)
regressor.fit(X, y)
joblib.dump(regressor, "classification/model.pkl")
classification_model = joblib.load("classification/model.pkl")
# Test model for returning false result
# print(
# classification_model.predict([[41, 0, 2, 130, 204, 0, 2, 172, 0, 1.4, 1, 0.0, 3.0]])
# )
# Test model for returning true result
# print(
# classification_model.predict([[67, 1, 4, 120, 229, 0, 2, 129, 1, 2.6, 2, 2.0, 3.0]])
# )
|
python
|
from flask import Flask
# 创建flask框架
# 静态文件访问的时候url匹配时,路由规则里的路径名字 默认值是、static
app = Flask(__name__, static_url_path='/static')
print(app.url_map)
# @app.route('/')
# def index():
# """处理index页面逻辑"""
# return 'nihao'
@app.route('/login.html')
def login():
"""登录的逻辑"""
# 读取login.html 并且返回
with open('login.html') as f:
content = f.read()
return content
num1 = 10
if __name__ == '__main__':
# 运行服务器、
app.run()
|
python
|
# -*- coding: utf-8 -*-
from setuptools import setup
import pathlib
here = pathlib.Path(__file__).parent.resolve()
long_description = (here / "README.md").read_text(encoding='utf-8')
setup(
name='zarr-swiftstore',
version="1.2.3",
description='swift storage backend for zarr',
long_description=long_description,
long_description_content_type='text/markdown',
python_requires=">=3.5",
package_dir={'': '.'},
packages=['zarrswift', 'zarrswift.tests'],
install_requires=[
'zarr>=2.4.0',
'python-swiftclient>=3.10.0',
'mock',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
author='Pavan Siligam',
author_email='[email protected]',
license='MIT',
url="https://github.com/siligam/zarr-swiftstore",
)
|
python
|
import argparse
from config.config import Config
from dataset.factory import DatasetModule
from domain.metadata import Metadata
from logger import logger
from model.factory import ModelModule
from trainer.factory import TrainerModule
def main(args):
mode = args.mode.lower()
config_file_name = args.config.lower()
# Get Parameters
params = Config(file_name=config_file_name).params
logger.info(f"Parameter information :\n{params}")
metadata_params = params.metadata
dataset_params = params.dataset
model_params = params.model
trainer_params = params.trainer
# Metadata Controller
metadata = Metadata(**metadata_params)
# Dataset Controller
dataset_module = DatasetModule(metadata=metadata, **dataset_params)
# Model Controller
model_module = ModelModule(metadata=metadata, **model_params)
# Trainer Controller
trainer_module = TrainerModule(
metadata=metadata,
model_module=model_module,
dataset_module=dataset_module,
**trainer_params
)
result_dict = trainer_module.do(mode=mode)
print(result_dict)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Pytorch Project Template [Byeonggil Jung (Korea Univ, AIR Lab)]")
parser.add_argument("--mode", required=False, default="train", help="Select the mode, train | inference")
parser.add_argument("--config", required=True, help="Select the config file")
args = parser.parse_args()
logger.info(f"Selected parameters : {args}")
main(args=args)
|
python
|
from qiskit.circuit.library import PauliFeatureMap
class ZZFeatureMap(PauliFeatureMap):
def __init__(
self,
feature_dimension,
reps=2,
entanglement="linear",
data_map_func=None,
insert_barriers=False,
name="ZZFeatureMap",
parameter_prefix="x",
):
"""
Create a new second-order Pauli-Z expansion.
@feature_dimension :: Number of features.
@reps :: The number of repeated circuits, has a min. 1.
@entanglement :: Specifies the entanglement structure. Refer to
@data_map_func :: A mapping function for data x.
@insert_barriers :: If True, barriers are inserted in between the
evolution instructions and hadamard layers.
"""
if feature_dimension < 2:
raise ValueError(
"The ZZFeatureMap contains 2-local interactions"
"and cannot be defined for less than 2 qubits."
f"You provided {feature_dimension}."
)
super().__init__(
feature_dimension=feature_dimension,
reps=reps,
entanglement=entanglement,
paulis=["Z", "ZZ"],
data_map_func=data_map_func,
insert_barriers=insert_barriers,
name=name,
parameter_prefix=parameter_prefix,
)
|
python
|
#
# @lc app=leetcode.cn id=1 lang=python3
#
# [1] 两数之和
#
# https://leetcode-cn.com/problems/two-sum/description/
#
# algorithms
# Easy (48.55%)
# Likes: 8314
# Dislikes: 0
# Total Accepted: 1.1M
# Total Submissions: 2.2M
# Testcase Example: '[2,7,11,15]\n9'
#
# 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
#
# 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
#
#
#
# 示例:
#
# 给定 nums = [2, 7, 11, 15], target = 9
#
# 因为 nums[0] + nums[1] = 2 + 7 = 9
# 所以返回 [0, 1]
#
#
#
# @lc code=start
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]: ## 一边遍历
dic = {}
for i in range(len(nums)):
if target - nums[i] in dic:
return [dic[target-nums[i]],i]
dic[nums[i]] = i
return []
# @lc code=end
# def twoSum(self, nums: List[int], target: int) -> List[int]: 两边遍历
# dic = {}
# for i in range(len(nums)):
# dic[nums[i]] = i
# for i in range(len(nums)):
# if target - nums[i] in dic and dic[target-nums[i]] != i:
# return [i,dic[target-nums[i]]]
# return []
|
python
|
class DetFace:
def __init__(self, conf, bbox):
self.conf = conf
self.bbox = bbox
self.name = ''
|
python
|
from pathlib import Path
import tables
import pandas as pd
class Stream:
def __init__(self, path):
self.path = path
self.frame_id_list = self._frame_id_list()
self.frame_dict = {k:frame_id for k, frame_id in enumerate(self.frame_id_list)}
def _frame_id_list(self):
if not Path(self.path).exists():
frame_id_list = []
else:
with tables.open_file(self.path) as h:
frame_id_list = [int(str(frame).split(' ')[0].replace('/frame_', ''))
for frame in h.iter_nodes('/')]
frame_id_list.sort()
return frame_id_list
def __len__(self):
return len(self.frame_id_list)
def to_pandas(self, frame_id):
frame_id = self.frame_dict[frame_id]
return pd.read_hdf(self.path, f'frame_{frame_id}')
def __getitem__(self, frame_id):
if len(self) == 0:
h = 'null'
else:
if frame_id in self.frame_id_list:
h = self.to_pandas(frame_id)
elif isinstance(frame_id, slice):
h = [self.to_pandas(ID)
for ID in range(*frame_id.indices(len(self)))]
h = pd.concat(h)
else:
h = 'unreal'
return h
@property
def min_id(self):
if len(self) == 0:
return 0
else:
return min(self.frame_id_list)
@property
def max_id(self):
if len(self) == 0:
return 0
else:
return len(self)
@property
def marks(self):
if len(self) == 0:
return {0: '0'}
else:
return {
k: '' # frame_id
for k, frame_id in self.frame_dict.items()
}
|
python
|
#!/usr/bin/env python
# encoding: utf-8
"""
@version: v1.0
@author: xiaxianba
@license: Apache Licence
@contact: [email protected]
@site: http://weibo.com/xiaxianba
@software: PyCharm
@file: SimTrade.py
@time: 2017/02/06 13:00
@describe: 展期数据
"""
import csv
import datetime as pydt
import numpy as np
import os
from WindPy import *
# 国内三大期货交易所共46个商品合约
list_item = ['CU.SHF', 'AL.SHF', 'ZN.SHF', 'PB.SHF', 'AU.SHF', 'AG.SHF', 'NI.SHF', 'SN.SHF',
'RB.SHF', 'WR.SHF', 'HC.SHF', 'BU.SHF', 'RU.SHF', 'M.DCE', 'Y.DCE',
'A.DCE', 'B.DCE', 'P.DCE', 'C.DCE', 'J.DCE', 'V.DCE', 'I.DCE',
'BB.DCE', 'FB.DCE', 'L.DCE', 'PP.DCE', 'JM.DCE', 'CS.DCE', 'CY.CZC',
'SR.CZC', 'CF.CZC', 'ZC.CZC', 'FG.CZC', 'TA.CZC', 'MA.CZC', 'WH.CZC', 'PM.CZC',
'RI.CZC', 'LR.CZC', 'JR.CZC', 'RS.CZC', 'OI.CZC', 'RM.CZC', 'SF.CZC', 'SM.CZC', ]
# 商品合约对应的Wind板块id
dict_item = {'CU.SHF':'a599010202000000', 'AL.SHF':'a599010203000000', 'ZN.SHF':'a599010204000000',
'PB.SHF':'1000002892000000', 'AU.SHF':'a599010205000000', 'AG.SHF':'1000006502000000',
'NI.SHF':'1000011457000000', 'SN.SHF':'1000011458000000', 'RB.SHF':'a599010206000000',
'WR.SHF':'a599010207000000', 'HC.SHF':'1000011455000000',
'BU.SHF':'1000011013000000', 'RU.SHF':'a599010208000000', 'M.DCE':'a599010304000000',
'Y.DCE':'a599010306000000', 'A.DCE':'a599010302000000', 'B.DCE':'a599010303000000',
'P.DCE':'a599010307000000', 'C.DCE':'a599010305000000', 'J.DCE':'1000002976000000',
'V.DCE':'a599010309000000', 'I.DCE':'1000011439000000', 'BB.DCE':'1000011466000000',
'FB.DCE':'1000011465000000', 'L.DCE':'a599010308000000', 'PP.DCE':'1000011468000000',
'JM.DCE':'1000009338000000', 'CS.DCE':'1000011469000000',
'CY.CZC':'1000011479000000', 'SR.CZC':'a599010405000000', 'CF.CZC':'a599010404000000',
'ZC.CZC':'1000011012000000', 'FG.CZC':'1000008549000000', 'TA.CZC':'a599010407000000',
'MA.CZC':'1000005981000000', 'WH.CZC':'a599010403000000', 'PM.CZC':'1000006567000000',
'RI.CZC':'a599010406000000', 'LR.CZC':'1000011476000000', 'JR.CZC':'1000011474000000',
'RS.CZC':'1000008621000000', 'OI.CZC':'a599010408000000', 'RM.CZC':'1000008622000000',
'SF.CZC':'1000011478000000', 'SM.CZC':'1000011477000000'}
def get_zhanqi(ext_list, datestr):
dict_rate = {}
prefix = "date="
suffix = ";sectorid="
file = os.getcwd() + "\\" + datestr + ".csv"
with open(file, "wb") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["secuid", "exchangeid", "updatetime", "actionday", "tradingday", "value"])
for item in ext_list:
a = item.split('.')
dicts = {}
scope = prefix + datestr + suffix + dict_item[item]
result = w.wset("sectorconstituent", scope)
if result.ErrorCode == 0:
list_contract = result.Data[1]
for contract in list_contract:
result_volume = w.wsd(contract, "volume", datestr, datestr, "")
if result_volume.ErrorCode == 0:
dicts[contract] = result_volume.Data[0][0]
result_main = w.wsd(item, "trade_hiscode", datestr, datestr, "")
if result_main.ErrorCode == 0 and len(result_main.Data[0]) != 0:
main_contract = result_main.Data[0][0]
main_contract_price = w.wsd(main_contract, "close", datestr, datestr, "")
main_contract_delivery = w.wsd(main_contract, "lastdelivery_date", datestr, datestr, "")
dicts.pop(main_contract)
second_contract = sorted(dicts.items(), key=lambda item: item[1], reverse=True)[:1]
second_contract_price = w.wsd(dict(second_contract).keys(), "close", datestr, datestr, "")
second_contract_delivery = w.wsd(dict(second_contract).keys(), "lastdelivery_date", datestr, datestr, "")
if isinstance(main_contract_price.Data[0][0],float) and isinstance(second_contract_price.Data[0][0],float):
diff_price = np.log(float(main_contract_price.Data[0][0])) - np.log(float(second_contract_price.Data[0][0]))
diff_date = (second_contract_delivery.Data[0][0] - main_contract_delivery.Data[0][0]).days
dict_rate[item] = 365 * diff_price / diff_date
writer.writerow([a[0], a[1], "000000", datestr, datestr, dict_rate[item]])
def gene_file(date):
file = os.getcwd() + "\\" + date + ".csv"
with open(file,"wb") as csvfile:
writer=csv.writer(csvfile)
writer.writerow(["secuid","exchangeid","updatetime","actionday","tradingday","value"])
if __name__ == "__main__":
date_now = pydt.date.today() - pydt.timedelta(days=1)
datestr = date_now.strftime("%Y%m%d")
#datestr='20180822'
if len(sys.argv) > 1:
print sys.argv[1]
datestr = sys.argv[1]
w.start()
date_date = pydt.datetime.strptime(datestr, "%Y%m%d")
if date.isoweekday(date_date) < 6:
get_zhanqi(list_item, datestr)
else:
gene_file(datestr)
w.close()
|
python
|
import obswebsocket, obswebsocket.requests
import logging
import time
import random
from obs.actions.Action import Action
from obs.actions.ShowSource import ShowSource
from obs.actions.HideSource import HideSource
from obs.Permission import Permission
class Toggle(Action):
def __init__(self, obs_client, command_name, aliases, description, permission, min_votes, args):
"""Initializes this class, see Action.py
"""
super().__init__(obs_client, command_name, aliases, description, permission, min_votes, args)
self.log = logging.getLogger(__name__)
self._init_args(args)
def execute(self, user):
"""Shows a scene item, such as an image or video, and then hides it after
a specified duration
"""
# Check user permissions and votes
if(not (
self._has_permission(user)
and self._has_enough_votes(user)
)
):
self._twitch_failed()
return False
# finally execute the command
if(not self.toggle_off_obj2.execute(user)):
return False
if(not self.toggle_on_obj1.execute(user)):
return False
# if a duration was specified then sleep and then hide the scene
if(self.duration is not None):
# wait the specified duration
time.sleep(self.duration)
if(not self.toggle_on_obj2.execute(user)):
return False
if(not self.toggle_off_obj1.execute(user)):
return False
self._twitch_done()
return True
def _init_args(self, args):
"""This validates the arguments are valid for this instance,
and raises a ValueError if they aren't.
Mandatory args:
scene item (string): Name of the scene to show.
Optional args:
scene (string): Name of scene where scene item is nested. If not provided,
then the current scene is used.
duration (int): Duration (seconds) to show scene.
"""
self.duration = args.get('duration', None) # Optional
self.toggle_on = args.get('toggle_on', None)
self.toggle_off = args.get('toggle_off', None)
if(self.toggle_on is None or self.toggle_off is None):
raise ValueError("Command {}: Args error, missing 'toggle_on' or 'toggle_off'".format(self.command_name))
if(self.duration is not None and self.duration < 0):
raise ValueError("Command {}: Args error, duration must be greater than zero".format(self.command_name))
# Try to instantiate the toggle on and off action classes
self.log.debug("Command {}: Toggle on/off args are {}/{}".format(self.command_name, self.toggle_on, self.toggle_off))
try:
self.toggle_on_obj1 = ShowSource(
self.obs_client,
self.command_name + "_toggle_on1",
None,
"Toggle On for {}".format(self.command_name),
Permission.EVERYONE,
0,
self.toggle_on)
except ValueError as e:
self.log.error("ERROR: " + e)
raise e
try:
self.toggle_off_obj1 = HideSource(
self.obs_client,
self.command_name + "_toggle_off1",
None,
"Toggle On for {}".format(self.command_name),
Permission.EVERYONE,
0,
self.toggle_on)
except ValueError as e:
self.log.error("ERROR: " + e)
raise e
try:
self.toggle_on_obj2 = ShowSource(
self.obs_client,
self.command_name + "_toggle_on2",
None,
"Toggle On for {}".format(self.command_name),
Permission.EVERYONE,
0,
self.toggle_off)
except ValueError as e:
self.log.error("ERROR: " + e)
raise e
try:
self.toggle_off_obj2 = HideSource(
self.obs_client,
self.command_name + "_toggle_off2",
None,
"Toggle On for {}".format(self.command_name),
Permission.EVERYONE,
0,
self.toggle_off)
except ValueError as e:
self.log.error("ERROR: " + e)
raise e
# disable randomizers to keep it simple for now
if(isinstance(self.toggle_on_obj1.source, list) or isinstance(self.toggle_off_obj1.source, list)):
self.toggle_on_obj1.source = self.toggle_on_obj1.source[0]
self.toggle_off_obj1.source = self.toggle_off_obj1.source[0]
if(isinstance(self.toggle_on_obj2.source, list) or isinstance(self.toggle_off_obj2.source, list)):
self.toggle_on_obj2.source = self.toggle_on_obj2.source[0]
self.toggle_off_obj2.source = self.toggle_off_obj2.source[0]
self.toggle_on_obj1.pick_from_group = False
self.toggle_off_obj1.pick_from_group = False
self.toggle_on_obj2.pick_from_group = False
self.toggle_off_obj2.pick_from_group = False
# Disable any duration args, it's controlled here instead
self.toggle_on_obj1.duration = None
self.toggle_off_obj1.duration = None
self.toggle_on_obj2.duration = None
self.toggle_off_obj2.duration = None
|
python
|
from collections import namedtuple
from . import meta, pagination, resource_identifier
class ToOneLinks(namedtuple('ToOneLinks', ['maybe_self', 'maybe_related'])):
"""
Representation of links for a to-one relationship anywhere in a response.
"""
__slots__ = ()
def __new__(cls, maybe_self=None, maybe_related=None):
return super(ToOneLinks, cls).__new__(cls, maybe_self, maybe_related)
class ToManyLinks(namedtuple('ToManyLinks', ['pagination', 'maybe_self',
'maybe_related'])):
"""
Representation of links for a to-many relationship anywhere in a response.
"""
__slots__ = ()
def __new__(cls, pagination, maybe_self=None, maybe_related=None):
return super(ToManyLinks, cls).__new__(cls, pagination, maybe_self,
maybe_related)
class ToOne(namedtuple('ToOne', ['maybe_resource_id'])):
"""Representation of a to-one relationship."""
__slots__ = ()
def __new__(cls, maybe_resource_id=None):
return super(ToOne, cls).__new__(cls, maybe_resource_id)
class ToMany(namedtuple('ToMany', ['list_resource_ids'])):
"""Representation of at to-many relationship."""
__slots__ = ()
def __new__(cls, list_resource_ids):
return super(ToMany, cls).__new__(cls, list_resource_ids)
class Data(namedtuple('Data', ['either_to_many_or_to_one'])):
"""Representation of "data" section of relationships."""
__slots__ = ()
def __new__(cls, either_to_many_or_to_one):
return super(Data, cls).__new__(cls, either_to_many_or_to_one)
class Relationship(namedtuple(
'Relationship',
['name', 'any_data_or_links_or_meta', 'maybe_data',
'maybe_either_to_one_links_or_to_many_links', 'maybe_meta'])):
"""Representation of a relationship in a relationships lookup."""
__slots__ = ()
def __new__(cls, name, any_data_or_links_or_meta, maybe_data=None,
maybe_either_to_one_links_or_to_many_links=None,
maybe_meta=None):
return \
super(Relationship, cls).__new__(
cls, name, any_data_or_links_or_meta, maybe_data,
maybe_either_to_one_links_or_to_many_links, maybe_meta
)
class Relationships(namedtuple('Relationships', ['dict_relationships'])):
"""Representation of a relationships lookup anywhere in a response."""
__slots__ = ()
def __new__(cls, dict_relationships):
return super(Relationships, cls).__new__(cls, dict_relationships)
def mk_single_data(obj, config):
if type(obj) is list:
list_rid = [resource_identifier.mk(obj_rid, config) for obj_rid in obj]
return Data(ToMany(list_rid))
if type(obj) is dict:
return Data(ToOne(resource_identifier.mk(obj, config)))
if not obj:
return Data(ToOne(None))
msg = "relationships['data'] is unintelligible: {0}".format(str(obj))
raise RuntimeError(msg)
def mk_single_maybe_data(obj, config):
if 'data' in obj:
return mk_single_data(obj['data'], config)
else:
return None
def mk_to_one_links(obj, config):
maybe_self = obj.get( 'self', None)
maybe_related = obj.get('related', None)
return ToOneLinks(maybe_self, maybe_related)
def mk_to_many_links(obj, config):
_pagination = pagination.mk(obj, config)
maybe_self = obj.get( 'self', None)
maybe_related = obj.get('related', None)
return ToManyLinks(_pagination, maybe_self, maybe_related)
def mk_single_maybe_links(maybe_data, obj, config):
if 'links' in obj:
obj_links = obj['links']
if type(maybe_data.either_to_many_or_to_one) in [ToOne, type(None)]:
return mk_to_one_links(obj_links, config)
if type(maybe_data.either_to_many_or_to_one) is ToMany:
return mk_to_many_links(obj_links, config)
raise RuntimeError('insanity: {0}'.format(str(maybe_data)))
else:
return None
def mk_single_maybe_meta(obj, config):
if 'meta' in obj:
return meta.mk(obj['meta'], config)
else:
return None
def mk_single(name, obj, config):
maybe_data = mk_single_maybe_data(obj, config)
maybe_links = mk_single_maybe_links(maybe_data, obj, config)
maybe_meta = mk_single_maybe_meta(obj, config)
any_data_or_links_or_meta = maybe_data or maybe_links or maybe_meta
return Relationship(name, any_data_or_links_or_meta, maybe_data,
maybe_links, maybe_meta)
def mk(obj, config):
dict_relationships = {}
for name, obj_relationship in obj.items():
relationship = mk_single(name, obj_relationship, config)
if not relationship.any_data_or_links_or_meta:
raise RuntimeError('response must contain data, links, or meta')
dict_relationships[name] = relationship
return Relationships(dict_relationships)
|
python
|
import random
import networkx as nx
from LightningGraph.LN_parser import read_data_to_xgraph, process_lightning_graph
LIGHTNING_GRAPH_DUMP_PATH = 'LightningGraph/old_dumps/LN_2020.05.13-08.00.01.json'
def sample_long_route(graph, amount, get_route_func, min_route_length=4, max_trials=10000):
"""
Sample src, dst nodes from graph and use the given function to find a long enough route between them
Try until success or max_trials.
"""
# Select random two nodes as src and dest, with the route between them being of length at least 'min_route_length'.
unisolated_nodes = list(set(graph) - set(nx.isolates(graph)))
for trial in range(max_trials):
src = random.choice(unisolated_nodes)
dest = random.choice(unisolated_nodes)
route = get_route_func(graph, src, dest, amount)
if len(route) >= min_route_length:
break
if trial == max_trials - 1:
raise RuntimeError("Warning: Too hard to find route in graph. Consider changing restrictions or graph")
return route, src, dest
def create_sub_graph_by_node_capacity(dump_path=LIGHTNING_GRAPH_DUMP_PATH, k=64, highest_capacity_offset=0):
"""
Creates a sub graph with at most k nodes, selecting nodes by their total capacities.
:param dump_path: The path to the JSON describing the lightning graph dump.
:param k: The maximal number of nodes in the resulting graph.
:param highest_capacity_offset: If it's 0, takes the k nodes with the highest capacity.
If its m > 0, takes the k first nodes after the first m nodes.
This is used to get a less connected graph.
We can't take lowest nodes as removing high
nodes usually makes the graph highly unconnected.
:returns: a connected graph with at most k nodes
"""
graph = read_data_to_xgraph(dump_path)
process_lightning_graph(graph, remove_isolated=True, total_capacity=True, infer_implementation=True)
sorted_nodes = sorted(graph.nodes, key=lambda node: graph.nodes[node]['total_capacity'], reverse=True)
# Can't take last nodes as removing highest capacity nodes makes most of them isolated
best_nodes = sorted_nodes[highest_capacity_offset: k + highest_capacity_offset]
graph = graph.subgraph(best_nodes).copy() # without copy a view is returned and the graph can not be changed.
# This may return a graph with less than k nodes
process_lightning_graph(graph, remove_isolated=True, total_capacity=True)
print(f"Creating sub graph with {len(graph.nodes)}/{len(sorted_nodes)} nodes and {len(graph.edges)} edges")
return graph
|
python
|
# identifies patients with gout and thiazides
import csv
import statsmodels.api as statsmodels
from atcs import *
from icd import is_gout
highrisk_prescription_identified = 0
true_positive = 0
true_negative = 0
false_positive = 0
false_negative = 0
gout_treatment = allopurinol | benzbromaron | colchicin | febuxostat | probenecid
gout_contraindicated = xipamid | hydrochlorothiazid | torasemid
file = open('test_1847_geputzt.csv')
reader = csv.reader(file, delimiter=';')
headers = next(reader, None)
data = []
for row in reader:
data.append(dict(zip(headers, row)))
for row in data:
atc_codes = set()
for pos in range(1, 25 + 1):
row_name = 'atc_%02d' % pos
if row[row_name]:
atc_codes.add(row[row_name])
icd_codes = set()
for pos in range(1, 20 + 1):
row_name = 'icd10_%02d' % pos
if row[row_name]:
icd_codes.add(row[row_name])
if gout_treatment & atc_codes and any([is_gout(icd) for icd in icd_codes]):
true_positive += 1
if gout_treatment & atc_codes and not any([is_gout(icd) for icd in icd_codes]):
false_positive += 1
if not gout_treatment & atc_codes and any([is_gout(icd) for icd in icd_codes]):
false_negative += 1
if not gout_treatment & atc_codes and not any([is_gout(icd) for icd in icd_codes]):
true_negative += 1
try:
specificity = true_negative / (true_negative + false_positive)
except:
specificity = 1
try:
sensitivity = true_positive / (true_positive + false_negative)
except:
sensitivity = 1
ppv = true_positive / (true_positive + false_positive)
npv = true_negative / (true_negative + false_negative)
print('Specificity:', specificity,
statsmodels.stats.proportion_confint(true_negative, true_negative + false_positive, alpha=0.05, method='wilson'))
print('Sensitivity:', sensitivity,
statsmodels.stats.proportion_confint(true_positive, true_positive + false_negative, alpha=0.05, method='wilson'))
print('PPV:', ppv,
statsmodels.stats.proportion_confint(true_positive, true_positive + false_positive, alpha=0.05, method='wilson'))
print('NPV:', npv,
statsmodels.stats.proportion_confint(true_negative, true_negative + false_negative, alpha=0.05, method='wilson'))
print('High risk Prescriptions:', highrisk_prescription_identified)
print('True Positives:', true_positive, 'True Negatives:', true_negative, 'False Positives:', false_positive,
'False Negatives:', false_negative) # validation: Gout(true) - true_positive = false_negative
precision = ppv
recall = sensitivity
print('Precision:', precision, 'Recall:', recall, 'F1', 2 * precision * recall / (precision + recall))
|
python
|
from AoCUtils import *
result = 0
partNumber = "1"
writeToLog = False
if writeToLog:
logFile = open("log" + partNumber + ".txt", "w")
else:
logFile = "stdout"
printLog = printLogFactory(logFile)
heights = {}
with open("input.txt", "r") as inputFile:
lines = inputFile.read().strip().split("\n")
for (y, line) in enumerate(lines):
line = line.strip()
for (x, char) in enumerate(line):
heights[Position(x, y)] = int(char)
for (x, y) in product(range(len(lines[0])), range(len(lines))):
p = MapPosition(x, y, frame=lines)
m = min([heights[q] for q in p.adjacent()])
if heights[p] < m:
result += heights[p] + 1
with open("output" + partNumber + ".txt", "w") as outputFile:
outputFile.write(str(result))
print(str(result))
if writeToLog:
cast(TextIOWrapper, logFile).close()
|
python
|
import setuptools
__version__ = "0.2.0"
__author__ = "Ricardo Montañana Gómez"
def readme():
with open("README.md") as f:
return f.read()
setuptools.setup(
name="Odte",
version=__version__,
license="MIT License",
description="Oblique decision tree Ensemble",
long_description=readme(),
long_description_content_type="text/markdown",
packages=setuptools.find_packages(),
url="https://github.com/doctorado-ml/stree",
author=__author__,
author_email="[email protected]",
keywords="scikit-learn oblique-classifier oblique-decision-tree decision-\
tree ensemble svm svc",
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.8",
"Natural Language :: English",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Intended Audience :: Science/Research",
],
install_requires=["scikit-learn", "numpy", "ipympl", "stree"],
test_suite="odte.tests",
zip_safe=False,
)
|
python
|
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='ddp_asyncio',
version='0.3.0',
description='Asynchronous DDP library',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/hunternet93/ddp_asyncio',
download_url='https://github.com/hunternet93/ddp_asyncio/releases/download/0.2.0/ddp_asyncio-0.2.0.tar.gz',
author='Isaac Smith',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Framework :: AsyncIO'
],
keywords='ddp meteor',
packages=find_packages(),
install_requires=['websockets', 'ejson'],
)
|
python
|
import random
import pandas as pd
def synthetic(n, categorical=[], continuous=[]):
"""Synthetic dataset.
For each element in ``categorical``, either 0 or 1 is generated randomly.
Similarly, for each element in ``continuous``, a random value between 0 and
100 is generated.
Parameters
----------
n: int
Number of people
categorical: iterable(str), optional
Categorical properties, e.g. gender, country, etc. Its values will be
either 0 or 1. Defaults to [].
values: iterable(str), optional
Continuous properties, e.g. age, average_mark, etc. Its values will be
between 0 and 100. Defaults to [].
Returns
-------
pd.DataFrame
Sythetic dataset
"""
return pd.DataFrame(dict(name=[f'person-{i}' for i in range(n)],
**{c: [random.randint(0, 1) for _ in range(n)] for c in categorical},
**{v: [random.randint(45, 90) for _ in range(n)] for v in continuous}))
|
python
|
# Copyright Aleksey Gurtovoy 2001-2004
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
#
# See http://www.boost.org/libs/mpl for documentation.
# $Source: /CVSROOT/boost/libs/mpl/preprocessed/preprocess_set.py,v $
# $Date: 2007/10/29 07:32:56 $
# $Revision: 1.1.1.1 $
import preprocess
preprocess.main(
[ "plain" ]
, "set"
, "boost\\mpl\\set\\aux_\\preprocessed"
)
|
python
|
#!/usr/bin/env python
from Bio import SeqIO
from Bio.SeqUtils import GC
import click
import math
import random
import sys
CONTEXT_SETTINGS = {
"help_option_names": ["-h", "--help"],
}
@click.command(no_args_is_help=True, context_settings=CONTEXT_SETTINGS)
@click.argument(
"fasta_file",
type=click.Path(exists=True, resolve_path=True),
)
@click.option(
"-f", "--filter-masked",
help="Filter masked DNA sequences.",
is_flag=True,
)
@click.option(
"-s", "--subsample",
help="Number of sequences to subsample.",
type=int,
default=1000,
show_default=True,
)
@click.option(
"-o", "--output-file",
help="Output file. [default: STDOUT]",
type=click.Path(writable=True, readable=False, resolve_path=True,
allow_dash=True),
)
def main(**args):
# Group sequences by %GC content
gc_groups = {}
for record in SeqIO.parse(args["fasta_file"], "fasta"):
if args["filter_masked"]:
if record.seq.count("N") or record.seq.count("n"):
continue
gc = round(GC(record.seq))
gc_groups.setdefault(gc, [])
gc_groups[gc].append(record)
# Subsampling
sampled = []
random_seed = 123
norm_factor = args["subsample"] / \
sum([len(v) for v in gc_groups.values()])
for i in sorted(gc_groups):
random.Random(random_seed).shuffle(gc_groups[i])
sampled.extend(gc_groups[i][:math.ceil(len(gc_groups[i])*norm_factor)])
random.Random(random_seed).shuffle(sampled)
# Write
if args["output_file"] is not None:
handle = open(args["output_file"], "wt")
else:
handle = sys.stdout
SeqIO.write(sampled[:args["subsample"]], handle, "fasta")
handle.close()
if __name__ == "__main__":
main()
|
python
|
# Copyright 2021 by B. Knueven, D. Mildebrath, C. Muir, J-P Watson, and D.L. Woodruff
# This software is distributed under the 3-clause BSD License.
# Code that is producing a xhat and a confidence interval using sequential sampling
# This is the implementation of the 2 following papers:
# [bm2011] Bayraksan, G., Morton,D.P.: A Sequential Sampling Procedure for Stochastic Programming. Operations Research 59(4), 898-913 (2011)
# [bpl2012] Bayraksan, G., Pierre-Louis, P.: Fixed-Width Sequential Stopping Rules for a Class of Stochastic Programs, SIAM Journal on Optimization 22(4), 1518-1548 (2012)
# see also multi_seqsampling.py, which has a class derived from this class
import pyomo.environ as pyo
import mpi4py.MPI as mpi
import mpisppy.utils.sputils as sputils
import numpy as np
import scipy.stats
import importlib
from mpisppy import global_toc
fullcomm = mpi.COMM_WORLD
global_rank = fullcomm.Get_rank()
import mpisppy.utils.amalgamator as amalgamator
import mpisppy.utils.xhat_eval as xhat_eval
import mpisppy.confidence_intervals.ciutils as ciutils
from mpisppy.tests.examples.apl1p import xhat_generator_apl1p
#==========
def is_needed(options,needed_things,message=""):
if not set(needed_things)<= set(options):
raise RuntimeError("Some options are missing from this list of reqiored options:\n"
f"{needed_things}\n"
f"{message}")
def add_options(options,optional_things,optional_default_settings):
# allow for defaults on options that Bayraksan et al establish
for i in range(len(optional_things)):
ething = optional_things[i]
if not ething in options :
options[ething]=optional_default_settings[i]
def xhat_generator_farmer(scenario_names, solvername="gurobi", solver_options=None, crops_multiplier=1):
''' For developer testing: Given scenario names and
options, create the scenarios and compute the xhat that is minimizing the
approximate problem associated with these scenarios.
Parameters
----------
scenario_names: int
Names of the scenario we use
solvername: str, optional
Name of the solver used. The default is "gurobi".
solver_options: dict, optional
Solving options. The default is None.
crops_multiplier: int, optional
A parameter of the farmer model. The default is 1.
Returns
-------
xhat: xhat object (dict containing a 'ROOT' key with a np.array)
A generated xhat.
NOTE: this is here for testing during development.
'''
num_scens = len(scenario_names)
ama_options = { "EF-2stage": True,
"EF_solver_name": solvername,
"EF_solver_options": solver_options,
"use_integer": False,
"crops_multiplier": crops_multiplier,
"num_scens": num_scens,
"_mpisppy_probability": 1/num_scens,
}
#We use from_module to build easily an Amalgamator object
ama = amalgamator.from_module("mpisppy.tests.examples.farmer",
ama_options,use_command_line=False)
#Correcting the building by putting the right scenarios.
ama.scenario_names = scenario_names
ama.run()
# get the xhat
xhat = sputils.nonant_cache_from_ef(ama.ef)
return xhat
class SeqSampling():
"""
Computing a solution xhat and a confidence interval for the optimality gap sequentially,
by taking an increasing number of scenarios.
Args:
refmodel (str): path of the model we use (e.g. farmer, uc)
xhat_generator (function): a function that takes scenario_names (and
and optional solvername and solver_options)
as input and returns a first stage policy
xhat.
options (dict): multiple parameters, e.g.:
- "solvername", str, the name of the solver we use
- "solver_options", dict containing solver options
(default is {}, an empty dict)
- "sample_size_ratio", float, the ratio (xhat sample size)/(gap estimators sample size)
(default is 1)
- "xhat_gen_options" dict containing options passed to the xhat generator
(default is {}, an empty dict)
- "ArRP", int, how many estimators should be pooled to compute G and s ?
(default is 1, no pooling)
- "kf_Gs", int, resampling frequency to compute estimators
(default is 1, always resample completely)
- "kf_xhat", int, resampling frequency to compute xhat
(default is 1, always resample completely)
-"confidence_level", float, asymptotic confidence level
of the output confidence interval
(default is 0.95)
-Some other parameters, depending on what model
(BM or BPL, deterministic or sequential sampling)
stochastic_sampling (bool, default False): should we compute sample sizes using estimators ?
if stochastic_sampling is True, we compute sample size using §5 of [Bayraksan and Pierre-Louis]
else, we compute them using [Bayraksan and Morton] technique
stopping_criterion (str, default 'BM'): which stopping criterion should be used ?
2 criterions are supported : 'BM' for [Bayraksan and Morton] and 'BPL' for [Bayraksan and Pierre-Louis]
solving_type (str, default 'EF-2stage'): how do we solve the approximate problems ?
Must be one of 'EF-2stage' and 'EF-mstage' (for problems with more than 2 stages).
Solving methods outside EF are not supported yet.
"""
def __init__(self,
refmodel,
xhat_generator,
options,
stochastic_sampling = False,
stopping_criterion = "BM",
solving_type = "None"):
self.refmodel = importlib.import_module(refmodel)
self.refmodelname = refmodel
self.xhat_generator = xhat_generator
self.options = options
self.stochastic_sampling = stochastic_sampling
self.stopping_criterion = stopping_criterion
self.solving_type = solving_type
self.solvername = options.get("solvername", None)
self.solver_options = options["solver_options"] if "solver_options" in options else None
self.sample_size_ratio = options["sample_size_ratio"] if "sample_size_ration" in options else 1
self.xhat_gen_options = options["xhat_gen_options"] if "xhat_gen_options" in options else {}
#Check if refmodel has all needed attributes
everything = ["scenario_names_creator",
"scenario_creator",
"kw_creator"] # denouement can be missing.
you_can_have_it_all = True
for ething in everything:
if not hasattr(self.refmodel, ething):
print(f"Module {refmodel} is missing {ething}")
you_can_have_it_all = False
if not you_can_have_it_all:
raise RuntimeError(f"Module {refmodel} not complete for seqsampling")
#Manage options
optional_options = ["ArRP","kf_Gs","kf_xhat","confidence_level"]
optional_default_settings = [1,1,1,0.95]
add_options(options, optional_options, optional_default_settings)
if self.stochastic_sampling :
add_options(options, ["n0min"], [50])
if self.stopping_criterion == "BM":
needed_things = ["epsprime","hprime","eps","h","p"]
is_needed(options, needed_things)
optional_things = ["q"]
optional_default_settings = [None]
add_options(options, optional_things, optional_default_settings)
elif self.stopping_criterion == "BPL":
is_needed(options, ["eps"])
if not self.stochastic_sampling :
optional_things = ["c0","c1","growth_function"]
optional_default_settings = [50,2,(lambda x : x-1)]
add_options(options, optional_things, optional_default_settings)
else:
raise RuntimeError("Only BM and BPL criteria are supported at this time.")
for oname in options:
setattr(self, oname, options[oname]) #Set every option as an attribute
#Check the solving_type, and find if the problem is multistage
two_stage_types = ['EF-2stage']
multistage_types = ['EF-mstage']
if self.solving_type in two_stage_types:
self.multistage = False
elif self.solving_type in multistage_types:
self.multistage = True
else:
raise RuntimeError(f"The solving_type {self.solving_type} is not supported."
f"If you want to run a 2-stage problem, please use a solving_type in {two_stage_types}"
f"If you want to run a multistage stage problem, please use a solving_type in {multistage_types}")
#Check the multistage options
if self.multistage:
needed_things = ["branching_factors"]
is_needed(options, needed_things)
if options['kf_Gs'] != 1 or options['kf_xhat'] != 1:
raise RuntimeError("Resampling frequencies must be set equal to one for multistage.")
#Get the stopping criterion
if self.stopping_criterion == "BM":
self.stop_criterion = self.bm_stopping_criterion
elif self.stopping_criterion == "BPL":
self.stop_criterion = self.bpl_stopping_criterion
else:
raise RuntimeError("Only BM and BPL criteria are supported.")
#Get the function computing sample size
if self.stochastic_sampling:
self.sample_size = self.stochastic_sampsize
elif self.stopping_criterion == "BM":
self.sample_size = self.bm_sampsize
elif self.stopping_criterion == "BPL":
self.sample_size = self.bpl_fsp_sampsize
else:
raise RuntimeError("Only BM and BPL sample sizes are supported yet")
#To be sure to always use new scenarios, we set a ScenCount that is
#telling us how many scenarios has been used so far
self.ScenCount = 0
#If we are running a multistage problem, we also need a seed count
self.SeedCount = 0
def bm_stopping_criterion(self,G,s,nk):
# arguments defined in [bm2011]
return(G>self.hprime*s+self.epsprime)
def bpl_stopping_criterion(self,G,s,nk):
# arguments defined in [bpl2012]
t = scipy.stats.t.ppf(self.confidence_level,nk-1)
sample_error = t*s/np.sqrt(nk)
inflation_factor = 1/np.sqrt(nk)
return(G+sample_error+inflation_factor>self.eps)
def bm_sampsize(self,k,G,s,nk_m1, r=2):
# arguments defined in [bm2011]
h = self.h
hprime = self.hprime
p = self.p
q = self.q
confidence_level = self.confidence_level
if q is None :
# Computing n_k as in (5) of [Bayraksan and Morton, 2009]
if hasattr(self, "c") :
c = self.c
else:
if confidence_level is None :
raise RuntimeError("We need the confidence level to compute the constant cp")
j = np.arange(1,1000)
s = sum(np.power(j,-p*np.log(j)))
c = max(1,2*np.log(s/(np.sqrt(2*np.pi)*(1-confidence_level))))
lower_bound = (c+2*p* np.log(k)**2)/((h-hprime)**2)
else :
# Computing n_k as in (14) of [Bayraksan and Morton, 2009]
if hasattr(self, "c") :
c = self.c
else:
if confidence_level is None :
RuntimeError("We need the confidence level to compute the constant c_pq")
j = np.arange(1,1000)
s = sum(np.exp(-p*np.power(j,2*q/r)))
c = max(1,2*np.log(s/(np.sqrt(2*np.pi)*(1-confidence_level))))
lower_bound = (c+2*p*np.power(k,2*q/r))/((h-hprime)**2)
#print(f"nk={lower_bound}")
return int(np.ceil(lower_bound))
def bpl_fsp_sampsize(self,k,G,s,nk_m1):
# arguments defined in [bpl2012]
return(int(np.ceil(self.c0+self.c1*self.growth_function(k))))
def stochastic_sampsize(self,k,G,s,nk_m1):
# arguments defined in [bpl2012]
if (k==1):
#Initialization
return(int(np.ceil(max(self.n0min,np.log(1/self.eps)))))
#§5 of [Bayraksan and Pierre-Louis] : solving a 2nd degree equation in sqrt(n)
t = scipy.stats.t.ppf(self.confidence_level,nk_m1-1)
a = - self.eps
b = 1+t*s
c = nk_m1*G
maxroot = -(np.sqrt(b**2-4*a*c)+b)/(2*a)
print(f"s={s}, t={t}, G={G}")
print(f"a={a}, b={b},c={c},delta={b**2-4*a*c}")
print(f"At iteration {k}, we took n_k={int(np.ceil((maxroot**2)))}")
return(int(np.ceil(maxroot**2)))
def run(self,maxit=200):
""" Execute a sequental sampling algorithm
Args:
maxit (int): override the stopping criteria based on iterations
Returns:
{"T":T,"Candidate_solution":final_xhat,"CI":CI,}
"""
if self.multistage:
raise RuntimeWarning("Multistage sequential sampling can be done "
"using the SeqSampling, but dependent samples\n"
"will be used. The class IndepScens_SeqSampling uses independent samples and therefor has better theoretical support.")
refmodel = self.refmodel
mult = self.sample_size_ratio # used to set m_k= mult*n_k
#----------------------------Step 0 -------------------------------------#
#Initialization
k =1
#Computing the lower bound for n_1
if self.stopping_criterion == "BM":
#Finding a constant used to compute nk
r = 2 #TODO : we could add flexibility here
j = np.arange(1,1000)
if self.q is None:
s = sum(np.power(j,-self.p*np.log(j)))
else:
if self.q<1:
raise RuntimeError("Parameter q should be greater than 1.")
s = sum(np.exp(-self.p*np.power(j,2*self.q/r)))
self.c = max(1,2*np.log(s/(np.sqrt(2*np.pi)*(1-self.confidence_level))))
lower_bound_k = self.sample_size(k, None, None, None)
#Computing xhat_1.
#We use sample_size_ratio*n_k observations to compute xhat_k
if self.multistage:
xhat_branching_factors = ciutils.scalable_branching_factors(mult*lower_bound_k, self.options['branching_factors'])
mk = np.prod(xhat_branching_factors)
self.xhat_gen_options['start_seed'] = self.SeedCount #TODO: Maybe find a better way to manage seed
xhat_scenario_names = refmodel.scenario_names_creator(mk)
else:
mk = int(np.floor(mult*lower_bound_k))
xhat_scenario_names = refmodel.scenario_names_creator(mk, start=self.ScenCount)
self.ScenCount+=mk
xgo = self.xhat_gen_options.copy()
xgo.pop("solvername", None) # it will be given explicitly
xgo.pop("solver_options", None) # it will be given explicitly
xgo.pop("scenario_names", None) # given explicitly
xhat_k = self.xhat_generator(xhat_scenario_names,
solvername=self.solvername,
solver_options=self.solver_options,
**xgo)
#----------------------------Step 1 -------------------------------------#
#Computing n_1 and associated scenario names
if self.multistage:
self.SeedCount += sputils.number_of_nodes(xhat_branching_factors)
gap_branching_factors = ciutils.scalable_branching_factors(lower_bound_k, self.options['branching_factors'])
nk = np.prod(gap_branching_factors)
estimator_scenario_names = refmodel.scenario_names_creator(nk)
sample_options = {'branching_factors':gap_branching_factors, 'seed':self.SeedCount}
else:
nk = self.ArRP *int(np.ceil(lower_bound_k/self.ArRP))
estimator_scenario_names = refmodel.scenario_names_creator(nk,
start=self.ScenCount)
sample_options = None
self.ScenCount+= nk
#Computing G_nkand s_k associated with xhat_1
self.options['num_scens'] = nk
scenario_creator_kwargs = self.refmodel.kw_creator(self.options)
scenario_denouement = refmodel.scenario_denouement if hasattr(refmodel, "scenario_denouement") else None
estim = ciutils.gap_estimators(xhat_k, self.refmodelname,
solving_type=self.solving_type,
scenario_names=estimator_scenario_names,
sample_options=sample_options,
ArRP=self.ArRP,
scenario_creator_kwargs=scenario_creator_kwargs,
scenario_denouement=scenario_denouement,
solvername=self.solvername,
solver_options=self.solver_options)
Gk,sk = estim['G'],estim['s']
if self.multistage:
self.SeedCount = estim['seed']
#----------------------------Step 2 -------------------------------------#
while( self.stop_criterion(Gk,sk,nk) and k<maxit):
#----------------------------Step 3 -------------------------------------#
k+=1
nk_m1 = nk #n_{k-1}
mk_m1 = mk
lower_bound_k = self.sample_size(k, Gk, sk, nk_m1)
#Computing m_k and associated scenario names
if self.multistage:
xhat_branching_factors = ciutils.scalable_branching_factors(mult*lower_bound_k, self.options['branching_factors'])
mk = np.prod(xhat_branching_factors)
self.xhat_gen_options['start_seed'] = self.SeedCount #TODO: Maybe find a better way to manage seed
xhat_scenario_names = refmodel.scenario_names_creator(mk)
else:
mk = int(np.floor(mult*lower_bound_k))
assert mk>= mk_m1, "Our sample size should be increasing"
if (k%self.kf_xhat==0):
#We use only new scenarios to compute xhat
xhat_scenario_names = refmodel.scenario_names_creator(int(mult*nk),
start=self.ScenCount)
self.ScenCount+= mk
else:
#We reuse the previous scenarios
xhat_scenario_names+= refmodel.scenario_names_creator(mult*(nk-nk_m1),
start=self.ScenCount)
self.ScenCount+= mk-mk_m1
#Computing xhat_k
xgo = self.xhat_gen_options.copy()
xgo.pop("solvername", None) # it will be given explicitly
xgo.pop("solver_options", None) # it will be given explicitly
xgo.pop("scenario_names", None) # given explicitly
xhat_k = self.xhat_generator(xhat_scenario_names,
solvername=self.solvername,
solver_options=self.solver_options,
**xgo)
#Computing n_k and associated scenario names
if self.multistage:
self.SeedCount += sputils.number_of_nodes(xhat_branching_factors)
gap_branching_factors = ciutils.scalable_branching_factors(lower_bound_k, self.options['branching_factors'])
nk = np.prod(gap_branching_factors)
estimator_scenario_names = refmodel.scenario_names_creator(nk)
sample_options = {'branching_factors':gap_branching_factors, 'seed':self.SeedCount}
else:
nk = self.ArRP *int(np.ceil(lower_bound_k/self.ArRP))
assert nk>= nk_m1, "Our sample size should be increasing"
if (k%self.kf_Gs==0):
#We use only new scenarios to compute gap estimators
estimator_scenario_names = refmodel.scenario_names_creator(nk,
start=self.ScenCount)
self.ScenCount+=nk
else:
#We reuse the previous scenarios
estimator_scenario_names+= refmodel.scenario_names_creator((nk-nk_m1),
start=self.ScenCount)
self.ScenCount+= (nk-nk_m1)
sample_options = None
#Computing G_k and s_k
self.options['num_scens'] = nk
scenario_creator_kwargs = self.refmodel.kw_creator(self.options)
estim = ciutils.gap_estimators(xhat_k, self.refmodelname,
solving_type=self.solving_type,
scenario_names=estimator_scenario_names,
sample_options=sample_options,
ArRP=self.ArRP,
scenario_creator_kwargs=scenario_creator_kwargs,
scenario_denouement=scenario_denouement,
solvername=self.solvername,
solver_options=self.solver_options)
if self.multistage:
self.SeedCount = estim['seed']
Gk,sk = estim['G'],estim['s']
if (k%10==0) and global_rank==0:
print(f"k={k}")
print(f"n_k={nk}")
print(f"G_k={Gk}")
print(f"s_k={sk}")
#----------------------------Step 4 -------------------------------------#
if (k==maxit) :
raise RuntimeError(f"The loop terminated after {maxit} iteration with no acceptable solution")
T = k
final_xhat=xhat_k
if self.stopping_criterion == "BM":
upper_bound=self.h*sk+self.eps
elif self.stopping_criterion == "BPL":
upper_bound = self.eps
else:
raise RuntimeError("Only BM and BPL criterion are supported yet.")
CI=[0,upper_bound]
global_toc(f"G={Gk} sk={sk}; xhat has been computed with {nk*mult} observations.")
return {"T":T,"Candidate_solution":final_xhat,"CI":CI,}
if __name__ == "__main__":
# for developer testing
solvername = "cplex"
refmodel = "mpisppy.tests.examples.farmer"
farmer_opt_dict = {"crops_multiplier":3}
# create three options dictionaries, then use one of them
# relative width
optionsBM = {'h':0.2,
'hprime':0.015,
'eps':0.5,
'epsprime':0.4,
"p":0.2,
"q":1.2,
"solvername":solvername,
"stopping": "BM" # TBD use this and drop stopping_criterion from the constructor
}
# fixed width, fully sequential
optionsFSP = {'eps': 50.0,
'solvername': solvername,
"c0":50, # starting sample size
"xhat_gen_options":farmer_opt_dict,
"crops_multiplier":3, # option for the farmer problem
"ArRP":2, # this must be 1 for any multi-stage problems
"stopping": "BPL"
}
# fixed width sequential with stochastic samples
optionsSSP = {'eps': 1.0,
'solvername': solvername,
"n0min":200, # only for stochastic sampling
"stopping": "BPL",
#"xhat_gen_options": farmer_opt_dict,
#"crops_multiplier": 3,
}
# change the options argument and stopping criterion
our_pb = SeqSampling(refmodel,
xhat_generator_farmer,
optionsFSP,
stochastic_sampling=False, # maybe this should move to the options dict?
stopping_criterion="BPL",
)
res = our_pb.run()
print(res)
|
python
|
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.python.tasks.isort_run import IsortRun
from pants_test.pants_run_integration_test import PantsRunIntegrationTest, ensure_daemon
class IsortRunIntegrationTest(PantsRunIntegrationTest):
@ensure_daemon
def test_isort_no_python_sources_should_noop(self):
command = ['-ldebug',
'fmt.isort',
'testprojects/tests/java/org/pantsbuild/testproject/dummies/::',
'--',
'--check-only']
pants_run = self.run_pants(command=command)
self.assert_success(pants_run)
self.assertIn(IsortRun.NOOP_MSG_HAS_TARGET_BUT_NO_SOURCE, pants_run.stderr_data)
|
python
|
import cv2
import random
import numpy as np
from utils.bbox_utils import iou, object_coverage
from utils.textboxes_utils import get_bboxes_from_quads
def random_crop_quad(
image,
quads,
classes,
min_size=0.1,
max_size=1,
min_ar=1,
max_ar=2,
overlap_modes=[
None,
[0.1, None],
[0.3, None],
[0.7, None],
[0.9, None],
[None, None],
],
max_attempts=100,
p=0.5
):
""" Randomly crops a patch from the image.
Args:
- image: numpy array representing the input image.
- quads: numpy array representing the quads.
- classes: the list of classes associating with each quads.
- min_size: the maximum size a crop can be
- max_size: the maximum size a crop can be
- min_ar: the minimum aspect ratio a crop can be
- max_ar: the maximum aspect ratio a crop can be
- overlap_modes: the list of overlapping modes the function can randomly choose from.
- max_attempts: the max number of attempts to generate a patch.
Returns:
- image: the modified image
- quads: the modified quads
- classes: the modified classes
"""
assert p >= 0, "p must be larger than or equal to zero"
assert p <= 1, "p must be less than or equal to 1"
assert min_size > 0, "min_size must be larger than zero."
assert max_size <= 1, "max_size must be less than or equals to one."
assert max_size > min_size, "max_size must be larger than min_size."
assert max_ar > min_ar, "max_ar must be larger than min_ar."
assert max_attempts > 0, "max_attempts must be larger than zero."
# if (random.random() > p):
# return image, bboxes, classes
height, width, channels = image.shape
overlap_mode = [0.7, None]
# overlap_mode = random.choice(overlap_modes)
# if overlap_mode == None:
# return image, bboxes, classes
bboxes = get_bboxes_from_quads(quads)
min_iou, max_iou = overlap_mode
if min_iou == None:
min_iou = float(-np.inf)
if max_iou == None:
max_iou = float(np.inf)
temp_image = image.copy()
for i in range(max_attempts):
crop_w = random.uniform(min_size * width, max_size * width)
crop_h = random.uniform(min_size * height, max_size * height)
crop_ar = crop_h / crop_w
if crop_ar < min_ar or crop_ar > max_ar: # crop ar does not match criteria, next attempt
continue
crop_left = random.uniform(0, width-crop_w)
crop_top = random.uniform(0, height-crop_h)
crop_rect = np.array([crop_left, crop_top, crop_left + crop_w, crop_top + crop_h], dtype=np.float)
crop_rect = np.expand_dims(crop_rect, axis=0)
crop_rect = np.tile(crop_rect, (bboxes.shape[0], 1))
ious = iou(crop_rect, bboxes)
obj_coverage = object_coverage(crop_rect, bboxes)
if (ious.min() < min_iou and ious.max() > max_iou) or (obj_coverage.min() < min_iou and obj_coverage.max() > max_iou):
continue
bbox_centers = np.zeros((bboxes.shape[0], 2), dtype=np.float)
bbox_centers[:, 0] = (bboxes[:, 0] + bboxes[:, 2]) / 2
bbox_centers[:, 1] = (bboxes[:, 1] + bboxes[:, 3]) / 2
cx_in_crop = (bbox_centers[:, 0] > crop_left) * (bbox_centers[:, 0] < crop_left + crop_w)
cy_in_crop = (bbox_centers[:, 1] > crop_top) * (bbox_centers[:, 1] < crop_top + crop_h)
boxes_in_crop = cx_in_crop * cy_in_crop
if not boxes_in_crop.any():
continue
print(ious, obj_coverage, boxes_in_crop)
print("======")
temp_image = temp_image[int(crop_top): int(crop_top+crop_h), int(crop_left): int(crop_left+crop_w), :]
temp_classes = np.array(classes, dtype=np.object)
temp_classes = temp_classes[boxes_in_crop]
temp_bboxes = bboxes[boxes_in_crop]
temp_quads = quads[boxes_in_crop]
crop_rect = np.array([crop_left, crop_top, crop_left + crop_w, crop_top + crop_h], dtype=np.float)
crop_rect = np.expand_dims(crop_rect, axis=0)
crop_rect = np.tile(crop_rect, (temp_bboxes.shape[0], 1))
print(temp_quads.shape)
temp_bboxes[:, :2] = np.maximum(temp_bboxes[:, :2], crop_rect[:, :2]) # if bboxes top left is out of crop then use crop's xmin, ymin
temp_bboxes[:, :2] -= crop_rect[:, :2] # translate xmin, ymin to fit crop
temp_bboxes[:, 2:] = np.minimum(temp_bboxes[:, 2:], crop_rect[:, 2:])
temp_bboxes[:, 2:] -= crop_rect[:, :2] # translate xmax, ymax to fit crop
return temp_image, temp_quads, temp_classes.tolist()
return image, bboxes, classes
|
python
|
import torch
import torch.nn as nn
import torchvision
from . import resnet as resnet
from . import resnext as resnext
from torch.nn.init import kaiming_normal_,constant_,normal_
from core.config import cfg
import torch.nn.functional as F
import modeling.CRL as CRL
import modeling.cspn as cspn
import time
timer=time.time
if not cfg.SEM.BN_LEARN:
from lib.nn import SynchronizedBatchNorm2d
else:
import torch.nn.BatchNorm2d as SynchronizedBatchNorm2d
def correlate(input1, input2):
out_corr = spatial_correlation_sample(input1,
input2,
kernel_size=1,
patch_size=21,
stride=1,
padding=0,
dilation_patch=2)
# collate dimensions 1 and 2 in order to be treated as a
# regular 4D tensor
b, ph, pw, h, w = out_corr.size()
out_corr = out_corr.view(b, ph * pw, h, w)/input1.size(1)
return F.leaky_relu_(out_corr, 0.1)
class CorrelationLayer1D(nn.Module):
def __init__(self, max_disp=40, stride_2=1):
super(CorrelationLayer1D, self).__init__()
self.max_displacement = max_disp
self.stride_2 = stride_2
def forward(self, x_1, x_2):
x_1 = x_1
x_2 = F.pad(x_2, (int(self.max_displacement*0.2),int(self.max_displacement*0.8), 0, 0))
return torch.cat([torch.sum(x_1 * x_2[:, :, :, _y:_y + x_1.size(3)], 1).unsqueeze(1) for _y in
range(0, self.max_displacement +1, self.stride_2)], 1)
class CorrelationLayer1DMinus(nn.Module):
def __init__(self, max_disp=40, stride_2=1):
super(CorrelationLayer1DMinus, self).__init__()
self.max_displacement = max_disp
self.stride_2 = stride_2
def forward(self, x_1, x_2):
x_1 = x_1
ee=0.000001
x_2 = F.pad(x_2, (int(self.max_displacement*0.2),int(self.max_displacement*0.8), 0, 0))
minus=torch.cat([torch.sum(x_1 - x_2[:, :, :, _y:_y + x_1.size(3)], 1).unsqueeze(1) for _y in
range(0, self.max_displacement +1, self.stride_2)], 1)
inverse=1/(minus+ee)
return torch.sigmoid_(inverse)
def costVolume(leftFeature,rightFeature,max_displacement):
cost = torch.zeros(leftFeature.size()[0], leftFeature.size()[1]*2, max_displacement, leftFeature.size()[2], leftFeature.size()[3])
for i in range(max_displacement):
if i > 0 :
cost[:, :leftFeature.size()[1], i, :,i:] = leftFeature[:,:,:,i:]
cost[:, leftFeature.size()[1]:, i, :,i:] = rightFeature[:,:,:,:-i]
else:
cost[:, :leftFeature.size()[1], i, :,:] = leftFeature
cost[:, leftFeature.size()[1]:, i, :,:] = rightFeature
cost = cost.contiguous()
return cost
class CorrelationLayerCosineSimilarity(nn.Module):
def __init__(self, max_disp=40, stride_2=1,dim=1,eps=1e-6):
super(CorrelationLayerCosineSimilarity, self).__init__()
self.max_displacement = max_disp
self.stride_2 = stride_2
self.cos=torch.nn.CosineSimilarity(dim=1,eps=1e-6)
def forward(self, x_1, x_2):
x_1 = x_1
x_2 = F.pad(x_2, (int(self.max_displacement*0),int(self.max_displacement*1), 0, 0))
similarity=torch.cat([self.cos(x_1 ,x_2[:, :, :, _y:_y + x_1.size(3)]).unsqueeze(1) for _y in
range(0, self.max_displacement +1, self.stride_2)], 1)
return similarity
def costVolume2(leftFeature,rightFeature,max_displacement):
cost = torch.zeros(leftFeature.size()[0], leftFeature.size()[1]*2, max_displacement, leftFeature.size()[2], leftFeature.size()[3]).cuda()
for b in range(cost.size()[0]):
i=0
while i < cost.size()[1]:
for j in range(max_displacement):
if j>0:
cost[b,i,j,:,j:]=leftFeature[b,i//2,:,j:]
cost[b,i+1,j,:,j:]=rightFeature[b,i//2,:,:-j]
else:
cost[b,i,j,:,:]=leftFeature[b,i//2,...]
cost[b,i+1,j,:,:]=rightFeature[b,i//2,...]
i+=2
return cost
class SegmentationModuleBase(nn.Module):
def __init__(self):
super(SegmentationModuleBase, self).__init__()
def pixel_acc(self, pred, label):
_, preds = torch.max(pred, dim=1)
valid = (label >= 0).long()
acc_sum = torch.sum(valid * (preds == label).long())
pixel_sum = torch.sum(valid)
acc = acc_sum.float() / (pixel_sum.float() + 1e-10)
return acc
class SegmentationModule(SegmentationModuleBase):
def __init__(self, net_enc, net_dec, crit, deep_sup_scale=None):
super(SegmentationModule, self).__init__()
self.encoder = net_enc
self.decoder = net_dec
self.crit = crit
self.deep_sup_scale = deep_sup_scale
def forward(self, feed_dict, *, segSize=None):
if segSize is None: # training
if self.deep_sup_scale is not None: # use deep supervision technique
(pred, pred_deepsup) = self.decoder(self.encoder(feed_dict['data'], return_feature_maps=True))
else:
pred = self.decoder(self.encoder(feed_dict['data'], return_feature_maps=True))
loss = self.crit(pred, feed_dict[cfg.SEM.OUTPUT_PRIFEX+'_0'])
if self.deep_sup_scale is not None:
for i in range(2, len(cfg.SEM.DOWNSAMPLE)):
loss_deepsup = self.crit(pred_deepsup,
feed_dict['{}_{}'.format(cfg.SEM.OUTPUT_PRIFEX, i)])
loss = loss + loss_deepsup * self.deep_sup_scale[i]
acc = self.pixel_acc(pred, feed_dict[cfg.SEM.OUTPUT_PRIFEX+'_0'])
return loss, acc
else: # inference
pred = self.decoder(self.encoder(feed_dict['data'], return_feature_maps=True), segSize=segSize)
return pred
def conv3x3(in_planes, out_planes, stride=1, has_bias=False):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=has_bias)
def conv3x3_bn_relu(in_planes, out_planes, stride=1):
return nn.Sequential(
conv3x3(in_planes, out_planes, stride),
SynchronizedBatchNorm2d(out_planes),
nn.ReLU(inplace=True),
)
class ModelBuilder():
# custom weights initialization
def weights_init(self, m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.kaiming_normal_(m.weight.data)
elif classname.find('BatchNorm') != -1:
m.weight.data.fill_(1.)
m.bias.data.fill_(1e-4)
#elif classname.find('Linear') != -1:
# m.weight.data.normal_(0.0, 0.0001)
def build_encoder(self, arch='resnet50_dilated8', fc_dim=512, weights=''):
pretrained = True if len(weights) == 0 else False
if arch == 'resnet18':
orig_resnet = resnet.__dict__['resnet18'](pretrained=pretrained)
net_encoder = Resnet(orig_resnet)
elif arch == 'resnet18_dilated8':
orig_resnet = resnet.__dict__['resnet18'](pretrained=pretrained)
net_encoder = ResnetDilated(orig_resnet,
dilate_scale=8)
elif arch == 'resnet18_dilated16':
orig_resnet = resnet.__dict__['resnet18'](pretrained=pretrained)
net_encoder = ResnetDilated(orig_resnet,
dilate_scale=16)
elif arch == 'resnet34':
raise NotImplementedError
orig_resnet = resnet.__dict__['resnet34'](pretrained=pretrained)
net_encoder = Resnet(orig_resnet)
elif arch == 'resnet34_dilated8':
raise NotImplementedError
orig_resnet = resnet.__dict__['resnet34'](pretrained=pretrained)
net_encoder = ResnetDilated(orig_resnet,
dilate_scale=8)
elif arch == 'resnet34_dilated16':
raise NotImplementedError
orig_resnet = resnet.__dict__['resnet34'](pretrained=pretrained)
net_encoder = ResnetDilated(orig_resnet,
dilate_scale=16)
elif arch == 'resnet50':
orig_resnet = resnet.__dict__['resnet50'](pretrained=pretrained)
net_encoder = Resnet(orig_resnet)
elif arch == 'resnet50_dilated8':
orig_resnet = resnet.__dict__['resnet50'](pretrained=pretrained)
net_encoder = ResnetDilated(orig_resnet,
dilate_scale=8)
elif arch == 'resnet50_dilated8_3DConv':
orig_resnet = resnet.__dict__['resnet50'](pretrained=pretrained)
net_encoder = ResnetDilated3DConv(orig_resnet,
dilate_scale=8)
elif arch == 'resnet50_dilated16':
orig_resnet = resnet.__dict__['resnet50'](pretrained=pretrained)
net_encoder = ResnetDilated(orig_resnet,
dilate_scale=16)
elif arch == 'resnet101':
orig_resnet = resnet.__dict__['resnet101'](pretrained=pretrained)
net_encoder = Resnet(orig_resnet)
elif arch == 'resnet101_dilated8':
orig_resnet = resnet.__dict__['resnet101'](pretrained=pretrained)
net_encoder = ResnetDilated(orig_resnet,
dilate_scale=8)
elif arch == 'resnet101_dilated16':
orig_resnet = resnet.__dict__['resnet101'](pretrained=pretrained)
net_encoder = ResnetDilated(orig_resnet,
dilate_scale=16)
elif arch == 'resnext101':
orig_resnext = resnext.__dict__['resnext101'](pretrained=pretrained)
net_encoder = Resnet(orig_resnext) # we can still use class Resnet
elif arch == 'resnext101_dilated8':
orig_resnet = resnext.__dict__['resnext101'](pretrained=pretrained)
net_encoder = ResnetDilated(orig_resnet,
dilate_scale=8)
elif arch == 'resnext101_dilated8_64':
orig_resnet = resnext.__dict__['resnext101_64'](pretrained=pretrained)
net_encoder = ResnetDilated(orig_resnet,
dilate_scale=8)
else:
raise Exception('Architecture undefined!')
# net_encoder.apply(self.weights_init)
if len(weights) > 0:
print('Loading weights for net_encoder')
net_encoder.load_state_dict(
torch.load(weights, map_location=lambda storage, loc: storage), strict=False)
return net_encoder
def build_decoder(self, arch='ppm_bilinear_deepsup',
fc_dim=512, num_class=150,
weights='', use_softmax=False):
if arch == 'c1_bilinear_deepsup':
net_decoder = C1BilinearDeepSup(
num_class=num_class,
fc_dim=fc_dim,
use_softmax=use_softmax)
elif arch == 'c1_bilinear':
net_decoder = C1Bilinear(
num_class=num_class,
fc_dim=fc_dim,
use_softmax=use_softmax)
elif arch == 'ppm_bilinear':
net_decoder = PPMBilinear(
num_class=num_class,
fc_dim=fc_dim,
use_softmax=use_softmax)
elif arch == 'ppm_bilinear_deepsup':
net_decoder = PPMBilinearDeepsup(
num_class=num_class,
fc_dim=fc_dim,
use_softmax=use_softmax)
elif arch == 'ppm_bilinear3D':
net_decoder = PPMBilinear3D(
num_class=num_class,
fc_dim=fc_dim,
use_softmax=use_softmax)
elif arch == 'upernet_lite':
net_decoder = UPerNet(
num_class=num_class,
fc_dim=fc_dim,
use_softmax=use_softmax,
fpn_dim=256)
elif arch == 'upernet':
net_decoder = UPerNet(
num_class=num_class,
fc_dim=fc_dim,
use_softmax=use_softmax,
fpn_dim=512)
elif arch == 'upernet_tmp':
net_decoder = UPerNetTmp(
num_class=num_class,
fc_dim=fc_dim,
use_softmax=use_softmax,
fpn_dim=512)
else:
raise Exception('Architecture undefined!')
net_decoder.apply(self.weights_init)
if len(weights) > 0:
print('Loading weights for net_decoder')
net_decoder.load_state_dict(
torch.load(weights, map_location=lambda storage, loc: storage), strict=False)
return net_decoder
class Resnet(nn.Module):
def __init__(self, orig_resnet):
super(Resnet, self).__init__()
# take pretrained resnet, except AvgPool and FC
self.conv1 = orig_resnet.conv1
self.bn1 = orig_resnet.bn1
self.relu1 = orig_resnet.relu1
self.conv2 = orig_resnet.conv2
self.bn2 = orig_resnet.bn2
self.relu2 = orig_resnet.relu2
self.conv3 = orig_resnet.conv3
self.bn3 = orig_resnet.bn3
self.relu3 = orig_resnet.relu3
self.maxpool = orig_resnet.maxpool
self.layer1 = orig_resnet.layer1
self.layer2 = orig_resnet.layer2
self.layer3 = orig_resnet.layer3
self.layer4 = orig_resnet.layer4
self.correlation=CorrelationLayer1D(max_disp=40,stride_2=1)
self.conv_rdi = nn.Sequential(nn.Conv2d(512, 256, kernel_size=1, stride=1, padding=0),
nn.ReLU(inplace=True))
self.conv_r = nn.Conv2d(357, 512, kernel_size=3, stride=1,padding=1, bias=False)
self.bn4=SynchronizedBatchNorm2d(512)
def forward(self, x, return_feature_maps=False):
conv_out = []
x = self.relu1(self.bn1(self.conv1(x)))
x = self.relu2(self.bn2(self.conv2(x)))
x = self.relu3(self.bn3(self.conv3(x)))
x = self.maxpool(x)
x = self.layer1(x); conv_out.append(x); #256
x = self.layer2(x); conv_out.append(x); #512
left, right=torch.split(x, cfg.TRAIN.IMS_PER_BATCH, dim=0)
corr=self.correlation(left,right)
conv_rdi=self.conv_rdi(left)
x =torch.cat((conv_rdi,corr),dim=1)
x=self.relu2(self.bn4(self.conv_r(x)))
x = torch.cat((left, x), dim=0)
x = self.layer3(x); conv_out.append(x); #1024
x = self.layer4(x); conv_out.append(x); #2048
if return_feature_maps:
return conv_out
return [x]
def forward(self, x, return_feature_maps=False):
conv_out = []
x = self.relu1(self.bn1(self.conv1(x)))
x = self.relu2(self.bn2(self.conv2(x)))
x = self.relu3(self.bn3(self.conv3(x)))
x = self.maxpool(x)
x = self.layer1(x); conv_out.append(x);
#print("layer1:",x.shape)
x = self.layer2(x); conv_out.append(x);
#print("layer2:",x.shape)
left, right=torch.split(x, cfg.TRAIN.IMS_PER_BATCH, dim=0)
#print("left:",left.shape)
#print("right:",right.shape)
corr=self.correlation(left,right)
#print("corr:",corr.shape)
conv_rdi=self.conv_rdi(left)
#print("conv_rdi:",conv_rdi.shape)
x =torch.cat((conv_rdi,corr),dim=1)
x=self.relu2(self.bn4(self.conv_r(x)))
x = torch.cat((left, x), dim=0)
x = self.layer3(x); conv_out.append(x);
x = self.layer4(x); conv_out.append(x);
if return_feature_maps:
return conv_out
return [x]
class ResnetDilated3DConv(nn.Module):
def __init__(self, orig_resnet, dilate_scale=8,max_displacement=40):
super(ResnetDilated3DConv, self).__init__()
from functools import partial
self.max_displacement=max_displacement
if dilate_scale == 8:
orig_resnet.layer3.apply(
partial(self._nostride_dilate, dilate=2))
orig_resnet.layer4.apply(
partial(self._nostride_dilate, dilate=4))
elif dilate_scale == 16:
orig_resnet.layer4.apply(
partial(self._nostride_dilate, dilate=2))
# take pretrained resnet, except AvgPool and FC
self.conv1 = orig_resnet.conv1
self.bn1 = orig_resnet.bn1
self.relu1 = orig_resnet.relu1
self.conv2 = orig_resnet.conv2
self.bn2 = orig_resnet.bn2
self.relu2 = orig_resnet.relu2
self.conv3 = orig_resnet.conv3
self.bn3 = orig_resnet.bn3
self.relu3 = orig_resnet.relu3
self.maxpool = orig_resnet.maxpool
self.layer1 = orig_resnet.layer1
self.layer2 = orig_resnet.layer2
self.layer3 = orig_resnet.layer3
self.layer4 = orig_resnet.layer4
if cfg.SEM.LAYER_FIXED:
for param in self.conv1.parameters():
param.requires_grad = False
for param in self.conv2.parameters():
param.requires_grad = False
for param in self.conv3.parameters():
param.requires_grad = False
for param in self.layer1.parameters():
param.requires_grad = False
for param in self.layer2.parameters():
param.requires_grad = False
def _nostride_dilate(self, m, dilate):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
# the convolution with stride
if m.stride == (2, 2):
m.stride = (1, 1)
if m.kernel_size == (3, 3):
m.dilation = (dilate//2, dilate//2)
m.padding = (dilate//2, dilate//2)
# other convoluions
else:
if m.kernel_size == (3, 3):
m.dilation = (dilate, dilate)
m.padding = (dilate, dilate)
def forward(self, x, return_feature_maps=False):
conv_out = []
x = self.relu1(self.bn1(self.conv1(x)))
conv_out.append(x)
x = self.relu2(self.bn2(self.conv2(x)))
x = self.relu3(self.bn3(self.conv3(x)))
x = self.maxpool(x)
x = self.layer1(x); conv_out.append(x);
x = self.layer2(x); conv_out.append(x);
x = self.layer3(x); conv_out.append(x);
x = self.layer4(x); conv_out.append(x);
if return_feature_maps:
return conv_out
return [x]
class ResnetDilated(nn.Module):
def __init__(self, orig_resnet, dilate_scale=8):
super(ResnetDilated, self).__init__()
from functools import partial
if dilate_scale == 8:
orig_resnet.layer3.apply(
partial(self._nostride_dilate, dilate=2))
orig_resnet.layer4.apply(
partial(self._nostride_dilate, dilate=4))
elif dilate_scale == 16:
orig_resnet.layer4.apply(
partial(self._nostride_dilate, dilate=2))
# take pretrained resnet, except AvgPool and FC
self.conv1 = orig_resnet.conv1
self.bn1 = orig_resnet.bn1
self.relu1 = orig_resnet.relu1
self.conv2 = orig_resnet.conv2
self.bn2 = orig_resnet.bn2
self.relu2 = orig_resnet.relu2
self.conv3 = orig_resnet.conv3
self.bn3 = orig_resnet.bn3
self.relu3 = orig_resnet.relu3
self.maxpool = orig_resnet.maxpool
self.layer1 = orig_resnet.layer1
self.layer2 = orig_resnet.layer2
self.layer3 = orig_resnet.layer3
self.layer4 = orig_resnet.layer4
if cfg.DISP.COST_VOLUME_TYPE == 'CorrelationLayer1D':
self.correlation=CorrelationLayer1D(max_disp=40,stride_2=1)
if cfg.DISP.COST_VOLUME_TYPE == 'CorrelationLayer1DMinus':
self.correlation=CorrelationLayer1DMinus(max_disp=40,stride_2=1)
if cfg.DISP.COST_VOLUME_TYPE =='CorrelationLayerCosineSimilarity':
self.correlation=CorrelationLayerCosineSimilarity(max_disp=40)
self.bn4=SynchronizedBatchNorm2d(512)
self.conv_rdi = nn.Sequential(nn.Conv2d(512, 256, kernel_size=1, stride=1, padding=0),
nn.ReLU(inplace=True))
self.conv_r = nn.Conv2d(297, 512, kernel_size=3, stride=1,padding=1, bias=False)
for param in self.conv1.parameters():
param.requires_grad = False
for param in self.conv2.parameters():
param.requires_grad = False
if cfg.SEM.LAYER_FIXED:
for param in self.conv1.parameters():
param.requires_grad = False
for param in self.conv2.parameters():
param.requires_grad = False
for param in self.conv3.parameters():
param.requires_grad = False
for param in self.layer1.parameters():
param.requires_grad = False
for param in self.layer2.parameters():
param.requires_grad = False
def _nostride_dilate(self, m, dilate):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
# the convolution with stride
if m.stride == (2, 2):
m.stride = (1, 1)
if m.kernel_size == (3, 3):
m.dilation = (dilate//2, dilate//2)
m.padding = (dilate//2, dilate//2)
# other convoluions
else:
if m.kernel_size == (3, 3):
m.dilation = (dilate, dilate)
m.padding = (dilate, dilate)
def forward(self, x, return_feature_maps=False):
conv_out = []
x = self.relu1(self.bn1(self.conv1(x)))
conv_out.append(x)
x = self.relu2(self.bn2(self.conv2(x)))
x = self.relu3(self.bn3(self.conv3(x)))
x = self.maxpool(x)
x = self.layer1(x); conv_out.append(x);
x = self.layer2(x); conv_out.append(x);
left, right=torch.split(x, cfg.TRAIN.IMS_PER_BATCH, dim=0)
corr=self.correlation(left,right)
conv_rdi=self.conv_rdi(left)
x =torch.cat((conv_rdi,corr),dim=1)
x=self.relu2(self.bn4(self.conv_r(x)))
x = torch.cat((left, x), dim=0)
x = self.layer3(x); conv_out.append(x);
x = self.layer4(x); conv_out.append(x);
if return_feature_maps:
return conv_out
return [x]
# last conv, bilinear upsample
class C1BilinearDeepSup(nn.Module):
def __init__(self, num_class=150, fc_dim=2048, use_softmax=False):
super(C1BilinearDeepSup, self).__init__()
self.use_softmax = use_softmax
self.cbr = conv3x3_bn_relu(fc_dim, fc_dim // 4, 1)
self.cbr_deepsup = conv3x3_bn_relu(fc_dim // 2, fc_dim // 4, 1)
# last conv
self.conv_last = nn.Conv2d(fc_dim // 4, num_class, 1, 1, 0)
self.conv_last_deepsup = nn.Conv2d(fc_dim // 4, num_class, 1, 1, 0)
def forward(self, conv_out, segSize=None):
conv5 = conv_out[-1]
x = self.cbr(conv5)
x = self.conv_last(x)
if self.use_softmax: # is True during inference
x = nn.functional.interpolate(
x, size=segSize, mode='bilinear', align_corners=False)
x = nn.functional.softmax(x, dim=1)
return x
# deep sup
conv4 = conv_out[-2]
_ = self.cbr_deepsup(conv4)
_ = self.conv_last_deepsup(_)
x = nn.functional.log_softmax(x, dim=1)
_ = nn.functional.log_softmax(_, dim=1)
return (x, _)
# last conv, bilinear upsample
class C1Bilinear(nn.Module):
def __init__(self, num_class=150, fc_dim=2048, use_softmax=False):
super(C1Bilinear, self).__init__()
self.use_softmax = use_softmax
self.cbr = conv3x3_bn_relu(fc_dim, fc_dim // 4, 1)
# last conv
self.conv_last = nn.Conv2d(fc_dim // 4, num_class, 1, 1, 0)
def forward(self, conv_out, segSize=None):
conv5 = conv_out[-1]
x = self.cbr(conv5)
x = self.conv_last(x)
if self.use_softmax: # is True during inference
x = nn.functional.interpolate(
x, size=segSize, mode='bilinear', align_corners=False)
x = nn.functional.softmax(x, dim=1)
else:
x = nn.functional.log_softmax(x, dim=1)
return x
# pyramid pooling, bilinear upsample
class PPMBilinear(nn.Module):
def __init__(self, num_class=150, fc_dim=4096,
use_softmax=False, pool_scales=(1, 2, 3, 6)):
super(PPMBilinear, self).__init__()
self.use_softmax = use_softmax
self.ppm = []
for scale in pool_scales:
self.ppm.append(nn.Sequential(
nn.AdaptiveAvgPool2d(scale),
nn.Conv2d(fc_dim, 512, kernel_size=1, bias=False),
SynchronizedBatchNorm2d(512),
nn.ReLU(inplace=True)
))
self.ppm = nn.ModuleList(self.ppm)
self.conv_last = nn.Sequential(
nn.Conv2d(fc_dim+len(pool_scales)*512, 512,
kernel_size=3, padding=1, bias=False),
SynchronizedBatchNorm2d(512),
nn.ReLU(inplace=True),
nn.Dropout2d(0.1)
)
def forward(self, conv_out, segSize=None):
if cfg.SEM.USE_RESNET:
conv5=conv_out
else:
conv5 = conv_out[-1]
#conv5=conv_out
input_size = conv5.size()
ppm_out = [conv5]
for pool_scale in self.ppm:
ppm_out.append(nn.functional.interpolate(
pool_scale(conv5),
(input_size[2], input_size[3]),
mode='bilinear', align_corners=False))
ppm_out = torch.cat(ppm_out, 1)
x = self.conv_last(ppm_out)
return x
# pyramid pooling, bilinear upsample
class PPMBilinearDeepsup(nn.Module):
def __init__(self, num_class=150, fc_dim=1024,
use_softmax=False, pool_scales=(1, 2, 3, 6)):
super(PPMBilinearDeepsup, self).__init__()
self.use_softmax = use_softmax
self.ppm = []
for scale in pool_scales:
self.ppm.append(nn.Sequential(
nn.AdaptiveAvgPool2d(scale),
nn.Conv2d(fc_dim, 512, kernel_size=1, bias=False),
#SynchronizedBatchNorm2d(512),
nn.ReLU(inplace=True)
))
self.ppm = nn.ModuleList(self.ppm)
#self.reduce=nn.Conv2d(fc_dim*2,fc_dim,kernel_size=1,stride=1,padding=0,bias=False)
#self.cbr_deepsup = conv3x3_bn_relu(fc_dim // 2, fc_dim // 4, 1)
self.aspp_last = nn.Sequential(
nn.Conv2d(fc_dim+len(pool_scales)*512, 512,
kernel_size=3, padding=1, bias=False),
SynchronizedBatchNorm2d(512),
nn.ReLU(inplace=True),
nn.Dropout2d(0.1)
)
#self.conv_last_deepsup = nn.Conv2d(fc_dim // 4, num_class, 1, 1, 0)
#self.dropout_deepsup = nn.Dropout2d(0.1)
def forward(self, conv_out, segSize=None):
if cfg.SEM.USE_RESNET:
conv5=conv_out
else:
conv5 = conv_out[-1]
#conv_out, 2, c, h, w, dim 0 is semseg and disp
input_size = conv5.size()
semseg_conv, disp_conv = torch.split(conv5, input_size[0]//2 ,dim=0)
#conv5 is 1, 2*c, h, w
conv5 = torch.cat([semseg_conv, disp_conv], dim=1)
#conv5=self.reduce(conv5)
ppm_out = [conv5]
for pool_scale in self.ppm:
ppm_out.append(nn.functional.interpolate(
pool_scale(conv5),
(input_size[2], input_size[3]),
mode='bilinear', align_corners=False))
ppm_out = torch.cat(ppm_out, 1)
x = self.aspp_last(ppm_out)
# deep sup
conv4 = conv_out[-2]
#_ = self.cbr_deepsup(conv4)
#_ = self.dropout_deepsup(_)
#_ = self.conv_last_deepsup(_)
#X = nn.functional.log_softmax(x, dim=1)
#_ = nn.functional.log_softmax(_, dim=1)
return [x, conv4]
class PPMBilinear3D(nn.Module):
def __init__(self, num_class=150, fc_dim=2048,
use_softmax=False, pool_scales=(1, 2, 3, 6),channelsReduction=19):
super(PPMBilinear3D, self).__init__()
self.use_softmax = use_softmax
self.channelsReduction=channelsReduction
self.ppm = []
self.width=96
self.height=96
self.semseg=cfg.MODEL.NUM_CLASSES
self.max_displacement=cfg.DISP.FEATURE_MAX_DISPLACEMENT
for scale in pool_scales:
self.ppm.append(nn.Sequential(
nn.AdaptiveAvgPool2d(scale),
nn.Conv2d(fc_dim, 512, kernel_size=1, bias=False),
nn.BatchNorm2d(512),
nn.ReLU(inplace=True)
))
self.ppm = nn.ModuleList(self.ppm)
#self.cbr_deepsup = conv3x3_bn_relu(fc_dim // 2, fc_dim // 4, 1)
self.aspp_last = nn.Sequential(
nn.Conv2d(fc_dim+len(pool_scales)*512, 512,
kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(512),
nn.ReLU(inplace=True),
nn.Dropout2d(0.1)
)
cost_channels = channelsReduction*2
self.stack0 = self._createStack(cost_channels,cost_channels,stride1=1)
self.stack1_1 = self._createStack(cost_channels,cost_channels*2)
self.stack1_2 = self._createStack(cost_channels*2,cost_channels*4)
self.stack1_3 = self._createStack(cost_channels*4,cost_channels*8)
self.stack2_1 = self._Deconv3D(cost_channels*8,cost_channels*4)
self.stack2_2 = self._Deconv3D(cost_channels*4,cost_channels*2)
self.stack2_3 = self._Deconv3D(cost_channels*2,cost_channels)
self.gcn1=GCNASPP(cost_channels*4,self.semseg,self.max_displacement//4,self.height//4,self.width//4,scale=2,pool_scales=(4,8,13,24))
self.gcn2=GCNASPP(cost_channels*2,self.semseg,self.max_displacement//2,self.height//2,self.width//2,scale=1,pool_scales=(2,4,6,12))
self.gcn3=GCNASPP(cost_channels,self.semseg,self.max_displacement,self.height,self.width,scale=0,pool_scales=(2,3,4,6))
self.reduce = nn.Sequential(
nn.Conv2d(512,self.channelsReduction,kernel_size=1,stride=1,bias=False),
nn.BatchNorm2d(channelsReduction)
)
for m in self.modules():
if isinstance(m,nn.Conv2d) or isinstance(m,nn.Conv3d) or isinstance(m,nn.ConvTranspose3d):
kaiming_normal_(m.weight,0.1)
if m.bias is not None:
constant_(m.bias,0)
elif isinstance(m,nn.BatchNorm2d) or isinstance(m,nn.BatchNorm3d):
constant_(m.weight,1)
constant_(m.bias,0)
#self.conv_last_deepsup = nn.Conv2d(fc_dim // 4, num_class, 1, 1, 0)
#self.dropout_deepsup = nn.Dropout2d(0.1)
def _createStack(self,inplanes=512,planes=256,kernel_size=3,stride1=2,groups=19,stride2=1,bias=False,padding=1):
return nn.Sequential(
nn.Conv3d(inplanes,planes,kernel_size=3,stride=stride1,groups=groups,padding=1,bias=False),
nn.BatchNorm3d(planes),
nn.Conv3d(planes,planes,kernel_size=3,stride=stride2,groups=groups,padding=1,bias=False),
nn.BatchNorm3d(planes),
nn.ReLU(inplace=True)
)
def _Deconv3D(self,inplanes,planes,kernel_size=3,stride=2,padding=1,out_padding=1,groups=19,bias=False):
return nn.ConvTranspose3d(inplanes,planes,kernel_size,stride,padding,out_padding,groups=groups,bias=bias)
def forward(self, conv_out, segSize=None):
conv5 = conv_out[-1]
input_size = conv5.size()
ppm_out = [conv5]
for pool_scale in self.ppm:
ppm_out.append(nn.functional.interpolate(
pool_scale(conv5),
(input_size[2], input_size[3]),
mode='bilinear', align_corners=False))
ppm_out = torch.cat(ppm_out, 1)
x = self.aspp_last(ppm_out)
x = self.reduce(x)
left, right=torch.split(x, cfg.TRAIN.IMS_PER_BATCH, dim=0)
cost = costVolume2(left,right,cfg.DISP.FEATURE_MAX_DISPLACEMENT)
stack0=self.stack0(cost)
stack1_1=self.stack1_1(stack0)
stack1_2=self.stack1_2(stack1_1)
stack1_3=self.stack1_3(stack1_2)
stack2_1=self.stack2_1(stack1_3)
stack2_2=self.stack2_2(stack2_1)
stack2_3=self.stack2_3(stack2_2)
if self.training:
#gcn1=self.gcn1(stack2_1)
#gcn2=self.gcn2(stack2_2)
gcn3=self.gcn3(stack2_3)
return gcn3
else:
gcn3=self.gcn3(stack2_3)
return gcn3
class GCNASPP(nn.Module):
def __init__(self,inplanes,planes,d,h,w,scale,pool_scales=(2,4,8,16)):
super(GCNASPP,self).__init__()
self.inplanes=inplanes
self.planes=planes
self.semsegNums=19
self.disparity=self._Conv3d(self.inplanes,self.planes,kernel_size=(11,1,1),padding=(5,0,0))
self.width=self._Conv3d(self.inplanes,self.planes,kernel_size=(1,1,11),padding=(0,0,5))
self.height=self._Conv3d(self.inplanes,self.planes,kernel_size=(1,11,1),padding=(0,5,0))
self.ppm = []
for scale in pool_scales:
self.ppm.append(nn.Sequential(
nn.AdaptiveAvgPool3d(scale),
nn.Conv3d(self.semsegNums,self.semsegNums,kernel_size=1,bias=False),
nn.BatchNorm3d(self.semsegNums),
nn.ReLU(inplace=True)
))
self.ppm = nn.ModuleList(self.ppm)
self.aspp_last = nn.Sequential(
nn.Conv3d(5*self.semsegNums,self.semsegNums,kernel_size=3,padding=1,bias=False),
nn.BatchNorm3d(self.semsegNums),
nn.ReLU(inplace=True),
nn.Dropout3d(0.1)
)
for m in self.modules():
if isinstance(m,nn.Conv2d) or isinstance(m,nn.Conv3d) or isinstance(m,nn.ConvTranspose3d):
kaiming_normal_(m.weight,0.1)
if m.bias is not None:
constant_(m.bias,0)
elif isinstance(m,nn.BatchNorm2d) or isinstance(m,nn.BatchNorm3d):
constant_(m.weight,1)
constant_(m.bias,0)
def _Conv3d(self,inplanes,planes,kernel_size,stride=1,groups=1,padding=1):
return nn.Sequential(
nn.Conv3d(inplanes,planes,kernel_size,stride,padding=padding,bias=False),
nn.BatchNorm3d(planes),
nn.ReLU(inplace=True)
)
def forward(self,x):
disparity=self.disparity(x)
width = self.width(x)
height = self.height(x)
out=disparity+width+height
input_size = (out).size()
ppm_out=[out]
for pool_scale in self.ppm:
ppm_out.append(nn.functional.interpolate(
pool_scale(out),(input_size[2],input_size[3],input_size[4]),
mode='trilinear',align_corners=False
))
ppm_out=torch.cat(ppm_out,1)
out = self.aspp_last(ppm_out)
return out
# upernet
class UPerNet(nn.Module):
def __init__(self, num_class=150, fc_dim=4096,
use_softmax=False, pool_scales=(1, 2, 3, 6),
fpn_inplanes=(256,512,1024,2048), fpn_dim=256):
super(UPerNet, self).__init__()
self.use_softmax = use_softmax
# PPM Module
self.ppm_pooling = []
self.ppm_conv = []
for scale in pool_scales:
self.ppm_pooling.append(nn.AdaptiveAvgPool2d(scale))
self.ppm_conv.append(nn.Sequential(
nn.Conv2d(fc_dim, 512, kernel_size=1, bias=False),
SynchronizedBatchNorm2d(512),
nn.ReLU(inplace=True)
))
self.ppm_pooling = nn.ModuleList(self.ppm_pooling)
self.ppm_conv = nn.ModuleList(self.ppm_conv)
self.ppm_last_conv = conv3x3_bn_relu(fc_dim + len(pool_scales)*512, fpn_dim, 1)
# FPN Module
self.fpn_in = []
for fpn_inplane in fpn_inplanes[:-1]: # skip the top layer
self.fpn_in.append(nn.Sequential(
nn.Conv2d(fpn_inplane, fpn_dim, kernel_size=1, bias=False),
SynchronizedBatchNorm2d(fpn_dim),
nn.ReLU(inplace=True)
))
self.fpn_in = nn.ModuleList(self.fpn_in)
self.fpn_out = []
for i in range(len(fpn_inplanes) - 1): # skip the top layer
self.fpn_out.append(nn.Sequential(
conv3x3_bn_relu(fpn_dim, fpn_dim, 1),
))
self.fpn_out = nn.ModuleList(self.fpn_out)
self.conv_last = nn.Sequential(
conv3x3_bn_relu(len(fpn_inplanes) * fpn_dim, fpn_dim, 1),
nn.Conv2d(fpn_dim, num_class, kernel_size=1)
)
def forward(self, conv_out, segSize=None):
conv5 = conv_out[-1]
input_size = conv5.size()
ppm_out = [conv5]
for pool_scale, pool_conv in zip(self.ppm_pooling, self.ppm_conv):
ppm_out.append(pool_conv(nn.functional.interpolate(
pool_scale(conv5),
(input_size[2], input_size[3]),
mode='bilinear', align_corners=False)))
ppm_out = torch.cat(ppm_out, 1)
f = self.ppm_last_conv(ppm_out)
fpn_feature_list = [f]
for i in reversed(range(len(conv_out) - 1)):
conv_x = conv_out[i]
conv_x = self.fpn_in[i](conv_x) # lateral branch
f = nn.functional.interpolate(
f, size=conv_x.size()[2:], mode='bilinear', align_corners=False) # top-down branch
f = conv_x + f
fpn_feature_list.append(self.fpn_out[i](f))
fpn_feature_list.reverse() # [P2 - P5]
output_size = fpn_feature_list[0].size()[2:]
fusion_list = [fpn_feature_list[0]]
for i in range(1, len(fpn_feature_list)):
fusion_list.append(nn.functional.interpolate(
fpn_feature_list[i],
output_size,
mode='bilinear', align_corners=False))
fusion_out = torch.cat(fusion_list, 1)
x = self.conv_last(fusion_out)
if self.use_softmax: # is True during inference
x = nn.functional.interpolate(
x, size=segSize, mode='bilinear', align_corners=False)
x = nn.functional.softmax(x, dim=1)
return x
x = nn.functional.log_softmax(x, dim=1)
class MiniPSMNet(nn.Module):
def __init__(self):
super(MiniPSMNet,self).__init__()
self.channelsReduction=cfg.SEM.SD_DIM
self.ppm = []
self.width=96
self.height=96
self.semseg=19
self.max_displacement=cfg.DISP.FEATURE_MAX_DISPLACEMENT
cost_channels = self.channelsReduction*2
self.stack0 = self._createStack(cost_channels,cost_channels,stride1=1)
self.stack1 = self._createStack(cost_channels,cost_channels,stride1=1)
self.stack1_1 = self._createStack(cost_channels,cost_channels*2)
self.stack1_2 = self._createStack(cost_channels*2,cost_channels*4)
self.stack1_3 = self._createStack(cost_channels*4,cost_channels*8)
self.stack2_1 = self._Deconv3D(cost_channels*8,cost_channels*4)
self.stack2_2 = self._Deconv3D(cost_channels*4,cost_channels*2)
self.stack2_3 = self._Deconv3D(cost_channels*2,cost_channels)
self.to2D = nn.Conv3d(cost_channels,1,kernel_size=1,strid=1)
self.reduce = self._ruduce2D(512,self.channelsReduction)
self.predict=self._predict(cost_channels)
"""
self.reduce = nn.Sequential(
nn.Conv2d(512,self.channelsReduction,kernel_size=1,stride=1,bias=False),
nn.BatchNorm2d(self.channelsReduction)
)
"""
for m in self.modules():
if isinstance(m,nn.Conv2d) or isinstance(m,nn.Conv3d) or isinstance(m,nn.ConvTranspose3d):
kaiming_normal_(m.weight,0.1)
if m.bias is not None:
constant_(m.bias,0)
elif isinstance(m,nn.BatchNorm2d) or isinstance(m,nn.BatchNorm3d):
constant_(m.weight,1)
constant_(m.bias,0)
#self.conv_last_deepsup = nn.Conv2d(fc_dim // 4, num_class, 1, 1, 0)
#self.dropout_deepsup = nn.Dropout2d(0.1)
def _createStack(self,inplanes=512,planes=256,kernel_size=3,stride1=2,stride2=1,groups=cfg.GROUP_NORM.NUM_GROUPS,bias=False,padding=1):
return nn.Sequential(
nn.Conv3d(inplanes,planes,kernel_size=3,stride=stride1,groups=groups,padding=1,bias=False),
nn.BatchNorm3d(planes),
nn.ReLU(inplace=True),
nn.Conv3d(planes,planes,kernel_size=3,stride=stride2,groups=groups,padding=1,bias=False),
nn.BatchNorm3d(planes),
nn.ReLU(inplace=True)
)
def _Deconv3D(self,inplanes,planes,kernel_size=3,stride=2,padding=1,out_padding=1,groups=19,bias=False):
return nn.ConvTranspose3d(inplanes,planes,kernel_size,stride,padding,out_padding,groups=cfg.GROUP_NORM.NUM_GROUPS,bias=bias)
def _ruduce2D(self,inplanes,planes):
return nn.Sequential(
nn.Conv2d(inplanes,planes,kernel_size=1,strid=1),
nn.Conv2d(planes,planes,kernel_size=3,strid=1,padding=1),
nn.BatchNorm2d(inplanes),
nn.ReLU(inplace=True)
)
def _predict(self,inplanes):
return nn.Sequential(
nn.Conv2d(inplanes,1,kernel_size=1,strid=1),
nn.ReLU(inplace=True)
)
def forward(self, conv_out):
x = self.reduce(conv_out)
left, right=torch.split(x, cfg.TRAIN.IMS_PER_BATCH, dim=0)
cost = costVolume2(left,right,self.max_displacement)
stack0=self.stack0(cost)
stack1=self.stack1(stack0)
stack1_1=self.stack1_1(stack1)
stack1_2=self.stack1_2(stack1_1)
stack1_3=self.stack1_3(stack1_2)
stack2_1=self.stack2_1(stack1_3)+stack1_2
stack2_2=self.stack2_2(stack2_1)+stack1_1
stack2_3=self.stack2_3(stack2_2)+stack1
out2d=self.to2D(stack2_3)
out=torch.squeeze(out2d,dim=1)
predict = self.predict(out)
return [out,predict]
class TConv(nn.Module):
def __init__(self, in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1):
super(TConv, self).__init__()
self.conv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride,
padding=padding, bias=False)
def forward(self, x):
return F.leaky_relu(self.conv.forward(x), negative_slope=0.1, inplace=True)
class FusionNet(nn.Module):
def __init__(self,inplanes):
super(FusionNet,self).__init__()
self.out_channels=32
self.rdi = nn.Conv2d(512+cfg.SEM.SD_DIM*2,self.out_channels*8)
self.upconv8_4 = self._TConv(self.out_channels*8,self.out_channels*4)
self.upconv4_2 = self._TConv(self.out_channels*4,self.out_channels*2)
self.upconv2_1 = self._TConv(self.out_channels*2,self.out_channels)
self.pr8 = nn.Conv2d(self.out_channels*8,1,kernel_size=3,strid=1,padding=1,bias=False) #512
self.pr4 = nn.Conv2d(self.out_channels*4,1,kernel_size=3,strid=1,padding=1,bias=False) #256
self.pr2 = nn.Conv2d(self.out_channels*2,1,kernel_size=3,strid=1,padding=1,bias=False) #128
self.pr1 = nn.Conv2d(self.out_channels,1,kernel_size=3,strid=1,padding=1,bias=False) #64
self.fusion8=self._fusion(512+512+cfg.SEM.SD_DIM*2,self.out_channels*8)
self.fusion4=self._fusion(self.out_channels*4+256,self.out_channels*4)
self.fusion2=self._fusion(self.out_channels*2+128,self.out_channels*2)
self.fusion1=self._fusion(self.out_channels*1,self.out_channels)
def _Tconv(self,inplanes,planes):
return nn.Sequential(
nn.ConvTranspose2d(inplanes,planes,kernel_size=3,strid=2,padding=1),
nn.Conv2d(planes,planes,kernel_size=3,stride=1,padding=1,bias=False),
nn.BatchNorm2d(planes),
nn.LeakyReLU(negative_slope=0.1,inplace=True)
)
def _fusion(self,inplanes,planes,kernel_size=3,stride=1,padding=1):
return nn.Sequential(
nn.Conv2d(inplanes,planes,kernel_size=kernel_size,stride=stride,padding=padding,bias=False),
nn.Conv2d(planes,planes,kernel_size=3,stride=1,padding=1,bias=False),
nn.BatchNorm2d(planes),
nn.LeakyReLU(negative_slope=0.1,inplace=True))
def forward(self,semdisp,psm,resFeature):
pred_semseg, pred_disp = torch.split(pred, cfg.TRAIN.IMS_PER_BATCH, dim=0)
conv1a, _ = torch.split(FeatureMap[0], cfg.TRAIN.IMS_PER_BATCH, dim=0) #64channels
#_ , conv1a = torch.split(conv1a, cfg.TRAIN.IMS_PER_BATCH, dim=0)
conv2a, _ = torch.split(FeatureMap[1], cfg.TRAIN.IMS_PER_BATCH, dim=0) #128channels
#_ , conv2a = torch.split(conv2a, cfg.TRAIN.IMS_PER_BATCH, dim=0)
_, layer4 = torch.split(FeatureMap[4], cfg.TRAIN.IMS_PER_BATCH, dim=0)
feature8 = self.fusion8(torch.cat((pred_disp,psm,layer4),dim=1))
pr8=self.pr8(feature8)
upfeature8_4=self.upconv8_4(torch.cat(pr8,feature8),dim=1)
feature4 = self.fusion4(torch.cat((upfeature8_4,conv2a),dim=1))
pr4=self.pr4(feature4)
upfeature4_2=self.upconv4_2(torch.cat(pr4,feature4),dim=1)
feature2 = self.fusion2(torch.cat((upfeature4_2,conv1a),dim=1))
pr2=self.pr2(feature2)
upfeature2_1 =sefl.upconv2_1(torch.cat(pr2,feature2),dim=1)
pr1=self.pr1(torch.cat(upfeature2_1),dim=1)
return[pr1,pr2,pr4,pr8]
class MiniCSPN(nn.Module):
def __init__(self,in_channels):
super(MiniCSPN,self).__init__()
self.in_channels=in_channels
self.FupCat=[]
fpn_dim = cfg.SEM.DIM
self.predisp_16x = nn.Sequential(
nn.Conv2d(2048, in_channels, kernel_size=3, padding=1, bias=False),
SynchronizedBatchNorm2d(in_channels),
nn.ReLU(inplace=True))
for i in range(4):
self.FupCat.append(
Gudi_UpProj_Block_Cat(self.in_channels//2**i,self.in_channels//2**(i+1)))
self.FupCat=nn.ModuleList(self.FupCat)
#disp output side
self.merge_spp_list = []
self.merge_spp_down = []
for i in range(5):
self.merge_spp_down.append(nn.Sequential(
nn.Conv2d(512, self.in_channels//2**i, kernel_size=1, padding=0, bias=False),
SynchronizedBatchNorm2d(self.in_channels//2**i),
nn.ReLU(inplace=True)))
self.merge_spp_list.append(nn.Sequential(
conv3x3_bn_relu(2*self.in_channels//2**i, self.in_channels//2**i, 1),
conv3x3_bn_relu(self.in_channels//2**i, 1, 1)
))
self.merge_spp_list = nn.ModuleList(self.merge_spp_list)
self.merge_spp_down = nn.ModuleList(self.merge_spp_down)
self.disp_outside = []
# FPN Module
self.fpn_in = []
for i in range(len(cfg.SEM.FPN_DIMS)): # skip the top layer
self.fpn_in.append(nn.Sequential(
nn.Conv2d(cfg.SEM.FPN_DIMS[i], fpn_dim, kernel_size=1, bias=False),
SynchronizedBatchNorm2d(fpn_dim),
nn.ReLU(inplace=True)
))
self.fpn_in = nn.ModuleList(self.fpn_in)
self.fpn_out = []
for i in range(len(cfg.SEM.FPN_DIMS)): # skip the top layer
self.fpn_out.append(nn.Sequential(
conv3x3_bn_relu(fpn_dim, fpn_dim, 1),
))
self.fpn_out = nn.ModuleList(self.fpn_out)
self.conv_last = nn.Sequential(
conv3x3_bn_relu(len(cfg.SEM.FPN_DIMS) * fpn_dim + fpn_dim, fpn_dim, 1),
nn.Conv2d(fpn_dim, cfg.MODEL.NUM_CLASSES, kernel_size=1)
)
self.semseg_deepsup=nn.Sequential(
conv3x3_bn_relu(1024, 512, 1),
nn.Conv2d(512, 19, kernel_size=3,padding=1,bias=False))
for m in self.modules():
if isinstance(m,nn.Conv2d):
kaiming_normal_(m.weight,0.1)
if m.bias is not None:
constant_(m.bias,0)
elif isinstance(m,nn.BatchNorm2d):
constant_(m.weight,1)
constant_(m.bias,0)
def _conv(self,inplanes,planes,kernel_size=3,stride=1,padding=1,bias=False):
return nn.Sequential(
nn.Conv2d(inplanes,planes,kernel_size,stride=stride,padding=padding,bias=bias),
nn.BatchNorm2d(planes),
nn.ReLU(inplace=True)
)
def _semOut(self,inplanes,kernel_size=3,stride=1,padding=1,bias=False):
return nn.Sequential(
nn.Conv2d(inplanes,19,kernel_size=kernel_size,stride=stride,padding=padding,bias=bias))
def _out(self,inplanes,kernel_size=3,stride=1,padding=1,bias=False):
return nn.Sequential(
nn.Conv2d(inplanes,inplanes,kernel_size=kernel_size,stride=1,padding=1,bias=True),
nn.BatchNorm2d(inplanes),
nn.ReLU(inplace=True),
nn.Conv2d(inplanes,1,kernel_size=kernel_size,stride=1,padding=1,bias=True))
def _up_pooling(self, x, scale_factor,mode='bilinear',oheight=0,owidth=0):
if mode =='bilinear':
return nn.functional.interpolate(x,scale_factor=scale_factor, mode='bilinear')
x = nn.Upsample(scale_factor=scale, mode='nearest')(x)
if oheight !=0 and owidth !=0:
x = x[:,:,0:oheight, 0:owidth]
mask = torch.zeros_like(x)
for h in range(0,oheight, 2):
for w in range(0, owidth, 2):
mask[:,:,h,w] = 1
x = torch.mul(mask, x)
return x
def forward(self,sspp,resFeature,left,right):
#decode: start from followed basic
res16x_semseg, res16x_disp = torch.split(resFeature[-1],cfg.TRAIN.IMS_PER_BATCH,dim=0)
# disp decoder
self.disp_outside=[]
dispNx_in = self.predisp_16x(res16x_disp)
self.disp_outside.append(dispNx_in)
#use up_cat to decoder
for i in range(4):
dispNx_in =self.FupCat[i](dispNx_in, left, right, ratio=0)
self.disp_outside.append(dispNx_in)
for i in range(5):
sspp_i = self.merge_spp_down[i](sspp)
sspp_i = F.interpolate(sspp_i, size=self.disp_outside[i].size()[2:], mode='bilinear', align_corners=False)
self.disp_outside[i] = self.merge_spp_list[i](torch.cat([self.disp_outside[i], sspp_i], dim=1))
#decode for semseg
fpn_feature_list = [sspp]
f = sspp
for i in range(len(cfg.SEM.FPN_DIMS)):
conv_x, _ = torch.split(resFeature[i+1], cfg.TRAIN.IMS_PER_BATCH,dim=0)
conv_x = self.fpn_in[i](conv_x)
f = F.interpolate(f, size=conv_x.size()[2:], mode='bilinear', align_corners=False)
f = conv_x + f
fpn_feature_list.append(self.fpn_out[i](f))
fpn_feature_list.reverse() # [P2 - P5]
output_size = fpn_feature_list[0].size()[2:]
fusion_list = [fpn_feature_list[0]]
for i in range(1, len(fpn_feature_list)):
fusion_list.append(nn.functional.interpolate(
fpn_feature_list[i],
output_size,
mode='bilinear', align_corners=False))
fusion_out = torch.cat(fusion_list, 1)
semseg_maps = self.conv_last(fusion_out)
semseg_final = self._up_pooling(semseg_maps, scale_factor=4)
res4_semseg, _ = torch.split(resFeature[-2], cfg.TRAIN.IMS_PER_BATCH, dim=0)
semseg_res4=self.semseg_deepsup(res4_semseg)
return self.disp_outside, [semseg_res4, semseg_final]
class Gudi_UpProj_Block(nn.Module):
def __init__(self, in_channels, out_channels, oheight=0, owidth=0):
super(Gudi_UpProj_Block, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=1, padding=2, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
self.sc_conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=1, padding=2, bias=False)
self.sc_bn1 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
self.oheight = oheight
self.owidth = owidth
for m in self.modules():
if isinstance(m,nn.Conv2d):
kaiming_normal_(m.weight,0.1)
if m.bias is not None:
constant_(m.bias,0)
elif isinstance(m,nn.BatchNorm2d):
constant_(m.weight,1)
constant_(m.bias,0)
def _up_pooling(self, x, scale):
x = nn.Upsample(scale_factor=scale, mode='nearest')(x)
if self.oheight !=0 and self.owidth !=0:
x = x[:,:,0:self.oheight, 0:self.owidth]
mask = torch.zeros_like(x)
for h in range(0, self.oheight, 2):
for w in range(0, self.owidth, 2):
mask[:,:,h,w] = 1
x = torch.mul(mask, x)
return x
def forward(self, x):
x = self._up_pooling(x, 2)
out = self.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
short_cut = self.sc_bn1(self.sc_conv1(x))
out += short_cut
out = self.relu(out)
return out
class Gudi_UpProj_Block_Cat(nn.Module):
def __init__(self, in_channels, out_channels, oheight=0, owidth=0):
super(Gudi_UpProj_Block_Cat, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=2, dilation=2, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv1_1 = nn.Conv2d(out_channels+6, out_channels, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1_1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
self.sc_conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=2, dilation=2, bias=False)
self.sc_bn1 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
self.oheight = oheight
self.owidth = owidth
def _up_pooling(self, x, scale,mode='bilinear',oheight=0,owidth=0):
if mode =='bilinear':
return nn.functional.interpolate(x,scale_factor=scale, mode='bilinear', align_corners=False)
x = nn.Upsample(scale_factor=scale, mode='nearest')(x)
if oheight !=0 and owidth !=0:
x = x[:,:,0:oheight, 0:owidth]
mask = torch.zeros_like(x)
for h in range(0,oheight, 2):
for w in range(0, owidth, 2):
mask[:,:,h,w] = 1
x = torch.mul(mask, x)
return x
def forward(self, x, left,right,ratio=0):
x = self._up_pooling(x, 2)
left=F.interpolate(left, x.size()[2:], mode='bilinear', align_corners=False)
right=F.interpolate(right, x.size()[2:], mode='bilinear', align_corners=False)
out = self.relu(self.bn1(self.conv1(x)))
out = torch.cat((out, left,right), 1)
out = self.relu(self.bn1_1(self.conv1_1(out)))
out = self.bn2(self.conv2(out))
short_cut = self.sc_bn1(self.sc_conv1(x))
out += short_cut
out = self.relu(out)
return out
class OriginalGudi_UpProj_Block_Cat(nn.Module):
def __init__(self, in_channels, out_channels, oheight=0, owidth=0):
super(OriginalGudi_UpProj_Block_Cat, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=1, padding=2, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv1_1 = nn.Conv2d(out_channels*2, out_channels, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1_1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
self.sc_conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=5, stride=1, padding=2, bias=False)
self.sc_bn1 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
self.oheight = oheight
self.owidth = owidth
def _up_pooling(self, x, scale):
x = nn.Upsample(scale_factor=scale, mode='nearest')(x)
if self.oheight !=0 and self.owidth !=0:
x = x[:,:,0:self.oheight, 0:self.owidth]
mask = torch.zeros_like(x)
for h in range(0, self.oheight, 2):
for w in range(0, self.owidth, 2):
mask[:,:,h,w] = 1
x = torch.mul(mask, x)
return x
def forward(self, x, side_input):
x = self._up_pooling(x, 2)
out = self.relu(self.bn1(self.conv1(x)))
out = torch.cat((out, side_input), 1)
out = self.relu(self.bn1_1(self.conv1_1(out)))
out = self.bn2(self.conv2(out))
short_cut = self.sc_bn1(self.sc_conv1(x))
out += short_cut
out = self.relu(out)
return out
|
python
|
# -*- coding: utf-8 -*-
# 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.
"""
test_dmcrypt
----------------------------------
Tests for `dmcrypt` module.
"""
import base64
from unittest import mock
from vaultlocker import dmcrypt
from vaultlocker.tests.unit import base
class TestDMCrypt(base.TestCase):
@mock.patch.object(dmcrypt, 'subprocess')
def test_luks_format(self, _subprocess):
dmcrypt.luks_format('mykey', '/dev/sdb', 'test-uuid')
_subprocess.check_output.assert_called_once_with(
['cryptsetup',
'--batch-mode',
'--uuid', 'test-uuid',
'--key-file', '-',
'luksFormat', '/dev/sdb'],
input='mykey'.encode('UTF-8')
)
@mock.patch.object(dmcrypt, 'subprocess')
def test_luks_open(self, _subprocess):
dmcrypt.luks_open('mykey', 'test-uuid')
_subprocess.check_output.assert_called_once_with(
['cryptsetup',
'--batch-mode',
'--key-file', '-',
'open', 'UUID=test-uuid', 'crypt-test-uuid',
'--type', 'luks'],
input='mykey'.encode('UTF-8')
)
@mock.patch.object(dmcrypt, 'os')
def test_generate_key(self, _os):
_key = b'randomdatastringfromentropy'
_os.urandom.return_value = _key
self.assertEqual(dmcrypt.generate_key(),
base64.b64encode(_key).decode('UTF-8'))
_os.urandom.assert_called_with(dmcrypt.KEY_SIZE / 8)
@mock.patch.object(dmcrypt, 'subprocess')
def test_udevadm_rescan(self, _subprocess):
dmcrypt.udevadm_rescan('/dev/vdb')
_subprocess.check_output.assert_called_once_with(
['udevadm',
'trigger',
'--name-match=/dev/vdb',
'--action=add']
)
@mock.patch.object(dmcrypt, 'subprocess')
def test_udevadm_settle(self, _subprocess):
dmcrypt.udevadm_settle('myuuid')
_subprocess.check_output.assert_called_once_with(
['udevadm',
'settle',
'--exit-if-exists=/dev/disk/by-uuid/myuuid']
)
|
python
|
#
# @lc app=leetcode id=1022 lang=python3
#
# [1022] Sum of Root To Leaf Binary Numbers
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumRootToLeaf(self, root: TreeNode):
if not root:
return 0
self.bins = []
self.finder(root, '')
ans = 0
for item in self.bins:
cur = 0
digit = 0
while item:
cur += (int(item[-1]) & 1) * (1 << digit)
item = item[:-1]
digit += 1
ans += cur
return ans
def finder(self, root, path):
path = path + str(root.val)
if not root.left and not root.right:
self.bins.append(path)
return
if root.left:
self.finder(root.left, path)
if root.right:
self.finder(root.right, path)
# @lc code=end
|
python
|
"""Setup script of django-blog-zinnia"""
from setuptools import find_packages
from setuptools import setup
import zinnia
setup(
dependency_links=[
"git+https://github.com/arrobalytics/django-tagging.git@027eb90c88ad2d4aead4f50bbbd8d6f0b1678954#egg=django-tagging",
"git+https://github.com/arrobalytics/django-xmlrpc.git@6cf59c555b207de7ecec75ac962751e8245cf8c9#egg=django-xmlrpc",
"git+https://github.com/arrobalytics/mots-vides.git@eaeccf73bdb415d0c5559ccd74de360b37a2bbac#egg=mots-vides",
],
name="django-blog-zinnia",
version=zinnia.__version__,
description="A clear and powerful weblog application powered with Django",
long_description="\n".join([open("README.rst").read(), open("CHANGELOG").read()]),
keywords="django, blog, weblog, zinnia, post, news",
author=zinnia.__author__,
author_email=zinnia.__email__,
url=zinnia.__url__,
packages=find_packages(exclude=["demo"]),
classifiers=[
"Framework :: Django",
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Programming Language :: Python :: 3",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"License :: OSI Approved :: BSD License",
"Topic :: Software Development :: Libraries :: Python Modules",
],
license=zinnia.__license__,
include_package_data=True,
zip_safe=False,
install_requires=[
"asgiref>=3.4.1; python_version >= '3.6'",
"beautifulsoup4>=4.10.0",
"django>=2.2",
"django-contrib-comments>=2.1.0",
"django-js-asset>=1.2.2",
"django-mptt>=0.13.4",
"html5lib>=1.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'",
"importlib-metadata>=4.9.0; python_version < '3.10'",
"markdown>=3.3.6",
"pillow>=8.4.0",
"pyparsing>=3.0.6",
"regex>=2021.11.10",
"six>=1.16.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'",
"soupsieve>=2.3.1; python_version >= '3.6'",
"sqlparse>=0.4.2; python_version >= '3.5'",
"textile>=4.0.2",
"webencodings>=0.5.1",
"zipp>=3.6.0; python_version >= '3.6'",
],
)
|
python
|
from numbers import Number
from timegraph.drawing.plotter import Plotter
class Drawing:
def __init__(self):
self.plotter = Plotter()
def create_graph(self, title, db_response):
value_list = self.get_value_list(db_response.get_points())
self.plotter.plot_timeseries(value_list)
def get_value_list(self, points):
result = []
for point in points:
point_keys = point.keys()
for key in point_keys:
if key != 'time':
if (point[key] is not None and
isinstance(point[key], Number)):
result.append(point[key])
return result
def print_graph(self, lines):
for line in lines:
print(line)
class DrawingException(Exception):
def __init__(self, code, message):
super().__init__(code, message)
self.code = code
self.message = message
|
python
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def __init__(self):
self.res=[]
def printnode(self,start,end):
if start==end:
return
if start.next==end:
# deal with end point the last element but not none
#if end and not end.next:
# self.res.append(end.val)
self.res.append(start.val)
return
if start.next.next==end:
# deal with end point the last element but not none
#if end and not end.next:
# self.res.append(end.val)
self.res.append(start.next.val)
self.res.append(start.val)
return
slow=start
fast=start
while fast!=end:
slow=slow.next
fast=fast.next.next if fast.next!=end else end
#print start.val,end.val,slow.val,fast.val
self.printnode(slow,fast)
self.printnode(start,slow)
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return self.res
if not head.next:
self.res.append(head.val)
return self.res
slow=head
fast=head
while fast:
slow=slow.next
fast=fast.next.next if fast.next else None
#print slow.val,fast.val
self.printnode(slow,fast)
self.printnode(head,slow)
return self.res
|
python
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.