hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
1c2cd1c7866b4166b599bfc1f3c0f6cd7966650c
625
py
Python
gnome/gnome2/gedit/plugins.symlink/ViGedit/actions/insert.py
icebreaker/dotfiles
5c3dc7f981069a728cc6b34ae39cd4c2da1122aa
[ "MIT" ]
4
2015-03-17T14:36:49.000Z
2019-06-10T09:34:35.000Z
gnome/gnome2/gedit/plugins.symlink/ViGedit/actions/insert.py
icebreaker/dotfiles
5c3dc7f981069a728cc6b34ae39cd4c2da1122aa
[ "MIT" ]
null
null
null
gnome/gnome2/gedit/plugins.symlink/ViGedit/actions/insert.py
icebreaker/dotfiles
5c3dc7f981069a728cc6b34ae39cd4c2da1122aa
[ "MIT" ]
1
2019-03-01T13:21:55.000Z
2019-03-01T13:21:55.000Z
def append_After(act): cursor = act.pos.getIter(act) if cursor.ends_line(): act.vibase.doc.insert_at_cursor(" ") else: act.pos.move_Forward(act) return True def insert_BeginLine(act): cursor = act.pos.getIter(act) cursor.backward_sentence_start() act.vibase.doc.place_cursor(cursor) def open_LineAbove(act): act.pos.move_LineBegin(act) act.bindings.mode = act.modes.insert act.keyboard.emitNewLine(act) act.pos.move_Up(act) def open_LineBelow(act): act.pos.move_LineEnd(act) act.bindings.mode = act.modes.insert act.keyboard.emitNewLine(act)
26.041667
44
0.6896
def append_After(act): cursor = act.pos.getIter(act) if cursor.ends_line(): act.vibase.doc.insert_at_cursor(" ") else: act.pos.move_Forward(act) return True def insert_BeginLine(act): cursor = act.pos.getIter(act) cursor.backward_sentence_start() act.vibase.doc.place_cursor(cursor) def open_LineAbove(act): act.pos.move_LineBegin(act) act.bindings.mode = act.modes.insert act.keyboard.emitNewLine(act) act.pos.move_Up(act) def open_LineBelow(act): act.pos.move_LineEnd(act) act.bindings.mode = act.modes.insert act.keyboard.emitNewLine(act)
true
true
1c2cd1d2776852b9bf6526a221d3934a7740e083
1,023
py
Python
Todoism/todoism/models.py
authetic-x/Flask_Practice
90ca69467cd6de8eb41669d2a87ab072fc11e1c8
[ "MIT" ]
1
2020-07-29T16:46:32.000Z
2020-07-29T16:46:32.000Z
Todoism/todoism/models.py
authetic-x/Flask_Practice
90ca69467cd6de8eb41669d2a87ab072fc11e1c8
[ "MIT" ]
null
null
null
Todoism/todoism/models.py
authetic-x/Flask_Practice
90ca69467cd6de8eb41669d2a87ab072fc11e1c8
[ "MIT" ]
null
null
null
from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from todoism.extensions import db class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, index=True) password_hash = db.Column(db.String(128)) locale = db.Column(db.String(20)) items = db.relationship('Item', backref='author', cascade='all') def __init__(self, username): super.__init__(self) self.username = username def set_password(self, password): self.password_hash = generate_password_hash(password) def validate_password(self, password): return check_password_hash(self.password_hash, password) class Item(db.Model): id = db.Column(db.Integer, primary_key=True) body = db.Column(db.Text) done = db.Column(db.Boolean, default=False) author_id = db.Column(db.Integer, db.ForeignKey('user.id')) author = db.relationship('User', backref='items')
31
73
0.71261
from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from todoism.extensions import db class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, index=True) password_hash = db.Column(db.String(128)) locale = db.Column(db.String(20)) items = db.relationship('Item', backref='author', cascade='all') def __init__(self, username): super.__init__(self) self.username = username def set_password(self, password): self.password_hash = generate_password_hash(password) def validate_password(self, password): return check_password_hash(self.password_hash, password) class Item(db.Model): id = db.Column(db.Integer, primary_key=True) body = db.Column(db.Text) done = db.Column(db.Boolean, default=False) author_id = db.Column(db.Integer, db.ForeignKey('user.id')) author = db.relationship('User', backref='items')
true
true
1c2cd22eb76d0c92377d54e89f2dbddf4c8d1416
349
py
Python
glc/cli/subs/c_info.py
evinoca/MyCli
bd6fcb98024c403f9562424f8e8acbacf1380a76
[ "MIT" ]
1
2021-06-08T08:18:21.000Z
2021-06-08T08:18:21.000Z
glc/cli/subs/c_info.py
evinoca/MyCli
bd6fcb98024c403f9562424f8e8acbacf1380a76
[ "MIT" ]
12
2020-05-29T07:08:27.000Z
2022-01-12T22:39:49.000Z
glc/cli/subs/c_info.py
evinoca/MyCli
bd6fcb98024c403f9562424f8e8acbacf1380a76
[ "MIT" ]
null
null
null
from __future__ import absolute_import from __future__ import unicode_literals import click @click.command("info", short_help="Display Information.") @click.pass_obj def cli(config): """Show current configuration information.""" click.echo("calling sub cmd info") click.echo(f"Profile: {config.profile} Config Path: {config.config}")
26.846154
73
0.756447
from __future__ import absolute_import from __future__ import unicode_literals import click @click.command("info", short_help="Display Information.") @click.pass_obj def cli(config): click.echo("calling sub cmd info") click.echo(f"Profile: {config.profile} Config Path: {config.config}")
true
true
1c2cd481e5efc64d8c4dadd72d1104ea81e872aa
1,215
py
Python
readSMPS/readCOR.py
siavashtab/readSMPS-Py
41c4c51c59be07a04d13ccf66558961fe5761945
[ "MIT" ]
null
null
null
readSMPS/readCOR.py
siavashtab/readSMPS-Py
41c4c51c59be07a04d13ccf66558961fe5761945
[ "MIT" ]
null
null
null
readSMPS/readCOR.py
siavashtab/readSMPS-Py
41c4c51c59be07a04d13ccf66558961fe5761945
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on May 4 - 2019 ---Based on the 2-stage stochastic program structure ---Assumption: RHS is random ---read cor file (.mps) ---save the distributoin of the random variables and return the ---random variables @author: Siavash Tabrizian - stabrizian@smu.edu """ from gurobipy import * class readcor: def __init__(self, name): self.name = name + ".mps" ## Read the cor file def readfile(self): self.mean_model = read(self.name) ## Get the mean model information def get_mean(self): self.mean_vars = self.mean_model.getVars() self.mean_const = self.mean_model.getConstrs() self.mean_model.optimize() print ('Mean value optimal: ', self.mean_model.objVal) self.mean_model.printAttr('x') self.mean_sol = [o.getAttr('x') for o in self.mean_vars] self.mean_status = self.mean_model.Status self.mean_objVal = self.mean_model.objVal self.mean_var_num = len(self.mean_vars) self.mean_const_num = len(self.mean_const)
26.413043
64
0.579424
from gurobipy import * class readcor: def __init__(self, name): self.name = name + ".mps" elf): self.mean_model = read(self.name) self.mean_vars = self.mean_model.getVars() self.mean_const = self.mean_model.getConstrs() self.mean_model.optimize() print ('Mean value optimal: ', self.mean_model.objVal) self.mean_model.printAttr('x') self.mean_sol = [o.getAttr('x') for o in self.mean_vars] self.mean_status = self.mean_model.Status self.mean_objVal = self.mean_model.objVal self.mean_var_num = len(self.mean_vars) self.mean_const_num = len(self.mean_const)
true
true
1c2cd528ad879234f51f89a48f46337603288a4d
1,744
py
Python
dss_sm_so/sm/log.py
MobileCloudNetworking/dssaas
87b6f7d60ecc397a88326a955b2ddfd3d73205d1
[ "Apache-2.0" ]
null
null
null
dss_sm_so/sm/log.py
MobileCloudNetworking/dssaas
87b6f7d60ecc397a88326a955b2ddfd3d73205d1
[ "Apache-2.0" ]
null
null
null
dss_sm_so/sm/log.py
MobileCloudNetworking/dssaas
87b6f7d60ecc397a88326a955b2ddfd3d73205d1
[ "Apache-2.0" ]
1
2018-10-09T06:28:36.000Z
2018-10-09T06:28:36.000Z
# Copyright 2014-2015 Zuercher Hochschule fuer Angewandte Wissenschaften # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging import graypy from sm.config import CONFIG __author__ = 'andy' # XXX this will not work inside of OpenShift - needs to be modded def config_logger(log_level=logging.DEBUG): logging.basicConfig(format='%(levelname)s %(asctime)s: \t%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', log_level=log_level) logger = logging.getLogger(__name__) logger.setLevel(log_level) if CONFIG.get('general', 'log_file', '') != '': hdlr = logging.FileHandler(CONFIG.get('general', 'log_file', '')) formatter = logging.Formatter(fmt='%(levelname)s %(asctime)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') hdlr.setFormatter(formatter) logger.addHandler(hdlr) if CONFIG.get('general', 'graylog_api', '') != '' and CONFIG.get('general', 'graylog_port', '') != '': gray_handler = graypy.GELFHandler(CONFIG.get('general', 'graylog_api', ''), CONFIG.getint('general', 'graylog_port')) logger.addHandler(gray_handler) return logger LOG = config_logger()
37.913043
125
0.670872
import logging import graypy from sm.config import CONFIG __author__ = 'andy' def config_logger(log_level=logging.DEBUG): logging.basicConfig(format='%(levelname)s %(asctime)s: \t%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', log_level=log_level) logger = logging.getLogger(__name__) logger.setLevel(log_level) if CONFIG.get('general', 'log_file', '') != '': hdlr = logging.FileHandler(CONFIG.get('general', 'log_file', '')) formatter = logging.Formatter(fmt='%(levelname)s %(asctime)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') hdlr.setFormatter(formatter) logger.addHandler(hdlr) if CONFIG.get('general', 'graylog_api', '') != '' and CONFIG.get('general', 'graylog_port', '') != '': gray_handler = graypy.GELFHandler(CONFIG.get('general', 'graylog_api', ''), CONFIG.getint('general', 'graylog_port')) logger.addHandler(gray_handler) return logger LOG = config_logger()
true
true
1c2cd5d4a84a0e4226675df6df00cb071958c524
15,957
py
Python
analytic/Cod_fuente_raytracing.py
jdlar1/ray_tracing
9a63858ee4918c477532d7484a6b09c87682e6dd
[ "MIT" ]
1
2020-12-28T21:32:23.000Z
2020-12-28T21:32:23.000Z
analytic/Cod_fuente_raytracing.py
jdlar1/ray_tracing
9a63858ee4918c477532d7484a6b09c87682e6dd
[ "MIT" ]
null
null
null
analytic/Cod_fuente_raytracing.py
jdlar1/ray_tracing
9a63858ee4918c477532d7484a6b09c87682e6dd
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Mon Oct 5 18:37:15 2020 @author: Usuario """ from .imagingpath import * from .laserpath import * from .specialtylenses import * from .axicon import * import raytracing.thorlabs as thorlabs import raytracing.eo as eo import raytracing.olympus as olympus import argparse ap = argparse.ArgumentParser(prog='python -m raytracing') ap.add_argument("-e", "--examples", required=False, default='all', help="Specific example numbers, separated by a comma") args = vars(ap.parse_args()) examples = args['examples'] if examples == 'all': examples = range(1,30) else: examples = [ int(y) for y in examples.split(',')] if 1 in examples: path = ImagingPath() path.label = "Demo #1: lens f = 5cm, infinite diameter" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display(comments= """Demo #1: lens with f=5 cm, infinite diameter An object at z=0 (front edge) is used. It is shown in blue. The image (or any intermediate images) are shown in red.\n\ This will use the default objectHeight and fanAngle but they can be changed with: path.objectHeight = 1.0 path.fanAngle = 0.5 path.fanNumber = 5 path.rayNumber = 3 Code: path = ImagingPath() path.label = "Demo #1: lens f = 5cm, infinite diameter" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display() """) if 2 in examples: path = ImagingPath() path.label = "Demo #2: Two lenses, infinite diameters" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=20)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display(comments="""Demo #2: Two lenses, infinite diameters An object at z=0 (front edge) is used with default properties (see Demo #1). Code: path = ImagingPath() path.label = "Demo #2: Two lenses, infinite diameters" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=20)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display() """) # or #path.save("Figure 2.pdf") if 3 in examples: path = ImagingPath() path.label = "Demo #3: Finite lens" path.append(Space(d=10)) path.append(Lens(f=5, diameter=2.5)) path.append(Space(d=3)) path.append(Space(d=17)) path.display(comments="""Demo #3: A finite lens An object at z=0 (front edge) is used with default properties (see Demo #1). Notice the aperture stop (AS) identified at the lens which blocks the cone of light. There is no field stop to restrict the field of view, which is why we must use the default object and cannot restrict the field of view. Notice how the default rays are blocked. path = ImagingPath() path.objectHeight = 1.0 # object height (full). path.objectPosition = 0.0 # always at z=0 for now. path.fanAngle = 0.5 # full fan angle for rays path.fanNumber = 9 # number of rays in fan path.rayNumber = 3 # number of points on object path.label = "Demo #3: Finite lens" path.append(Space(d=10)) path.append(Lens(f=5, diameter=2.5)) path.append(Space(d=3)) path.append(Space(d=17)) path.display() """) if 4 in examples: path = ImagingPath() path.label = "Demo #4: Aperture behind lens" path.append(Space(d=10)) path.append(Lens(f=5, diameter=3)) path.append(Space(d=3)) path.append(Aperture(diameter=3)) path.append(Space(d=17)) path.display(comments="""Demo #4: Aperture behind lens Notice the aperture stop (AS) identified after the lens, not at the lens. Again, since there is no field stop, we cannot restrict the object to the field of view because it is infinite. Code: path = ImagingPath() path.label = "Demo #4: Aperture behind lens" path.append(Space(d=10)) path.append(Lens(f=5, diameter=3)) path.append(Space(d=3)) path.append(Aperture(diameter=3)) path.append(Space(d=17)) path.display() """) if 5 in examples: path = ImagingPath() path.label = "Demo #5: Simple microscope system" path.fanAngle = 0.1 # full fan angle for rays path.fanNumber = 5 # number of rays in fan path.rayNumber = 5 # number of points on object path.append(Space(d=4)) path.append(Lens(f=4, diameter=0.8, label='Obj')) path.append(Space(d=4 + 18)) path.append(Lens(f=18, diameter=5.0, label='Tube Lens')) path.append(Space(d=18)) path.display(limitObjectToFieldOfView=True, comments="""# Demo #5: Simple microscope system The aperture stop (AS) is at the entrance of the objective lens, and the tube lens, in this particular microscope, is the field stop (FS) and limits the field of view. Because the field stop exists, we can use limitObjectToFieldOfView=True when displaying, which will set the objectHeight to the field of view, but will still trace all the rays using our parameters. path = ImagingPath() path.label = "Demo #5: Simple microscope system" path.fanAngle = 0.1 # full fan angle for rays path.fanNumber = 5 # number of rays in fan path.rayNumber = 5 # number of points on object path.append(Space(d=4)) path.append(Lens(f=4, diameter=0.8, label='Obj')) path.append(Space(d=4 + 18)) path.append(Lens(f=18, diameter=5.0, label='Tube Lens')) path.append(Space(d=18)) path.display() """) if 6 in examples: path = ImagingPath() path.label = "Demo #6: Simple microscope system, only principal rays" path.append(Space(d=4)) path.append(Lens(f=4, diameter=0.8, label='Obj')) path.append(Space(d=4 + 18)) path.append(Lens(f=18, diameter=5.0, label='Tube Lens')) path.append(Space(d=18)) path.display(limitObjectToFieldOfView=True, onlyChiefAndMarginalRays=True, comments="""# Demo #6: Simple microscope system, only principal rays The aperture stop (AS) is at the entrance of the objective lens, and the tube lens, in this particular microscope, is the field stop (FS) and limits the field of view. Because the field stop exists, we can use limitObjectToFieldOfView=True when displaying, which will set the objectHeight to the field of view. We can also require that only the principal rays are drawn: chief ray marginal ray (or axial ray). path = ImagingPath() path.label = "Demo #6: Simple microscope system, only principal rays" path.append(Space(d=4)) path.append(Lens(f=4, diameter=0.8, label='Obj')) path.append(Space(d=4 + 18)) path.append(Lens(f=18, diameter=5.0, label='Tube Lens')) path.append(Space(d=18)) path.display() """) if 7 in examples: path = ImagingPath() path.label = "Demo #7: Focussing through a dielectric slab" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=3)) path.append(DielectricSlab(n=1.5, thickness=4)) path.append(Space(d=10)) path.display(comments=path.label+"""\n path = ImagingPath() path.label = "Demo #7: Focussing through a dielectric slab" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=3)) path.append(DielectricSlab(n=1.5, thickness=4)) path.append(Space(d=10))""" ) if 8 in examples: # Demo #8: Virtual image path = ImagingPath() path.label = "Demo #8: Virtual image at -2f with object at f/2" path.append(Space(d=2.5)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display(comments=path.label+"""\n path = ImagingPath() path.label = "Demo #8: Virtual image at -2f with object at f/2" path.append(Space(d=2.5)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display()""") if 9 in examples: # Demo #9: Infinite telecentric 4f telescope path = ImagingPath() path.label = "Demo #9: Infinite telecentric 4f telescope" path.append(Space(d=5)) path.append(Lens(f=5)) path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=5)) path.display(comments=path.label+"""\n path = ImagingPath() path.label = "Demo #9: Infinite telecentric 4f telescope" path.append(Space(d=5)) path.append(Lens(f=5)) path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=5)) """) if 10 in examples: path = ImagingPath() path.fanAngle = 0.05 path.append(Space(d=20)) path.append(Lens(f=-10, label='Div')) path.append(Space(d=7)) path.append(Lens(f=10, label='Foc')) path.append(Space(d=40)) (focal,focal) = path.effectiveFocalLengths() bfl = path.backFocalLength() path.label = "Demo #10: Retrofocus $f_e$={0:.1f} cm, and BFL={1:.1f}".format(focal, bfl) path.display(comments=path.label+"""\n A retrofocus has a back focal length longer than the effective focal length. It comes from a diverging lens followed by a converging lens. We can always obtain the effective focal lengths and the back focal length of a system. path = ImagingPath() path.fanAngle = 0.05 path.append(Space(d=20)) path.append(Lens(f=-10, label='Div')) path.append(Space(d=7)) path.append(Lens(f=10, label='Foc')) path.append(Space(d=40)) (focal,focal) = path.effectiveFocalLengths() bfl = path.backFocalLength() path.label = "Demo #10: Retrofocus $f_e$={0:.1f} cm, and BFL={1:.1f}".format(focal, bfl) path.display() """) if 11 in examples: # Demo #11: Thick diverging lens path = ImagingPath() path.label = "Demo #11: Thick diverging lens" path.objectHeight = 20 path.append(Space(d=50)) path.append(ThickLens(R1=-20, R2=20, n=1.55, thickness=10, diameter=25, label='Lens')) path.append(Space(d=50)) path.display(onlyChiefAndMarginalRays=True, comments=path.label+"""\n path = ImagingPath() path.label = "Demo #11: Thick diverging lens" path.objectHeight = 20 path.append(Space(d=50)) path.append(ThickLens(R1=-20, R2=20, n=1.55, thickness=10, diameter=25, label='Lens')) path.append(Space(d=50)) path.display()""") if 12 in examples: # Demo #12: Thick diverging lens built from individual elements path = ImagingPath() path.label = "Demo #12: Thick diverging lens built from individual elements" path.objectHeight = 20 path.append(Space(d=50)) path.append(DielectricInterface(R=-20, n1=1.0, n2=1.55, diameter=25, label='Front')) path.append(Space(d=10, diameter=25, label='Lens')) path.append(DielectricInterface(R=20, n1=1.55, n2=1.0, diameter=25, label='Back')) path.append(Space(d=50)) path.display(onlyChiefAndMarginalRays=True, comments=path.label+"""\n path = ImagingPath() path.label = "Demo #12: Thick diverging lens built from individual elements" path.objectHeight = 20 path.append(Space(d=50)) path.append(DielectricInterface(R=-20, n1=1.0, n2=1.55, diameter=25, label='Front')) path.append(Space(d=10, diameter=25, label='Lens')) path.append(DielectricInterface(R=20, n1=1.55, n2=1.0, diameter=25, label='Back')) path.append(Space(d=50)) path.display()""") if 13 in examples: # Demo #13, forward and backward conjugates # We can obtain the position of the image for any matrix # by using forwardConjugate(): it calculates the distance # after the element where the image is, assuming an object # at the front surface. M1 = Space(d=10) M2 = Lens(f=5) M3 = M2*M1 print(M3.forwardConjugate()) print(M3.backwardConjugate()) if 14 in examples: # Demo #14: Generic objectives obj = Objective(f=10, NA=0.8, focusToFocusLength=60, backAperture=18, workingDistance=2, label="Objective") print("Focal distances: ", obj.focalDistances()) print("Position of PP1 and PP2: ", obj.principalPlanePositions(z=0)) print("Focal spots positions: ", obj.focusPositions(z=0)) print("Distance between entrance and exit planes: ", obj.L) path = ImagingPath() path.fanAngle = 0.0 path.fanNumber = 1 path.rayNumber = 15 path.objectHeight = 10.0 path.label = "Demo #14 Path with generic objective" path.append(Space(180)) path.append(obj) path.append(Space(10)) path.display(comments=path.label+""" path = ImagingPath() path.fanAngle = 0.0 path.fanNumber = 1 path.rayNumber = 15 path.objectHeight = 10.0 path.label = "Path with generic objective" path.append(Space(180)) path.append(obj) path.append(Space(10)) path.display()""") if 15 in examples: # Demo #15: Olympus objective LUMPlanFL40X path = ImagingPath() path.fanAngle = 0.0 path.fanNumber = 1 path.rayNumber = 15 path.objectHeight = 10.0 path.label = "Demo #15 Path with LUMPlanFL40X" path.append(Space(180)) path.append(olympus.LUMPlanFL40X()) path.display(comments=path.label+""" path = ImagingPath() path.fanAngle = 0.0 path.fanNumber = 1 path.rayNumber = 15 path.objectHeight = 10.0 path.label = "Path with LUMPlanFL40X" path.append(Space(180)) path.append(olympus.LUMPlanFL40X()) path.append(Space(10)) path.display()""") if 16 in examples: # Demo #16: Vendor lenses thorlabs.AC254_050_A().display() eo.PN_33_921().display() if 17 in examples: # Demo #17: Vendor lenses path = ImagingPath() path.label = "Demo #17: Vendor Lenses" path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=150)) path.append(eo.PN_33_921()) path.append(Space(d=50)) path.append(eo.PN_88_593()) path.append(Space(180)) path.append(olympus.LUMPlanFL40X()) path.append(Space(10)) path.display(comments=path.label+"""\n path = ImagingPath() path.label = "Demo #17: Vendor Lenses" path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=150)) path.append(eo.PN_33_921()) path.append(Space(d=50)) path.append(eo.PN_88_593()) path.append(Space(180)) path.append(olympus.LUMPlanFL40X()) path.append(Space(10)) path.display()""") if 18 in examples: # Demo #18: Laser beam and vendor lenses path = LaserPath() path.label = "Demo #18: Laser beam and vendor lenses" path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=150)) path.append(eo.PN_33_921()) path.append(Space(d=50)) path.append(eo.PN_88_593()) path.append(Space(d=180)) path.append(olympus.LUMPlanFL40X()) path.append(Space(d=10)) path.display(inputBeam=GaussianBeam(w=0.001), comments=""" path = LaserPath() path.label = "Demo #18: Laser beam and vendor lenses" path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=150)) path.append(eo.PN_33_921()) path.append(Space(d=50)) path.append(eo.PN_88_593()) path.append(Space(d=180)) path.append(olympus.LUMPlanFL40X()) path.append(Space(d=10)) path.display()""") if 19 in examples: cavity = LaserPath(label="Laser cavity: round trip\nCalculated laser modes") cavity.isResonator = True cavity.append(Space(d=160)) cavity.append(DielectricSlab(thickness=100, n=1.8)) cavity.append(Space(d=160)) cavity.append(CurvedMirror(R=400)) cavity.append(Space(d=160)) cavity.append(DielectricSlab(thickness=100, n=1.8)) cavity.append(Space(d=160)) # Calculate all self-replicating modes (i.e. eigenmodes) (q1,q2) = cavity.eigenModes() print(q1,q2) # Obtain all physical (i.e. finite) self-replicating modes qs = cavity.laserModes() for q in qs: print(q) # Show cavity.display()
36.514874
144
0.66134
from .imagingpath import * from .laserpath import * from .specialtylenses import * from .axicon import * import raytracing.thorlabs as thorlabs import raytracing.eo as eo import raytracing.olympus as olympus import argparse ap = argparse.ArgumentParser(prog='python -m raytracing') ap.add_argument("-e", "--examples", required=False, default='all', help="Specific example numbers, separated by a comma") args = vars(ap.parse_args()) examples = args['examples'] if examples == 'all': examples = range(1,30) else: examples = [ int(y) for y in examples.split(',')] if 1 in examples: path = ImagingPath() path.label = "Demo #1: lens f = 5cm, infinite diameter" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display(comments= """Demo #1: lens with f=5 cm, infinite diameter An object at z=0 (front edge) is used. It is shown in blue. The image (or any intermediate images) are shown in red.\n\ This will use the default objectHeight and fanAngle but they can be changed with: path.objectHeight = 1.0 path.fanAngle = 0.5 path.fanNumber = 5 path.rayNumber = 3 Code: path = ImagingPath() path.label = "Demo #1: lens f = 5cm, infinite diameter" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display() """) if 2 in examples: path = ImagingPath() path.label = "Demo #2: Two lenses, infinite diameters" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=20)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display(comments="""Demo #2: Two lenses, infinite diameters An object at z=0 (front edge) is used with default properties (see Demo #1). Code: path = ImagingPath() path.label = "Demo #2: Two lenses, infinite diameters" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=20)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display() """) if 3 in examples: path = ImagingPath() path.label = "Demo #3: Finite lens" path.append(Space(d=10)) path.append(Lens(f=5, diameter=2.5)) path.append(Space(d=3)) path.append(Space(d=17)) path.display(comments="""Demo #3: A finite lens An object at z=0 (front edge) is used with default properties (see Demo #1). Notice the aperture stop (AS) identified at the lens which blocks the cone of light. There is no field stop to restrict the field of view, which is why we must use the default object and cannot restrict the field of view. Notice how the default rays are blocked. path = ImagingPath() path.objectHeight = 1.0 # object height (full). path.objectPosition = 0.0 # always at z=0 for now. path.fanAngle = 0.5 # full fan angle for rays path.fanNumber = 9 # number of rays in fan path.rayNumber = 3 # number of points on object path.label = "Demo #3: Finite lens" path.append(Space(d=10)) path.append(Lens(f=5, diameter=2.5)) path.append(Space(d=3)) path.append(Space(d=17)) path.display() """) if 4 in examples: path = ImagingPath() path.label = "Demo #4: Aperture behind lens" path.append(Space(d=10)) path.append(Lens(f=5, diameter=3)) path.append(Space(d=3)) path.append(Aperture(diameter=3)) path.append(Space(d=17)) path.display(comments="""Demo #4: Aperture behind lens Notice the aperture stop (AS) identified after the lens, not at the lens. Again, since there is no field stop, we cannot restrict the object to the field of view because it is infinite. Code: path = ImagingPath() path.label = "Demo #4: Aperture behind lens" path.append(Space(d=10)) path.append(Lens(f=5, diameter=3)) path.append(Space(d=3)) path.append(Aperture(diameter=3)) path.append(Space(d=17)) path.display() """) if 5 in examples: path = ImagingPath() path.label = "Demo #5: Simple microscope system" path.fanAngle = 0.1 path.fanNumber = 5 path.rayNumber = 5 path.append(Space(d=4)) path.append(Lens(f=4, diameter=0.8, label='Obj')) path.append(Space(d=4 + 18)) path.append(Lens(f=18, diameter=5.0, label='Tube Lens')) path.append(Space(d=18)) path.display(limitObjectToFieldOfView=True, comments="""# Demo #5: Simple microscope system The aperture stop (AS) is at the entrance of the objective lens, and the tube lens, in this particular microscope, is the field stop (FS) and limits the field of view. Because the field stop exists, we can use limitObjectToFieldOfView=True when displaying, which will set the objectHeight to the field of view, but will still trace all the rays using our parameters. path = ImagingPath() path.label = "Demo #5: Simple microscope system" path.fanAngle = 0.1 # full fan angle for rays path.fanNumber = 5 # number of rays in fan path.rayNumber = 5 # number of points on object path.append(Space(d=4)) path.append(Lens(f=4, diameter=0.8, label='Obj')) path.append(Space(d=4 + 18)) path.append(Lens(f=18, diameter=5.0, label='Tube Lens')) path.append(Space(d=18)) path.display() """) if 6 in examples: path = ImagingPath() path.label = "Demo #6: Simple microscope system, only principal rays" path.append(Space(d=4)) path.append(Lens(f=4, diameter=0.8, label='Obj')) path.append(Space(d=4 + 18)) path.append(Lens(f=18, diameter=5.0, label='Tube Lens')) path.append(Space(d=18)) path.display(limitObjectToFieldOfView=True, onlyChiefAndMarginalRays=True, comments="""# Demo #6: Simple microscope system, only principal rays The aperture stop (AS) is at the entrance of the objective lens, and the tube lens, in this particular microscope, is the field stop (FS) and limits the field of view. Because the field stop exists, we can use limitObjectToFieldOfView=True when displaying, which will set the objectHeight to the field of view. We can also require that only the principal rays are drawn: chief ray marginal ray (or axial ray). path = ImagingPath() path.label = "Demo #6: Simple microscope system, only principal rays" path.append(Space(d=4)) path.append(Lens(f=4, diameter=0.8, label='Obj')) path.append(Space(d=4 + 18)) path.append(Lens(f=18, diameter=5.0, label='Tube Lens')) path.append(Space(d=18)) path.display() """) if 7 in examples: path = ImagingPath() path.label = "Demo #7: Focussing through a dielectric slab" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=3)) path.append(DielectricSlab(n=1.5, thickness=4)) path.append(Space(d=10)) path.display(comments=path.label+"""\n path = ImagingPath() path.label = "Demo #7: Focussing through a dielectric slab" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=3)) path.append(DielectricSlab(n=1.5, thickness=4)) path.append(Space(d=10))""" ) if 8 in examples: ngPath() path.label = "Demo #8: Virtual image at -2f with object at f/2" path.append(Space(d=2.5)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display(comments=path.label+"""\n path = ImagingPath() path.label = "Demo #8: Virtual image at -2f with object at f/2" path.append(Space(d=2.5)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display()""") if 9 in examples: bel = "Demo #9: Infinite telecentric 4f telescope" path.append(Space(d=5)) path.append(Lens(f=5)) path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=5)) path.display(comments=path.label+"""\n path = ImagingPath() path.label = "Demo #9: Infinite telecentric 4f telescope" path.append(Space(d=5)) path.append(Lens(f=5)) path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=5)) """) if 10 in examples: path = ImagingPath() path.fanAngle = 0.05 path.append(Space(d=20)) path.append(Lens(f=-10, label='Div')) path.append(Space(d=7)) path.append(Lens(f=10, label='Foc')) path.append(Space(d=40)) (focal,focal) = path.effectiveFocalLengths() bfl = path.backFocalLength() path.label = "Demo #10: Retrofocus $f_e$={0:.1f} cm, and BFL={1:.1f}".format(focal, bfl) path.display(comments=path.label+"""\n A retrofocus has a back focal length longer than the effective focal length. It comes from a diverging lens followed by a converging lens. We can always obtain the effective focal lengths and the back focal length of a system. path = ImagingPath() path.fanAngle = 0.05 path.append(Space(d=20)) path.append(Lens(f=-10, label='Div')) path.append(Space(d=7)) path.append(Lens(f=10, label='Foc')) path.append(Space(d=40)) (focal,focal) = path.effectiveFocalLengths() bfl = path.backFocalLength() path.label = "Demo #10: Retrofocus $f_e$={0:.1f} cm, and BFL={1:.1f}".format(focal, bfl) path.display() """) if 11 in examples: path.label = "Demo #11: Thick diverging lens" path.objectHeight = 20 path.append(Space(d=50)) path.append(ThickLens(R1=-20, R2=20, n=1.55, thickness=10, diameter=25, label='Lens')) path.append(Space(d=50)) path.display(onlyChiefAndMarginalRays=True, comments=path.label+"""\n path = ImagingPath() path.label = "Demo #11: Thick diverging lens" path.objectHeight = 20 path.append(Space(d=50)) path.append(ThickLens(R1=-20, R2=20, n=1.55, thickness=10, diameter=25, label='Lens')) path.append(Space(d=50)) path.display()""") if 12 in examples: ick diverging lens built from individual elements" path.objectHeight = 20 path.append(Space(d=50)) path.append(DielectricInterface(R=-20, n1=1.0, n2=1.55, diameter=25, label='Front')) path.append(Space(d=10, diameter=25, label='Lens')) path.append(DielectricInterface(R=20, n1=1.55, n2=1.0, diameter=25, label='Back')) path.append(Space(d=50)) path.display(onlyChiefAndMarginalRays=True, comments=path.label+"""\n path = ImagingPath() path.label = "Demo #12: Thick diverging lens built from individual elements" path.objectHeight = 20 path.append(Space(d=50)) path.append(DielectricInterface(R=-20, n1=1.0, n2=1.55, diameter=25, label='Front')) path.append(Space(d=10, diameter=25, label='Lens')) path.append(DielectricInterface(R=20, n1=1.55, n2=1.0, diameter=25, label='Back')) path.append(Space(d=50)) path.display()""") if 13 in examples: d=10) M2 = Lens(f=5) M3 = M2*M1 print(M3.forwardConjugate()) print(M3.backwardConjugate()) if 14 in examples: 10, NA=0.8, focusToFocusLength=60, backAperture=18, workingDistance=2, label="Objective") print("Focal distances: ", obj.focalDistances()) print("Position of PP1 and PP2: ", obj.principalPlanePositions(z=0)) print("Focal spots positions: ", obj.focusPositions(z=0)) print("Distance between entrance and exit planes: ", obj.L) path = ImagingPath() path.fanAngle = 0.0 path.fanNumber = 1 path.rayNumber = 15 path.objectHeight = 10.0 path.label = "Demo #14 Path with generic objective" path.append(Space(180)) path.append(obj) path.append(Space(10)) path.display(comments=path.label+""" path = ImagingPath() path.fanAngle = 0.0 path.fanNumber = 1 path.rayNumber = 15 path.objectHeight = 10.0 path.label = "Path with generic objective" path.append(Space(180)) path.append(obj) path.append(Space(10)) path.display()""") if 15 in examples: fanAngle = 0.0 path.fanNumber = 1 path.rayNumber = 15 path.objectHeight = 10.0 path.label = "Demo #15 Path with LUMPlanFL40X" path.append(Space(180)) path.append(olympus.LUMPlanFL40X()) path.display(comments=path.label+""" path = ImagingPath() path.fanAngle = 0.0 path.fanNumber = 1 path.rayNumber = 15 path.objectHeight = 10.0 path.label = "Path with LUMPlanFL40X" path.append(Space(180)) path.append(olympus.LUMPlanFL40X()) path.append(Space(10)) path.display()""") if 16 in examples: 4_050_A().display() eo.PN_33_921().display() if 17 in examples: gPath() path.label = "Demo #17: Vendor Lenses" path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=150)) path.append(eo.PN_33_921()) path.append(Space(d=50)) path.append(eo.PN_88_593()) path.append(Space(180)) path.append(olympus.LUMPlanFL40X()) path.append(Space(10)) path.display(comments=path.label+"""\n path = ImagingPath() path.label = "Demo #17: Vendor Lenses" path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=150)) path.append(eo.PN_33_921()) path.append(Space(d=50)) path.append(eo.PN_88_593()) path.append(Space(180)) path.append(olympus.LUMPlanFL40X()) path.append(Space(10)) path.display()""") if 18 in examples: label = "Demo #18: Laser beam and vendor lenses" path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=150)) path.append(eo.PN_33_921()) path.append(Space(d=50)) path.append(eo.PN_88_593()) path.append(Space(d=180)) path.append(olympus.LUMPlanFL40X()) path.append(Space(d=10)) path.display(inputBeam=GaussianBeam(w=0.001), comments=""" path = LaserPath() path.label = "Demo #18: Laser beam and vendor lenses" path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=50)) path.append(thorlabs.AC254_050_A()) path.append(Space(d=150)) path.append(eo.PN_33_921()) path.append(Space(d=50)) path.append(eo.PN_88_593()) path.append(Space(d=180)) path.append(olympus.LUMPlanFL40X()) path.append(Space(d=10)) path.display()""") if 19 in examples: cavity = LaserPath(label="Laser cavity: round trip\nCalculated laser modes") cavity.isResonator = True cavity.append(Space(d=160)) cavity.append(DielectricSlab(thickness=100, n=1.8)) cavity.append(Space(d=160)) cavity.append(CurvedMirror(R=400)) cavity.append(Space(d=160)) cavity.append(DielectricSlab(thickness=100, n=1.8)) cavity.append(Space(d=160)) (q1,q2) = cavity.eigenModes() print(q1,q2) qs = cavity.laserModes() for q in qs: print(q) cavity.display()
true
true
1c2cd63f83042932d56c695913a71a0a5c9a5726
4,588
py
Python
plotting/paper_hyp_robust_imagenetv2.py
saarimrahman/imagenet-testbed
55a867d091c7193225880010853ed2b4b0b73ec9
[ "MIT" ]
69
2020-07-21T01:17:45.000Z
2022-03-24T16:31:32.000Z
plotting/paper_hyp_robust_imagenetv2.py
saarimrahman/imagenet-testbed
55a867d091c7193225880010853ed2b4b0b73ec9
[ "MIT" ]
6
2020-12-07T19:17:05.000Z
2022-02-23T23:39:22.000Z
plotting/paper_hyp_robust_imagenetv2.py
saarimrahman/imagenet-testbed
55a867d091c7193225880010853ed2b4b0b73ec9
[ "MIT" ]
4
2020-10-31T23:51:58.000Z
2022-03-25T06:15:55.000Z
import os from os.path import join, exists import argparse import pathlib from enum import Enum import click import numpy as np import pandas as pd import download_data import dataframe import plotter from model_types import ModelTypes, model_types_map class HypModelTypes(Enum): HYP_ROBUST = ('Hypothetical robust model', 'tab:green', 400) STANDARD = ('Standard models', 'tab:blue', 150) models = [k for k, v in model_types_map.items() if v == ModelTypes.STANDARD] models = [m for m in models if 'subsample' not in m and 'batch64' not in m and 'aws' not in m] def get_model_type(df_row): if df_row.name in models: return HypModelTypes.STANDARD def show_in_plot(df_row): model_name, model_type = df_row.name.lower(), df_row.model_type return True def use_for_line_fit(df_row): model_name, model_type, in_plot = df_row.name.lower(), df_row.model_type, df_row.show_in_plot return True @click.command() @click.option('--x_axis', type=str, default='val') @click.option('--y_axis', type=str, default='imagenetv2-matched-frequency-format-val') @click.option('--transform', type=str, default='logit') @click.option('--output_dir', type=str, default=str((pathlib.Path(__file__).parent / '../outputs').resolve())) @click.option('--output_file_dir', type=str, default=str((pathlib.Path(__file__).parent / '../paper/figs').resolve())) @click.option('--skip_download', is_flag=True, type=bool) def generate_xy_plot(x_axis, y_axis, transform, output_dir, output_file_dir, skip_download): if skip_download: filename = join(output_dir, 'grid_df.pkl') if not exists(filename): raise Exception(f'Downloaded data not found at {filename}. Please run python src/plotting/download_data.py first') df = pd.read_pickle(filename) else: df = download_data.download_plotting_data(output_dir, store_data=True, verbose=True) df, df_metadata = dataframe.extract_metadata(df) df, df_metadata = dataframe.replace_10percent_with_metadata(df, df_metadata) df, df_metadata = dataframe.aggregate_corruptions_with_metadata(df, df_metadata) df = prepare_df_for_plotting(df, df_metadata, [x_axis, y_axis]) df = plotter.add_plotting_data(df, [x_axis, y_axis]) df = df.dropna() hyp_robust_model = df.loc['vgg19'].copy() arrow_params = (hyp_robust_model['val'], hyp_robust_model['imagenetv2-matched-frequency-format-val']+0.3, 0, 0.285) hyp_robust_model.model_type = HypModelTypes.HYP_ROBUST hyp_robust_model['imagenetv2-matched-frequency-format-val'] += 8 hyp_robust_model.name = 'vgg19_hyp_robust' hyp_robust_model.use_for_line_fit = False df = df.append(hyp_robust_model) # auto set xlim and ylim based on visible points df_visible = df[df.show_in_plot == True] xlim = [df_visible[x_axis].min() - 1, df_visible[x_axis].max() + 1] ylim = [df_visible[y_axis].min() - 2, df_visible[y_axis].values.max() + 2] fig, ax = plotter.model_scatter_plot_hyp(df, x_axis, y_axis, xlim, ylim, HypModelTypes, transform=transform, tick_multiplier=5, title='Hypothetical Robustness Intervention', x_label='ImageNet', y_label='ImageNetV2', figsize=(12, 9), include_legend=True, return_separate_legend=False, alpha=0.7, arrow_params=arrow_params) l = ax.legend(loc='lower right', ncol=1, bbox_to_anchor=(1, 0), fontsize=plotter.legend_fontsize, scatterpoints=1, columnspacing=0, handlelength=1.5, borderpad=0.2) for i, x in enumerate(l.legendHandles): x._sizes = [100] if i == 2: x._sizes = [400] os.makedirs(output_file_dir, exist_ok=True) fig.savefig(join(output_file_dir, f'hyp_robust_imagenetv2.pdf'), dpi='figure', bbox_inches='tight', pad_inches=0.1) print(f"Plot saved to {join(output_file_dir, f'hyp_robust_imagenetv2.pdf')}") def prepare_df_for_plotting(df, df_metadata, columns): assert set(columns).issubset(set(df.columns)) df = df[columns] df_metadata = df_metadata[[x+'_dataset_size' for x in columns]] df = df.merge(df_metadata, right_index=True, left_index=True) df = df.dropna() df['model_type'] = df.apply(get_model_type, axis=1) df['show_in_plot'] = df.apply(show_in_plot, axis=1) df['use_for_line_fit'] = df.apply(use_for_line_fit, axis=1) return df if __name__ == '__main__': generate_xy_plot()
37.917355
146
0.683522
import os from os.path import join, exists import argparse import pathlib from enum import Enum import click import numpy as np import pandas as pd import download_data import dataframe import plotter from model_types import ModelTypes, model_types_map class HypModelTypes(Enum): HYP_ROBUST = ('Hypothetical robust model', 'tab:green', 400) STANDARD = ('Standard models', 'tab:blue', 150) models = [k for k, v in model_types_map.items() if v == ModelTypes.STANDARD] models = [m for m in models if 'subsample' not in m and 'batch64' not in m and 'aws' not in m] def get_model_type(df_row): if df_row.name in models: return HypModelTypes.STANDARD def show_in_plot(df_row): model_name, model_type = df_row.name.lower(), df_row.model_type return True def use_for_line_fit(df_row): model_name, model_type, in_plot = df_row.name.lower(), df_row.model_type, df_row.show_in_plot return True @click.command() @click.option('--x_axis', type=str, default='val') @click.option('--y_axis', type=str, default='imagenetv2-matched-frequency-format-val') @click.option('--transform', type=str, default='logit') @click.option('--output_dir', type=str, default=str((pathlib.Path(__file__).parent / '../outputs').resolve())) @click.option('--output_file_dir', type=str, default=str((pathlib.Path(__file__).parent / '../paper/figs').resolve())) @click.option('--skip_download', is_flag=True, type=bool) def generate_xy_plot(x_axis, y_axis, transform, output_dir, output_file_dir, skip_download): if skip_download: filename = join(output_dir, 'grid_df.pkl') if not exists(filename): raise Exception(f'Downloaded data not found at {filename}. Please run python src/plotting/download_data.py first') df = pd.read_pickle(filename) else: df = download_data.download_plotting_data(output_dir, store_data=True, verbose=True) df, df_metadata = dataframe.extract_metadata(df) df, df_metadata = dataframe.replace_10percent_with_metadata(df, df_metadata) df, df_metadata = dataframe.aggregate_corruptions_with_metadata(df, df_metadata) df = prepare_df_for_plotting(df, df_metadata, [x_axis, y_axis]) df = plotter.add_plotting_data(df, [x_axis, y_axis]) df = df.dropna() hyp_robust_model = df.loc['vgg19'].copy() arrow_params = (hyp_robust_model['val'], hyp_robust_model['imagenetv2-matched-frequency-format-val']+0.3, 0, 0.285) hyp_robust_model.model_type = HypModelTypes.HYP_ROBUST hyp_robust_model['imagenetv2-matched-frequency-format-val'] += 8 hyp_robust_model.name = 'vgg19_hyp_robust' hyp_robust_model.use_for_line_fit = False df = df.append(hyp_robust_model) df_visible = df[df.show_in_plot == True] xlim = [df_visible[x_axis].min() - 1, df_visible[x_axis].max() + 1] ylim = [df_visible[y_axis].min() - 2, df_visible[y_axis].values.max() + 2] fig, ax = plotter.model_scatter_plot_hyp(df, x_axis, y_axis, xlim, ylim, HypModelTypes, transform=transform, tick_multiplier=5, title='Hypothetical Robustness Intervention', x_label='ImageNet', y_label='ImageNetV2', figsize=(12, 9), include_legend=True, return_separate_legend=False, alpha=0.7, arrow_params=arrow_params) l = ax.legend(loc='lower right', ncol=1, bbox_to_anchor=(1, 0), fontsize=plotter.legend_fontsize, scatterpoints=1, columnspacing=0, handlelength=1.5, borderpad=0.2) for i, x in enumerate(l.legendHandles): x._sizes = [100] if i == 2: x._sizes = [400] os.makedirs(output_file_dir, exist_ok=True) fig.savefig(join(output_file_dir, f'hyp_robust_imagenetv2.pdf'), dpi='figure', bbox_inches='tight', pad_inches=0.1) print(f"Plot saved to {join(output_file_dir, f'hyp_robust_imagenetv2.pdf')}") def prepare_df_for_plotting(df, df_metadata, columns): assert set(columns).issubset(set(df.columns)) df = df[columns] df_metadata = df_metadata[[x+'_dataset_size' for x in columns]] df = df.merge(df_metadata, right_index=True, left_index=True) df = df.dropna() df['model_type'] = df.apply(get_model_type, axis=1) df['show_in_plot'] = df.apply(show_in_plot, axis=1) df['use_for_line_fit'] = df.apply(use_for_line_fit, axis=1) return df if __name__ == '__main__': generate_xy_plot()
true
true
1c2cd79fe4e9e8b1785b4603b0c63b98fa2fcab6
1,371
py
Python
config.py
sproctor/photobooth
58cc86a3f984b2c53fdcb994a33678e86551a501
[ "MIT" ]
1
2019-11-20T17:22:17.000Z
2019-11-20T17:22:17.000Z
config.py
sproctor/photobooth
58cc86a3f984b2c53fdcb994a33678e86551a501
[ "MIT" ]
null
null
null
config.py
sproctor/photobooth
58cc86a3f984b2c53fdcb994a33678e86551a501
[ "MIT" ]
null
null
null
#Config settings to change behavior of photo booth file_path = '/home/pi/Pictures/Photobooth/' # path to save images clear_on_startup = False # True will clear previously stored photos as the program launches. False will leave all previous photos. post_online = False # True to upload images. False to store locally only. print_photos = True # Obvious printer_name = 'Canon_SELPHY_CP1300' # Specify your printer name. If you comment this out, it will print to the first printer it finds. Printer names are printed to std out when you run the photobooth. You can copy one from there if you do not know the name print_to_pdf = False # Whether to print to a PDF instead of a printer make_gifs = False # True to make an animated gif. False to post 4 jpgs into one post. hi_res_pics = True # True to save high res pics from camera. # If also uploading, the program will also convert each image to a smaller image before making the gif. # False to first capture low res pics. False is faster. # Careful, each photo costs against your daily Tumblr upload max. camera_iso = False # adjust for lighting issues. Normal is 100 or 200. Sort of dark is 400. Dark is 800 max. # available options: 100, 200, 320, 400, 500, 640, 800 black_and_white = False # Set to True to capture in black and white
85.6875
257
0.723559
file_path = '/home/pi/Pictures/Photobooth/' clear_on_startup = False post_online = False print_photos = True printer_name = 'Canon_SELPHY_CP1300' print_to_pdf = False make_gifs = False hi_res_pics = True camera_iso = False black_and_white = False
true
true
1c2cd84388f75b4cb816ea1c0019bf785286caa3
43,504
py
Python
lib/network.py
Legogris/electrum-zcl
fcffa73f944c1ee8f89b0a40f3dabc5c5bbfd4ec
[ "MIT" ]
153
2018-02-26T16:22:27.000Z
2020-10-08T09:15:05.000Z
lib/network.py
Legogris/electrum-zcl
fcffa73f944c1ee8f89b0a40f3dabc5c5bbfd4ec
[ "MIT" ]
89
2018-03-03T23:17:11.000Z
2020-07-13T10:19:29.000Z
lib/network.py
Legogris/electrum-zcl
fcffa73f944c1ee8f89b0a40f3dabc5c5bbfd4ec
[ "MIT" ]
30
2018-03-03T13:41:14.000Z
2019-11-01T18:05:07.000Z
# Electrum - Lightweight Bitcoin Client # Copyright (c) 2011-2016 Thomas Voegtlin # # 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 time import queue import os import stat import errno import random import re import select from collections import defaultdict import threading import socket import json import socks from . import util from . import bitcoin from .bitcoin import * from .interface import Connection, Interface from . import blockchain from .version import ELECTRUM_VERSION, PROTOCOL_VERSION NODES_RETRY_INTERVAL = 60 SERVER_RETRY_INTERVAL = 10 def parse_servers(result): """ parse servers list into dict format""" from .version import PROTOCOL_VERSION servers = {} for item in result: host = item[1] out = {} version = None pruning_level = '-' if len(item) > 2: for v in item[2]: if re.match("[st]\d*", v): protocol, port = v[0], v[1:] if port == '': port = NetworkConstants.DEFAULT_PORTS[protocol] out[protocol] = port elif re.match("v(.?)+", v): version = v[1:] elif re.match("p\d*", v): pruning_level = v[1:] if pruning_level == '': pruning_level = '0' if out: out['pruning'] = pruning_level out['version'] = version servers[host] = out return servers def filter_version(servers): def is_recent(version): try: return util.normalize_version(version) >= util.normalize_version(PROTOCOL_VERSION) except Exception as e: return False return {k: v for k, v in servers.items() if is_recent(v.get('version'))} def filter_protocol(hostmap, protocol = 's'): '''Filters the hostmap for those implementing protocol. The result is a list in serialized form.''' eligible = [] for host, portmap in hostmap.items(): port = portmap.get(protocol) if port: eligible.append(serialize_server(host, port, protocol)) return eligible def pick_random_server(hostmap = None, protocol = 's', exclude_set = set()): if hostmap is None: hostmap = NetworkConstants.DEFAULT_SERVERS eligible = list(set(filter_protocol(hostmap, protocol)) - exclude_set) return random.choice(eligible) if eligible else None from .simple_config import SimpleConfig proxy_modes = ['socks4', 'socks5', 'http'] def serialize_proxy(p): if not isinstance(p, dict): return None return ':'.join([p.get('mode'), p.get('host'), p.get('port'), p.get('user', ''), p.get('password', '')]) def deserialize_proxy(s): if not isinstance(s, str): return None if s.lower() == 'none': return None proxy = { "mode":"socks5", "host":"localhost" } args = s.split(':') n = 0 if proxy_modes.count(args[n]) == 1: proxy["mode"] = args[n] n += 1 if len(args) > n: proxy["host"] = args[n] n += 1 if len(args) > n: proxy["port"] = args[n] n += 1 else: proxy["port"] = "8080" if proxy["mode"] == "http" else "1080" if len(args) > n: proxy["user"] = args[n] n += 1 if len(args) > n: proxy["password"] = args[n] return proxy def deserialize_server(server_str): host, port, protocol = str(server_str).split(':') assert protocol in 'st' int(port) # Throw if cannot be converted to int return host, port, protocol def serialize_server(host, port, protocol): return str(':'.join([host, port, protocol])) class Network(util.DaemonThread): """The Network class manages a set of connections to remote electrum servers, each connected socket is handled by an Interface() object. Connections are initiated by a Connection() thread which stops once the connection succeeds or fails. Our external API: - Member functions get_header(), get_interfaces(), get_local_height(), get_parameters(), get_server_height(), get_status_value(), is_connected(), set_parameters(), stop() """ def __init__(self, config=None): if config is None: config = {} # Do not use mutables as default values! util.DaemonThread.__init__(self) self.config = SimpleConfig(config) if isinstance(config, dict) else config self.num_server = 10 if not self.config.get('oneserver') else 0 self.blockchains = blockchain.read_blockchains(self.config) self.print_error("blockchains", self.blockchains.keys()) self.blockchain_index = config.get('blockchain_index', 0) if self.blockchain_index not in self.blockchains.keys(): self.blockchain_index = 0 self.protocol = 't' if self.config.get('nossl') else 's' # Server for addresses and transactions self.default_server = self.config.get('server') # Sanitize default server try: host, port, protocol = deserialize_server(self.default_server) assert protocol == self.protocol except: self.default_server = None if not self.default_server: self.default_server = pick_random_server(protocol=self.protocol) self.lock = threading.Lock() self.pending_sends = [] self.message_id = 0 self.debug = False self.irc_servers = {} # returned by interface (list from irc) self.recent_servers = self.read_recent_servers() self.banner = '' self.donation_address = '' self.relay_fee = None # callbacks passed with subscriptions self.subscriptions = defaultdict(list) self.sub_cache = {} # callbacks set by the GUI self.callbacks = defaultdict(list) dir_path = os.path.join( self.config.path, 'certs') if not os.path.exists(dir_path): os.mkdir(dir_path) os.chmod(dir_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) # subscriptions and requests self.subscribed_addresses = set() self.h2addr = {} # Requests from client we've not seen a response to self.unanswered_requests = {} # retry times self.server_retry_time = time.time() self.nodes_retry_time = time.time() # kick off the network. interface is the main server we are currently # communicating with. interfaces is the set of servers we are connecting # to or have an ongoing connection with self.interface = None self.interfaces = {} self.auto_connect = self.config.get('auto_connect', True) self.connecting = set() self.requested_chunks = set() self.socket_queue = queue.Queue() self.start_network(self.protocol, deserialize_proxy(self.config.get('proxy'))) def register_callback(self, callback, events): with self.lock: for event in events: self.callbacks[event].append(callback) def unregister_callback(self, callback): with self.lock: for callbacks in self.callbacks.values(): if callback in callbacks: callbacks.remove(callback) def trigger_callback(self, event, *args): with self.lock: callbacks = self.callbacks[event][:] [callback(event, *args) for callback in callbacks] def read_recent_servers(self): if not self.config.path: return [] path = os.path.join(self.config.path, "recent_servers") try: with open(path, "r") as f: data = f.read() return json.loads(data) except: return [] def save_recent_servers(self): if not self.config.path: return path = os.path.join(self.config.path, "recent_servers") s = json.dumps(self.recent_servers, indent=4, sort_keys=True) try: with open(path, "w") as f: f.write(s) except: pass def get_server_height(self): return self.interface.tip if self.interface else 0 def server_is_lagging(self): sh = self.get_server_height() if not sh: self.print_error('no height for main interface') return True lh = self.get_local_height() result = (lh - sh) > 1 if result: self.print_error('%s is lagging (%d vs %d)' % (self.default_server, sh, lh)) return result def set_status(self, status): self.connection_status = status self.notify('status') def is_connected(self): return self.interface is not None def is_connecting(self): return self.connection_status == 'connecting' def is_up_to_date(self): return self.unanswered_requests == {} def queue_request(self, method, params, interface=None): # If you want to queue a request on any interface it must go # through this function so message ids are properly tracked if interface is None: interface = self.interface message_id = self.message_id self.message_id += 1 if self.debug: self.print_error(interface.host, "-->", method, params, message_id) interface.queue_request(method, params, message_id) return message_id def send_subscriptions(self): self.print_error('sending subscriptions to', self.interface.server, len(self.unanswered_requests), len(self.subscribed_addresses)) self.sub_cache.clear() # Resend unanswered requests requests = self.unanswered_requests.values() self.unanswered_requests = {} for request in requests: message_id = self.queue_request(request[0], request[1]) self.unanswered_requests[message_id] = request self.queue_request('server.banner', []) self.queue_request('server.donation_address', []) self.queue_request('server.peers.subscribe', []) self.request_fee_estimates() self.queue_request('blockchain.relayfee', []) if self.interface.ping_required(): params = [ELECTRUM_VERSION, PROTOCOL_VERSION] self.queue_request('server.version', params, self.interface) for h in self.subscribed_addresses: self.queue_request('blockchain.scripthash.subscribe', [h]) def request_fee_estimates(self): self.config.requested_fee_estimates() for i in bitcoin.FEE_TARGETS: self.queue_request('blockchain.estimatefee', [i]) def get_status_value(self, key): if key == 'status': value = self.connection_status elif key == 'banner': value = self.banner elif key == 'fee': value = self.config.fee_estimates elif key == 'updated': value = (self.get_local_height(), self.get_server_height()) elif key == 'servers': value = self.get_servers() elif key == 'interfaces': value = self.get_interfaces() return value def notify(self, key): if key in ['status', 'updated']: self.trigger_callback(key) else: self.trigger_callback(key, self.get_status_value(key)) def get_parameters(self): host, port, protocol = deserialize_server(self.default_server) return host, port, protocol, self.proxy, self.auto_connect def get_donation_address(self): if self.is_connected(): return self.donation_address def get_interfaces(self): '''The interfaces that are in connected state''' return list(self.interfaces.keys()) def get_servers(self): out = NetworkConstants.DEFAULT_SERVERS if self.irc_servers: out.update(filter_version(self.irc_servers.copy())) else: for s in self.recent_servers: try: host, port, protocol = deserialize_server(s) except: continue if host not in out: out[host] = { protocol:port } return out def start_interface(self, server): if (not server in self.interfaces and not server in self.connecting): if server == self.default_server: self.print_error("connecting to %s as new interface" % server) self.set_status('connecting') self.connecting.add(server) c = Connection(server, self.socket_queue, self.config.path) def start_random_interface(self): exclude_set = self.disconnected_servers.union(set(self.interfaces)) server = pick_random_server(self.get_servers(), self.protocol, exclude_set) if server: self.start_interface(server) def start_interfaces(self): self.start_interface(self.default_server) for i in range(self.num_server - 1): self.start_random_interface() def set_proxy(self, proxy): self.proxy = proxy # Store these somewhere so we can un-monkey-patch if not hasattr(socket, "_socketobject"): socket._socketobject = socket.socket socket._getaddrinfo = socket.getaddrinfo if proxy: self.print_error('setting proxy', proxy) proxy_mode = proxy_modes.index(proxy["mode"]) + 1 socks.setdefaultproxy(proxy_mode, proxy["host"], int(proxy["port"]), # socks.py seems to want either None or a non-empty string username=(proxy.get("user", "") or None), password=(proxy.get("password", "") or None)) socket.socket = socks.socksocket # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy socket.getaddrinfo = lambda *args: [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))] else: socket.socket = socket._socketobject socket.getaddrinfo = socket._getaddrinfo def start_network(self, protocol, proxy): assert not self.interface and not self.interfaces assert not self.connecting and self.socket_queue.empty() self.print_error('starting network') self.disconnected_servers = set([]) self.protocol = protocol self.set_proxy(proxy) self.start_interfaces() def stop_network(self): self.print_error("stopping network") for interface in list(self.interfaces.values()): self.close_interface(interface) if self.interface: self.close_interface(self.interface) assert self.interface is None assert not self.interfaces self.connecting = set() # Get a new queue - no old pending connections thanks! self.socket_queue = queue.Queue() def set_parameters(self, host, port, protocol, proxy, auto_connect): proxy_str = serialize_proxy(proxy) server = serialize_server(host, port, protocol) # sanitize parameters try: deserialize_server(serialize_server(host, port, protocol)) if proxy: proxy_modes.index(proxy["mode"]) + 1 int(proxy['port']) except: return self.config.set_key('auto_connect', auto_connect, False) self.config.set_key("proxy", proxy_str, False) self.config.set_key("server", server, True) # abort if changes were not allowed by config if self.config.get('server') != server or self.config.get('proxy') != proxy_str: return self.auto_connect = auto_connect if self.proxy != proxy or self.protocol != protocol: # Restart the network defaulting to the given server self.stop_network() self.default_server = server self.start_network(protocol, proxy) elif self.default_server != server: self.switch_to_interface(server) else: self.switch_lagging_interface() self.notify('updated') def switch_to_random_interface(self): '''Switch to a random connected server other than the current one''' servers = self.get_interfaces() # Those in connected state if self.default_server in servers: servers.remove(self.default_server) if servers: self.switch_to_interface(random.choice(servers)) def switch_lagging_interface(self): '''If auto_connect and lagging, switch interface''' if self.server_is_lagging() and self.auto_connect: # switch to one that has the correct header (not height) header = self.blockchain().read_header(self.get_local_height()) filtered = list(map(lambda x:x[0], filter(lambda x: x[1].tip_header==header, self.interfaces.items()))) if filtered: choice = random.choice(filtered) self.switch_to_interface(choice) def switch_to_interface(self, server): '''Switch to server as our interface. If no connection exists nor being opened, start a thread to connect. The actual switch will happen on receipt of the connection notification. Do nothing if server already is our interface.''' self.default_server = server if server not in self.interfaces: self.interface = None self.start_interface(server) return i = self.interfaces[server] if self.interface != i: self.print_error("switching to", server) # stop any current interface in order to terminate subscriptions # fixme: we don't want to close headers sub #self.close_interface(self.interface) self.interface = i self.send_subscriptions() self.set_status('connected') self.notify('updated') def close_interface(self, interface): if interface: if interface.server in self.interfaces: self.interfaces.pop(interface.server) if interface.server == self.default_server: self.interface = None interface.close() def add_recent_server(self, server): # list is ordered if server in self.recent_servers: self.recent_servers.remove(server) self.recent_servers.insert(0, server) self.recent_servers = self.recent_servers[0:20] self.save_recent_servers() def process_response(self, interface, response, callbacks): if self.debug: self.print_error("<--", response) error = response.get('error') result = response.get('result') method = response.get('method') params = response.get('params') # We handle some responses; return the rest to the client. if method == 'server.version': interface.server_version = result elif method == 'blockchain.headers.subscribe': if error is None: self.on_notify_header(interface, result) elif method == 'server.peers.subscribe': if error is None: self.irc_servers = parse_servers(result) self.notify('servers') elif method == 'server.banner': if error is None: self.banner = result self.notify('banner') elif method == 'server.donation_address': if error is None: self.donation_address = result elif method == 'blockchain.estimatefee': if error is None and result > 0: i = params[0] fee = int(result*COIN) self.config.update_fee_estimates(i, fee) self.print_error("fee_estimates[%d]" % i, fee) self.notify('fee') elif method == 'blockchain.relayfee': if error is None: self.relay_fee = int(result * COIN) self.print_error("relayfee", self.relay_fee) elif method == 'blockchain.block.get_chunk': self.on_get_chunk(interface, response) elif method == 'blockchain.block.get_header': self.on_get_header(interface, response) for callback in callbacks: callback(response) def get_index(self, method, params): """ hashable index for subscriptions and cache""" return str(method) + (':' + str(params[0]) if params else '') def process_responses(self, interface): responses = interface.get_responses() for request, response in responses: if request: method, params, message_id = request k = self.get_index(method, params) # client requests go through self.send() with a # callback, are only sent to the current interface, # and are placed in the unanswered_requests dictionary client_req = self.unanswered_requests.pop(message_id, None) if client_req: assert interface == self.interface callbacks = [client_req[2]] else: # fixme: will only work for subscriptions k = self.get_index(method, params) callbacks = self.subscriptions.get(k, []) # Copy the request method and params to the response response['method'] = method response['params'] = params # Only once we've received a response to an addr subscription # add it to the list; avoids double-sends on reconnection if method == 'blockchain.scripthash.subscribe': self.subscribed_addresses.add(params[0]) else: if not response: # Closed remotely / misbehaving self.connection_down(interface.server) break # Rewrite response shape to match subscription request response method = response.get('method') params = response.get('params') k = self.get_index(method, params) if method == 'blockchain.headers.subscribe': response['result'] = params[0] response['params'] = [] elif method == 'blockchain.scripthash.subscribe': response['params'] = [params[0]] # addr response['result'] = params[1] callbacks = self.subscriptions.get(k, []) # update cache if it's a subscription if method.endswith('.subscribe'): self.sub_cache[k] = response # Response is now in canonical form self.process_response(interface, response, callbacks) def addr_to_scripthash(self, addr): h = bitcoin.address_to_scripthash(addr) if h not in self.h2addr: self.h2addr[h] = addr return h def overload_cb(self, callback): def cb2(x): x2 = x.copy() p = x2.pop('params') addr = self.h2addr[p[0]] x2['params'] = [addr] callback(x2) return cb2 def subscribe_to_addresses(self, addresses, callback): hashes = [self.addr_to_scripthash(addr) for addr in addresses] msgs = [('blockchain.scripthash.subscribe', [x]) for x in hashes] self.send(msgs, self.overload_cb(callback)) def request_address_history(self, address, callback): h = self.addr_to_scripthash(address) self.send([('blockchain.scripthash.get_history', [h])], self.overload_cb(callback)) def send(self, messages, callback): '''Messages is a list of (method, params) tuples''' messages = list(messages) with self.lock: self.pending_sends.append((messages, callback)) def process_pending_sends(self): # Requests needs connectivity. If we don't have an interface, # we cannot process them. if not self.interface: return with self.lock: sends = self.pending_sends self.pending_sends = [] for messages, callback in sends: for method, params in messages: r = None if method.endswith('.subscribe'): k = self.get_index(method, params) # add callback to list l = self.subscriptions.get(k, []) if callback not in l: l.append(callback) self.subscriptions[k] = l # check cached response for subscriptions r = self.sub_cache.get(k) if r is not None: util.print_error("cache hit", k) callback(r) else: message_id = self.queue_request(method, params) self.unanswered_requests[message_id] = method, params, callback def unsubscribe(self, callback): '''Unsubscribe a callback to free object references to enable GC.''' # Note: we can't unsubscribe from the server, so if we receive # subsequent notifications process_response() will emit a harmless # "received unexpected notification" warning with self.lock: for v in self.subscriptions.values(): if callback in v: v.remove(callback) def connection_down(self, server): '''A connection to server either went down, or was never made. We distinguish by whether it is in self.interfaces.''' self.disconnected_servers.add(server) if server == self.default_server: self.set_status('disconnected') if server in self.interfaces: self.close_interface(self.interfaces[server]) self.notify('interfaces') for b in self.blockchains.values(): if b.catch_up == server: b.catch_up = None def new_interface(self, server, socket): # todo: get tip first, then decide which checkpoint to use. self.add_recent_server(server) interface = Interface(server, socket) interface.blockchain = None interface.tip_header = None interface.tip = 0 interface.mode = 'default' interface.request = None self.interfaces[server] = interface self.queue_request('blockchain.headers.subscribe', [], interface) if server == self.default_server: self.switch_to_interface(server) #self.notify('interfaces') def maintain_sockets(self): '''Socket maintenance.''' # Responses to connection attempts? while not self.socket_queue.empty(): server, socket = self.socket_queue.get() if server in self.connecting: self.connecting.remove(server) if socket: self.new_interface(server, socket) else: self.connection_down(server) # Send pings and shut down stale interfaces # must use copy of values for interface in list(self.interfaces.values()): if interface.has_timed_out(): self.connection_down(interface.server) elif interface.ping_required(): params = [ELECTRUM_VERSION, PROTOCOL_VERSION] self.queue_request('server.version', params, interface) now = time.time() # nodes if len(self.interfaces) + len(self.connecting) < self.num_server: self.start_random_interface() if now - self.nodes_retry_time > NODES_RETRY_INTERVAL: self.print_error('network: retrying connections') self.disconnected_servers = set([]) self.nodes_retry_time = now # main interface if not self.is_connected(): if self.auto_connect: if not self.is_connecting(): self.switch_to_random_interface() else: if self.default_server in self.disconnected_servers: if now - self.server_retry_time > SERVER_RETRY_INTERVAL: self.disconnected_servers.remove(self.default_server) self.server_retry_time = now else: self.switch_to_interface(self.default_server) else: if self.config.is_fee_estimates_update_required(): self.request_fee_estimates() def request_chunk(self, interface, index): if index in self.requested_chunks: return interface.print_error("requesting chunk %d" % index) self.requested_chunks.add(index) self.queue_request('blockchain.block.get_chunk', [index], interface) def on_get_chunk(self, interface, response): '''Handle receiving a chunk of block headers''' error = response.get('error') result = response.get('result') params = response.get('params') if result is None or params is None or error is not None: interface.print_error(error or 'bad response') return index = params[0] # Ignore unsolicited chunks if index not in self.requested_chunks: return self.requested_chunks.remove(index) connect = interface.blockchain.connect_chunk(index, result) if not connect: self.connection_down(interface.server) return # If not finished, get the next chunk if interface.blockchain.height() < interface.tip: self.request_chunk(interface, index+1) else: interface.mode = 'default' interface.print_error('catch up done', interface.blockchain.height()) interface.blockchain.catch_up = None self.notify('updated') def request_header(self, interface, height): interface.print_error("requesting header %d" % height) self.queue_request('blockchain.block.get_header', [height], interface) interface.request = height interface.req_time = time.time() def on_get_header(self, interface, response): '''Handle receiving a single block header''' header = response.get('result') if not header: interface.print_error(response) self.connection_down(interface.server) return height = header.get('block_height') if int(interface.request) != height: interface.print_error("unsolicited header",interface.request, height) self.connection_down(interface.server) return interface.print_error("interface.mode %s" % interface.mode) chain = blockchain.check_header(header) if interface.mode == 'backward': can_connect = blockchain.can_connect(header) if can_connect and can_connect.catch_up is None: interface.mode = 'catch_up' interface.blockchain = can_connect interface.blockchain.save_header(header) next_height = height + 1 interface.blockchain.catch_up = interface.server elif chain: interface.print_error("binary search") interface.mode = 'binary' interface.blockchain = chain interface.good = height next_height = (interface.bad + interface.good) // 2 else: if height == 0: self.connection_down(interface.server) next_height = None else: interface.bad = height interface.bad_header = header delta = interface.tip - height next_height = max(0, interface.tip - 2 * delta) elif interface.mode == 'binary': if chain: interface.good = height interface.blockchain = chain else: interface.bad = height interface.bad_header = header if interface.bad != interface.good + 1: next_height = (interface.bad + interface.good) // 2 elif not interface.blockchain.can_connect(interface.bad_header, check_height=False): self.connection_down(interface.server) next_height = None else: branch = self.blockchains.get(interface.bad) if branch is not None: if branch.check_header(interface.bad_header): interface.print_error('joining chain', interface.bad) next_height = None elif branch.parent().check_header(header): interface.print_error('reorg', interface.bad, interface.tip) interface.blockchain = branch.parent() next_height = None else: interface.print_error('checkpoint conflicts with existing fork', branch.path()) branch.write('', 0) branch.save_header(interface.bad_header) interface.mode = 'catch_up' interface.blockchain = branch next_height = interface.bad + 1 interface.blockchain.catch_up = interface.server else: bh = interface.blockchain.height() next_height = None if bh > interface.good: if not interface.blockchain.check_header(interface.bad_header): b = interface.blockchain.fork(interface.bad_header) self.blockchains[interface.bad] = b interface.blockchain = b interface.print_error("new chain", b.checkpoint) interface.mode = 'catch_up' next_height = interface.bad + 1 interface.blockchain.catch_up = interface.server else: assert bh == interface.good if interface.blockchain.catch_up is None and bh < interface.tip: interface.print_error("catching up from %d"% (bh + 1)) interface.mode = 'catch_up' next_height = bh + 1 interface.blockchain.catch_up = interface.server self.notify('updated') elif interface.mode == 'catch_up': can_connect = interface.blockchain.can_connect(header) if can_connect: interface.blockchain.save_header(header) next_height = height + 1 if height < interface.tip else None else: # go back interface.print_error("cannot connect", height) interface.mode = 'backward' interface.bad = height interface.bad_header = header next_height = height - 1 if next_height is None: # exit catch_up state interface.print_error('catch up done', interface.blockchain.height()) interface.blockchain.catch_up = None self.switch_lagging_interface() self.notify('updated') else: raise BaseException(interface.mode) # If not finished, get the next header if next_height: if interface.mode == 'catch_up' and interface.tip > next_height + 50: self.request_chunk(interface, next_height // NetworkConstants.CHUNK_SIZE) else: self.request_header(interface, next_height) else: interface.mode = 'default' interface.request = None self.notify('updated') # refresh network dialog self.notify('interfaces') def maintain_requests(self): for interface in list(self.interfaces.values()): if interface.request and time.time() - interface.request_time > 20: interface.print_error("blockchain request timed out") self.connection_down(interface.server) continue def wait_on_sockets(self): # Python docs say Windows doesn't like empty selects. # Sleep to prevent busy looping if not self.interfaces: time.sleep(0.1) return rin = [i for i in self.interfaces.values()] win = [i for i in self.interfaces.values() if i.num_requests()] try: rout, wout, xout = select.select(rin, win, [], 0.1) except socket.error as e: # TODO: py3, get code from e code = None if code == errno.EINTR: return raise assert not xout for interface in wout: interface.send_requests() for interface in rout: self.process_responses(interface) def init_headers_file(self): b = self.blockchains[0] print(b.get_hash(0), NetworkConstants.GENESIS) if b.get_hash(0) == NetworkConstants.GENESIS: self.downloading_headers = False return filename = b.path() def download_thread(): try: import urllib, socket socket.setdefaulttimeout(30) self.print_error("downloading ", NetworkConstants.HEADERS_URL) urllib.request.urlretrieve(NetworkConstants.HEADERS_URL, filename) self.print_error("done.") except Exception: import traceback traceback.print_exc() self.print_error("download failed. creating file", filename) open(filename, 'wb+').close() b = self.blockchains[0] with b.lock: b.update_size() self.downloading_headers = False self.downloading_headers = True t = threading.Thread(target = download_thread) t.daemon = True t.start() def run(self): self.init_headers_file() while self.is_running() and self.downloading_headers: time.sleep(1) while self.is_running(): self.maintain_sockets() self.wait_on_sockets() self.maintain_requests() self.run_jobs() # Synchronizer and Verifier self.process_pending_sends() self.stop_network() self.on_stop() def on_notify_header(self, interface, header): height = header.get('block_height') if not height: return interface.tip_header = header interface.tip = height if interface.mode != 'default': return b = blockchain.check_header(header) if b: interface.blockchain = b self.switch_lagging_interface() self.notify('updated') self.notify('interfaces') return b = blockchain.can_connect(header) if b: interface.blockchain = b b.save_header(header) self.switch_lagging_interface() self.notify('updated') self.notify('interfaces') return tip = max([x.height() for x in self.blockchains.values()]) if tip >=0: interface.mode = 'backward' interface.bad = height interface.bad_header = header self.request_header(interface, min(tip +1, height - 1)) else: chain = self.blockchains[0] if chain.catch_up is None: chain.catch_up = interface interface.mode = 'catch_up' interface.blockchain = chain self.print_error("switching to catchup mode", tip, self.blockchains) self.request_header(interface, 0) else: self.print_error("chain already catching up with", chain.catch_up.server) def blockchain(self): if self.interface and self.interface.blockchain is not None: self.blockchain_index = self.interface.blockchain.checkpoint return self.blockchains[self.blockchain_index] def get_blockchains(self): out = {} for k, b in self.blockchains.items(): r = list(filter(lambda i: i.blockchain==b, list(self.interfaces.values()))) if r: out[k] = r return out def follow_chain(self, index): blockchain = self.blockchains.get(index) if blockchain: self.blockchain_index = index self.config.set_key('blockchain_index', index) for i in self.interfaces.values(): if i.blockchain == blockchain: self.switch_to_interface(i.server) break else: raise BaseException('blockchain not found', index) if self.interface: server = self.interface.server host, port, protocol, proxy, auto_connect = self.get_parameters() host, port, protocol = server.split(':') self.set_parameters(host, port, protocol, proxy, auto_connect) def get_local_height(self): return self.blockchain().height() def synchronous_get(self, request, timeout=30): q = queue.Queue() self.send([request], q.put) try: r = q.get(True, timeout) except queue.Empty: raise BaseException('Server did not answer') if r.get('error'): raise BaseException(r.get('error')) return r.get('result') def broadcast(self, tx, timeout=30): tx_hash = tx.txid() try: out = self.synchronous_get(('blockchain.transaction.broadcast', [str(tx)]), timeout) except BaseException as e: return False, "error: " + str(e) if out != tx_hash: return False, "error: " + out return True, out
39.72968
138
0.588796
import time import queue import os import stat import errno import random import re import select from collections import defaultdict import threading import socket import json import socks from . import util from . import bitcoin from .bitcoin import * from .interface import Connection, Interface from . import blockchain from .version import ELECTRUM_VERSION, PROTOCOL_VERSION NODES_RETRY_INTERVAL = 60 SERVER_RETRY_INTERVAL = 10 def parse_servers(result): from .version import PROTOCOL_VERSION servers = {} for item in result: host = item[1] out = {} version = None pruning_level = '-' if len(item) > 2: for v in item[2]: if re.match("[st]\d*", v): protocol, port = v[0], v[1:] if port == '': port = NetworkConstants.DEFAULT_PORTS[protocol] out[protocol] = port elif re.match("v(.?)+", v): version = v[1:] elif re.match("p\d*", v): pruning_level = v[1:] if pruning_level == '': pruning_level = '0' if out: out['pruning'] = pruning_level out['version'] = version servers[host] = out return servers def filter_version(servers): def is_recent(version): try: return util.normalize_version(version) >= util.normalize_version(PROTOCOL_VERSION) except Exception as e: return False return {k: v for k, v in servers.items() if is_recent(v.get('version'))} def filter_protocol(hostmap, protocol = 's'): eligible = [] for host, portmap in hostmap.items(): port = portmap.get(protocol) if port: eligible.append(serialize_server(host, port, protocol)) return eligible def pick_random_server(hostmap = None, protocol = 's', exclude_set = set()): if hostmap is None: hostmap = NetworkConstants.DEFAULT_SERVERS eligible = list(set(filter_protocol(hostmap, protocol)) - exclude_set) return random.choice(eligible) if eligible else None from .simple_config import SimpleConfig proxy_modes = ['socks4', 'socks5', 'http'] def serialize_proxy(p): if not isinstance(p, dict): return None return ':'.join([p.get('mode'), p.get('host'), p.get('port'), p.get('user', ''), p.get('password', '')]) def deserialize_proxy(s): if not isinstance(s, str): return None if s.lower() == 'none': return None proxy = { "mode":"socks5", "host":"localhost" } args = s.split(':') n = 0 if proxy_modes.count(args[n]) == 1: proxy["mode"] = args[n] n += 1 if len(args) > n: proxy["host"] = args[n] n += 1 if len(args) > n: proxy["port"] = args[n] n += 1 else: proxy["port"] = "8080" if proxy["mode"] == "http" else "1080" if len(args) > n: proxy["user"] = args[n] n += 1 if len(args) > n: proxy["password"] = args[n] return proxy def deserialize_server(server_str): host, port, protocol = str(server_str).split(':') assert protocol in 'st' int(port) return host, port, protocol def serialize_server(host, port, protocol): return str(':'.join([host, port, protocol])) class Network(util.DaemonThread): def __init__(self, config=None): if config is None: config = {} util.DaemonThread.__init__(self) self.config = SimpleConfig(config) if isinstance(config, dict) else config self.num_server = 10 if not self.config.get('oneserver') else 0 self.blockchains = blockchain.read_blockchains(self.config) self.print_error("blockchains", self.blockchains.keys()) self.blockchain_index = config.get('blockchain_index', 0) if self.blockchain_index not in self.blockchains.keys(): self.blockchain_index = 0 self.protocol = 't' if self.config.get('nossl') else 's' self.default_server = self.config.get('server') try: host, port, protocol = deserialize_server(self.default_server) assert protocol == self.protocol except: self.default_server = None if not self.default_server: self.default_server = pick_random_server(protocol=self.protocol) self.lock = threading.Lock() self.pending_sends = [] self.message_id = 0 self.debug = False self.irc_servers = {} self.recent_servers = self.read_recent_servers() self.banner = '' self.donation_address = '' self.relay_fee = None self.subscriptions = defaultdict(list) self.sub_cache = {} self.callbacks = defaultdict(list) dir_path = os.path.join( self.config.path, 'certs') if not os.path.exists(dir_path): os.mkdir(dir_path) os.chmod(dir_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) self.subscribed_addresses = set() self.h2addr = {} self.unanswered_requests = {} # retry times self.server_retry_time = time.time() self.nodes_retry_time = time.time() # kick off the network. interface is the main server we are currently # communicating with. interfaces is the set of servers we are connecting # to or have an ongoing connection with self.interface = None self.interfaces = {} self.auto_connect = self.config.get('auto_connect', True) self.connecting = set() self.requested_chunks = set() self.socket_queue = queue.Queue() self.start_network(self.protocol, deserialize_proxy(self.config.get('proxy'))) def register_callback(self, callback, events): with self.lock: for event in events: self.callbacks[event].append(callback) def unregister_callback(self, callback): with self.lock: for callbacks in self.callbacks.values(): if callback in callbacks: callbacks.remove(callback) def trigger_callback(self, event, *args): with self.lock: callbacks = self.callbacks[event][:] [callback(event, *args) for callback in callbacks] def read_recent_servers(self): if not self.config.path: return [] path = os.path.join(self.config.path, "recent_servers") try: with open(path, "r") as f: data = f.read() return json.loads(data) except: return [] def save_recent_servers(self): if not self.config.path: return path = os.path.join(self.config.path, "recent_servers") s = json.dumps(self.recent_servers, indent=4, sort_keys=True) try: with open(path, "w") as f: f.write(s) except: pass def get_server_height(self): return self.interface.tip if self.interface else 0 def server_is_lagging(self): sh = self.get_server_height() if not sh: self.print_error('no height for main interface') return True lh = self.get_local_height() result = (lh - sh) > 1 if result: self.print_error('%s is lagging (%d vs %d)' % (self.default_server, sh, lh)) return result def set_status(self, status): self.connection_status = status self.notify('status') def is_connected(self): return self.interface is not None def is_connecting(self): return self.connection_status == 'connecting' def is_up_to_date(self): return self.unanswered_requests == {} def queue_request(self, method, params, interface=None): # If you want to queue a request on any interface it must go # through this function so message ids are properly tracked if interface is None: interface = self.interface message_id = self.message_id self.message_id += 1 if self.debug: self.print_error(interface.host, "-->", method, params, message_id) interface.queue_request(method, params, message_id) return message_id def send_subscriptions(self): self.print_error('sending subscriptions to', self.interface.server, len(self.unanswered_requests), len(self.subscribed_addresses)) self.sub_cache.clear() # Resend unanswered requests requests = self.unanswered_requests.values() self.unanswered_requests = {} for request in requests: message_id = self.queue_request(request[0], request[1]) self.unanswered_requests[message_id] = request self.queue_request('server.banner', []) self.queue_request('server.donation_address', []) self.queue_request('server.peers.subscribe', []) self.request_fee_estimates() self.queue_request('blockchain.relayfee', []) if self.interface.ping_required(): params = [ELECTRUM_VERSION, PROTOCOL_VERSION] self.queue_request('server.version', params, self.interface) for h in self.subscribed_addresses: self.queue_request('blockchain.scripthash.subscribe', [h]) def request_fee_estimates(self): self.config.requested_fee_estimates() for i in bitcoin.FEE_TARGETS: self.queue_request('blockchain.estimatefee', [i]) def get_status_value(self, key): if key == 'status': value = self.connection_status elif key == 'banner': value = self.banner elif key == 'fee': value = self.config.fee_estimates elif key == 'updated': value = (self.get_local_height(), self.get_server_height()) elif key == 'servers': value = self.get_servers() elif key == 'interfaces': value = self.get_interfaces() return value def notify(self, key): if key in ['status', 'updated']: self.trigger_callback(key) else: self.trigger_callback(key, self.get_status_value(key)) def get_parameters(self): host, port, protocol = deserialize_server(self.default_server) return host, port, protocol, self.proxy, self.auto_connect def get_donation_address(self): if self.is_connected(): return self.donation_address def get_interfaces(self): return list(self.interfaces.keys()) def get_servers(self): out = NetworkConstants.DEFAULT_SERVERS if self.irc_servers: out.update(filter_version(self.irc_servers.copy())) else: for s in self.recent_servers: try: host, port, protocol = deserialize_server(s) except: continue if host not in out: out[host] = { protocol:port } return out def start_interface(self, server): if (not server in self.interfaces and not server in self.connecting): if server == self.default_server: self.print_error("connecting to %s as new interface" % server) self.set_status('connecting') self.connecting.add(server) c = Connection(server, self.socket_queue, self.config.path) def start_random_interface(self): exclude_set = self.disconnected_servers.union(set(self.interfaces)) server = pick_random_server(self.get_servers(), self.protocol, exclude_set) if server: self.start_interface(server) def start_interfaces(self): self.start_interface(self.default_server) for i in range(self.num_server - 1): self.start_random_interface() def set_proxy(self, proxy): self.proxy = proxy # Store these somewhere so we can un-monkey-patch if not hasattr(socket, "_socketobject"): socket._socketobject = socket.socket socket._getaddrinfo = socket.getaddrinfo if proxy: self.print_error('setting proxy', proxy) proxy_mode = proxy_modes.index(proxy["mode"]) + 1 socks.setdefaultproxy(proxy_mode, proxy["host"], int(proxy["port"]), # socks.py seems to want either None or a non-empty string username=(proxy.get("user", "") or None), password=(proxy.get("password", "") or None)) socket.socket = socks.socksocket # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy socket.getaddrinfo = lambda *args: [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))] else: socket.socket = socket._socketobject socket.getaddrinfo = socket._getaddrinfo def start_network(self, protocol, proxy): assert not self.interface and not self.interfaces assert not self.connecting and self.socket_queue.empty() self.print_error('starting network') self.disconnected_servers = set([]) self.protocol = protocol self.set_proxy(proxy) self.start_interfaces() def stop_network(self): self.print_error("stopping network") for interface in list(self.interfaces.values()): self.close_interface(interface) if self.interface: self.close_interface(self.interface) assert self.interface is None assert not self.interfaces self.connecting = set() # Get a new queue - no old pending connections thanks! self.socket_queue = queue.Queue() def set_parameters(self, host, port, protocol, proxy, auto_connect): proxy_str = serialize_proxy(proxy) server = serialize_server(host, port, protocol) # sanitize parameters try: deserialize_server(serialize_server(host, port, protocol)) if proxy: proxy_modes.index(proxy["mode"]) + 1 int(proxy['port']) except: return self.config.set_key('auto_connect', auto_connect, False) self.config.set_key("proxy", proxy_str, False) self.config.set_key("server", server, True) # abort if changes were not allowed by config if self.config.get('server') != server or self.config.get('proxy') != proxy_str: return self.auto_connect = auto_connect if self.proxy != proxy or self.protocol != protocol: # Restart the network defaulting to the given server self.stop_network() self.default_server = server self.start_network(protocol, proxy) elif self.default_server != server: self.switch_to_interface(server) else: self.switch_lagging_interface() self.notify('updated') def switch_to_random_interface(self): servers = self.get_interfaces() # Those in connected state if self.default_server in servers: servers.remove(self.default_server) if servers: self.switch_to_interface(random.choice(servers)) def switch_lagging_interface(self): if self.server_is_lagging() and self.auto_connect: # switch to one that has the correct header (not height) header = self.blockchain().read_header(self.get_local_height()) filtered = list(map(lambda x:x[0], filter(lambda x: x[1].tip_header==header, self.interfaces.items()))) if filtered: choice = random.choice(filtered) self.switch_to_interface(choice) def switch_to_interface(self, server): self.default_server = server if server not in self.interfaces: self.interface = None self.start_interface(server) return i = self.interfaces[server] if self.interface != i: self.print_error("switching to", server) # stop any current interface in order to terminate subscriptions # fixme: we don't want to close headers sub self.interface = i self.send_subscriptions() self.set_status('connected') self.notify('updated') def close_interface(self, interface): if interface: if interface.server in self.interfaces: self.interfaces.pop(interface.server) if interface.server == self.default_server: self.interface = None interface.close() def add_recent_server(self, server): if server in self.recent_servers: self.recent_servers.remove(server) self.recent_servers.insert(0, server) self.recent_servers = self.recent_servers[0:20] self.save_recent_servers() def process_response(self, interface, response, callbacks): if self.debug: self.print_error("<--", response) error = response.get('error') result = response.get('result') method = response.get('method') params = response.get('params') if method == 'server.version': interface.server_version = result elif method == 'blockchain.headers.subscribe': if error is None: self.on_notify_header(interface, result) elif method == 'server.peers.subscribe': if error is None: self.irc_servers = parse_servers(result) self.notify('servers') elif method == 'server.banner': if error is None: self.banner = result self.notify('banner') elif method == 'server.donation_address': if error is None: self.donation_address = result elif method == 'blockchain.estimatefee': if error is None and result > 0: i = params[0] fee = int(result*COIN) self.config.update_fee_estimates(i, fee) self.print_error("fee_estimates[%d]" % i, fee) self.notify('fee') elif method == 'blockchain.relayfee': if error is None: self.relay_fee = int(result * COIN) self.print_error("relayfee", self.relay_fee) elif method == 'blockchain.block.get_chunk': self.on_get_chunk(interface, response) elif method == 'blockchain.block.get_header': self.on_get_header(interface, response) for callback in callbacks: callback(response) def get_index(self, method, params): return str(method) + (':' + str(params[0]) if params else '') def process_responses(self, interface): responses = interface.get_responses() for request, response in responses: if request: method, params, message_id = request k = self.get_index(method, params) client_req = self.unanswered_requests.pop(message_id, None) if client_req: assert interface == self.interface callbacks = [client_req[2]] else: k = self.get_index(method, params) callbacks = self.subscriptions.get(k, []) response['method'] = method response['params'] = params # add it to the list; avoids double-sends on reconnection if method == 'blockchain.scripthash.subscribe': self.subscribed_addresses.add(params[0]) else: if not response: # Closed remotely / misbehaving self.connection_down(interface.server) break # Rewrite response shape to match subscription request response method = response.get('method') params = response.get('params') k = self.get_index(method, params) if method == 'blockchain.headers.subscribe': response['result'] = params[0] response['params'] = [] elif method == 'blockchain.scripthash.subscribe': response['params'] = [params[0]] # addr response['result'] = params[1] callbacks = self.subscriptions.get(k, []) # update cache if it's a subscription if method.endswith('.subscribe'): self.sub_cache[k] = response self.process_response(interface, response, callbacks) def addr_to_scripthash(self, addr): h = bitcoin.address_to_scripthash(addr) if h not in self.h2addr: self.h2addr[h] = addr return h def overload_cb(self, callback): def cb2(x): x2 = x.copy() p = x2.pop('params') addr = self.h2addr[p[0]] x2['params'] = [addr] callback(x2) return cb2 def subscribe_to_addresses(self, addresses, callback): hashes = [self.addr_to_scripthash(addr) for addr in addresses] msgs = [('blockchain.scripthash.subscribe', [x]) for x in hashes] self.send(msgs, self.overload_cb(callback)) def request_address_history(self, address, callback): h = self.addr_to_scripthash(address) self.send([('blockchain.scripthash.get_history', [h])], self.overload_cb(callback)) def send(self, messages, callback): messages = list(messages) with self.lock: self.pending_sends.append((messages, callback)) def process_pending_sends(self): # we cannot process them. if not self.interface: return with self.lock: sends = self.pending_sends self.pending_sends = [] for messages, callback in sends: for method, params in messages: r = None if method.endswith('.subscribe'): k = self.get_index(method, params) # add callback to list l = self.subscriptions.get(k, []) if callback not in l: l.append(callback) self.subscriptions[k] = l # check cached response for subscriptions r = self.sub_cache.get(k) if r is not None: util.print_error("cache hit", k) callback(r) else: message_id = self.queue_request(method, params) self.unanswered_requests[message_id] = method, params, callback def unsubscribe(self, callback): # Note: we can't unsubscribe from the server, so if we receive with self.lock: for v in self.subscriptions.values(): if callback in v: v.remove(callback) def connection_down(self, server): self.disconnected_servers.add(server) if server == self.default_server: self.set_status('disconnected') if server in self.interfaces: self.close_interface(self.interfaces[server]) self.notify('interfaces') for b in self.blockchains.values(): if b.catch_up == server: b.catch_up = None def new_interface(self, server, socket): self.add_recent_server(server) interface = Interface(server, socket) interface.blockchain = None interface.tip_header = None interface.tip = 0 interface.mode = 'default' interface.request = None self.interfaces[server] = interface self.queue_request('blockchain.headers.subscribe', [], interface) if server == self.default_server: self.switch_to_interface(server) def maintain_sockets(self): while not self.socket_queue.empty(): server, socket = self.socket_queue.get() if server in self.connecting: self.connecting.remove(server) if socket: self.new_interface(server, socket) else: self.connection_down(server) for interface in list(self.interfaces.values()): if interface.has_timed_out(): self.connection_down(interface.server) elif interface.ping_required(): params = [ELECTRUM_VERSION, PROTOCOL_VERSION] self.queue_request('server.version', params, interface) now = time.time() if len(self.interfaces) + len(self.connecting) < self.num_server: self.start_random_interface() if now - self.nodes_retry_time > NODES_RETRY_INTERVAL: self.print_error('network: retrying connections') self.disconnected_servers = set([]) self.nodes_retry_time = now if not self.is_connected(): if self.auto_connect: if not self.is_connecting(): self.switch_to_random_interface() else: if self.default_server in self.disconnected_servers: if now - self.server_retry_time > SERVER_RETRY_INTERVAL: self.disconnected_servers.remove(self.default_server) self.server_retry_time = now else: self.switch_to_interface(self.default_server) else: if self.config.is_fee_estimates_update_required(): self.request_fee_estimates() def request_chunk(self, interface, index): if index in self.requested_chunks: return interface.print_error("requesting chunk %d" % index) self.requested_chunks.add(index) self.queue_request('blockchain.block.get_chunk', [index], interface) def on_get_chunk(self, interface, response): error = response.get('error') result = response.get('result') params = response.get('params') if result is None or params is None or error is not None: interface.print_error(error or 'bad response') return index = params[0] if index not in self.requested_chunks: return self.requested_chunks.remove(index) connect = interface.blockchain.connect_chunk(index, result) if not connect: self.connection_down(interface.server) return if interface.blockchain.height() < interface.tip: self.request_chunk(interface, index+1) else: interface.mode = 'default' interface.print_error('catch up done', interface.blockchain.height()) interface.blockchain.catch_up = None self.notify('updated') def request_header(self, interface, height): interface.print_error("requesting header %d" % height) self.queue_request('blockchain.block.get_header', [height], interface) interface.request = height interface.req_time = time.time() def on_get_header(self, interface, response): header = response.get('result') if not header: interface.print_error(response) self.connection_down(interface.server) return height = header.get('block_height') if int(interface.request) != height: interface.print_error("unsolicited header",interface.request, height) self.connection_down(interface.server) return interface.print_error("interface.mode %s" % interface.mode) chain = blockchain.check_header(header) if interface.mode == 'backward': can_connect = blockchain.can_connect(header) if can_connect and can_connect.catch_up is None: interface.mode = 'catch_up' interface.blockchain = can_connect interface.blockchain.save_header(header) next_height = height + 1 interface.blockchain.catch_up = interface.server elif chain: interface.print_error("binary search") interface.mode = 'binary' interface.blockchain = chain interface.good = height next_height = (interface.bad + interface.good) // 2 else: if height == 0: self.connection_down(interface.server) next_height = None else: interface.bad = height interface.bad_header = header delta = interface.tip - height next_height = max(0, interface.tip - 2 * delta) elif interface.mode == 'binary': if chain: interface.good = height interface.blockchain = chain else: interface.bad = height interface.bad_header = header if interface.bad != interface.good + 1: next_height = (interface.bad + interface.good) // 2 elif not interface.blockchain.can_connect(interface.bad_header, check_height=False): self.connection_down(interface.server) next_height = None else: branch = self.blockchains.get(interface.bad) if branch is not None: if branch.check_header(interface.bad_header): interface.print_error('joining chain', interface.bad) next_height = None elif branch.parent().check_header(header): interface.print_error('reorg', interface.bad, interface.tip) interface.blockchain = branch.parent() next_height = None else: interface.print_error('checkpoint conflicts with existing fork', branch.path()) branch.write('', 0) branch.save_header(interface.bad_header) interface.mode = 'catch_up' interface.blockchain = branch next_height = interface.bad + 1 interface.blockchain.catch_up = interface.server else: bh = interface.blockchain.height() next_height = None if bh > interface.good: if not interface.blockchain.check_header(interface.bad_header): b = interface.blockchain.fork(interface.bad_header) self.blockchains[interface.bad] = b interface.blockchain = b interface.print_error("new chain", b.checkpoint) interface.mode = 'catch_up' next_height = interface.bad + 1 interface.blockchain.catch_up = interface.server else: assert bh == interface.good if interface.blockchain.catch_up is None and bh < interface.tip: interface.print_error("catching up from %d"% (bh + 1)) interface.mode = 'catch_up' next_height = bh + 1 interface.blockchain.catch_up = interface.server self.notify('updated') elif interface.mode == 'catch_up': can_connect = interface.blockchain.can_connect(header) if can_connect: interface.blockchain.save_header(header) next_height = height + 1 if height < interface.tip else None else: interface.print_error("cannot connect", height) interface.mode = 'backward' interface.bad = height interface.bad_header = header next_height = height - 1 if next_height is None: interface.print_error('catch up done', interface.blockchain.height()) interface.blockchain.catch_up = None self.switch_lagging_interface() self.notify('updated') else: raise BaseException(interface.mode) if next_height: if interface.mode == 'catch_up' and interface.tip > next_height + 50: self.request_chunk(interface, next_height // NetworkConstants.CHUNK_SIZE) else: self.request_header(interface, next_height) else: interface.mode = 'default' interface.request = None self.notify('updated') self.notify('interfaces') def maintain_requests(self): for interface in list(self.interfaces.values()): if interface.request and time.time() - interface.request_time > 20: interface.print_error("blockchain request timed out") self.connection_down(interface.server) continue def wait_on_sockets(self): # Sleep to prevent busy looping if not self.interfaces: time.sleep(0.1) return rin = [i for i in self.interfaces.values()] win = [i for i in self.interfaces.values() if i.num_requests()] try: rout, wout, xout = select.select(rin, win, [], 0.1) except socket.error as e: # TODO: py3, get code from e code = None if code == errno.EINTR: return raise assert not xout for interface in wout: interface.send_requests() for interface in rout: self.process_responses(interface) def init_headers_file(self): b = self.blockchains[0] print(b.get_hash(0), NetworkConstants.GENESIS) if b.get_hash(0) == NetworkConstants.GENESIS: self.downloading_headers = False return filename = b.path() def download_thread(): try: import urllib, socket socket.setdefaulttimeout(30) self.print_error("downloading ", NetworkConstants.HEADERS_URL) urllib.request.urlretrieve(NetworkConstants.HEADERS_URL, filename) self.print_error("done.") except Exception: import traceback traceback.print_exc() self.print_error("download failed. creating file", filename) open(filename, 'wb+').close() b = self.blockchains[0] with b.lock: b.update_size() self.downloading_headers = False self.downloading_headers = True t = threading.Thread(target = download_thread) t.daemon = True t.start() def run(self): self.init_headers_file() while self.is_running() and self.downloading_headers: time.sleep(1) while self.is_running(): self.maintain_sockets() self.wait_on_sockets() self.maintain_requests() self.run_jobs() # Synchronizer and Verifier self.process_pending_sends() self.stop_network() self.on_stop() def on_notify_header(self, interface, header): height = header.get('block_height') if not height: return interface.tip_header = header interface.tip = height if interface.mode != 'default': return b = blockchain.check_header(header) if b: interface.blockchain = b self.switch_lagging_interface() self.notify('updated') self.notify('interfaces') return b = blockchain.can_connect(header) if b: interface.blockchain = b b.save_header(header) self.switch_lagging_interface() self.notify('updated') self.notify('interfaces') return tip = max([x.height() for x in self.blockchains.values()]) if tip >=0: interface.mode = 'backward' interface.bad = height interface.bad_header = header self.request_header(interface, min(tip +1, height - 1)) else: chain = self.blockchains[0] if chain.catch_up is None: chain.catch_up = interface interface.mode = 'catch_up' interface.blockchain = chain self.print_error("switching to catchup mode", tip, self.blockchains) self.request_header(interface, 0) else: self.print_error("chain already catching up with", chain.catch_up.server) def blockchain(self): if self.interface and self.interface.blockchain is not None: self.blockchain_index = self.interface.blockchain.checkpoint return self.blockchains[self.blockchain_index] def get_blockchains(self): out = {} for k, b in self.blockchains.items(): r = list(filter(lambda i: i.blockchain==b, list(self.interfaces.values()))) if r: out[k] = r return out def follow_chain(self, index): blockchain = self.blockchains.get(index) if blockchain: self.blockchain_index = index self.config.set_key('blockchain_index', index) for i in self.interfaces.values(): if i.blockchain == blockchain: self.switch_to_interface(i.server) break else: raise BaseException('blockchain not found', index) if self.interface: server = self.interface.server host, port, protocol, proxy, auto_connect = self.get_parameters() host, port, protocol = server.split(':') self.set_parameters(host, port, protocol, proxy, auto_connect) def get_local_height(self): return self.blockchain().height() def synchronous_get(self, request, timeout=30): q = queue.Queue() self.send([request], q.put) try: r = q.get(True, timeout) except queue.Empty: raise BaseException('Server did not answer') if r.get('error'): raise BaseException(r.get('error')) return r.get('result') def broadcast(self, tx, timeout=30): tx_hash = tx.txid() try: out = self.synchronous_get(('blockchain.transaction.broadcast', [str(tx)]), timeout) except BaseException as e: return False, "error: " + str(e) if out != tx_hash: return False, "error: " + out return True, out
true
true
1c2cd86cb2a7af4365c15125b12c4689002cab3c
7,771
py
Python
fhirbug/Fhir/Resources/group.py
VerdantAI/fhirbug
8a8e2555c0edfeee0a7edbc8d67f2fcb2edd3c2d
[ "MIT" ]
8
2019-01-06T18:11:20.000Z
2022-02-24T02:06:55.000Z
fhirbug/Fhir/Resources/group.py
VerdantAI/fhirbug
8a8e2555c0edfeee0a7edbc8d67f2fcb2edd3c2d
[ "MIT" ]
5
2019-01-25T14:15:35.000Z
2021-06-01T23:22:41.000Z
fhirbug/Fhir/Resources/group.py
VerdantAI/fhirbug
8a8e2555c0edfeee0a7edbc8d67f2fcb2edd3c2d
[ "MIT" ]
3
2020-10-14T23:09:29.000Z
2021-08-09T19:27:31.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/Group) on 2019-01-25. # 2019, SMART Health IT. ## from . import domainresource class Group(domainresource.DomainResource): """ Group of multiple entities. Represents a defined collection of entities that may be discussed or acted upon collectively but which are not expected to act collectively, and are not formally or legally recognized; i.e. a collection of entities that isn't an Organization. """ resource_type = "Group" def __init__(self, jsondict=None, strict=True, **kwargs): """ Initialize all valid properties. :raises: FHIRValidationError on validation errors, unless strict is False :param dict jsondict: A JSON dictionary to use for initialization :param bool strict: If True (the default), invalid variables will raise a TypeError """ self.active = None """ Whether this group's record is in active use. Type `bool`. """ self.actual = None """ Descriptive or actual. Type `bool`. """ self.characteristic = None """ Include / Exclude group members by Trait. List of `GroupCharacteristic` items (represented as `dict` in JSON). """ self.code = None """ Kind of Group members. Type `CodeableConcept` (represented as `dict` in JSON). """ self.identifier = None """ Unique id. List of `Identifier` items (represented as `dict` in JSON). """ self.managingEntity = None """ Entity that is the custodian of the Group's definition. Type `FHIRReference` (represented as `dict` in JSON). """ self.member = None """ Who or what is in group. List of `GroupMember` items (represented as `dict` in JSON). """ self.name = None """ Label for Group. Type `str`. """ self.quantity = None """ Number of members. Type `int`. """ self.type = None """ person | animal | practitioner | device | medication | substance. Type `str`. """ super(Group, self).__init__(jsondict=jsondict, strict=strict, **kwargs) def elementProperties(self): js = super(Group, self).elementProperties() js.extend([ ("active", "active", bool, False, None, False), ("actual", "actual", bool, False, None, True), ("characteristic", "characteristic", GroupCharacteristic, True, None, False), ("code", "code", codeableconcept.CodeableConcept, False, None, False), ("identifier", "identifier", identifier.Identifier, True, None, False), ("managingEntity", "managingEntity", fhirreference.FHIRReference, False, None, False), ("member", "member", GroupMember, True, None, False), ("name", "name", str, False, None, False), ("quantity", "quantity", int, False, None, False), ("type", "type", str, False, None, True), ]) return js from . import backboneelement class GroupCharacteristic(backboneelement.BackboneElement): """ Include / Exclude group members by Trait. Identifies traits whose presence r absence is shared by members of the group. """ resource_type = "GroupCharacteristic" def __init__(self, jsondict=None, strict=True, **kwargs): """ Initialize all valid properties. :raises: FHIRValidationError on validation errors, unless strict is False :param dict jsondict: A JSON dictionary to use for initialization :param bool strict: If True (the default), invalid variables will raise a TypeError """ self.code = None """ Kind of characteristic. Type `CodeableConcept` (represented as `dict` in JSON). """ self.exclude = None """ Group includes or excludes. Type `bool`. """ self.period = None """ Period over which characteristic is tested. Type `Period` (represented as `dict` in JSON). """ self.valueBoolean = None """ Value held by characteristic. Type `bool`. """ self.valueCodeableConcept = None """ Value held by characteristic. Type `CodeableConcept` (represented as `dict` in JSON). """ self.valueQuantity = None """ Value held by characteristic. Type `Quantity` (represented as `dict` in JSON). """ self.valueRange = None """ Value held by characteristic. Type `Range` (represented as `dict` in JSON). """ self.valueReference = None """ Value held by characteristic. Type `FHIRReference` (represented as `dict` in JSON). """ super(GroupCharacteristic, self).__init__(jsondict=jsondict, strict=strict, **kwargs) def elementProperties(self): js = super(GroupCharacteristic, self).elementProperties() js.extend([ ("code", "code", codeableconcept.CodeableConcept, False, None, True), ("exclude", "exclude", bool, False, None, True), ("period", "period", period.Period, False, None, False), ("valueBoolean", "valueBoolean", bool, False, "value", True), ("valueCodeableConcept", "valueCodeableConcept", codeableconcept.CodeableConcept, False, "value", True), ("valueQuantity", "valueQuantity", quantity.Quantity, False, "value", True), ("valueRange", "valueRange", range.Range, False, "value", True), ("valueReference", "valueReference", fhirreference.FHIRReference, False, "value", True), ]) return js class GroupMember(backboneelement.BackboneElement): """ Who or what is in group. Identifies the resource instances that are members of the group. """ resource_type = "GroupMember" def __init__(self, jsondict=None, strict=True, **kwargs): """ Initialize all valid properties. :raises: FHIRValidationError on validation errors, unless strict is False :param dict jsondict: A JSON dictionary to use for initialization :param bool strict: If True (the default), invalid variables will raise a TypeError """ self.entity = None """ Reference to the group member. Type `FHIRReference` (represented as `dict` in JSON). """ self.inactive = None """ If member is no longer in group. Type `bool`. """ self.period = None """ Period member belonged to the group. Type `Period` (represented as `dict` in JSON). """ super(GroupMember, self).__init__(jsondict=jsondict, strict=strict, **kwargs) def elementProperties(self): js = super(GroupMember, self).elementProperties() js.extend([ ("entity", "entity", fhirreference.FHIRReference, False, None, True), ("inactive", "inactive", bool, False, None, False), ("period", "period", period.Period, False, None, False), ]) return js import sys try: from . import codeableconcept except ImportError: codeableconcept = sys.modules[__package__ + '.codeableconcept'] try: from . import fhirreference except ImportError: fhirreference = sys.modules[__package__ + '.fhirreference'] try: from . import identifier except ImportError: identifier = sys.modules[__package__ + '.identifier'] try: from . import period except ImportError: period = sys.modules[__package__ + '.period'] try: from . import quantity except ImportError: quantity = sys.modules[__package__ + '.quantity'] try: from . import range except ImportError: range = sys.modules[__package__ + '.range']
35.162896
116
0.62566
from . import domainresource class Group(domainresource.DomainResource): resource_type = "Group" def __init__(self, jsondict=None, strict=True, **kwargs): self.active = None self.actual = None self.characteristic = None self.code = None self.identifier = None self.managingEntity = None self.member = None self.name = None self.quantity = None self.type = None super(Group, self).__init__(jsondict=jsondict, strict=strict, **kwargs) def elementProperties(self): js = super(Group, self).elementProperties() js.extend([ ("active", "active", bool, False, None, False), ("actual", "actual", bool, False, None, True), ("characteristic", "characteristic", GroupCharacteristic, True, None, False), ("code", "code", codeableconcept.CodeableConcept, False, None, False), ("identifier", "identifier", identifier.Identifier, True, None, False), ("managingEntity", "managingEntity", fhirreference.FHIRReference, False, None, False), ("member", "member", GroupMember, True, None, False), ("name", "name", str, False, None, False), ("quantity", "quantity", int, False, None, False), ("type", "type", str, False, None, True), ]) return js from . import backboneelement class GroupCharacteristic(backboneelement.BackboneElement): resource_type = "GroupCharacteristic" def __init__(self, jsondict=None, strict=True, **kwargs): self.code = None self.exclude = None self.period = None self.valueBoolean = None self.valueCodeableConcept = None self.valueQuantity = None self.valueRange = None self.valueReference = None super(GroupCharacteristic, self).__init__(jsondict=jsondict, strict=strict, **kwargs) def elementProperties(self): js = super(GroupCharacteristic, self).elementProperties() js.extend([ ("code", "code", codeableconcept.CodeableConcept, False, None, True), ("exclude", "exclude", bool, False, None, True), ("period", "period", period.Period, False, None, False), ("valueBoolean", "valueBoolean", bool, False, "value", True), ("valueCodeableConcept", "valueCodeableConcept", codeableconcept.CodeableConcept, False, "value", True), ("valueQuantity", "valueQuantity", quantity.Quantity, False, "value", True), ("valueRange", "valueRange", range.Range, False, "value", True), ("valueReference", "valueReference", fhirreference.FHIRReference, False, "value", True), ]) return js class GroupMember(backboneelement.BackboneElement): resource_type = "GroupMember" def __init__(self, jsondict=None, strict=True, **kwargs): self.entity = None self.inactive = None self.period = None super(GroupMember, self).__init__(jsondict=jsondict, strict=strict, **kwargs) def elementProperties(self): js = super(GroupMember, self).elementProperties() js.extend([ ("entity", "entity", fhirreference.FHIRReference, False, None, True), ("inactive", "inactive", bool, False, None, False), ("period", "period", period.Period, False, None, False), ]) return js import sys try: from . import codeableconcept except ImportError: codeableconcept = sys.modules[__package__ + '.codeableconcept'] try: from . import fhirreference except ImportError: fhirreference = sys.modules[__package__ + '.fhirreference'] try: from . import identifier except ImportError: identifier = sys.modules[__package__ + '.identifier'] try: from . import period except ImportError: period = sys.modules[__package__ + '.period'] try: from . import quantity except ImportError: quantity = sys.modules[__package__ + '.quantity'] try: from . import range except ImportError: range = sys.modules[__package__ + '.range']
true
true
1c2cd9ef28cf6bf76316a9a5fb744ba891bdc63e
5,279
py
Python
pyexamples/moran.py
AndySer37/Draw_CNN_Network
5f8c3a3c602d475de3f6d56613cfd88ab368fc75
[ "MIT" ]
null
null
null
pyexamples/moran.py
AndySer37/Draw_CNN_Network
5f8c3a3c602d475de3f6d56613cfd88ab368fc75
[ "MIT" ]
null
null
null
pyexamples/moran.py
AndySer37/Draw_CNN_Network
5f8c3a3c602d475de3f6d56613cfd88ab368fc75
[ "MIT" ]
null
null
null
import sys sys.path.append('../') from pycore.tikzeng import * from pycore.blocks import * # defined your arch arch = [ to_head( '..' ), to_cor(), to_begin(), to_input('../img/hunts.png' , name="input", width=9, height=6), #block-001 to_Pool(name="pool_b1", offset="(0,0,0)", to="(0,0,0)", width=1, height=20, depth=40, opacity=0.5), to_Conv( name='ccr_b1', s_filer="16 * 50", n_filer=64, offset="(0,0,0)", to="(pool_b1-east)", width=2, height=20, depth=40 ,caption="conv1"), to_Pool(name="pool_b2", offset="(1.5,0,0)", to="(ccr_b1-east)", width=1, height=15, depth=30, opacity=0.5), to_Conv( name='ccr_b2', s_filer="8 * 25", n_filer=128, offset="(0,0,0)", to="(pool_b2-east)", width=2, height=15, depth=30 ,caption="conv2"), to_Pool(name="pool_b3", offset="(1.5,0,0)", to="(ccr_b2-east)", width=1, height=10, depth=20, opacity=0.5), to_Conv( name='ccr_b3_1', s_filer="", n_filer="", offset="(0,0,0)", to="(pool_b3-east)", width=2, height=10, depth=20 ), to_Conv( name='ccr_b3_2', s_filer="", n_filer="128", offset="(0,0,0)", to="(ccr_b3_1-east)", width=2, height=10, depth=20 ,caption="conv3"), to_Conv( name='ccr_b3_3', s_filer="4 * 12", n_filer="", offset="(0,0,0)", to="(ccr_b3_2-east)", width=2, height=10, depth=20 ), to_Pool(name="pool_b4", offset="(1.5,0,0)", to="(ccr_b3_3-east)", width=1, height=8, depth=16, opacity=0.5,caption="pool"), to_SoftMax(name="tanh", s_filer="3 * 11", offset="(1,0,0)", to="(pool_b4-east)", width=1, height=8, depth=16, opacity=0.5,caption="tanh"), to_UnPool( name='dconv1', offset="(1.5,0,0)", to="(tanh-east)", width=2, height=20, depth=40,caption="Offset Map"), to_connection( "ccr_b1", "pool_b2"), to_connection( "ccr_b2", "pool_b3"), to_connection( "ccr_b3_3", "pool_b4"), to_connection( "pool_b4", "tanh"), to_connection( "tanh", "dconv1"), to_Conv( name='ccr_b4', s_filer="32 * 100", n_filer=64, offset="(1.5,0,0)", to="(dconv1-east)", width=2, height=20, depth=40 ,caption="conv4"), to_Pool(name="pool_b5", offset="(1,0,0)", to="(ccr_b4-east)", width=1, height=15, depth=30, opacity=0.5), to_Conv( name='ccr_b5', s_filer="16 * 50", n_filer=128, offset="(1.5,0,0)", to="(pool_b5-east)", width=2, height=15, depth=30 ,caption="conv5"), to_Pool(name="pool_b6", offset="(1,0,0)", to="(ccr_b5-east)", width=1, height=10, depth=20, opacity=0.5), to_Conv( name='ccr_b6_1', s_filer="", n_filer="", offset="(1.5,0,0)", to="(pool_b6-east)", width=2, height=10, depth=20 ,caption=""), to_Conv( name='ccr_b6_2', s_filer="8 * 25", n_filer=256, offset="(0,0,0)", to="(ccr_b6_1-east)", width=2, height=10, depth=20 ,caption="conv6"), to_Pool(name="pool_b7", offset="(1,0,0)", to="(ccr_b6_2-east)", width=1, height=8, depth=16, opacity=0.5), to_Conv( name='ccr_b7_1', s_filer="", n_filer="", offset="(1.5,0,0)", to="(pool_b7-east)", width=2, height=8, depth=16 ,caption=""), to_Conv( name='ccr_b7_2', s_filer="4 * 25", n_filer=512, offset="(0,0,0)", to="(ccr_b7_1-east)", width=2, height=8, depth=16 ,caption="conv7"), to_Pool(name="pool_b8", offset="(1,0,0)", to="(ccr_b7_2-east)", width=1, height=6, depth=12, opacity=0.5), to_Conv( name='ccr_b8', s_filer="1*25", n_filer=512, offset="(1,0,0)", to="(pool_b8-east)", width=1, height=3, depth=6 ,caption="conv8"), to_SoftMax(name="blstm1", s_filer="", offset="(1.5,0,0)", to="(ccr_b8-east)", width=2, height=3, depth=6, opacity=0.5,caption="BLSTM"), to_SoftMax(name="blstm2", s_filer="1*25", offset="(0,0,0)", to="(blstm1-east)", width=2, height=3, depth=6, opacity=0.5,caption=""), to_SoftMax(name="gru", s_filer="1*25", offset="(1,0,0)", to="(blstm2-east)", width=2, height=3, depth=6, opacity=0.5,caption="GRU"), to_connection( "dconv1", "ccr_b4"), to_connection( "pool_b5", "ccr_b5"), to_connection( "pool_b6", "ccr_b6_1"), to_connection( "pool_b7", "ccr_b7_1"), to_connection( "pool_b8", "ccr_b8"), to_connection( "ccr_b8", "blstm1"), to_connection( "blstm2", "gru"), to_Conv("senet_1", 1, 64, offset="(2,0,15)", to="(ccr_b4-east)", height=1, depth=1, width=6 ,caption="SE Block 1"), to_connection( "ccr_b4", "senet_1"), to_connection( "senet_1", "pool_b5"), to_connection( "ccr_b4", "pool_b5"), to_Conv("senet_2", 1, 128, offset="(2,0,13)", to="(ccr_b5-east)", height=1, depth=1, width=6 ,caption="SE Block 2"), to_connection( "ccr_b5", "senet_2"), to_connection( "senet_2", "pool_b6"), to_connection( "ccr_b5", "pool_b6"), to_Conv("senet_3", 1, 256, offset="(2,0,11)", to="(ccr_b6_2-east)", height=1, depth=1, width=6 ,caption="SE Block 3"), to_connection( "ccr_b6_2", "senet_3"), to_connection( "senet_3", "pool_b7"), to_connection( "ccr_b6_2", "pool_b7"), to_Conv("senet_4", 1, 512, offset="(2,0,10)", to="(ccr_b7_2-east)", height=1, depth=1, width=6 ,caption="SE Block 4"), to_connection( "ccr_b7_2", "senet_4"), to_connection( "senet_4", "pool_b8"), to_connection( "ccr_b7_2", "pool_b8"), to_input('../img/word.png' ,to="(30.2,0,0)", name="output", width=6, height=4), to_end() ] def main(): namefile = str(sys.argv[0]).split('.')[0] to_generate(arch, namefile + '.tex' ) if __name__ == '__main__': main()
59.988636
148
0.620193
import sys sys.path.append('../') from pycore.tikzeng import * from pycore.blocks import * arch = [ to_head( '..' ), to_cor(), to_begin(), to_input('../img/hunts.png' , name="input", width=9, height=6), to_Pool(name="pool_b1", offset="(0,0,0)", to="(0,0,0)", width=1, height=20, depth=40, opacity=0.5), to_Conv( name='ccr_b1', s_filer="16 * 50", n_filer=64, offset="(0,0,0)", to="(pool_b1-east)", width=2, height=20, depth=40 ,caption="conv1"), to_Pool(name="pool_b2", offset="(1.5,0,0)", to="(ccr_b1-east)", width=1, height=15, depth=30, opacity=0.5), to_Conv( name='ccr_b2', s_filer="8 * 25", n_filer=128, offset="(0,0,0)", to="(pool_b2-east)", width=2, height=15, depth=30 ,caption="conv2"), to_Pool(name="pool_b3", offset="(1.5,0,0)", to="(ccr_b2-east)", width=1, height=10, depth=20, opacity=0.5), to_Conv( name='ccr_b3_1', s_filer="", n_filer="", offset="(0,0,0)", to="(pool_b3-east)", width=2, height=10, depth=20 ), to_Conv( name='ccr_b3_2', s_filer="", n_filer="128", offset="(0,0,0)", to="(ccr_b3_1-east)", width=2, height=10, depth=20 ,caption="conv3"), to_Conv( name='ccr_b3_3', s_filer="4 * 12", n_filer="", offset="(0,0,0)", to="(ccr_b3_2-east)", width=2, height=10, depth=20 ), to_Pool(name="pool_b4", offset="(1.5,0,0)", to="(ccr_b3_3-east)", width=1, height=8, depth=16, opacity=0.5,caption="pool"), to_SoftMax(name="tanh", s_filer="3 * 11", offset="(1,0,0)", to="(pool_b4-east)", width=1, height=8, depth=16, opacity=0.5,caption="tanh"), to_UnPool( name='dconv1', offset="(1.5,0,0)", to="(tanh-east)", width=2, height=20, depth=40,caption="Offset Map"), to_connection( "ccr_b1", "pool_b2"), to_connection( "ccr_b2", "pool_b3"), to_connection( "ccr_b3_3", "pool_b4"), to_connection( "pool_b4", "tanh"), to_connection( "tanh", "dconv1"), to_Conv( name='ccr_b4', s_filer="32 * 100", n_filer=64, offset="(1.5,0,0)", to="(dconv1-east)", width=2, height=20, depth=40 ,caption="conv4"), to_Pool(name="pool_b5", offset="(1,0,0)", to="(ccr_b4-east)", width=1, height=15, depth=30, opacity=0.5), to_Conv( name='ccr_b5', s_filer="16 * 50", n_filer=128, offset="(1.5,0,0)", to="(pool_b5-east)", width=2, height=15, depth=30 ,caption="conv5"), to_Pool(name="pool_b6", offset="(1,0,0)", to="(ccr_b5-east)", width=1, height=10, depth=20, opacity=0.5), to_Conv( name='ccr_b6_1', s_filer="", n_filer="", offset="(1.5,0,0)", to="(pool_b6-east)", width=2, height=10, depth=20 ,caption=""), to_Conv( name='ccr_b6_2', s_filer="8 * 25", n_filer=256, offset="(0,0,0)", to="(ccr_b6_1-east)", width=2, height=10, depth=20 ,caption="conv6"), to_Pool(name="pool_b7", offset="(1,0,0)", to="(ccr_b6_2-east)", width=1, height=8, depth=16, opacity=0.5), to_Conv( name='ccr_b7_1', s_filer="", n_filer="", offset="(1.5,0,0)", to="(pool_b7-east)", width=2, height=8, depth=16 ,caption=""), to_Conv( name='ccr_b7_2', s_filer="4 * 25", n_filer=512, offset="(0,0,0)", to="(ccr_b7_1-east)", width=2, height=8, depth=16 ,caption="conv7"), to_Pool(name="pool_b8", offset="(1,0,0)", to="(ccr_b7_2-east)", width=1, height=6, depth=12, opacity=0.5), to_Conv( name='ccr_b8', s_filer="1*25", n_filer=512, offset="(1,0,0)", to="(pool_b8-east)", width=1, height=3, depth=6 ,caption="conv8"), to_SoftMax(name="blstm1", s_filer="", offset="(1.5,0,0)", to="(ccr_b8-east)", width=2, height=3, depth=6, opacity=0.5,caption="BLSTM"), to_SoftMax(name="blstm2", s_filer="1*25", offset="(0,0,0)", to="(blstm1-east)", width=2, height=3, depth=6, opacity=0.5,caption=""), to_SoftMax(name="gru", s_filer="1*25", offset="(1,0,0)", to="(blstm2-east)", width=2, height=3, depth=6, opacity=0.5,caption="GRU"), to_connection( "dconv1", "ccr_b4"), to_connection( "pool_b5", "ccr_b5"), to_connection( "pool_b6", "ccr_b6_1"), to_connection( "pool_b7", "ccr_b7_1"), to_connection( "pool_b8", "ccr_b8"), to_connection( "ccr_b8", "blstm1"), to_connection( "blstm2", "gru"), to_Conv("senet_1", 1, 64, offset="(2,0,15)", to="(ccr_b4-east)", height=1, depth=1, width=6 ,caption="SE Block 1"), to_connection( "ccr_b4", "senet_1"), to_connection( "senet_1", "pool_b5"), to_connection( "ccr_b4", "pool_b5"), to_Conv("senet_2", 1, 128, offset="(2,0,13)", to="(ccr_b5-east)", height=1, depth=1, width=6 ,caption="SE Block 2"), to_connection( "ccr_b5", "senet_2"), to_connection( "senet_2", "pool_b6"), to_connection( "ccr_b5", "pool_b6"), to_Conv("senet_3", 1, 256, offset="(2,0,11)", to="(ccr_b6_2-east)", height=1, depth=1, width=6 ,caption="SE Block 3"), to_connection( "ccr_b6_2", "senet_3"), to_connection( "senet_3", "pool_b7"), to_connection( "ccr_b6_2", "pool_b7"), to_Conv("senet_4", 1, 512, offset="(2,0,10)", to="(ccr_b7_2-east)", height=1, depth=1, width=6 ,caption="SE Block 4"), to_connection( "ccr_b7_2", "senet_4"), to_connection( "senet_4", "pool_b8"), to_connection( "ccr_b7_2", "pool_b8"), to_input('../img/word.png' ,to="(30.2,0,0)", name="output", width=6, height=4), to_end() ] def main(): namefile = str(sys.argv[0]).split('.')[0] to_generate(arch, namefile + '.tex' ) if __name__ == '__main__': main()
true
true
1c2cda42a13e7104efdddd228e460b4ad3ef517f
24
py
Python
testing.py
Ilvcardib69/testing123
3ed02e7e8d7aadf9211d41073f208cc58c5198e4
[ "MIT" ]
null
null
null
testing.py
Ilvcardib69/testing123
3ed02e7e8d7aadf9211d41073f208cc58c5198e4
[ "MIT" ]
null
null
null
testing.py
Ilvcardib69/testing123
3ed02e7e8d7aadf9211d41073f208cc58c5198e4
[ "MIT" ]
null
null
null
class Testing: pass
8
14
0.666667
class Testing: pass
true
true
1c2cdbd1f36593d865777d010c87cac4e9f0238d
6,750
py
Python
mistral/tests/unit/engine/test_reverse_workflow_rerun_cancelled.py
shubhamdang/mistral
3c83837f6ce1e4ab74fb519a63e82eaae70f9d2d
[ "Apache-2.0" ]
205
2015-06-21T11:51:47.000Z
2022-03-05T04:00:04.000Z
mistral/tests/unit/engine/test_reverse_workflow_rerun_cancelled.py
shubhamdang/mistral
3c83837f6ce1e4ab74fb519a63e82eaae70f9d2d
[ "Apache-2.0" ]
8
2015-06-23T14:47:58.000Z
2021-01-28T06:06:44.000Z
mistral/tests/unit/engine/test_reverse_workflow_rerun_cancelled.py
shubhamdang/mistral
3c83837f6ce1e4ab74fb519a63e82eaae70f9d2d
[ "Apache-2.0" ]
110
2015-06-14T03:34:38.000Z
2021-11-11T12:12:56.000Z
# Copyright 2016 - Brocade Communications Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from unittest import mock from oslo_config import cfg from mistral.actions import std_actions from mistral.db.v2 import api as db_api from mistral.services import workbooks as wb_service from mistral.tests.unit.engine import base from mistral.workflow import states from mistral_lib import actions as ml_actions # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') class ReverseWorkflowRerunCancelledTest(base.EngineTestCase): @mock.patch.object( std_actions.EchoAction, 'run', mock.MagicMock( side_effect=[ 'Task 2', # Mock task2 success. 'Task 3' # Mock task3 success. ] ) ) def test_rerun_cancelled_task(self): wb_def = """ version: '2.0' name: wb1 workflows: wf1: type: reverse tasks: t1: action: std.async_noop t2: action: std.echo output="Task 2" requires: - t1 t3: action: std.echo output="Task 3" requires: - t2 """ wb_service.create_workbook_v2(wb_def) wf1_ex = self.engine.start_workflow('wb1.wf1', task_name='t3') self.await_workflow_state(wf1_ex.id, states.RUNNING) with db_api.transaction(): wf1_execs = db_api.get_workflow_executions() wf1_ex = self._assert_single_item(wf1_execs, name='wb1.wf1') wf1_t1_ex = self._assert_single_item( wf1_ex.task_executions, name='t1' ) wf1_t1_action_exs = db_api.get_action_executions( task_execution_id=wf1_t1_ex.id ) self.assertEqual(1, len(wf1_t1_action_exs)) self.assertEqual(states.RUNNING, wf1_t1_action_exs[0].state) # Cancel action execution for task. self.engine.on_action_complete( wf1_t1_action_exs[0].id, ml_actions.Result(cancel=True) ) self.await_workflow_cancelled(wf1_ex.id) with db_api.transaction(): wf1_ex = db_api.get_workflow_execution(wf1_ex.id) wf1_t1_ex = self._assert_single_item( wf1_ex.task_executions, name='t1' ) self.await_task_cancelled(wf1_t1_ex.id) with db_api.transaction(): wf1_ex = db_api.get_workflow_execution(wf1_ex.id) wf1_t1_ex = self._assert_single_item( wf1_ex.task_executions, name='t1' ) self.assertEqual(states.CANCELLED, wf1_ex.state) self.assertEqual("Cancelled tasks: t1", wf1_ex.state_info) self.assertEqual(1, len(wf1_ex.task_executions)) self.assertEqual(states.CANCELLED, wf1_t1_ex.state) self.assertIsNone(wf1_t1_ex.state_info) # Resume workflow and re-run cancelled task. self.engine.rerun_workflow(wf1_t1_ex.id) with db_api.transaction(): wf1_ex = db_api.get_workflow_execution(wf1_ex.id) wf1_task_execs = wf1_ex.task_executions self.assertEqual(states.RUNNING, wf1_ex.state) self.assertIsNone(wf1_ex.state_info) # Mark async action execution complete. wf1_t1_ex = self._assert_single_item(wf1_task_execs, name='t1') wf1_t1_action_exs = db_api.get_action_executions( task_execution_id=wf1_t1_ex.id ) self.assertEqual(states.RUNNING, wf1_t1_ex.state) self.assertEqual(2, len(wf1_t1_action_exs)) # Check there is exactly 1 action in Running and 1 in Cancelled state. # Order doesn't matter. self._assert_single_item(wf1_t1_action_exs, state=states.CANCELLED) running_execution = self._assert_single_item( wf1_t1_action_exs, state=states.RUNNING ) self.engine.on_action_complete( running_execution.id, ml_actions.Result(data={'foo': 'bar'}) ) # Wait for the workflow to succeed. self.await_workflow_success(wf1_ex.id) with db_api.transaction(): wf1_ex = db_api.get_workflow_execution(wf1_ex.id) wf1_task_execs = wf1_ex.task_executions self.assertEqual(states.SUCCESS, wf1_ex.state) self.assertIsNone(wf1_ex.state_info) self.assertEqual(3, len(wf1_task_execs)) wf1_t1_ex = self._assert_single_item(wf1_task_execs, name='t1') wf1_t2_ex = self._assert_single_item(wf1_task_execs, name='t2') wf1_t3_ex = self._assert_single_item(wf1_task_execs, name='t3') # Check action executions of task 1. self.assertEqual(states.SUCCESS, wf1_t1_ex.state) self.assertIsNone(wf1_t2_ex.state_info) wf1_t1_action_exs = db_api.get_action_executions( task_execution_id=wf1_t1_ex.id ) self.assertEqual(2, len(wf1_t1_action_exs)) # Check there is exactly 1 action in Success and 1 in Cancelled state. # Order doesn't matter. self._assert_single_item(wf1_t1_action_exs, state=states.SUCCESS) self._assert_single_item(wf1_t1_action_exs, state=states.CANCELLED) # Check action executions of task 2. self.assertEqual(states.SUCCESS, wf1_t2_ex.state) wf1_t2_action_exs = db_api.get_action_executions( task_execution_id=wf1_t2_ex.id ) self.assertEqual(1, len(wf1_t2_action_exs)) self.assertEqual(states.SUCCESS, wf1_t2_action_exs[0].state) # Check action executions of task 3. self.assertEqual(states.SUCCESS, wf1_t3_ex.state) wf1_t3_action_exs = db_api.get_action_executions( task_execution_id=wf1_t3_ex.id ) self.assertEqual(1, len(wf1_t3_action_exs)) self.assertEqual(states.SUCCESS, wf1_t3_action_exs[0].state)
33.75
78
0.63763
from unittest import mock from oslo_config import cfg from mistral.actions import std_actions from mistral.db.v2 import api as db_api from mistral.services import workbooks as wb_service from mistral.tests.unit.engine import base from mistral.workflow import states from mistral_lib import actions as ml_actions cfg.CONF.set_default('auth_enable', False, group='pecan') class ReverseWorkflowRerunCancelledTest(base.EngineTestCase): @mock.patch.object( std_actions.EchoAction, 'run', mock.MagicMock( side_effect=[ 'Task 2', 'Task 3' ] ) ) def test_rerun_cancelled_task(self): wb_def = """ version: '2.0' name: wb1 workflows: wf1: type: reverse tasks: t1: action: std.async_noop t2: action: std.echo output="Task 2" requires: - t1 t3: action: std.echo output="Task 3" requires: - t2 """ wb_service.create_workbook_v2(wb_def) wf1_ex = self.engine.start_workflow('wb1.wf1', task_name='t3') self.await_workflow_state(wf1_ex.id, states.RUNNING) with db_api.transaction(): wf1_execs = db_api.get_workflow_executions() wf1_ex = self._assert_single_item(wf1_execs, name='wb1.wf1') wf1_t1_ex = self._assert_single_item( wf1_ex.task_executions, name='t1' ) wf1_t1_action_exs = db_api.get_action_executions( task_execution_id=wf1_t1_ex.id ) self.assertEqual(1, len(wf1_t1_action_exs)) self.assertEqual(states.RUNNING, wf1_t1_action_exs[0].state) self.engine.on_action_complete( wf1_t1_action_exs[0].id, ml_actions.Result(cancel=True) ) self.await_workflow_cancelled(wf1_ex.id) with db_api.transaction(): wf1_ex = db_api.get_workflow_execution(wf1_ex.id) wf1_t1_ex = self._assert_single_item( wf1_ex.task_executions, name='t1' ) self.await_task_cancelled(wf1_t1_ex.id) with db_api.transaction(): wf1_ex = db_api.get_workflow_execution(wf1_ex.id) wf1_t1_ex = self._assert_single_item( wf1_ex.task_executions, name='t1' ) self.assertEqual(states.CANCELLED, wf1_ex.state) self.assertEqual("Cancelled tasks: t1", wf1_ex.state_info) self.assertEqual(1, len(wf1_ex.task_executions)) self.assertEqual(states.CANCELLED, wf1_t1_ex.state) self.assertIsNone(wf1_t1_ex.state_info) self.engine.rerun_workflow(wf1_t1_ex.id) with db_api.transaction(): wf1_ex = db_api.get_workflow_execution(wf1_ex.id) wf1_task_execs = wf1_ex.task_executions self.assertEqual(states.RUNNING, wf1_ex.state) self.assertIsNone(wf1_ex.state_info) wf1_t1_ex = self._assert_single_item(wf1_task_execs, name='t1') wf1_t1_action_exs = db_api.get_action_executions( task_execution_id=wf1_t1_ex.id ) self.assertEqual(states.RUNNING, wf1_t1_ex.state) self.assertEqual(2, len(wf1_t1_action_exs)) self._assert_single_item(wf1_t1_action_exs, state=states.CANCELLED) running_execution = self._assert_single_item( wf1_t1_action_exs, state=states.RUNNING ) self.engine.on_action_complete( running_execution.id, ml_actions.Result(data={'foo': 'bar'}) ) # Wait for the workflow to succeed. self.await_workflow_success(wf1_ex.id) with db_api.transaction(): wf1_ex = db_api.get_workflow_execution(wf1_ex.id) wf1_task_execs = wf1_ex.task_executions self.assertEqual(states.SUCCESS, wf1_ex.state) self.assertIsNone(wf1_ex.state_info) self.assertEqual(3, len(wf1_task_execs)) wf1_t1_ex = self._assert_single_item(wf1_task_execs, name='t1') wf1_t2_ex = self._assert_single_item(wf1_task_execs, name='t2') wf1_t3_ex = self._assert_single_item(wf1_task_execs, name='t3') # Check action executions of task 1. self.assertEqual(states.SUCCESS, wf1_t1_ex.state) self.assertIsNone(wf1_t2_ex.state_info) wf1_t1_action_exs = db_api.get_action_executions( task_execution_id=wf1_t1_ex.id ) self.assertEqual(2, len(wf1_t1_action_exs)) # Check there is exactly 1 action in Success and 1 in Cancelled state. # Order doesn't matter. self._assert_single_item(wf1_t1_action_exs, state=states.SUCCESS) self._assert_single_item(wf1_t1_action_exs, state=states.CANCELLED) self.assertEqual(states.SUCCESS, wf1_t2_ex.state) wf1_t2_action_exs = db_api.get_action_executions( task_execution_id=wf1_t2_ex.id ) self.assertEqual(1, len(wf1_t2_action_exs)) self.assertEqual(states.SUCCESS, wf1_t2_action_exs[0].state) self.assertEqual(states.SUCCESS, wf1_t3_ex.state) wf1_t3_action_exs = db_api.get_action_executions( task_execution_id=wf1_t3_ex.id ) self.assertEqual(1, len(wf1_t3_action_exs)) self.assertEqual(states.SUCCESS, wf1_t3_action_exs[0].state)
true
true
1c2cdc63782d129ae8916ef7cfc9b2ab641a58c5
3,242
py
Python
train_code/train_crnn/prepare_data.py
mathemusician/ocr_pytorch
07e56f4d240ca76d5cb447c912fef573a0869577
[ "MIT" ]
5
2021-08-23T10:25:48.000Z
2022-01-22T23:03:39.000Z
train_code/train_crnn/prepare_data.py
mathemusician/ocr_pytorch
07e56f4d240ca76d5cb447c912fef573a0869577
[ "MIT" ]
null
null
null
train_code/train_crnn/prepare_data.py
mathemusician/ocr_pytorch
07e56f4d240ca76d5cb447c912fef573a0869577
[ "MIT" ]
2
2021-09-04T11:07:50.000Z
2021-12-12T06:13:21.000Z
""" 1) convert image files to text file 2) transfer characters from text file to pickled file """ import os import config import pickle as pl from typing import Any from pathed import Path, filedir, cwd def make_text_file(image_dir): """ makes text_file.txt which contains file_paths to images and the corresponding text: /absolute/path/to/image_1.jpg\tword_in_image_1 /absolute/path/to/image_2.jpg\tword_in_image_2 ... you may have to modify this to fit your dataset Parameters: image_dir: directory that stores images Returns: path to text_file.txt """ # path to image files image_dir = Path(image_dir, custom=True) # get valid files file_list = [ filename for filename in image_dir.ls() if ((os.path.isfile(image_dir / filename)) and (filename != ".DS_Store")) ] text_list = [] # files names look like randomnum_word_randomnum.jpg for file_name in file_list: image_text = file_name.split("_")[1] if "." in image_text: image_text = image_text.split(".")[0] text_list.append(image_dir / (file_name + r"\t" + image_text + "\n")) text = "".join(text_list) with open(filedir/"text_file.txt", "w") as file_handler: file_handler.write(text) return filedir / "text_file.txt" def pickle(data: Any, path: str) -> None: """ one-liner for pickling python objects: pickle(data, 'path/to/pickled/file') Parameters: data: almost any python object path: /path/to/pickle/file.pl Returns: Nothing """ with open(path, "wb") as file_handler: pl.dump(data, file_handler) def unpickle(path: str) -> Any: """ one-liner for retrieving pickled data: data = unpickle('path/to/pickled/file') Parameters: path Returns: pickled data """ with open(path, "rb") as file_handler: return pl.load(file_handler) def view_pickled_data(path: str) -> str: """ Parameters: path to pickled file Returns: string version of pickled file """ data = unpickle(path) print(data) return str(data) def pickle_from_text_file(path: str) -> str: """ makes custom_alphabet.pkl custom_alphabet.pkl contains a list of valid characters: [ ' ', 'a', 'b', 'c', ... ] Parameters: path: path to text_file.txt Returns: path to custom_alphabet.pkl """ words = [] with open(path, "r") as file_handler: lines = file_handler.readlines() for line in lines: url, word = line.split("\\t") word = word.replace("\n", "") words.append(word) # convert words into a set of characters # the set automatically contains one of every item words = set([char for char in ("".join(words))]) pickle([' '] + list(words), filedir/"custom_alphabet.pkl") return filedir / "custom_alphabet.pkl" if __name__ == "__main__": path_to_text_file = make_text_file(config.image_dir) print(path_to_text_file) path_to_pickle = pickle_from_text_file(path_to_text_file) print(path_to_pickle) view_pickled_data(path_to_pickle)
23.323741
87
0.62955
import os import config import pickle as pl from typing import Any from pathed import Path, filedir, cwd def make_text_file(image_dir): image_dir = Path(image_dir, custom=True) file_list = [ filename for filename in image_dir.ls() if ((os.path.isfile(image_dir / filename)) and (filename != ".DS_Store")) ] text_list = [] for file_name in file_list: image_text = file_name.split("_")[1] if "." in image_text: image_text = image_text.split(".")[0] text_list.append(image_dir / (file_name + r"\t" + image_text + "\n")) text = "".join(text_list) with open(filedir/"text_file.txt", "w") as file_handler: file_handler.write(text) return filedir / "text_file.txt" def pickle(data: Any, path: str) -> None: with open(path, "wb") as file_handler: pl.dump(data, file_handler) def unpickle(path: str) -> Any: with open(path, "rb") as file_handler: return pl.load(file_handler) def view_pickled_data(path: str) -> str: data = unpickle(path) print(data) return str(data) def pickle_from_text_file(path: str) -> str: words = [] with open(path, "r") as file_handler: lines = file_handler.readlines() for line in lines: url, word = line.split("\\t") word = word.replace("\n", "") words.append(word) words = set([char for char in ("".join(words))]) pickle([' '] + list(words), filedir/"custom_alphabet.pkl") return filedir / "custom_alphabet.pkl" if __name__ == "__main__": path_to_text_file = make_text_file(config.image_dir) print(path_to_text_file) path_to_pickle = pickle_from_text_file(path_to_text_file) print(path_to_pickle) view_pickled_data(path_to_pickle)
true
true
1c2cdc779d8b1de9fa3d958c94c10c2ddb50fa8c
2,341
py
Python
test/test_model.py
tjingrant/onnx-tf
3412d86238bf99bf4908e829af115693df161988
[ "Apache-2.0" ]
16
2017-10-27T20:07:57.000Z
2021-07-14T02:01:27.000Z
test/test_model.py
tjingrant/onnx-tf
3412d86238bf99bf4908e829af115693df161988
[ "Apache-2.0" ]
3
2017-10-29T04:10:04.000Z
2017-10-31T15:06:20.000Z
test/test_model.py
tjingrant/onnx-tf
3412d86238bf99bf4908e829af115693df161988
[ "Apache-2.0" ]
1
2021-03-18T23:23:23.000Z
2021-03-18T23:23:23.000Z
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import numpy as np import tensorflow as tf import onnx from onnx_tf.backend import run_node, prepare from onnx import helper from onnx.onnx_pb2 import TensorProto class TestModel(unittest.TestCase): """ Tests for models """ def test_relu_node_inplace(self): X = np.random.randn(3, 2).astype(np.float32) Y_ref = np.clip(X, 0, np.inf) node_def = helper.make_node( "Relu", ["X"], ["X"]) graph_def = helper.make_graph( [node_def], name="test", inputs=[helper.make_tensor_value_info("X", TensorProto.FLOAT, [3, 2])], outputs=[helper.make_tensor_value_info("X", TensorProto.FLOAT, [3, 2])]) tf_rep = prepare(helper.make_model(graph_def)) output = tf_rep.run({"X": X}) np.testing.assert_almost_equal(output.X, Y_ref) def test_initializer(self): X = np.array([[1, 2], [3, 4]]).astype(np.float32) Y = np.array([[1, 2], [3, 4]]).astype(np.float32) weight = np.array([[1, 0], [0, 1]]) graph_def = helper.make_graph( [helper.make_node("Add", ["X", "Y"], ["Z0"]), helper.make_node("Cast", ["Z0"], ["Z"], to="float"), helper.make_node("Mul", ["Z", "weight"], ["W"]), helper.make_node("Tanh", ["W"], ["W"]), helper.make_node("Sigmoid", ["W"], ["W"])], name="test_initializer", inputs=[ helper.make_tensor_value_info("X", TensorProto.FLOAT, (2, 2)), helper.make_tensor_value_info("Y", TensorProto.FLOAT, (2, 2)), helper.make_tensor_value_info("weight", TensorProto.FLOAT, (2, 2)), ], outputs=[ helper.make_tensor_value_info("W", TensorProto.FLOAT, (2, 2)) ], initializer=[helper.make_tensor("weight", TensorProto.FLOAT, [2, 2], weight.flatten().astype(float))] ) def sigmoid(x): return 1 / (1 + np.exp(-x)) W_ref = sigmoid(np.tanh((X + Y) * weight)) tf_rep = prepare(helper.make_model(graph_def)) output = tf_rep.run({"X": X, "Y": Y}) np.testing.assert_almost_equal(output["W"], W_ref) if __name__ == '__main__': unittest.main()
34.426471
79
0.597608
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import numpy as np import tensorflow as tf import onnx from onnx_tf.backend import run_node, prepare from onnx import helper from onnx.onnx_pb2 import TensorProto class TestModel(unittest.TestCase): def test_relu_node_inplace(self): X = np.random.randn(3, 2).astype(np.float32) Y_ref = np.clip(X, 0, np.inf) node_def = helper.make_node( "Relu", ["X"], ["X"]) graph_def = helper.make_graph( [node_def], name="test", inputs=[helper.make_tensor_value_info("X", TensorProto.FLOAT, [3, 2])], outputs=[helper.make_tensor_value_info("X", TensorProto.FLOAT, [3, 2])]) tf_rep = prepare(helper.make_model(graph_def)) output = tf_rep.run({"X": X}) np.testing.assert_almost_equal(output.X, Y_ref) def test_initializer(self): X = np.array([[1, 2], [3, 4]]).astype(np.float32) Y = np.array([[1, 2], [3, 4]]).astype(np.float32) weight = np.array([[1, 0], [0, 1]]) graph_def = helper.make_graph( [helper.make_node("Add", ["X", "Y"], ["Z0"]), helper.make_node("Cast", ["Z0"], ["Z"], to="float"), helper.make_node("Mul", ["Z", "weight"], ["W"]), helper.make_node("Tanh", ["W"], ["W"]), helper.make_node("Sigmoid", ["W"], ["W"])], name="test_initializer", inputs=[ helper.make_tensor_value_info("X", TensorProto.FLOAT, (2, 2)), helper.make_tensor_value_info("Y", TensorProto.FLOAT, (2, 2)), helper.make_tensor_value_info("weight", TensorProto.FLOAT, (2, 2)), ], outputs=[ helper.make_tensor_value_info("W", TensorProto.FLOAT, (2, 2)) ], initializer=[helper.make_tensor("weight", TensorProto.FLOAT, [2, 2], weight.flatten().astype(float))] ) def sigmoid(x): return 1 / (1 + np.exp(-x)) W_ref = sigmoid(np.tanh((X + Y) * weight)) tf_rep = prepare(helper.make_model(graph_def)) output = tf_rep.run({"X": X, "Y": Y}) np.testing.assert_almost_equal(output["W"], W_ref) if __name__ == '__main__': unittest.main()
true
true
1c2cdcee8c20701e6b9c30738803954fe5a98f17
2,347
py
Python
Python/lexer/src/tokens.py
wendrewdevelop/Estudos
f75d62574a0455ff35b97d404329e43f12f419fb
[ "MIT" ]
null
null
null
Python/lexer/src/tokens.py
wendrewdevelop/Estudos
f75d62574a0455ff35b97d404329e43f12f419fb
[ "MIT" ]
null
null
null
Python/lexer/src/tokens.py
wendrewdevelop/Estudos
f75d62574a0455ff35b97d404329e43f12f419fb
[ "MIT" ]
null
null
null
tokens = [ ('{', 'LKEY'), ('}', 'RKEY'), ('[', 'LBRACKETS'), (']', 'RBRACKETS'), ('(', 'LPARENTHESES'), (')', 'RPARENTHESES'), ('+', 'PLUS'), ('-', 'MINUS'), ('/', 'DIVISION'), ('%', 'MODULO'), ('~', 'NOT'), ('=', 'EQUALS'), ('<', 'LT'), ('>', 'GT'), ('<=', 'LTE'), ('>=', 'GTE'), ('==', 'DOUBLEEQUAL'), ('&', 'AND'), ('|', 'OR'), ('int', 'INTEGER'), ('float', 'FLOAT'), ('str', 'STRING'), ('#', 'COMMENT'), # capital ('A', 'CHAR a'), ('B', 'CHAR b'), ('C', 'CHAR c'), ('D', 'CHAR d'), ('E', 'CHAR e'), ('F', 'CHAR f'), ('G', 'CHAR g'), ('H', 'CHAR h'), ('I', 'CHAR i'), ('J', 'CHAR j'), ('K', 'CHAR k'), ('L', 'CHAR l'), ('M', 'CHAR m'), ('N', 'CHAR n'), ('O', 'CHAR o'), ('P', 'CHAR p'), ('Q', 'CHAR q'), ('R', 'CHAR r'), ('S', 'CHAR s'), ('T', 'CHAR t'), ('U', 'CHAR u'), ('Y', 'CHAR y'), ('V', 'CHAR v'), ('X', 'CHAR x'), ('W', 'CHAR w'), ('Y', 'CHAR y'), ('Z', 'CHAR z'), # tiny ('a', 'CHAR a'), ('b', 'CHAR b'), ('c', 'CHAR c'), ('d', 'CHAR d'), ('e', 'CHAR e'), ('f', 'CHAR f'), ('g', 'CHAR g'), ('h', 'CHAR h'), ('i', 'CHAR i'), ('j', 'CHAR j'), ('k', 'CHAR k'), ('l', 'CHAR l'), ('m', 'CHAR m'), ('n', 'CHAR n'), ('o', 'CHAR o'), ('p', 'CHAR p'), ('q', 'CHAR q'), ('r', 'CHAR r'), ('s', 'CHAR s'), ('t', 'CHAR t'), ('u', 'CHAR u'), ('v', 'CHAR v'), ('x', 'CHAR x'), ('w', 'CHAR w'), ('y', 'CHAR y'), ('z', 'CHAR z'), ('0', 'INT zero'), ('1', 'INT one'), ('2', 'INT two'), ('3', 'INT three'), ('4', 'INT four'), ('5', 'INT five'), ('6', 'INT six'), ('7', 'INT seven'), ('8', 'INT eight'), ('9', 'INT nine'), ] # Regular expression rules for simple tokens t_PLUS = r'\+' t_MINUS = r'-' t_MULTIPLY = r'\*' t_DIVIDE = r'/' t_MODULO = r'%' t_LPAREN = r'\(' t_RPAREN = r'\)' t_LBRACE = r'\[' t_RBRACE = r'\]' t_BLOCKSTART = r'\{' t_BLOCKEND = r'\}' t_NOT = r'\~' t_EQUALS = r'\=' t_GT = r'\>' t_LT = r'\<' t_LTE = r'\<\=' t_GTE = r'\>\=' t_DOUBLEEQUAL = r'\=\=' t_NE = r'\!\=' t_AND = r'\&' t_OR = r'\|' t_COMMENT = r'\#.*' t_ignore = ' \t' # ignore spaces and tabs
19.889831
44
0.342991
tokens = [ ('{', 'LKEY'), ('}', 'RKEY'), ('[', 'LBRACKETS'), (']', 'RBRACKETS'), ('(', 'LPARENTHESES'), (')', 'RPARENTHESES'), ('+', 'PLUS'), ('-', 'MINUS'), ('/', 'DIVISION'), ('%', 'MODULO'), ('~', 'NOT'), ('=', 'EQUALS'), ('<', 'LT'), ('>', 'GT'), ('<=', 'LTE'), ('>=', 'GTE'), ('==', 'DOUBLEEQUAL'), ('&', 'AND'), ('|', 'OR'), ('int', 'INTEGER'), ('float', 'FLOAT'), ('str', 'STRING'), ('#', 'COMMENT'), ('A', 'CHAR a'), ('B', 'CHAR b'), ('C', 'CHAR c'), ('D', 'CHAR d'), ('E', 'CHAR e'), ('F', 'CHAR f'), ('G', 'CHAR g'), ('H', 'CHAR h'), ('I', 'CHAR i'), ('J', 'CHAR j'), ('K', 'CHAR k'), ('L', 'CHAR l'), ('M', 'CHAR m'), ('N', 'CHAR n'), ('O', 'CHAR o'), ('P', 'CHAR p'), ('Q', 'CHAR q'), ('R', 'CHAR r'), ('S', 'CHAR s'), ('T', 'CHAR t'), ('U', 'CHAR u'), ('Y', 'CHAR y'), ('V', 'CHAR v'), ('X', 'CHAR x'), ('W', 'CHAR w'), ('Y', 'CHAR y'), ('Z', 'CHAR z'), ('a', 'CHAR a'), ('b', 'CHAR b'), ('c', 'CHAR c'), ('d', 'CHAR d'), ('e', 'CHAR e'), ('f', 'CHAR f'), ('g', 'CHAR g'), ('h', 'CHAR h'), ('i', 'CHAR i'), ('j', 'CHAR j'), ('k', 'CHAR k'), ('l', 'CHAR l'), ('m', 'CHAR m'), ('n', 'CHAR n'), ('o', 'CHAR o'), ('p', 'CHAR p'), ('q', 'CHAR q'), ('r', 'CHAR r'), ('s', 'CHAR s'), ('t', 'CHAR t'), ('u', 'CHAR u'), ('v', 'CHAR v'), ('x', 'CHAR x'), ('w', 'CHAR w'), ('y', 'CHAR y'), ('z', 'CHAR z'), ('0', 'INT zero'), ('1', 'INT one'), ('2', 'INT two'), ('3', 'INT three'), ('4', 'INT four'), ('5', 'INT five'), ('6', 'INT six'), ('7', 'INT seven'), ('8', 'INT eight'), ('9', 'INT nine'), ] t_PLUS = r'\+' t_MINUS = r'-' t_MULTIPLY = r'\*' t_DIVIDE = r'/' t_MODULO = r'%' t_LPAREN = r'\(' t_RPAREN = r'\)' t_LBRACE = r'\[' t_RBRACE = r'\]' t_BLOCKSTART = r'\{' t_BLOCKEND = r'\}' t_NOT = r'\~' t_EQUALS = r'\=' t_GT = r'\>' t_LT = r'\<' t_LTE = r'\<\=' t_GTE = r'\>\=' t_DOUBLEEQUAL = r'\=\=' t_NE = r'\!\=' t_AND = r'\&' t_OR = r'\|' t_COMMENT = r'\#.*' t_ignore = ' \t'
true
true
1c2cdd16677c9730abc586127f04cef9da7a2435
5,825
py
Python
server/libs/outputs/output_raspi.py
teemosauce/rpi-cube
6fd8cff81da5efe87fe4c911ce4b067644ea266f
[ "MIT" ]
195
2019-12-26T11:19:27.000Z
2022-03-28T04:20:34.000Z
server/libs/outputs/output_raspi.py
teemosauce/rpi-cube
6fd8cff81da5efe87fe4c911ce4b067644ea266f
[ "MIT" ]
144
2019-09-07T19:10:13.000Z
2022-03-30T07:24:02.000Z
server/libs/outputs/output_raspi.py
teemosauce/rpi-cube
6fd8cff81da5efe87fe4c911ce4b067644ea266f
[ "MIT" ]
51
2019-12-02T00:13:47.000Z
2022-03-29T17:26:47.000Z
from libs.outputs.output import Output # pylint: disable=E0611, E0401 import numpy as np import logging class OutputRaspi(Output): def __init__(self, device): # Call the constructor of the base class. super(OutputRaspi, self).__init__(device) self.logger = logging.getLogger(__name__) import _rpi_ws281x as ws # pylint: disable=import-error output_id = "output_raspi" # LED strip configuration: self._led_count = int(self._device_config["led_count"]) # Number of LED pixels. self._led_pin = int(self._device_config["output"][output_id]["led_pin"]) # GPIO pin connected to the pixels (18 uses PWM!). self._led_freq_hz = int(self._device_config["output"][output_id]["led_freq_hz"]) # LED signal frequency in hertz (usually 800khz). self._led_dma = int(self._device_config["output"][output_id]["led_dma"]) # DMA channel to use for generating signal (try 10). self._led_brightness = int(self._device_config["led_brightness"]) # Set to '0' for darkest and 100 for brightest. self._led_invert = int(self._device_config["output"][output_id]["led_invert"]) # Set to 'True' to invert the signal (when using NPN transistor level shift). self._led_channel = int(self._device_config["output"][output_id]["led_channel"]) # set to '1' for GPIOs 13, 19, 41, 45 or 53. self._led_strip = self._device_config["led_strip"] # Set Fallback Strip self._led_strip_translated = ws.WS2811_STRIP_RGB self._led_strip_mapper = { "sk6812_strip_rgbw": ws.SK6812_STRIP_RGBW, "sk6812_strip_rbgw": ws.SK6812_STRIP_RBGW, "sk6812_strip_grbw": ws.SK6812_STRIP_GRBW, "sk6812_strip_gbrw": ws.SK6812_STRIP_GBRW, "sk6812_strip_brgw": ws.SK6812_STRIP_BRGW, "sk6812_strip_bgrw": ws.SK6812_STRIP_BGRW, "sk6812_shift_wmask": ws.SK6812_SHIFT_WMASK, "ws2811_strip_rgb": ws.WS2811_STRIP_RGB, "ws2811_strip_rbg": ws.WS2811_STRIP_RBG, "ws2811_strip_grb": ws.WS2811_STRIP_GRB, "ws2811_strip_gbr": ws.WS2811_STRIP_GBR, "ws2811_strip_brg": ws.WS2811_STRIP_BRG, "ws2811_strip_bgr": ws.WS2811_STRIP_BGR, "ws2812_strip": ws.WS2812_STRIP, "sk6812_strip": ws.SK6812_STRIP, "sk6812w_strip": ws.SK6812W_STRIP } try: led_strip = self._led_strip_mapper[self._led_strip] if led_strip is not None: self._led_strip_translated = led_strip self.logger.debug(f"Found Led Strip {self._led_strip}") except Exception as e: self.logger.exception(f"Could not find LED Strip Type. Exception: {str(e)}") pass self._led_brightness_translated = int(255 * (self._led_brightness / 100)) self.logger.debug(f"LED Brightness: {self._led_brightness}") self.logger.debug(f"LED Brightness converted: {self._led_brightness_translated}") self._leds = ws.new_ws2811_t() self.channel = ws.ws2811_channel_get(self._leds, self._led_channel) ws.ws2811_channel_t_strip_type_set(self.channel, self._led_strip_translated) ws.ws2811_channel_t_count_set(self.channel, self._led_count) ws.ws2811_channel_t_gpionum_set(self.channel, self._led_pin) ws.ws2811_channel_t_invert_set(self.channel, self._led_invert) ws.ws2811_channel_t_brightness_set(self.channel, self._led_brightness_translated) ws.ws2811_t_freq_set(self._leds, self._led_freq_hz) ws.ws2811_t_dmanum_set(self._leds, self._led_dma) # Initialize library with LED configuration. resp = ws.ws2811_init(self._leds) if resp != ws.WS2811_SUCCESS: message = ws.ws2811_get_return_t_str(resp) raise RuntimeError(f'ws2811_init failed with code {resp} ({message})') def show(self, output_array): import _rpi_ws281x as ws # pylint: disable=import-error # Typecast the array to int. output_array = output_array.clip(0, 255).astype(int) # Check if we have a white channel or not. if len(output_array[:]) == 4 and "SK6812" in self._led_strip: # Sort the colors as RGB type. g = np.left_shift(output_array[1][:].astype(int), 24) # pylint: disable=assignment-from-no-return r = np.left_shift(output_array[0][:].astype(int), 16) # pylint: disable=assignment-from-no-return b = np.left_shift(output_array[2][:].astype(int), 8) # pylint: disable=assignment-from-no-return w = output_array[3][:].astype(int) grbw = np.bitwise_or(np.bitwise_or(np.bitwise_or(r, g), b), w).astype(int) # You can only use ws2811_leds_set with the custom version. for i in range(self._led_count): ws.ws2811_led_set(self.channel, i, int(grbw[i].item())) else: # Sort the colors as RGB type. g = np.left_shift(output_array[1][:].astype(int), 16) # pylint: disable=assignment-from-no-return r = np.left_shift(output_array[0][:].astype(int), 8) # pylint: disable=assignment-from-no-return b = output_array[2][:].astype(int) grb = np.bitwise_or(np.bitwise_or(r, g), b).astype(int) # You can only use ws2811_leds_set with the custom version. for i in range(self._led_count): ws.ws2811_led_set(self.channel, i, grb[i].item()) resp = ws.ws2811_render(self._leds) if resp != ws.WS2811_SUCCESS: message = ws.ws2811_get_return_t_str(resp) raise RuntimeError(f'ws2811_render failed with code {resp} ({message})')
50.215517
173
0.647039
from libs.outputs.output import Output import numpy as np import logging class OutputRaspi(Output): def __init__(self, device): super(OutputRaspi, self).__init__(device) self.logger = logging.getLogger(__name__) import _rpi_ws281x as ws output_id = "output_raspi" self._led_count = int(self._device_config["led_count"]) self._led_pin = int(self._device_config["output"][output_id]["led_pin"]) self._led_freq_hz = int(self._device_config["output"][output_id]["led_freq_hz"]) self._led_dma = int(self._device_config["output"][output_id]["led_dma"]) self._led_brightness = int(self._device_config["led_brightness"]) self._led_invert = int(self._device_config["output"][output_id]["led_invert"]) self._led_channel = int(self._device_config["output"][output_id]["led_channel"]) self._led_strip = self._device_config["led_strip"] self._led_strip_translated = ws.WS2811_STRIP_RGB self._led_strip_mapper = { "sk6812_strip_rgbw": ws.SK6812_STRIP_RGBW, "sk6812_strip_rbgw": ws.SK6812_STRIP_RBGW, "sk6812_strip_grbw": ws.SK6812_STRIP_GRBW, "sk6812_strip_gbrw": ws.SK6812_STRIP_GBRW, "sk6812_strip_brgw": ws.SK6812_STRIP_BRGW, "sk6812_strip_bgrw": ws.SK6812_STRIP_BGRW, "sk6812_shift_wmask": ws.SK6812_SHIFT_WMASK, "ws2811_strip_rgb": ws.WS2811_STRIP_RGB, "ws2811_strip_rbg": ws.WS2811_STRIP_RBG, "ws2811_strip_grb": ws.WS2811_STRIP_GRB, "ws2811_strip_gbr": ws.WS2811_STRIP_GBR, "ws2811_strip_brg": ws.WS2811_STRIP_BRG, "ws2811_strip_bgr": ws.WS2811_STRIP_BGR, "ws2812_strip": ws.WS2812_STRIP, "sk6812_strip": ws.SK6812_STRIP, "sk6812w_strip": ws.SK6812W_STRIP } try: led_strip = self._led_strip_mapper[self._led_strip] if led_strip is not None: self._led_strip_translated = led_strip self.logger.debug(f"Found Led Strip {self._led_strip}") except Exception as e: self.logger.exception(f"Could not find LED Strip Type. Exception: {str(e)}") pass self._led_brightness_translated = int(255 * (self._led_brightness / 100)) self.logger.debug(f"LED Brightness: {self._led_brightness}") self.logger.debug(f"LED Brightness converted: {self._led_brightness_translated}") self._leds = ws.new_ws2811_t() self.channel = ws.ws2811_channel_get(self._leds, self._led_channel) ws.ws2811_channel_t_strip_type_set(self.channel, self._led_strip_translated) ws.ws2811_channel_t_count_set(self.channel, self._led_count) ws.ws2811_channel_t_gpionum_set(self.channel, self._led_pin) ws.ws2811_channel_t_invert_set(self.channel, self._led_invert) ws.ws2811_channel_t_brightness_set(self.channel, self._led_brightness_translated) ws.ws2811_t_freq_set(self._leds, self._led_freq_hz) ws.ws2811_t_dmanum_set(self._leds, self._led_dma) resp = ws.ws2811_init(self._leds) if resp != ws.WS2811_SUCCESS: message = ws.ws2811_get_return_t_str(resp) raise RuntimeError(f'ws2811_init failed with code {resp} ({message})') def show(self, output_array): import _rpi_ws281x as ws output_array = output_array.clip(0, 255).astype(int) if len(output_array[:]) == 4 and "SK6812" in self._led_strip: g = np.left_shift(output_array[1][:].astype(int), 24) r = np.left_shift(output_array[0][:].astype(int), 16) b = np.left_shift(output_array[2][:].astype(int), 8) w = output_array[3][:].astype(int) grbw = np.bitwise_or(np.bitwise_or(np.bitwise_or(r, g), b), w).astype(int) for i in range(self._led_count): ws.ws2811_led_set(self.channel, i, int(grbw[i].item())) else: g = np.left_shift(output_array[1][:].astype(int), 16) r = np.left_shift(output_array[0][:].astype(int), 8) b = output_array[2][:].astype(int) grb = np.bitwise_or(np.bitwise_or(r, g), b).astype(int) for i in range(self._led_count): ws.ws2811_led_set(self.channel, i, grb[i].item()) resp = ws.ws2811_render(self._leds) if resp != ws.WS2811_SUCCESS: message = ws.ws2811_get_return_t_str(resp) raise RuntimeError(f'ws2811_render failed with code {resp} ({message})')
true
true
1c2cdd4c96a07c86e4063ad6ac2cbf5917e09ecf
6,784
py
Python
bluesky_queueserver/server/server.py
cryos/bluesky-queueserver
26779cfb9795f29718769a0334295101c9c8e928
[ "BSD-3-Clause" ]
null
null
null
bluesky_queueserver/server/server.py
cryos/bluesky-queueserver
26779cfb9795f29718769a0334295101c9c8e928
[ "BSD-3-Clause" ]
null
null
null
bluesky_queueserver/server/server.py
cryos/bluesky-queueserver
26779cfb9795f29718769a0334295101c9c8e928
[ "BSD-3-Clause" ]
null
null
null
import asyncio import logging from enum import Enum import zmq import zmq.asyncio from fastapi import FastAPI, HTTPException logger = logging.getLogger(__name__) """ # The following plans that can be used to test the server http POST http://localhost:8080/add_to_queue plan:='{"name":"count", "args":[["det1", "det2"]]}' # This is the slowly running plan (convenient to test pausing) http POST http://localhost:8080/add_to_queue plan:='{"name":"count", "args":[["det1", "det2"]], "kwargs":{"num":10, "delay":1}}' http POST http://localhost:8080/add_to_queue plan:='{"name":"scan", "args":[["det1", "det2"], "motor", -1, 1, 10]}' """ class ZMQ_Comm: def __init__(self, zmq_host='localhost', zmq_port='5555'): self._loop = asyncio.get_event_loop() # ZeroMQ communication self._ctx = zmq.asyncio.Context() self._zmq_socket = None self._zmq_server_address = f"tcp://{zmq_host}:{zmq_port}" # Start communication task self._event_zmq_stop = None self._task_zmq_client_conn = asyncio.ensure_future(self._zmq_start_client_conn()) def __del__(self): # Cancel the communication task if not self._task_zmq_client_conn.done(): self._task_zmq_client_conn.cancel() def get_loop(self): """ Returns the asyncio loop. """ return self._loop # ========================================================================== # Functions that support ZeroMQ communications with RE Manager async def _zmq_send(self, msg): await self._zmq_socket.send_json(msg) async def _zmq_receive(self): try: msg = await self._zmq_socket.recv_json() except Exception as ex: # TODO: proper error handling for cases when connection is interrupted. # This is primitive error handling to make sure the server doesn't get stuck # if there is no reply after timeout. The server still needs to be restarted # if it was disconnected, since there is not mechanism to reestablish # connection. logger.exception("ZeroMQ communication failed: %s" % str(ex)) msg = {} return msg async def _zmq_communicate(self, msg_out): await self._zmq_send(msg_out) msg_in = await self._zmq_receive() return msg_in async def _zmq_start_client_conn(self): self._event_zmq_stop = asyncio.Event() self._zmq_socket = self._ctx.socket(zmq.REQ) self._zmq_socket.RCVTIMEO = 2000 # Timeout for 'recv' operation self._zmq_socket.connect(self._zmq_server_address) logger.info("Connected to ZeroMQ server '%s'" % str(self._zmq_server_address)) # The event must be set somewhere else await self._event_zmq_stop.wait() def _create_msg(self, *, command, params=None): return {"method": command, "params": params} async def _send_command(self, *, command, params=None): msg_out = self._create_msg(command=command, params=params) msg_in = await self._zmq_communicate(msg_out) return msg_in logging.basicConfig(level=logging.WARNING) logging.getLogger('bluesky_queueserver').setLevel("DEBUG") # Use FastAPI app = FastAPI() re_server = ZMQ_Comm() class REPauseOptions(str, Enum): deferred = 'deferred' immediate = 'immediate' class REResumeOptions(str, Enum): resume = 'resume' abort = 'abort' stop = 'stop' halt = 'halt' @app.get('/') async def _hello_handler(): """ May be called to get response from the server. Returns the number of plans in the queue. """ msg = await re_server._send_command(command="") return msg @app.get('/queue_view') async def _queue_view_handler(): """ Returns the contents of the current queue. """ msg = await re_server._send_command(command="queue_view") return msg @app.get('/list_allowed_plans_and_devices') async def _list_allowed_plans_and_devices_handler(): """ Returns the lists of allowed plans and devices. """ msg = await re_server._send_command(command="list_allowed_plans_and_devices") return msg @app.post('/add_to_queue') async def _add_to_queue_handler(payload: dict): """ Adds new plan to the end of the queue """ # TODO: validate inputs! msg = await re_server._send_command(command="add_to_queue", params=payload) return msg @app.post('/pop_from_queue') async def _pop_from_queue_handler(): """ Pop the last item from back of the queue """ msg = await re_server._send_command(command="pop_from_queue") return msg @app.post('/create_environment') async def _create_environment_handler(): """ Creates RE environment: creates RE Worker process, starts and configures Run Engine. """ msg = await re_server._send_command(command="create_environment") return msg @app.post('/close_environment') async def _close_environment_handler(): """ Deletes RE environment. In the current 'demo' prototype the environment will be deleted only after RE completes the current scan. """ msg = await re_server._send_command(command="close_environment") return msg @app.post('/process_queue') async def _process_queue_handler(): """ Start execution of the loaded queue. Additional runs can be added to the queue while it is executed. If the queue is empty, then nothing will happen. """ msg = await re_server._send_command(command="process_queue") return msg @app.post('/re_pause') async def _re_pause_handler(payload: dict): """ Pause Run Engine """ if not hasattr(REPauseOptions, payload['option']): msg = (f'The specified option "{payload["option"]}" is not allowed.\n' f'Allowed options: {list(REPauseOptions.__members__.keys())}') raise HTTPException(status_code=444, detail=msg) msg = await re_server._send_command(command="re_pause", params=payload) return msg @app.post('/re_continue') async def _re_continue_handler(payload: dict): """ Control Run Engine in the paused state """ if not hasattr(REResumeOptions, payload['option']): msg = (f'The specified option "{payload["option"]}" is not allowed.\n' f'Allowed options: {list(REResumeOptions.__members__.keys())}') raise HTTPException(status_code=444, detail=msg) msg = await re_server._send_command(command="re_continue", params=payload) return msg @app.post('/print_db_uids') async def _print_db_uids_handler(): """ Prints the UIDs of the scans in 'temp' database. Just for the demo. Not part of future API. """ msg = await re_server._send_command(command="print_db_uids") return msg
30.696833
115
0.667748
import asyncio import logging from enum import Enum import zmq import zmq.asyncio from fastapi import FastAPI, HTTPException logger = logging.getLogger(__name__) class ZMQ_Comm: def __init__(self, zmq_host='localhost', zmq_port='5555'): self._loop = asyncio.get_event_loop() self._ctx = zmq.asyncio.Context() self._zmq_socket = None self._zmq_server_address = f"tcp://{zmq_host}:{zmq_port}" self._event_zmq_stop = None self._task_zmq_client_conn = asyncio.ensure_future(self._zmq_start_client_conn()) def __del__(self): if not self._task_zmq_client_conn.done(): self._task_zmq_client_conn.cancel() def get_loop(self): return self._loop async def _zmq_send(self, msg): await self._zmq_socket.send_json(msg) async def _zmq_receive(self): try: msg = await self._zmq_socket.recv_json() except Exception as ex: # if there is no reply after timeout. The server still needs to be restarted # if it was disconnected, since there is not mechanism to reestablish # connection. logger.exception("ZeroMQ communication failed: %s" % str(ex)) msg = {} return msg async def _zmq_communicate(self, msg_out): await self._zmq_send(msg_out) msg_in = await self._zmq_receive() return msg_in async def _zmq_start_client_conn(self): self._event_zmq_stop = asyncio.Event() self._zmq_socket = self._ctx.socket(zmq.REQ) self._zmq_socket.RCVTIMEO = 2000 # Timeout for 'recv' operation self._zmq_socket.connect(self._zmq_server_address) logger.info("Connected to ZeroMQ server '%s'" % str(self._zmq_server_address)) # The event must be set somewhere else await self._event_zmq_stop.wait() def _create_msg(self, *, command, params=None): return {"method": command, "params": params} async def _send_command(self, *, command, params=None): msg_out = self._create_msg(command=command, params=params) msg_in = await self._zmq_communicate(msg_out) return msg_in logging.basicConfig(level=logging.WARNING) logging.getLogger('bluesky_queueserver').setLevel("DEBUG") # Use FastAPI app = FastAPI() re_server = ZMQ_Comm() class REPauseOptions(str, Enum): deferred = 'deferred' immediate = 'immediate' class REResumeOptions(str, Enum): resume = 'resume' abort = 'abort' stop = 'stop' halt = 'halt' @app.get('/') async def _hello_handler(): msg = await re_server._send_command(command="") return msg @app.get('/queue_view') async def _queue_view_handler(): msg = await re_server._send_command(command="queue_view") return msg @app.get('/list_allowed_plans_and_devices') async def _list_allowed_plans_and_devices_handler(): msg = await re_server._send_command(command="list_allowed_plans_and_devices") return msg @app.post('/add_to_queue') async def _add_to_queue_handler(payload: dict): # TODO: validate inputs! msg = await re_server._send_command(command="add_to_queue", params=payload) return msg @app.post('/pop_from_queue') async def _pop_from_queue_handler(): msg = await re_server._send_command(command="pop_from_queue") return msg @app.post('/create_environment') async def _create_environment_handler(): msg = await re_server._send_command(command="create_environment") return msg @app.post('/close_environment') async def _close_environment_handler(): msg = await re_server._send_command(command="close_environment") return msg @app.post('/process_queue') async def _process_queue_handler(): msg = await re_server._send_command(command="process_queue") return msg @app.post('/re_pause') async def _re_pause_handler(payload: dict): if not hasattr(REPauseOptions, payload['option']): msg = (f'The specified option "{payload["option"]}" is not allowed.\n' f'Allowed options: {list(REPauseOptions.__members__.keys())}') raise HTTPException(status_code=444, detail=msg) msg = await re_server._send_command(command="re_pause", params=payload) return msg @app.post('/re_continue') async def _re_continue_handler(payload: dict): if not hasattr(REResumeOptions, payload['option']): msg = (f'The specified option "{payload["option"]}" is not allowed.\n' f'Allowed options: {list(REResumeOptions.__members__.keys())}') raise HTTPException(status_code=444, detail=msg) msg = await re_server._send_command(command="re_continue", params=payload) return msg @app.post('/print_db_uids') async def _print_db_uids_handler(): msg = await re_server._send_command(command="print_db_uids") return msg
true
true
1c2cdd8d2589cf367c8d58ec2633071a4db6a946
3,878
py
Python
karl_markov.py
hawkw/COMINTERNALS
dfa3da4352414e27fa08b0672ec95c65f3807bd5
[ "CC0-1.0" ]
null
null
null
karl_markov.py
hawkw/COMINTERNALS
dfa3da4352414e27fa08b0672ec95c65f3807bd5
[ "CC0-1.0" ]
null
null
null
karl_markov.py
hawkw/COMINTERNALS
dfa3da4352414e27fa08b0672ec95c65f3807bd5
[ "CC0-1.0" ]
null
null
null
import markovify import textwrap import re model_json_path = "karl.json" cite_re = re.compile( r"""([0-9IVXMivx]*[\.\s,;]*(?:[0-9IVXMivx]+[\.\s;,]*c[\.\s;,]*)?[\.\s;,]*(?:(?:(?:t)|(?:Vol)|(?:Book)|(?:Ch))[\.\s,;]+[0-9IVXMivx]+[\.\s;,]*)*[\.\s,]*[p]+(?:[\.\s;,]+[0-9IVXMivx]+[\.\s,;]*)+)""", re.MULTILINE) hyphen_newline_re = re.compile(r"""(-$)""", re.MULTILINE) def dehyphenate(string): """Remove hyphenated linebreaks from 'string'.""" return hyphen_newline_re.sub("", string) def preprocess(string): """Remove hyphenated linebreaks and citations from 'string'.""" string = cite_re.sub("", string) string = dehyphenate(string) return string def load_file(path): """Load a text file for making a model.""" with open(path) as f: return preprocess(f.read()) def make_karl(): """Makes the Karl Markov model""" # Get raw text as string. manifesto_text = load_file("communist_manifesto.txt") kapital_text = load_file("kapital_vol_1.txt") # skip the Project Gutenberg footer at the end gutenberg_footer = 72910 manifesto_text = manifesto_text[:gutenberg_footer] # make the models for each input corpus manifesto = markovify.Text(manifesto_text) kapital = markovify.Text(kapital_text) # combine the models manifesto_weight = 1 kapital_weight = len(manifesto_text) / len(kapital_text) # print("Das Kapital weight: {}".format(kapital_weight)) return markovify.combine([manifesto, kapital], [manifesto_weight, kapital_weight]) def get_karl(): """Loads the Karl Markov model from JSON or else creates it""" try: with open(model_json_path) as f: json = f.read() return markovify.Text.from_json(json) except FileNotFoundError: model = make_karl() with open(model_json_path, "r") as f: f.write(model.to_json()) return model class KarlMarkov(object): def __init__(self): self.model = make_karl() self.the_peoples_idents = {} def make_ident(old_ident): length = len(old_id) ident = self.idents[old_ident] while not ident: length = length + 1 if length <= 30 else length id_try = self.model.make_short_sentence(length, tries=100, max_overlap_ratio=100, max_overlap_total=300) # ensure the new identifier is valid if id_try: id_try = c.invalid_id_re.sub("", id_try.replace(' ', '_')) id_try = id_try.upper() if old_id.isupper() else id_try.lower() if not id_try[0].isalpha(): id_try = id_try[1:] if id_try not in self.idents.values(): ident = id_try self.idents[old_ident] = idents return ident def replace_comment_line(old_line): if old_line.startswith("/*"): begin = "/* " elif old_line.startswith(" *"): begin = " * " else: begin = "" end = " */" if old_line.endswith("*/") else "" new_line = None length = 30 if len(old_line) < 30 else len(old_line) while not new_line: new_line = self.model.make_short_sentence(length, tries=100, max_overlap_ratio=100, max_overlap_total=600) return begin + new_line + end if __name__ == "__main__": com = make_karl() sentence = None while not sentence: sentence = com.make_sentence() print("\n\"{}\" \n -- Karl Markov\n".format(textwrap.fill(sentence, 50)))
34.936937
195
0.552347
import markovify import textwrap import re model_json_path = "karl.json" cite_re = re.compile( r"""([0-9IVXMivx]*[\.\s,;]*(?:[0-9IVXMivx]+[\.\s;,]*c[\.\s;,]*)?[\.\s;,]*(?:(?:(?:t)|(?:Vol)|(?:Book)|(?:Ch))[\.\s,;]+[0-9IVXMivx]+[\.\s;,]*)*[\.\s,]*[p]+(?:[\.\s;,]+[0-9IVXMivx]+[\.\s,;]*)+)""", re.MULTILINE) hyphen_newline_re = re.compile(r"""(-$)""", re.MULTILINE) def dehyphenate(string): return hyphen_newline_re.sub("", string) def preprocess(string): string = cite_re.sub("", string) string = dehyphenate(string) return string def load_file(path): with open(path) as f: return preprocess(f.read()) def make_karl(): manifesto_text = load_file("communist_manifesto.txt") kapital_text = load_file("kapital_vol_1.txt") gutenberg_footer = 72910 manifesto_text = manifesto_text[:gutenberg_footer] manifesto = markovify.Text(manifesto_text) kapital = markovify.Text(kapital_text) manifesto_weight = 1 kapital_weight = len(manifesto_text) / len(kapital_text) return markovify.combine([manifesto, kapital], [manifesto_weight, kapital_weight]) def get_karl(): try: with open(model_json_path) as f: json = f.read() return markovify.Text.from_json(json) except FileNotFoundError: model = make_karl() with open(model_json_path, "r") as f: f.write(model.to_json()) return model class KarlMarkov(object): def __init__(self): self.model = make_karl() self.the_peoples_idents = {} def make_ident(old_ident): length = len(old_id) ident = self.idents[old_ident] while not ident: length = length + 1 if length <= 30 else length id_try = self.model.make_short_sentence(length, tries=100, max_overlap_ratio=100, max_overlap_total=300) if id_try: id_try = c.invalid_id_re.sub("", id_try.replace(' ', '_')) id_try = id_try.upper() if old_id.isupper() else id_try.lower() if not id_try[0].isalpha(): id_try = id_try[1:] if id_try not in self.idents.values(): ident = id_try self.idents[old_ident] = idents return ident def replace_comment_line(old_line): if old_line.startswith("/*"): begin = "/* " elif old_line.startswith(" *"): begin = " * " else: begin = "" end = " */" if old_line.endswith("*/") else "" new_line = None length = 30 if len(old_line) < 30 else len(old_line) while not new_line: new_line = self.model.make_short_sentence(length, tries=100, max_overlap_ratio=100, max_overlap_total=600) return begin + new_line + end if __name__ == "__main__": com = make_karl() sentence = None while not sentence: sentence = com.make_sentence() print("\n\"{}\" \n -- Karl Markov\n".format(textwrap.fill(sentence, 50)))
true
true
1c2cddd59cc5334436eae05da35778bc3a6ac137
4,674
py
Python
models/User.py
jacobbieker/smugwrapper
b1ccf198bb6c3c98f7c5dcf77471fad50ca13ae6
[ "MIT" ]
2
2017-12-11T22:33:50.000Z
2021-03-20T23:09:26.000Z
models/User.py
jacobbieker/smugwrapper
b1ccf198bb6c3c98f7c5dcf77471fad50ca13ae6
[ "MIT" ]
10
2018-06-14T18:57:29.000Z
2022-01-06T02:09:26.000Z
models/User.py
jacobbieker/smugwrapper
b1ccf198bb6c3c98f7c5dcf77471fad50ca13ae6
[ "MIT" ]
null
null
null
import http import SmugMug import Image, Album, Folder, Node, UserProfile, AlbumImage class User(object): def __init__(self, name, smugmug=None): self.name = name self.account_status = None self.first_name = "" self.friends_view = False self.image_count = 0 self.is_trial = False self.last_name = "" self.nick_name = "" self.sort_by = None self.view_pass_hint = "" self.view_password = "" self.domain = "" self.domain_only = "" self.ref_tag = "" self.name = "" self.plan = None self.total_account_size = None self.total_uploaded_size = None self.quick_share = False self.uri = "" self.bio_image = None self.cover_image = None self.user_profile = None self.node = None self.folder = None self.user_albums = None self.geo_media = None self.popular_media = None self.featured_albums = None self.recent_images = None self.image_search = None self.top_keywords = None self.url_path_lookup = None self.web_uri = None self.smugmug = smugmug def _follow_uri(self, uri, end_tag): """ Given a uri and tag to get, returns the value of that tag :param uri: URI to query :param end_tag: Tag, such as "AlbumImage" to search for in the response :return: """ return 0 def _get_object(self, uri, object_type): """ Given a URI and object_type, get the object :param uri: URI value :param object_type: Type of Object :return: Object of object_type located at the URI """ representation = None if self.smugmug is not None: downloader = http.downloader.Downloader(smugmug=self.smugmug) else: downloader = http.downloader.Downloader() if object_type == "UserProfile": representation = UserProfile._unpack_json(downloader.refresh_by_uri(object_type, uri)) elif object_type == "Node": representation = Node._unpack_json(downloader.refresh_by_uri(object_type, uri)) elif object_type == "Image": representation = Image._unpack_json(downloader.refresh_by_uri(object_type, uri)) elif object_type == "Folder": representation = Folder._unpack_json(downloader.refresh_by_uri(object_type, uri)) elif object_type == "Album": representation = Album._unpack_json(downloader.refresh_by_uri(object_type, uri)) elif object_type == "AlbumImage": representation = AlbumImage._unpack_json(downloader.refresh_by_uri(object_type, uri)) else: RuntimeError("Need valid object_type") return representation def _unpack_json(self, json_dictionary): """ Unpack to dictionary containing the JSON response for the album. Used to update values for Album object. ":param json_dictionary: Dictionary containing the JSON of the "Response" key, tested for, and assumed to be, with '_shorturis' and '_verbosity=1' options enabled for the JSON""" user_root = json_dictionary["User"] uri_root = user_root["Uris"] self.name = user_root["Name"] self.nick_name = user_root["NickName"] self.view_pass_hint = user_root["ViewPassHint"] self.quick_share = user_root["QuickShare"] self.uri = user_root["Uri"] self.web_uri = user_root["WebUri"] self.ref_tag = user_root["RefTag"] self.bio_image = self._get_object("Image", uri_root["BioImage"]["Uri"]) self.cover_image = self._get_object("Image", uri_root["CoverImage"]["Uri"]) self.user_profile = self._get_object("UserProfile", uri_root["UserProfile"]["Uri"]) self.user_albums = self._get_object("Node", uri_root["Node"]["Uri"]) self.folder = self._get_object("Folder", uri_root["Folder"]["Uri"]) return 0 def refresh(self): """ Updates Image object with data from SmugMug """ if self.nick_name is not None: if self.smugmug is not None: downloader = http.downloader.Downloader(smugmug=self.smugmug) else: downloader = http.downloader.Downloader() data = downloader.refresh_by_key("User", self.nick_name) self._unpack_json(data) return self def update(self): """ Updates the SmugMug Image with new data""" return self def upload(self): """ Uploads image to SmugMug""" return self
36.80315
117
0.619812
import http import SmugMug import Image, Album, Folder, Node, UserProfile, AlbumImage class User(object): def __init__(self, name, smugmug=None): self.name = name self.account_status = None self.first_name = "" self.friends_view = False self.image_count = 0 self.is_trial = False self.last_name = "" self.nick_name = "" self.sort_by = None self.view_pass_hint = "" self.view_password = "" self.domain = "" self.domain_only = "" self.ref_tag = "" self.name = "" self.plan = None self.total_account_size = None self.total_uploaded_size = None self.quick_share = False self.uri = "" self.bio_image = None self.cover_image = None self.user_profile = None self.node = None self.folder = None self.user_albums = None self.geo_media = None self.popular_media = None self.featured_albums = None self.recent_images = None self.image_search = None self.top_keywords = None self.url_path_lookup = None self.web_uri = None self.smugmug = smugmug def _follow_uri(self, uri, end_tag): return 0 def _get_object(self, uri, object_type): representation = None if self.smugmug is not None: downloader = http.downloader.Downloader(smugmug=self.smugmug) else: downloader = http.downloader.Downloader() if object_type == "UserProfile": representation = UserProfile._unpack_json(downloader.refresh_by_uri(object_type, uri)) elif object_type == "Node": representation = Node._unpack_json(downloader.refresh_by_uri(object_type, uri)) elif object_type == "Image": representation = Image._unpack_json(downloader.refresh_by_uri(object_type, uri)) elif object_type == "Folder": representation = Folder._unpack_json(downloader.refresh_by_uri(object_type, uri)) elif object_type == "Album": representation = Album._unpack_json(downloader.refresh_by_uri(object_type, uri)) elif object_type == "AlbumImage": representation = AlbumImage._unpack_json(downloader.refresh_by_uri(object_type, uri)) else: RuntimeError("Need valid object_type") return representation def _unpack_json(self, json_dictionary): user_root = json_dictionary["User"] uri_root = user_root["Uris"] self.name = user_root["Name"] self.nick_name = user_root["NickName"] self.view_pass_hint = user_root["ViewPassHint"] self.quick_share = user_root["QuickShare"] self.uri = user_root["Uri"] self.web_uri = user_root["WebUri"] self.ref_tag = user_root["RefTag"] self.bio_image = self._get_object("Image", uri_root["BioImage"]["Uri"]) self.cover_image = self._get_object("Image", uri_root["CoverImage"]["Uri"]) self.user_profile = self._get_object("UserProfile", uri_root["UserProfile"]["Uri"]) self.user_albums = self._get_object("Node", uri_root["Node"]["Uri"]) self.folder = self._get_object("Folder", uri_root["Folder"]["Uri"]) return 0 def refresh(self): if self.nick_name is not None: if self.smugmug is not None: downloader = http.downloader.Downloader(smugmug=self.smugmug) else: downloader = http.downloader.Downloader() data = downloader.refresh_by_key("User", self.nick_name) self._unpack_json(data) return self def update(self): return self def upload(self): return self
true
true
1c2cde369b76344112d3b0f62cd45ad785238f20
548
py
Python
python/movedirs.py
fieldingtron/wktvusa.com
42ddfd001decc7c0c45246ec24092f78e0744cf0
[ "MIT" ]
1
2018-11-15T13:14:54.000Z
2018-11-15T13:14:54.000Z
python/movedirs.py
fieldingtron/wktvusa
0e18e217ee68c76d20b6829f20fd5619b48f0e8b
[ "MIT" ]
3
2020-07-17T03:55:37.000Z
2021-05-09T00:07:22.000Z
python/movedirs.py
fieldingtron/wktvusa
0e18e217ee68c76d20b6829f20fd5619b48f0e8b
[ "MIT" ]
null
null
null
import os import shutil path = 'c:\\projects\\hc2\\' path = os.path.join("content", "videos") folders = [] # r=root, d=directories, f = files for r, d, f in os.walk(path): for folder in d: # folders.append(os.path.join(r, folder)) folders.append(folder) print("folder " + folder) oldname = os.path.join(r, folder,"index.md") newname = os.path.join(r, folder + "-.md") print ("move from " + oldname + " to " + newname ) shutil.move(oldname, newname) # for f in folders: # print(f)
26.095238
58
0.580292
import os import shutil path = 'c:\\projects\\hc2\\' path = os.path.join("content", "videos") folders = [] for r, d, f in os.walk(path): for folder in d: folders.append(folder) print("folder " + folder) oldname = os.path.join(r, folder,"index.md") newname = os.path.join(r, folder + "-.md") print ("move from " + oldname + " to " + newname ) shutil.move(oldname, newname)
true
true
1c2cde7f41d93bc9e0314ddb787048325ffe28bd
992
py
Python
diskimager.py
gallimania/lanbackuputil
d873bf852a98dc5c17987e3b6f38d060260a0de4
[ "MIT" ]
1
2020-01-14T06:15:51.000Z
2020-01-14T06:15:51.000Z
diskimager.py
gallimania/lanbackuputil
d873bf852a98dc5c17987e3b6f38d060260a0de4
[ "MIT" ]
1
2018-08-27T03:12:21.000Z
2018-08-27T03:12:21.000Z
diskimager.py
gallimania/netbackuputil
d873bf852a98dc5c17987e3b6f38d060260a0de4
[ "MIT" ]
null
null
null
# Copyright (C) 2018 Garrett Fifer # # This file contains the functions needed to provide to main python file with the ability # create and write ISO image files in order to provide an easy container for backed-up files. # # Begin diskimager.py try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO import pycdlib def create_iso_image(): """ Creates instance of pycdlib and initializes new iso object in system RAM. """ backup_iso = pycdlib.PyCdlib() iso.new() def add_iso_dir(): """ Allows user to specify a specific directory containing a group of files in which will be eventually written to the created iso file. """ dir_path = input('Path to directory with files you wish to backup to server: ') iso.add_directory(dir_path) def write_iso(): """ Writes the ISO to the hard disk before sending over the network to recieving backup server. """ iso_filename = input('Name your new backup file: ') iso.write(iso_filename)
32
101
0.745968
try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO import pycdlib def create_iso_image(): backup_iso = pycdlib.PyCdlib() iso.new() def add_iso_dir(): dir_path = input('Path to directory with files you wish to backup to server: ') iso.add_directory(dir_path) def write_iso(): iso_filename = input('Name your new backup file: ') iso.write(iso_filename)
true
true
1c2cdfc3bee042f498baac38566de655d6a0cdc2
5,117
py
Python
mix_style.py
tien1504/idinvert_pytorch
19999e9945aef4843a464930426a565256863ded
[ "MIT" ]
319
2020-07-21T02:26:55.000Z
2022-03-29T18:12:47.000Z
mix_style.py
tien1504/idinvert_pytorch
19999e9945aef4843a464930426a565256863ded
[ "MIT" ]
29
2020-07-21T03:19:56.000Z
2022-02-15T09:14:56.000Z
mix_style.py
tien1504/idinvert_pytorch
19999e9945aef4843a464930426a565256863ded
[ "MIT" ]
53
2020-07-22T07:47:52.000Z
2022-03-30T15:08:14.000Z
# python 3.6 """Mixes styles with In-domain GAN Inversion. The real images should be first inverted to latent codes with `invert.py`. After that, this script can be used for style mixing. NOTE: This script will mix every `style-content` image pair from style directory to content directory. """ import os import argparse from tqdm import tqdm import numpy as np from models.helper import build_generator from utils.logger import setup_logger from utils.editor import mix_style from utils.visualizer import load_image from utils.visualizer import HtmlPageVisualizer def parse_args(): """Parses arguments.""" parser = argparse.ArgumentParser() parser.add_argument('model_name', type=str, help='Name of the GAN model.') parser.add_argument('style_dir', type=str, help='Style directory, which includes original images, ' 'inverted codes, and image list.') parser.add_argument('content_dir', type=str, help='Content directory, which includes original images, ' 'inverted codes, and image list.') parser.add_argument('-o', '--output_dir', type=str, default='', help='Directory to save the results. If not specified, ' '`./results/style_mixing` will be used by default.') parser.add_argument('--mix_layer_start_idx', type=int, default=10, help='0-based layer index. Style mixing is performed ' 'from this layer to the last layer. (default: 10)') parser.add_argument('--viz_size', type=int, default=256, help='Image size for visualization. (default: 256)') parser.add_argument('--gpu_id', type=str, default='0', help='Which GPU(s) to use. (default: `0`)') return parser.parse_args() def main(): """Main function.""" args = parse_args() os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu_id style_dir = args.style_dir style_dir_name = os.path.basename(style_dir.rstrip('/')) assert os.path.exists(style_dir) assert os.path.exists(f'{style_dir}/image_list.txt') assert os.path.exists(f'{style_dir}/inverted_codes.npy') content_dir = args.content_dir content_dir_name = os.path.basename(content_dir.rstrip('/')) assert os.path.exists(content_dir) assert os.path.exists(f'{content_dir}/image_list.txt') assert os.path.exists(f'{content_dir}/inverted_codes.npy') output_dir = args.output_dir or 'results/style_mixing' job_name = f'{style_dir_name}_STYLIZE_{content_dir_name}' logger = setup_logger(output_dir, f'{job_name}.log', f'{job_name}_logger') # Load model. logger.info(f'Loading generator.') generator = build_generator(args.model_name) mix_layers = list(range(args.mix_layer_start_idx, generator.num_layers)) # Load image and codes. logger.info(f'Loading images and corresponding inverted latent codes.') style_list = [] with open(f'{style_dir}/image_list.txt', 'r') as f: for line in f: name = os.path.splitext(os.path.basename(line.strip()))[0] assert os.path.exists(f'{style_dir}/{name}_ori.png') style_list.append(name) logger.info(f'Loading inverted latent codes.') style_codes = np.load(f'{style_dir}/inverted_codes.npy') assert style_codes.shape[0] == len(style_list) num_styles = style_codes.shape[0] content_list = [] with open(f'{content_dir}/image_list.txt', 'r') as f: for line in f: name = os.path.splitext(os.path.basename(line.strip()))[0] assert os.path.exists(f'{content_dir}/{name}_ori.png') content_list.append(name) logger.info(f'Loading inverted latent codes.') content_codes = np.load(f'{content_dir}/inverted_codes.npy') assert content_codes.shape[0] == len(content_list) num_contents = content_codes.shape[0] # Mix styles. logger.info(f'Start style mixing.') viz_size = None if args.viz_size == 0 else args.viz_size visualizer = HtmlPageVisualizer( num_rows=num_styles + 1, num_cols=num_contents + 1, viz_size=viz_size) visualizer.set_headers( ['Style'] + [f'Content {i:03d}' for i in range(num_contents)] ) for style_idx, style_name in enumerate(style_list): style_image = load_image(f'{style_dir}/{style_name}_ori.png') visualizer.set_cell(style_idx + 1, 0, image=style_image) for content_idx, content_name in enumerate(content_list): content_image = load_image(f'{content_dir}/{content_name}_ori.png') visualizer.set_cell(0, content_idx + 1, image=content_image) codes = mix_style(style_codes=style_codes, content_codes=content_codes, num_layers=generator.num_layers, mix_layers=mix_layers) for style_idx in tqdm(range(num_styles), leave=False): output_images = generator.easy_synthesize( codes[style_idx], latent_space_type='wp')['image'] for content_idx, output_image in enumerate(output_images): visualizer.set_cell(style_idx + 1, content_idx + 1, image=output_image) # Save results. visualizer.save(f'{output_dir}/{job_name}.html') if __name__ == '__main__': main()
41.266129
80
0.693375
import os import argparse from tqdm import tqdm import numpy as np from models.helper import build_generator from utils.logger import setup_logger from utils.editor import mix_style from utils.visualizer import load_image from utils.visualizer import HtmlPageVisualizer def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('model_name', type=str, help='Name of the GAN model.') parser.add_argument('style_dir', type=str, help='Style directory, which includes original images, ' 'inverted codes, and image list.') parser.add_argument('content_dir', type=str, help='Content directory, which includes original images, ' 'inverted codes, and image list.') parser.add_argument('-o', '--output_dir', type=str, default='', help='Directory to save the results. If not specified, ' '`./results/style_mixing` will be used by default.') parser.add_argument('--mix_layer_start_idx', type=int, default=10, help='0-based layer index. Style mixing is performed ' 'from this layer to the last layer. (default: 10)') parser.add_argument('--viz_size', type=int, default=256, help='Image size for visualization. (default: 256)') parser.add_argument('--gpu_id', type=str, default='0', help='Which GPU(s) to use. (default: `0`)') return parser.parse_args() def main(): args = parse_args() os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu_id style_dir = args.style_dir style_dir_name = os.path.basename(style_dir.rstrip('/')) assert os.path.exists(style_dir) assert os.path.exists(f'{style_dir}/image_list.txt') assert os.path.exists(f'{style_dir}/inverted_codes.npy') content_dir = args.content_dir content_dir_name = os.path.basename(content_dir.rstrip('/')) assert os.path.exists(content_dir) assert os.path.exists(f'{content_dir}/image_list.txt') assert os.path.exists(f'{content_dir}/inverted_codes.npy') output_dir = args.output_dir or 'results/style_mixing' job_name = f'{style_dir_name}_STYLIZE_{content_dir_name}' logger = setup_logger(output_dir, f'{job_name}.log', f'{job_name}_logger') logger.info(f'Loading generator.') generator = build_generator(args.model_name) mix_layers = list(range(args.mix_layer_start_idx, generator.num_layers)) logger.info(f'Loading images and corresponding inverted latent codes.') style_list = [] with open(f'{style_dir}/image_list.txt', 'r') as f: for line in f: name = os.path.splitext(os.path.basename(line.strip()))[0] assert os.path.exists(f'{style_dir}/{name}_ori.png') style_list.append(name) logger.info(f'Loading inverted latent codes.') style_codes = np.load(f'{style_dir}/inverted_codes.npy') assert style_codes.shape[0] == len(style_list) num_styles = style_codes.shape[0] content_list = [] with open(f'{content_dir}/image_list.txt', 'r') as f: for line in f: name = os.path.splitext(os.path.basename(line.strip()))[0] assert os.path.exists(f'{content_dir}/{name}_ori.png') content_list.append(name) logger.info(f'Loading inverted latent codes.') content_codes = np.load(f'{content_dir}/inverted_codes.npy') assert content_codes.shape[0] == len(content_list) num_contents = content_codes.shape[0] logger.info(f'Start style mixing.') viz_size = None if args.viz_size == 0 else args.viz_size visualizer = HtmlPageVisualizer( num_rows=num_styles + 1, num_cols=num_contents + 1, viz_size=viz_size) visualizer.set_headers( ['Style'] + [f'Content {i:03d}' for i in range(num_contents)] ) for style_idx, style_name in enumerate(style_list): style_image = load_image(f'{style_dir}/{style_name}_ori.png') visualizer.set_cell(style_idx + 1, 0, image=style_image) for content_idx, content_name in enumerate(content_list): content_image = load_image(f'{content_dir}/{content_name}_ori.png') visualizer.set_cell(0, content_idx + 1, image=content_image) codes = mix_style(style_codes=style_codes, content_codes=content_codes, num_layers=generator.num_layers, mix_layers=mix_layers) for style_idx in tqdm(range(num_styles), leave=False): output_images = generator.easy_synthesize( codes[style_idx], latent_space_type='wp')['image'] for content_idx, output_image in enumerate(output_images): visualizer.set_cell(style_idx + 1, content_idx + 1, image=output_image) visualizer.save(f'{output_dir}/{job_name}.html') if __name__ == '__main__': main()
true
true
1c2ce02887f28d749adfb08b9531827e4142048e
312
py
Python
docs/examples/dns/google/dns_internal_auth.py
zimventures/libcloud
be0765df384f1baccde24539156119856cb96816
[ "Apache-2.0" ]
1,435
2015-01-07T05:32:51.000Z
2022-03-25T19:39:34.000Z
docs/examples/dns/google/dns_internal_auth.py
zimventures/libcloud
be0765df384f1baccde24539156119856cb96816
[ "Apache-2.0" ]
1,158
2015-01-04T18:08:42.000Z
2022-03-24T14:34:57.000Z
docs/examples/dns/google/dns_internal_auth.py
zimventures/libcloud
be0765df384f1baccde24539156119856cb96816
[ "Apache-2.0" ]
832
2015-01-05T09:20:21.000Z
2022-03-24T19:22:19.000Z
from libcloud.dns.types import Provider from libcloud.dns.providers import get_driver # This example assumes you are running an instance within Google Compute Engine # in which case you only need to provide the project ID. DNSDriver = get_driver(Provider.GOOGLE) driver = DNSDriver('', '', project='project ID')
44.571429
79
0.791667
from libcloud.dns.types import Provider from libcloud.dns.providers import get_driver DNSDriver = get_driver(Provider.GOOGLE) driver = DNSDriver('', '', project='project ID')
true
true
1c2ce0a24df2ae151ddf420bead8e986e77917b2
7,167
py
Python
src/clld/cliutil.py
blurks/clld
d9900f88af726eb6a4d2668f517d5af23bcc6f9d
[ "MIT" ]
32
2015-02-22T02:09:29.000Z
2022-02-18T14:40:16.000Z
src/clld/cliutil.py
blurks/clld
d9900f88af726eb6a4d2668f517d5af23bcc6f9d
[ "MIT" ]
199
2015-01-05T11:58:38.000Z
2022-02-22T14:34:52.000Z
src/clld/cliutil.py
blurks/clld
d9900f88af726eb6a4d2668f517d5af23bcc6f9d
[ "MIT" ]
18
2015-01-23T13:00:47.000Z
2022-02-21T16:32:36.000Z
"""Shared functionality for clld console scripts.""" import sys import pathlib import argparse import warnings import functools import importlib import collections from sqlalchemy import engine_from_config from pyramid.paster import get_appsettings, bootstrap from nameparser import HumanName from clldutils.misc import slug from clld.db.meta import DBSession, Base from clld.db.models import common from clld.lib import bibtex __all__ = [ 'AppConfig', 'BootstrappedAppConfig', 'SessionContext', 'data_file', 'add_language_codes', 'bibtex2source', 'confirm', 'Data'] # Moved here from distutils.util, due to this package being deprecated. def strtobool(val): # pragma: no cover """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ val = val.lower() if val in ('y', 'yes', 't', 'true', 'on', '1'): return 1 if val in ('n', 'no', 'f', 'false', 'off', '0'): return 0 raise ValueError("invalid truth value %r" % (val,)) class AppConfig(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): p = pathlib.Path(values.split('#')[0]) if not (p.exists() and p.is_file()): raise ValueError() setattr(namespace, self.dest, p) namespace.module = p.resolve().parent.name namespace.settings = get_appsettings(values) if namespace.module == 'tests': namespace.module = 'clld' namespace.module = importlib.import_module(namespace.module) namespace.data_file = functools.partial(data_file, namespace.module) namespace.module_dir = pathlib.Path(namespace.module.__file__).parent namespace.migrations_dir = namespace.module_dir.joinpath('..', 'migrations') class BootstrappedAppConfig(AppConfig): def __call__(self, parser, namespace, values, option_string=None): AppConfig.__call__(self, parser, namespace, values, option_string=option_string) namespace.env = bootstrap(values) try: namespace.initializedb = importlib.import_module( '.'.join([namespace.module.__name__, 'scripts', 'initializedb'])) except ImportError as e: warnings.warn(str(e)) namespace.initializedb = None class SessionContext: """ To support accessing configured sessions in cli commands. """ def __init__(self, settings): self.settings = {'sqlalchemy.url': settings} if isinstance(settings, str) else settings self.engine = None def __enter__(self): self.engine = engine_from_config(self.settings) DBSession.remove() DBSession.configure(bind=self.engine) assert DBSession.bind == self.engine Base.metadata.create_all(self.engine) return DBSession def __exit__(self, exc_type, exc_val, exc_tb): if self.engine: self.engine.dispose() DBSession.remove() def add_language_codes(data, lang, isocode, glottocodes=None, glottocode=None): def identifier(type_, id_): return data.add( common.Identifier, '%s:%s' % (type_, id_), id='%s:%s' % (type_, id_), name=id_, type=getattr(common.IdentifierType, type_).value) if isocode and len(isocode) == 3: DBSession.add(common.LanguageIdentifier( language=lang, identifier=identifier('iso', isocode))) if glottocode or (glottocodes and isocode and isocode in glottocodes): glottocode = glottocode or glottocodes[isocode] DBSession.add(common.LanguageIdentifier( language=lang, identifier=identifier('glottolog', glottocode))) def bibtex2source(rec, cls=common.Source, lowercase_id=False): year = bibtex.unescape(rec.get('year', 'nd')) fields = {} jsondata = {} for field in bibtex.FIELDS: if field in rec: value = bibtex.unescape(rec[field]) container = fields if hasattr(cls, field) else jsondata container[field] = value etal = '' eds = '' authors = rec.get('author') if not authors: authors = rec.get('editor', '') if authors: eds = ' (eds.)' if authors: authors = bibtex.unescape(authors).split(' and ') if len(authors) > 2: authors = authors[:1] etal = ' et al.' authors = [HumanName(a) for a in authors] authors = [n.last or n.first for n in authors] authors = '%s%s%s' % (' and '.join(authors), etal, eds) return cls( id=slug(rec.id, lowercase=lowercase_id), name=('%s %s' % (authors, year)).strip(), description=bibtex.unescape(rec.get('title', rec.get('booktitle', ''))), jsondata=jsondata, bibtex_type=rec.genre, **fields) def confirm(question, default=False): # pragma: no cover """Ask a yes/no question via input() and return their answer. "question" is a string that is presented to the user. """ while True: sys.stdout.write(question + (" [Y|n] " if default else " [y|N] ")) choice = input().lower() if not choice: return default try: return strtobool(choice) except ValueError: sys.stdout.write( "Please respond with 'yes' or 'no' (or 'y' or 'n').\n") def data_file(module, *comps): """Return Path object of file in the data directory of an app.""" return pathlib.Path(module.__file__).parent.joinpath('..', 'data', *comps) class Data(collections.defaultdict): """Dictionary, serving to store references to new db objects during data imports. The values are dictionaries, keyed by the name of the model class used to create the new objects. >>> data = Data() >>> l = data.add(common.Language, 'l', id='abc', name='Abc Language') >>> assert l == data['Language']['l'] """ def __init__(self, **kw): super(Data, self).__init__(dict) self.defaults = kw def add(self, model_, key_, **kw): """ Create an instance of a model class to be persisted in the database. :param model_: The model class we want to create an instance of. :param key_: A key which can be used to retrieve the instance later. :param kw: Keyword parameters passed to model class for initialisation. :return: The newly created instance of model class. """ if '.' in kw.get('id', ''): raise ValueError('Object id contains illegal character "."') if list(kw.keys()) == ['_obj']: # if a single keyword parameter _obj is passed, we take it to be the object # which should be added to the session. new = kw['_obj'] else: for k, v in self.defaults.items(): kw.setdefault(k, v) new = model_(**kw) self[model_.__name__][key_] = new DBSession.add(new) return new
33.806604
95
0.619646
import sys import pathlib import argparse import warnings import functools import importlib import collections from sqlalchemy import engine_from_config from pyramid.paster import get_appsettings, bootstrap from nameparser import HumanName from clldutils.misc import slug from clld.db.meta import DBSession, Base from clld.db.models import common from clld.lib import bibtex __all__ = [ 'AppConfig', 'BootstrappedAppConfig', 'SessionContext', 'data_file', 'add_language_codes', 'bibtex2source', 'confirm', 'Data'] def strtobool(val): val = val.lower() if val in ('y', 'yes', 't', 'true', 'on', '1'): return 1 if val in ('n', 'no', 'f', 'false', 'off', '0'): return 0 raise ValueError("invalid truth value %r" % (val,)) class AppConfig(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): p = pathlib.Path(values.split('#')[0]) if not (p.exists() and p.is_file()): raise ValueError() setattr(namespace, self.dest, p) namespace.module = p.resolve().parent.name namespace.settings = get_appsettings(values) if namespace.module == 'tests': namespace.module = 'clld' namespace.module = importlib.import_module(namespace.module) namespace.data_file = functools.partial(data_file, namespace.module) namespace.module_dir = pathlib.Path(namespace.module.__file__).parent namespace.migrations_dir = namespace.module_dir.joinpath('..', 'migrations') class BootstrappedAppConfig(AppConfig): def __call__(self, parser, namespace, values, option_string=None): AppConfig.__call__(self, parser, namespace, values, option_string=option_string) namespace.env = bootstrap(values) try: namespace.initializedb = importlib.import_module( '.'.join([namespace.module.__name__, 'scripts', 'initializedb'])) except ImportError as e: warnings.warn(str(e)) namespace.initializedb = None class SessionContext: def __init__(self, settings): self.settings = {'sqlalchemy.url': settings} if isinstance(settings, str) else settings self.engine = None def __enter__(self): self.engine = engine_from_config(self.settings) DBSession.remove() DBSession.configure(bind=self.engine) assert DBSession.bind == self.engine Base.metadata.create_all(self.engine) return DBSession def __exit__(self, exc_type, exc_val, exc_tb): if self.engine: self.engine.dispose() DBSession.remove() def add_language_codes(data, lang, isocode, glottocodes=None, glottocode=None): def identifier(type_, id_): return data.add( common.Identifier, '%s:%s' % (type_, id_), id='%s:%s' % (type_, id_), name=id_, type=getattr(common.IdentifierType, type_).value) if isocode and len(isocode) == 3: DBSession.add(common.LanguageIdentifier( language=lang, identifier=identifier('iso', isocode))) if glottocode or (glottocodes and isocode and isocode in glottocodes): glottocode = glottocode or glottocodes[isocode] DBSession.add(common.LanguageIdentifier( language=lang, identifier=identifier('glottolog', glottocode))) def bibtex2source(rec, cls=common.Source, lowercase_id=False): year = bibtex.unescape(rec.get('year', 'nd')) fields = {} jsondata = {} for field in bibtex.FIELDS: if field in rec: value = bibtex.unescape(rec[field]) container = fields if hasattr(cls, field) else jsondata container[field] = value etal = '' eds = '' authors = rec.get('author') if not authors: authors = rec.get('editor', '') if authors: eds = ' (eds.)' if authors: authors = bibtex.unescape(authors).split(' and ') if len(authors) > 2: authors = authors[:1] etal = ' et al.' authors = [HumanName(a) for a in authors] authors = [n.last or n.first for n in authors] authors = '%s%s%s' % (' and '.join(authors), etal, eds) return cls( id=slug(rec.id, lowercase=lowercase_id), name=('%s %s' % (authors, year)).strip(), description=bibtex.unescape(rec.get('title', rec.get('booktitle', ''))), jsondata=jsondata, bibtex_type=rec.genre, **fields) def confirm(question, default=False): while True: sys.stdout.write(question + (" [Y|n] " if default else " [y|N] ")) choice = input().lower() if not choice: return default try: return strtobool(choice) except ValueError: sys.stdout.write( "Please respond with 'yes' or 'no' (or 'y' or 'n').\n") def data_file(module, *comps): return pathlib.Path(module.__file__).parent.joinpath('..', 'data', *comps) class Data(collections.defaultdict): def __init__(self, **kw): super(Data, self).__init__(dict) self.defaults = kw def add(self, model_, key_, **kw): if '.' in kw.get('id', ''): raise ValueError('Object id contains illegal character "."') if list(kw.keys()) == ['_obj']: new = kw['_obj'] else: for k, v in self.defaults.items(): kw.setdefault(k, v) new = model_(**kw) self[model_.__name__][key_] = new DBSession.add(new) return new
true
true
1c2ce0dd82a785f6abbfad925561a8ddf77a8cb9
3,668
py
Python
huaweicloud-sdk-apig/huaweicloudsdkapig/v2/model/update_engress_eip_v2_request.py
huaweicloud/huaweicloud-sdk-python-v3
7a6270390fcbf192b3882bf763e7016e6026ef78
[ "Apache-2.0" ]
64
2020-06-12T07:05:07.000Z
2022-03-30T03:32:50.000Z
huaweicloud-sdk-apig/huaweicloudsdkapig/v2/model/update_engress_eip_v2_request.py
huaweicloud/huaweicloud-sdk-python-v3
7a6270390fcbf192b3882bf763e7016e6026ef78
[ "Apache-2.0" ]
11
2020-07-06T07:56:54.000Z
2022-01-11T11:14:40.000Z
huaweicloud-sdk-apig/huaweicloudsdkapig/v2/model/update_engress_eip_v2_request.py
huaweicloud/huaweicloud-sdk-python-v3
7a6270390fcbf192b3882bf763e7016e6026ef78
[ "Apache-2.0" ]
24
2020-06-08T11:42:13.000Z
2022-03-04T06:44:08.000Z
# coding: utf-8 import re import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class UpdateEngressEipV2Request: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'instance_id': 'str', 'body': 'OpenEngressEipReq' } attribute_map = { 'instance_id': 'instance_id', 'body': 'body' } def __init__(self, instance_id=None, body=None): """UpdateEngressEipV2Request - a model defined in huaweicloud sdk""" self._instance_id = None self._body = None self.discriminator = None self.instance_id = instance_id if body is not None: self.body = body @property def instance_id(self): """Gets the instance_id of this UpdateEngressEipV2Request. 实例编号 :return: The instance_id of this UpdateEngressEipV2Request. :rtype: str """ return self._instance_id @instance_id.setter def instance_id(self, instance_id): """Sets the instance_id of this UpdateEngressEipV2Request. 实例编号 :param instance_id: The instance_id of this UpdateEngressEipV2Request. :type: str """ self._instance_id = instance_id @property def body(self): """Gets the body of this UpdateEngressEipV2Request. :return: The body of this UpdateEngressEipV2Request. :rtype: OpenEngressEipReq """ return self._body @body.setter def body(self, body): """Sets the body of this UpdateEngressEipV2Request. :param body: The body of this UpdateEngressEipV2Request. :type: OpenEngressEipReq """ self._body = body def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, UpdateEngressEipV2Request): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
26.388489
79
0.56325
import re import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class UpdateEngressEipV2Request: sensitive_list = [] openapi_types = { 'instance_id': 'str', 'body': 'OpenEngressEipReq' } attribute_map = { 'instance_id': 'instance_id', 'body': 'body' } def __init__(self, instance_id=None, body=None): self._instance_id = None self._body = None self.discriminator = None self.instance_id = instance_id if body is not None: self.body = body @property def instance_id(self): return self._instance_id @instance_id.setter def instance_id(self, instance_id): self._instance_id = instance_id @property def body(self): return self._body @body.setter def body(self, body): self._body = body def to_dict(self): result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, UpdateEngressEipV2Request): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
1c2ce2462fbe0b2370b982dd9c8330ec8406d551
5,573
py
Python
lightconvpoint/nn/conv_fkaconv.py
valeoai/POCO
c6ab56b1b7f01c51d1bc6987eae0a8c79725e63f
[ "Apache-2.0" ]
13
2022-01-07T07:53:15.000Z
2022-03-31T10:53:43.000Z
lightconvpoint/nn/conv_fkaconv.py
valeoai/POCO
c6ab56b1b7f01c51d1bc6987eae0a8c79725e63f
[ "Apache-2.0" ]
2
2022-02-16T18:58:22.000Z
2022-03-28T11:34:03.000Z
lightconvpoint/nn/conv_fkaconv.py
valeoai/POCO
c6ab56b1b7f01c51d1bc6987eae0a8c79725e63f
[ "Apache-2.0" ]
3
2022-01-25T05:24:31.000Z
2022-03-28T07:17:44.000Z
import torch import torch.nn as nn import torch.nn.functional as F from math import ceil # from lightconvpoint.spatial import knn, sampling_quantized from lightconvpoint.utils.functional import batch_gather import torch class Convolution_FKAConv(torch.nn.Module): def __init__(self, in_channels, out_channels, kernel_size=16, bias=False, dim=3, kernel_separation=False, adaptive_normalization=True,**kwargs): super().__init__() # parameters self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.bias = bias self.dim = dim self.adaptive_normalization = adaptive_normalization # convolution kernel if kernel_separation: # equivalent to two kernels K1 * K2 dm = int(ceil(self.out_channels / self.in_channels)) self.cv = nn.Sequential( nn.Conv2d(in_channels, dm*in_channels, (1, kernel_size), bias=bias, groups=self.in_channels), nn.Conv2d(in_channels*dm, out_channels, (1, 1), bias=bias) ) else: self.cv = nn.Conv2d(in_channels, out_channels, (1, kernel_size), bias=bias) # normalization radius if self.adaptive_normalization: self.norm_radius_momentum = 0.1 self.norm_radius = nn.Parameter(torch.Tensor(1,), requires_grad=False) self.alpha = nn.Parameter(torch.Tensor(1,), requires_grad=True) self.beta = nn.Parameter(torch.Tensor(1,), requires_grad=True) torch.nn.init.ones_(self.norm_radius.data) torch.nn.init.ones_(self.alpha.data) torch.nn.init.ones_(self.beta.data) # features to kernel weights self.fc1 = nn.Conv2d(self.dim, self.kernel_size, 1, bias=False) self.fc2 = nn.Conv2d(2 * self.kernel_size, self.kernel_size, 1, bias=False) self.fc3 = nn.Conv2d(2 * self.kernel_size, self.kernel_size, 1, bias=False) self.bn1 = nn.InstanceNorm2d(self.kernel_size, affine=True) self.bn2 = nn.InstanceNorm2d(self.kernel_size, affine=True) def fixed_normalization(self, pts, radius=None): maxi = torch.sqrt((pts.detach() ** 2).sum(1).max(2)[0]) maxi = maxi + (maxi == 0) return pts / maxi.view(maxi.size(0), 1, maxi.size(1), 1) def forward(self, x, pos, support_points, neighbors_indices): if x is None: return None pos = batch_gather(pos, dim=2, index=neighbors_indices).contiguous() x = batch_gather(x, dim=2, index=neighbors_indices).contiguous() # center the neighborhoods (local coordinates) pts = pos - support_points.unsqueeze(3) # normalize points if self.adaptive_normalization: # compute distances from points to their support point distances = torch.sqrt((pts.detach() ** 2).sum(1)) # update the normalization radius if self.training: mean_radius = distances.max(2)[0].mean() self.norm_radius.data = ( self.norm_radius.data * (1 - self.norm_radius_momentum) + mean_radius * self.norm_radius_momentum ) # normalize pts = pts / self.norm_radius # estimate distance weights distance_weight = torch.sigmoid(-self.alpha * distances + self.beta) distance_weight_s = distance_weight.sum(2, keepdim=True) distance_weight_s = distance_weight_s + (distance_weight_s == 0) + 1e-6 distance_weight = ( distance_weight / distance_weight_s * distances.shape[2] ).unsqueeze(1) # feature weighting matrix estimation if pts.shape[3] == 1: mat = F.relu(self.fc1(pts)) else: mat = F.relu(self.bn1(self.fc1(pts))) mp1 = torch.max(mat * distance_weight, dim=3, keepdim=True)[0].expand( (-1, -1, -1, mat.shape[3]) ) mat = torch.cat([mat, mp1], dim=1) if pts.shape[3] == 1: mat = F.relu(self.fc2(mat)) else: mat = F.relu(self.bn2(self.fc2(mat))) mp2 = torch.max(mat * distance_weight, dim=3, keepdim=True)[0].expand( (-1, -1, -1, mat.shape[3]) ) mat = torch.cat([mat, mp2], dim=1) mat = F.relu(self.fc3(mat)) * distance_weight # mat = torch.sigmoid(self.fc3(mat)) * distance_weight else: pts = self.fixed_normalization(pts) # feature weighting matrix estimation if pts.shape[3] == 1: mat = F.relu(self.fc1(pts)) else: mat = F.relu(self.bn1(self.fc1(pts))) mp1 = torch.max(mat, dim=3, keepdim=True)[0].expand( (-1, -1, -1, mat.shape[3]) ) mat = torch.cat([mat, mp1], dim=1) if pts.shape[3] == 1: mat = F.relu(self.fc2(mat)) else: mat = F.relu(self.bn2(self.fc2(mat))) mp2 = torch.max(mat, dim=3, keepdim=True)[0].expand( (-1, -1, -1, mat.shape[3]) ) mat = torch.cat([mat, mp2], dim=1) mat = F.relu(self.fc3(mat)) # compute features features = torch.matmul( x.transpose(1, 2), mat.permute(0, 2, 3, 1) ).transpose(1, 2) features = self.cv(features).squeeze(3) return features
37.911565
148
0.570967
import torch import torch.nn as nn import torch.nn.functional as F from math import ceil from lightconvpoint.utils.functional import batch_gather import torch class Convolution_FKAConv(torch.nn.Module): def __init__(self, in_channels, out_channels, kernel_size=16, bias=False, dim=3, kernel_separation=False, adaptive_normalization=True,**kwargs): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.bias = bias self.dim = dim self.adaptive_normalization = adaptive_normalization if kernel_separation: dm = int(ceil(self.out_channels / self.in_channels)) self.cv = nn.Sequential( nn.Conv2d(in_channels, dm*in_channels, (1, kernel_size), bias=bias, groups=self.in_channels), nn.Conv2d(in_channels*dm, out_channels, (1, 1), bias=bias) ) else: self.cv = nn.Conv2d(in_channels, out_channels, (1, kernel_size), bias=bias) if self.adaptive_normalization: self.norm_radius_momentum = 0.1 self.norm_radius = nn.Parameter(torch.Tensor(1,), requires_grad=False) self.alpha = nn.Parameter(torch.Tensor(1,), requires_grad=True) self.beta = nn.Parameter(torch.Tensor(1,), requires_grad=True) torch.nn.init.ones_(self.norm_radius.data) torch.nn.init.ones_(self.alpha.data) torch.nn.init.ones_(self.beta.data) self.fc1 = nn.Conv2d(self.dim, self.kernel_size, 1, bias=False) self.fc2 = nn.Conv2d(2 * self.kernel_size, self.kernel_size, 1, bias=False) self.fc3 = nn.Conv2d(2 * self.kernel_size, self.kernel_size, 1, bias=False) self.bn1 = nn.InstanceNorm2d(self.kernel_size, affine=True) self.bn2 = nn.InstanceNorm2d(self.kernel_size, affine=True) def fixed_normalization(self, pts, radius=None): maxi = torch.sqrt((pts.detach() ** 2).sum(1).max(2)[0]) maxi = maxi + (maxi == 0) return pts / maxi.view(maxi.size(0), 1, maxi.size(1), 1) def forward(self, x, pos, support_points, neighbors_indices): if x is None: return None pos = batch_gather(pos, dim=2, index=neighbors_indices).contiguous() x = batch_gather(x, dim=2, index=neighbors_indices).contiguous() pts = pos - support_points.unsqueeze(3) if self.adaptive_normalization: distances = torch.sqrt((pts.detach() ** 2).sum(1)) if self.training: mean_radius = distances.max(2)[0].mean() self.norm_radius.data = ( self.norm_radius.data * (1 - self.norm_radius_momentum) + mean_radius * self.norm_radius_momentum ) pts = pts / self.norm_radius distance_weight = torch.sigmoid(-self.alpha * distances + self.beta) distance_weight_s = distance_weight.sum(2, keepdim=True) distance_weight_s = distance_weight_s + (distance_weight_s == 0) + 1e-6 distance_weight = ( distance_weight / distance_weight_s * distances.shape[2] ).unsqueeze(1) if pts.shape[3] == 1: mat = F.relu(self.fc1(pts)) else: mat = F.relu(self.bn1(self.fc1(pts))) mp1 = torch.max(mat * distance_weight, dim=3, keepdim=True)[0].expand( (-1, -1, -1, mat.shape[3]) ) mat = torch.cat([mat, mp1], dim=1) if pts.shape[3] == 1: mat = F.relu(self.fc2(mat)) else: mat = F.relu(self.bn2(self.fc2(mat))) mp2 = torch.max(mat * distance_weight, dim=3, keepdim=True)[0].expand( (-1, -1, -1, mat.shape[3]) ) mat = torch.cat([mat, mp2], dim=1) mat = F.relu(self.fc3(mat)) * distance_weight else: pts = self.fixed_normalization(pts) if pts.shape[3] == 1: mat = F.relu(self.fc1(pts)) else: mat = F.relu(self.bn1(self.fc1(pts))) mp1 = torch.max(mat, dim=3, keepdim=True)[0].expand( (-1, -1, -1, mat.shape[3]) ) mat = torch.cat([mat, mp1], dim=1) if pts.shape[3] == 1: mat = F.relu(self.fc2(mat)) else: mat = F.relu(self.bn2(self.fc2(mat))) mp2 = torch.max(mat, dim=3, keepdim=True)[0].expand( (-1, -1, -1, mat.shape[3]) ) mat = torch.cat([mat, mp2], dim=1) mat = F.relu(self.fc3(mat)) features = torch.matmul( x.transpose(1, 2), mat.permute(0, 2, 3, 1) ).transpose(1, 2) features = self.cv(features).squeeze(3) return features
true
true
1c2ce26db0156de6165c1332f32d5a91c6348de4
2,279
py
Python
data/p4VQE/R4/benchmark/startQiskit_noisy12.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/p4VQE/R4/benchmark/startQiskit_noisy12.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/p4VQE/R4/benchmark/startQiskit_noisy12.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
# qubit number=3 # total number=7 import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ import networkx as nx from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from qiskit.test.mock import FakeVigo, FakeYorktown kernel = 'circuit/bernstein' def make_circuit(n:int) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") prog = QuantumCircuit(input_qubit) prog.h(input_qubit[0]) # number=1 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.x(input_qubit[2]) # number=6 prog.h(input_qubit[3]) # number=4 prog.y(input_qubit[3]) # number=5 for edge in E: k = edge[0] l = edge[1] prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1]) prog.p(gamma, k) prog.p(gamma, l) prog.rx(2 * beta, range(len(V))) # circuit end return prog if __name__ == '__main__': n = 4 V = np.arange(0, n, 1) E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)] G = nx.Graph() G.add_nodes_from(V) G.add_weighted_edges_from(E) step_size = 0.1 a_gamma = np.arange(0, np.pi, step_size) a_beta = np.arange(0, np.pi, step_size) a_gamma, a_beta = np.meshgrid(a_gamma, a_beta) F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * ( 1 + np.cos(4 * a_gamma) ** 2) result = np.where(F1 == np.amax(F1)) a = list(zip(result[0], result[1]))[0] gamma = a[0] * step_size beta = a[1] * step_size prog = make_circuit(4) sample_shot =5600 writefile = open("../data/startQiskit_noisy12.csv", "w") # prog.draw('mpl', filename=(kernel + '.png')) backend = FakeYorktown() circuit1 = transpile(prog, FakeYorktown()) circuit1.measure_all() prog = circuit1 info = execute(prog,backend=backend, shots=sample_shot).result().get_counts() print(info, file=writefile) print("results end", file=writefile) print(circuit1.depth(), file=writefile) print(circuit1, file=writefile) writefile.close()
26.195402
118
0.628346
import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ import networkx as nx from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from qiskit.test.mock import FakeVigo, FakeYorktown kernel = 'circuit/bernstein' def make_circuit(n:int) -> QuantumCircuit: input_qubit = QuantumRegister(n,"qc") prog = QuantumCircuit(input_qubit) prog.h(input_qubit[0]) prog.h(input_qubit[1]) prog.h(input_qubit[2]) prog.x(input_qubit[2]) prog.h(input_qubit[3]) prog.y(input_qubit[3]) for edge in E: k = edge[0] l = edge[1] prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1]) prog.p(gamma, k) prog.p(gamma, l) prog.rx(2 * beta, range(len(V))) return prog if __name__ == '__main__': n = 4 V = np.arange(0, n, 1) E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)] G = nx.Graph() G.add_nodes_from(V) G.add_weighted_edges_from(E) step_size = 0.1 a_gamma = np.arange(0, np.pi, step_size) a_beta = np.arange(0, np.pi, step_size) a_gamma, a_beta = np.meshgrid(a_gamma, a_beta) F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * ( 1 + np.cos(4 * a_gamma) ** 2) result = np.where(F1 == np.amax(F1)) a = list(zip(result[0], result[1]))[0] gamma = a[0] * step_size beta = a[1] * step_size prog = make_circuit(4) sample_shot =5600 writefile = open("../data/startQiskit_noisy12.csv", "w") backend = FakeYorktown() circuit1 = transpile(prog, FakeYorktown()) circuit1.measure_all() prog = circuit1 info = execute(prog,backend=backend, shots=sample_shot).result().get_counts() print(info, file=writefile) print("results end", file=writefile) print(circuit1.depth(), file=writefile) print(circuit1, file=writefile) writefile.close()
true
true
1c2ce294e199b890881d8682eef9ec7edaf7f4f3
1,822
py
Python
mint/types/unfinished_block.py
sai-genesis/rc1-test
56e565952b283450c8589296f87c31b1c67b8502
[ "Apache-2.0" ]
12
2021-08-18T20:53:31.000Z
2022-03-15T21:45:13.000Z
mint/types/unfinished_block.py
sai-genesis/rc1-test
56e565952b283450c8589296f87c31b1c67b8502
[ "Apache-2.0" ]
34
2021-08-18T19:12:11.000Z
2022-01-06T17:15:34.000Z
mint/types/unfinished_block.py
sai-genesis/rc1-test
56e565952b283450c8589296f87c31b1c67b8502
[ "Apache-2.0" ]
7
2021-08-18T20:53:34.000Z
2022-03-15T08:37:40.000Z
from dataclasses import dataclass from typing import List, Optional from mint.types.blockchain_format.foliage import Foliage, FoliageTransactionBlock, TransactionsInfo from mint.types.blockchain_format.program import SerializedProgram from mint.types.blockchain_format.reward_chain_block import RewardChainBlockUnfinished from mint.types.blockchain_format.vdf import VDFProof from mint.types.end_of_slot_bundle import EndOfSubSlotBundle from mint.util.ints import uint32 from mint.util.streamable import Streamable, streamable @dataclass(frozen=True) @streamable class UnfinishedBlock(Streamable): # Full block, without the final VDFs finished_sub_slots: List[EndOfSubSlotBundle] # If first sb reward_chain_block: RewardChainBlockUnfinished # Reward chain trunk data challenge_chain_sp_proof: Optional[VDFProof] # If not first sp in sub-slot reward_chain_sp_proof: Optional[VDFProof] # If not first sp in sub-slot foliage: Foliage # Reward chain foliage data foliage_transaction_block: Optional[FoliageTransactionBlock] # Reward chain foliage data (tx block) transactions_info: Optional[TransactionsInfo] # Reward chain foliage data (tx block additional) transactions_generator: Optional[SerializedProgram] # Program that generates transactions transactions_generator_ref_list: List[ uint32 ] # List of block heights of previous generators referenced in this block @property def prev_header_hash(self): return self.foliage.prev_block_hash @property def partial_hash(self): return self.reward_chain_block.get_hash() def is_transaction_block(self) -> bool: return self.foliage.foliage_transaction_block_hash is not None @property def total_iters(self): return self.reward_chain_block.total_iters
42.372093
104
0.791438
from dataclasses import dataclass from typing import List, Optional from mint.types.blockchain_format.foliage import Foliage, FoliageTransactionBlock, TransactionsInfo from mint.types.blockchain_format.program import SerializedProgram from mint.types.blockchain_format.reward_chain_block import RewardChainBlockUnfinished from mint.types.blockchain_format.vdf import VDFProof from mint.types.end_of_slot_bundle import EndOfSubSlotBundle from mint.util.ints import uint32 from mint.util.streamable import Streamable, streamable @dataclass(frozen=True) @streamable class UnfinishedBlock(Streamable): finished_sub_slots: List[EndOfSubSlotBundle] reward_chain_block: RewardChainBlockUnfinished challenge_chain_sp_proof: Optional[VDFProof] reward_chain_sp_proof: Optional[VDFProof] foliage: Foliage foliage_transaction_block: Optional[FoliageTransactionBlock] transactions_info: Optional[TransactionsInfo] transactions_generator: Optional[SerializedProgram] transactions_generator_ref_list: List[ uint32 ] @property def prev_header_hash(self): return self.foliage.prev_block_hash @property def partial_hash(self): return self.reward_chain_block.get_hash() def is_transaction_block(self) -> bool: return self.foliage.foliage_transaction_block_hash is not None @property def total_iters(self): return self.reward_chain_block.total_iters
true
true
1c2ce3b36a271a491d36bcea60e375acdecee587
2,926
py
Python
src/probabilistic_models/grammars.py
pfreifer/zxcvbn
22674a65bc6ff56281bdd5415ebdb30bb19811ef
[ "MIT" ]
null
null
null
src/probabilistic_models/grammars.py
pfreifer/zxcvbn
22674a65bc6ff56281bdd5415ebdb30bb19811ef
[ "MIT" ]
null
null
null
src/probabilistic_models/grammars.py
pfreifer/zxcvbn
22674a65bc6ff56281bdd5415ebdb30bb19811ef
[ "MIT" ]
null
null
null
import probabilistic_models.grammar_utils as gru from zxcvbn_functions.frequency_lists import FREQUENCY_LISTS import pickle def build_dict(list): d = dict() for w in list: if w in d: d[w] += 1 else: d[w] = 1 return d FREQUENCY_DICTIONARIES = {} def add_frequency_lists(frequency_lists_): for name, lst in frequency_lists_.items(): FREQUENCY_DICTIONARIES[name] = build_dict(lst) add_frequency_lists(FREQUENCY_LISTS) def construct_grammar_model(_ranked_dictionaries=FREQUENCY_DICTIONARIES): composed_bases_dict = dict() simple_bases_dict = dict() composed_bases_list = dict() simple_bases_lists = dict() cb_counter = 0 sb_counter = 0 tmp_cb_dict = dict() tmp_sb_lists = dict() for dictionary_name, frequency_dict in _ranked_dictionaries.items(): iter_verif = 0 ll = len(frequency_dict)//100 for w in frequency_dict: if w != "" : if iter_verif % ll == 0 : print(iter_verif//ll, '%') iter_verif += 1 k = frequency_dict[w] simple_bases, composed_base = gru.bases(w) if composed_base in tmp_cb_dict: tmp_cb_dict[composed_base] += k else: tmp_cb_dict[composed_base] = k simple_bases_pattern = gru.cut(composed_base) for i in range(len(simple_bases)): p = simple_bases_pattern[i] if p in tmp_sb_lists: if simple_bases[i] in tmp_sb_lists[p]: tmp_sb_lists[p][simple_bases[i]] += k else: tmp_sb_lists[p][simple_bases[i]] = k else: tmp_sb_lists[p] = {simple_bases[i]: k} cb_counter += k if composed_base in composed_bases_dict: composed_bases_dict[composed_base] += k else: composed_bases_dict[composed_base] = k for b in simple_bases: sb_counter += k if b in simple_bases_dict: simple_bases_dict[b] += k else: simple_bases_dict[b] = k pickle.dump((cb_counter, composed_bases_dict), open("cb_dictionary.p", "wb")) pickle.dump((sb_counter, simple_bases_dict), open("sb_dictionary.p", "wb")) key = 0 for cb in tmp_cb_dict: key += tmp_cb_dict[cb] composed_bases_list[key] = cb for cbp in tmp_sb_lists: key = 0 simple_bases_lists[cbp] = {} for cb in tmp_sb_lists[cbp]: key += tmp_sb_lists[cbp][cb] simple_bases_lists[cbp][key] = cb pickle.dump((composed_bases_list, simple_bases_lists), open("lists.p", "wb")) return
28.407767
81
0.55434
import probabilistic_models.grammar_utils as gru from zxcvbn_functions.frequency_lists import FREQUENCY_LISTS import pickle def build_dict(list): d = dict() for w in list: if w in d: d[w] += 1 else: d[w] = 1 return d FREQUENCY_DICTIONARIES = {} def add_frequency_lists(frequency_lists_): for name, lst in frequency_lists_.items(): FREQUENCY_DICTIONARIES[name] = build_dict(lst) add_frequency_lists(FREQUENCY_LISTS) def construct_grammar_model(_ranked_dictionaries=FREQUENCY_DICTIONARIES): composed_bases_dict = dict() simple_bases_dict = dict() composed_bases_list = dict() simple_bases_lists = dict() cb_counter = 0 sb_counter = 0 tmp_cb_dict = dict() tmp_sb_lists = dict() for dictionary_name, frequency_dict in _ranked_dictionaries.items(): iter_verif = 0 ll = len(frequency_dict)//100 for w in frequency_dict: if w != "" : if iter_verif % ll == 0 : print(iter_verif//ll, '%') iter_verif += 1 k = frequency_dict[w] simple_bases, composed_base = gru.bases(w) if composed_base in tmp_cb_dict: tmp_cb_dict[composed_base] += k else: tmp_cb_dict[composed_base] = k simple_bases_pattern = gru.cut(composed_base) for i in range(len(simple_bases)): p = simple_bases_pattern[i] if p in tmp_sb_lists: if simple_bases[i] in tmp_sb_lists[p]: tmp_sb_lists[p][simple_bases[i]] += k else: tmp_sb_lists[p][simple_bases[i]] = k else: tmp_sb_lists[p] = {simple_bases[i]: k} cb_counter += k if composed_base in composed_bases_dict: composed_bases_dict[composed_base] += k else: composed_bases_dict[composed_base] = k for b in simple_bases: sb_counter += k if b in simple_bases_dict: simple_bases_dict[b] += k else: simple_bases_dict[b] = k pickle.dump((cb_counter, composed_bases_dict), open("cb_dictionary.p", "wb")) pickle.dump((sb_counter, simple_bases_dict), open("sb_dictionary.p", "wb")) key = 0 for cb in tmp_cb_dict: key += tmp_cb_dict[cb] composed_bases_list[key] = cb for cbp in tmp_sb_lists: key = 0 simple_bases_lists[cbp] = {} for cb in tmp_sb_lists[cbp]: key += tmp_sb_lists[cbp][cb] simple_bases_lists[cbp][key] = cb pickle.dump((composed_bases_list, simple_bases_lists), open("lists.p", "wb")) return
true
true
1c2ce3fd309b26cb12ed1f9e97e75f11dd12f949
5,089
py
Python
neuro-cli/tests/unit/test_click_utils.py
neuro-inc/platform-client-python
012e355249ea900b76f9ce4209fb9d029652f9b2
[ "Apache-2.0" ]
11
2020-10-11T15:38:11.000Z
2021-11-09T11:29:50.000Z
neuro-cli/tests/unit/test_click_utils.py
neuro-inc/platform-client-python
012e355249ea900b76f9ce4209fb9d029652f9b2
[ "Apache-2.0" ]
611
2020-09-30T21:27:52.000Z
2022-01-10T10:44:44.000Z
neuro-cli/tests/unit/test_click_utils.py
neuro-inc/platform-client-python
012e355249ea900b76f9ce4209fb9d029652f9b2
[ "Apache-2.0" ]
1
2020-10-05T15:10:24.000Z
2020-10-05T15:10:24.000Z
from textwrap import dedent from click.testing import CliRunner from neuro_cli.main import MainGroup from neuro_cli.root import Root from neuro_cli.utils import DeprecatedGroup, command, group def test_print() -> None: @group() def sub_command() -> None: pass @command() async def plain_cmd(root: Root) -> None: pass @group(cls=MainGroup) def main() -> None: pass main.add_command(sub_command) main.add_command(plain_cmd) main.skip_init = True runner = CliRunner() result = runner.invoke(main, []) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] COMMAND [ARGS]... Commands: sub-command Command Shortcuts: plain-cmd Use "main help <command>" for more information about a given command or topic. Use "main --options" for a list of global command-line options (applies to all commands). """ ) def test_print_use_group_helpers() -> None: @group(cls=MainGroup) def main() -> None: pass @main.group() def sub_command() -> None: pass @main.command() async def plain_cmd(root: Root) -> None: pass main.skip_init = True runner = CliRunner() result = runner.invoke(main, []) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] COMMAND [ARGS]... Commands: sub-command Command Shortcuts: plain-cmd Use "main help <command>" for more information about a given command or topic. Use "main --options" for a list of global command-line options (applies to all commands). """ ) def test_print_hidden() -> None: @group() def sub_command() -> None: pass @command(hidden=True) async def plain_cmd(root: Root) -> None: pass @group() def main() -> None: pass main.add_command(sub_command) main.add_command(plain_cmd) runner = CliRunner() result = runner.invoke(main, []) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] COMMAND [ARGS]... Commands: sub-command """ ) def test_print_deprecated_group() -> None: @group() def sub_command() -> None: """ Sub-command. """ @group() def main() -> None: pass main.add_command(sub_command) main.add_command(DeprecatedGroup(sub_command, name="alias")) runner = CliRunner() result = runner.invoke(main, []) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] COMMAND [ARGS]... Commands: sub-command Sub-command alias (Deprecated) Alias for sub-command """ ) def test_print_deprecated_group_content() -> None: @group() def sub_command() -> None: """ Sub-command. """ @sub_command.command() async def cmd(root: Root) -> None: """Command. Detailed description is here. """ @group(cls=MainGroup) def main() -> None: pass main.add_command(sub_command) main.add_command(DeprecatedGroup(sub_command, name="alias")) main.skip_init = True runner = CliRunner() result = runner.invoke(main, ["alias"]) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main alias [OPTIONS] COMMAND [ARGS]... Alias for sub-command (DEPRECATED) Commands: cmd Command """ ) def test_print_deprecated_no_help() -> None: @command(deprecated=True) async def main(root: Root) -> None: pass runner = CliRunner() result = runner.invoke(main, ["--help"]) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] (DEPRECATED) Options: --help Show this message and exit. """ ) def test_print_deprecated_with_help() -> None: @command(deprecated=True) async def main(root: Root) -> None: """Main help.""" runner = CliRunner() result = runner.invoke(main, ["--help"]) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] Main help. (DEPRECATED) Options: --help Show this message and exit. """ ) def test_print_help_with_examples() -> None: @command() async def main(root: Root) -> None: """ Main help. Examples: # comment example """ runner = CliRunner() result = runner.invoke(main, ["--help"]) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] Main help. Examples: # comment example Options: --help Show this message and exit. """ )
20.771429
86
0.565927
from textwrap import dedent from click.testing import CliRunner from neuro_cli.main import MainGroup from neuro_cli.root import Root from neuro_cli.utils import DeprecatedGroup, command, group def test_print() -> None: @group() def sub_command() -> None: pass @command() async def plain_cmd(root: Root) -> None: pass @group(cls=MainGroup) def main() -> None: pass main.add_command(sub_command) main.add_command(plain_cmd) main.skip_init = True runner = CliRunner() result = runner.invoke(main, []) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] COMMAND [ARGS]... Commands: sub-command Command Shortcuts: plain-cmd Use "main help <command>" for more information about a given command or topic. Use "main --options" for a list of global command-line options (applies to all commands). """ ) def test_print_use_group_helpers() -> None: @group(cls=MainGroup) def main() -> None: pass @main.group() def sub_command() -> None: pass @main.command() async def plain_cmd(root: Root) -> None: pass main.skip_init = True runner = CliRunner() result = runner.invoke(main, []) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] COMMAND [ARGS]... Commands: sub-command Command Shortcuts: plain-cmd Use "main help <command>" for more information about a given command or topic. Use "main --options" for a list of global command-line options (applies to all commands). """ ) def test_print_hidden() -> None: @group() def sub_command() -> None: pass @command(hidden=True) async def plain_cmd(root: Root) -> None: pass @group() def main() -> None: pass main.add_command(sub_command) main.add_command(plain_cmd) runner = CliRunner() result = runner.invoke(main, []) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] COMMAND [ARGS]... Commands: sub-command """ ) def test_print_deprecated_group() -> None: @group() def sub_command() -> None: @group() def main() -> None: pass main.add_command(sub_command) main.add_command(DeprecatedGroup(sub_command, name="alias")) runner = CliRunner() result = runner.invoke(main, []) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] COMMAND [ARGS]... Commands: sub-command Sub-command alias (Deprecated) Alias for sub-command """ ) def test_print_deprecated_group_content() -> None: @group() def sub_command() -> None: @sub_command.command() async def cmd(root: Root) -> None: @group(cls=MainGroup) def main() -> None: pass main.add_command(sub_command) main.add_command(DeprecatedGroup(sub_command, name="alias")) main.skip_init = True runner = CliRunner() result = runner.invoke(main, ["alias"]) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main alias [OPTIONS] COMMAND [ARGS]... Alias for sub-command (DEPRECATED) Commands: cmd Command """ ) def test_print_deprecated_no_help() -> None: @command(deprecated=True) async def main(root: Root) -> None: pass runner = CliRunner() result = runner.invoke(main, ["--help"]) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] (DEPRECATED) Options: --help Show this message and exit. """ ) def test_print_deprecated_with_help() -> None: @command(deprecated=True) async def main(root: Root) -> None: runner = CliRunner() result = runner.invoke(main, ["--help"]) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] Main help. (DEPRECATED) Options: --help Show this message and exit. """ ) def test_print_help_with_examples() -> None: @command() async def main(root: Root) -> None: runner = CliRunner() result = runner.invoke(main, ["--help"]) assert result.exit_code == 0 assert result.output == dedent( """\ Usage: main [OPTIONS] Main help. Examples: # comment example Options: --help Show this message and exit. """ )
true
true
1c2ce440cdcc2c092b20677207323cedbe5e1b4d
5,554
py
Python
data/librispeech.py
Peach-He/deepspeech
ef99c8f3c1eaabc0d5e9b2a7b366d5c0a6456d16
[ "MIT" ]
null
null
null
data/librispeech.py
Peach-He/deepspeech
ef99c8f3c1eaabc0d5e9b2a7b366d5c0a6456d16
[ "MIT" ]
null
null
null
data/librispeech.py
Peach-He/deepspeech
ef99c8f3c1eaabc0d5e9b2a7b366d5c0a6456d16
[ "MIT" ]
null
null
null
import os import wget import tarfile import argparse import subprocess from utils import create_manifest from tqdm import tqdm import shutil parser = argparse.ArgumentParser(description='Processes and downloads LibriSpeech dataset.') parser.add_argument("--target-dir", default='LibriSpeech_dataset/', type=str, help="Directory to store the dataset.") parser.add_argument('--sample-rate', default=16000, type=int, help='Sample rate') parser.add_argument('--files-to-use', default="train-clean-100.tar.gz," "train-clean-360.tar.gz,train-other-500.tar.gz," "dev-clean.tar.gz,dev-other.tar.gz," "test-clean.tar.gz,test-other.tar.gz", type=str, help='list of file names to download') parser.add_argument('--min-duration', default=1, type=int, help='Prunes training samples shorter than the min duration (given in seconds, default 1)') parser.add_argument('--max-duration', default=15, type=int, help='Prunes training samples longer than the max duration (given in seconds, default 15)') args = parser.parse_args() LIBRI_SPEECH_URLS = { "train": ["http://www.openslr.org/resources/12/train-clean-100.tar.gz", # "http://www.openslr.org/resources/12/train-clean-360.tar.gz", # "http://www.openslr.org/resources/12/train-other-500.tar.gz" ], # "val": ["http://www.openslr.org/resources/12/dev-clean.tar.gz", # "http://www.openslr.org/resources/12/dev-other.tar.gz" # ], # "test_clean": ["http://www.openslr.org/resources/12/test-clean.tar.gz"], # "test_other": ["http://www.openslr.org/resources/12/test-other.tar.gz"] } def _preprocess_transcript(phrase): return phrase.strip().upper() def _process_file(wav_dir, txt_dir, base_filename, root_dir): full_recording_path = os.path.join(root_dir, base_filename) assert os.path.exists(full_recording_path) and os.path.exists(root_dir) wav_recording_path = os.path.join(wav_dir, base_filename.replace(".flac", ".wav")) subprocess.call(["sox {} -r {} -b 16 -c 1 {}".format(full_recording_path, str(args.sample_rate), wav_recording_path)], shell=True) # process transcript txt_transcript_path = os.path.join(txt_dir, base_filename.replace(".flac", ".txt")) transcript_file = os.path.join(root_dir, "-".join(base_filename.split('-')[:-1]) + ".trans.txt") assert os.path.exists(transcript_file), "Transcript file {} does not exist.".format(transcript_file) transcriptions = open(transcript_file).read().strip().split("\n") transcriptions = {t.split()[0].split("-")[-1]: " ".join(t.split()[1:]) for t in transcriptions} with open(txt_transcript_path, "w") as f: key = base_filename.replace(".flac", "").split("-")[-1] assert key in transcriptions, "{} is not in the transcriptions".format(key) f.write(_preprocess_transcript(transcriptions[key])) f.flush() def main(): target_dl_dir = args.target_dir if not os.path.exists(target_dl_dir): os.makedirs(target_dl_dir) files_to_dl = args.files_to_use.strip().split(',') for split_type, lst_libri_urls in LIBRI_SPEECH_URLS.items(): split_dir = os.path.join(target_dl_dir, split_type) if not os.path.exists(split_dir): os.makedirs(split_dir) split_wav_dir = os.path.join(split_dir, "wav") if not os.path.exists(split_wav_dir): os.makedirs(split_wav_dir) split_txt_dir = os.path.join(split_dir, "txt") if not os.path.exists(split_txt_dir): os.makedirs(split_txt_dir) extracted_dir = os.path.join(split_dir, "LibriSpeech") if os.path.exists(extracted_dir): shutil.rmtree(extracted_dir) for url in lst_libri_urls: # check if we want to dl this file dl_flag = False for f in files_to_dl: if url.find(f) != -1: dl_flag = True if not dl_flag: print("Skipping url: {}".format(url)) continue filename = url.split("/")[-1] target_filename = os.path.join(split_dir, filename) if not os.path.exists(target_filename): wget.download(url, split_dir) print("Unpacking {}...".format(filename)) tar = tarfile.open(target_filename) tar.extractall(split_dir) tar.close() # os.remove(target_filename) print("Converting flac files to wav and extracting transcripts...") assert os.path.exists(extracted_dir), "Archive {} was not properly uncompressed.".format(filename) for root, subdirs, files in tqdm(os.walk(extracted_dir)): for f in files: if f.find(".flac") != -1: _process_file(wav_dir=split_wav_dir, txt_dir=split_txt_dir, base_filename=f, root_dir=root) print("Finished {}".format(url)) shutil.rmtree(extracted_dir) if split_type == 'train': # Prune to min/max duration create_manifest(split_dir, 'libri_' + split_type + '_manifest.csv', args.min_duration, args.max_duration) else: create_manifest(split_dir, 'libri_' + split_type + '_manifest.csv') if __name__ == "__main__": main()
47.87931
117
0.617213
import os import wget import tarfile import argparse import subprocess from utils import create_manifest from tqdm import tqdm import shutil parser = argparse.ArgumentParser(description='Processes and downloads LibriSpeech dataset.') parser.add_argument("--target-dir", default='LibriSpeech_dataset/', type=str, help="Directory to store the dataset.") parser.add_argument('--sample-rate', default=16000, type=int, help='Sample rate') parser.add_argument('--files-to-use', default="train-clean-100.tar.gz," "train-clean-360.tar.gz,train-other-500.tar.gz," "dev-clean.tar.gz,dev-other.tar.gz," "test-clean.tar.gz,test-other.tar.gz", type=str, help='list of file names to download') parser.add_argument('--min-duration', default=1, type=int, help='Prunes training samples shorter than the min duration (given in seconds, default 1)') parser.add_argument('--max-duration', default=15, type=int, help='Prunes training samples longer than the max duration (given in seconds, default 15)') args = parser.parse_args() LIBRI_SPEECH_URLS = { "train": ["http://www.openslr.org/resources/12/train-clean-100.tar.gz", ], } def _preprocess_transcript(phrase): return phrase.strip().upper() def _process_file(wav_dir, txt_dir, base_filename, root_dir): full_recording_path = os.path.join(root_dir, base_filename) assert os.path.exists(full_recording_path) and os.path.exists(root_dir) wav_recording_path = os.path.join(wav_dir, base_filename.replace(".flac", ".wav")) subprocess.call(["sox {} -r {} -b 16 -c 1 {}".format(full_recording_path, str(args.sample_rate), wav_recording_path)], shell=True) txt_transcript_path = os.path.join(txt_dir, base_filename.replace(".flac", ".txt")) transcript_file = os.path.join(root_dir, "-".join(base_filename.split('-')[:-1]) + ".trans.txt") assert os.path.exists(transcript_file), "Transcript file {} does not exist.".format(transcript_file) transcriptions = open(transcript_file).read().strip().split("\n") transcriptions = {t.split()[0].split("-")[-1]: " ".join(t.split()[1:]) for t in transcriptions} with open(txt_transcript_path, "w") as f: key = base_filename.replace(".flac", "").split("-")[-1] assert key in transcriptions, "{} is not in the transcriptions".format(key) f.write(_preprocess_transcript(transcriptions[key])) f.flush() def main(): target_dl_dir = args.target_dir if not os.path.exists(target_dl_dir): os.makedirs(target_dl_dir) files_to_dl = args.files_to_use.strip().split(',') for split_type, lst_libri_urls in LIBRI_SPEECH_URLS.items(): split_dir = os.path.join(target_dl_dir, split_type) if not os.path.exists(split_dir): os.makedirs(split_dir) split_wav_dir = os.path.join(split_dir, "wav") if not os.path.exists(split_wav_dir): os.makedirs(split_wav_dir) split_txt_dir = os.path.join(split_dir, "txt") if not os.path.exists(split_txt_dir): os.makedirs(split_txt_dir) extracted_dir = os.path.join(split_dir, "LibriSpeech") if os.path.exists(extracted_dir): shutil.rmtree(extracted_dir) for url in lst_libri_urls: dl_flag = False for f in files_to_dl: if url.find(f) != -1: dl_flag = True if not dl_flag: print("Skipping url: {}".format(url)) continue filename = url.split("/")[-1] target_filename = os.path.join(split_dir, filename) if not os.path.exists(target_filename): wget.download(url, split_dir) print("Unpacking {}...".format(filename)) tar = tarfile.open(target_filename) tar.extractall(split_dir) tar.close() print("Converting flac files to wav and extracting transcripts...") assert os.path.exists(extracted_dir), "Archive {} was not properly uncompressed.".format(filename) for root, subdirs, files in tqdm(os.walk(extracted_dir)): for f in files: if f.find(".flac") != -1: _process_file(wav_dir=split_wav_dir, txt_dir=split_txt_dir, base_filename=f, root_dir=root) print("Finished {}".format(url)) shutil.rmtree(extracted_dir) if split_type == 'train': create_manifest(split_dir, 'libri_' + split_type + '_manifest.csv', args.min_duration, args.max_duration) else: create_manifest(split_dir, 'libri_' + split_type + '_manifest.csv') if __name__ == "__main__": main()
true
true
1c2ce441da030c6da08196c2cdf3f504a68ae65c
47
py
Python
codigofacilito/__init__.py
eduardogpg/codigofacilito_package
f1691f087a0cf567e5f97c939106cc4852d5f6f0
[ "MIT" ]
1
2022-01-13T00:12:54.000Z
2022-01-13T00:12:54.000Z
codigofacilito/__init__.py
eduardogpg/codigofacilito_package
f1691f087a0cf567e5f97c939106cc4852d5f6f0
[ "MIT" ]
null
null
null
codigofacilito/__init__.py
eduardogpg/codigofacilito_package
f1691f087a0cf567e5f97c939106cc4852d5f6f0
[ "MIT" ]
4
2022-01-13T00:29:31.000Z
2022-01-24T23:48:33.000Z
from codigofacilito.workshops import unreleased
47
47
0.914894
from codigofacilito.workshops import unreleased
true
true
1c2ce50f1e76aa809b860bc9c7b496d390f10c10
279
py
Python
Leetcode/921. Minimum Add to Make Parentheses Valid/solution1.py
asanoviskhak/Outtalent
c500e8ad498f76d57eb87a9776a04af7bdda913d
[ "MIT" ]
51
2020-07-12T21:27:47.000Z
2022-02-11T19:25:36.000Z
Leetcode/921. Minimum Add to Make Parentheses Valid/solution1.py
CrazySquirrel/Outtalent
8a10b23335d8e9f080e5c39715b38bcc2916ff00
[ "MIT" ]
null
null
null
Leetcode/921. Minimum Add to Make Parentheses Valid/solution1.py
CrazySquirrel/Outtalent
8a10b23335d8e9f080e5c39715b38bcc2916ff00
[ "MIT" ]
32
2020-07-27T13:54:24.000Z
2021-12-25T18:12:50.000Z
class Solution: def minAddToMakeValid(self, S: str) -> int: result = counter = 0 for c in S: counter += 1 if c == '(' else -1 if counter == -1: counter += 1 result += 1 return result + counter
23.25
47
0.448029
class Solution: def minAddToMakeValid(self, S: str) -> int: result = counter = 0 for c in S: counter += 1 if c == '(' else -1 if counter == -1: counter += 1 result += 1 return result + counter
true
true
1c2ce6145b672cdd2bcd88e082ca1018c3e4ea4d
4,659
py
Python
src/FunctionApps/python/IntakePipeline/fhir.py
CDCgov/prime-public-health-data-infrastructure
7e4849c3a486a84e94765bf0023b80261c510c57
[ "Apache-2.0" ]
3
2022-02-24T18:16:39.000Z
2022-03-29T20:21:41.000Z
src/FunctionApps/python/IntakePipeline/fhir.py
CDCgov/prime-public-health-data-infrastructure
7e4849c3a486a84e94765bf0023b80261c510c57
[ "Apache-2.0" ]
17
2022-02-08T17:13:55.000Z
2022-03-28T16:49:00.000Z
src/FunctionApps/python/IntakePipeline/fhir.py
CDCgov/prime-public-health-data-infrastructure
7e4849c3a486a84e94765bf0023b80261c510c57
[ "Apache-2.0" ]
3
2022-02-27T23:12:50.000Z
2022-03-17T04:51:47.000Z
from datetime import datetime, timezone import json import logging import pathlib import requests from requests.adapters import HTTPAdapter from urllib3 import Retry from azure.core.credentials import AccessToken from azure.identity import DefaultAzureCredential from azure.storage.blob import ContainerClient def get_blob_client(container_url: str) -> ContainerClient: """Use whatever creds Azure can find to authenticate with the storage container""" creds = DefaultAzureCredential() return ContainerClient.from_container_url(container_url, credential=creds) def generate_filename(blob_name: str, message_index: int) -> str: """Strip the file type suffix from the blob name, and append message index.""" fname = blob_name.split("/")[-1] fname, _ = fname.rsplit(".", 1) return f"{fname}-{message_index}" def store_data( container_url: str, prefix: str, filename: str, bundle_type: str, message_json: dict = None, message: str = None, ) -> None: """ Store the given data, which is either a FHIR bundle or an HL7 message in the appropriate output container """ client = get_blob_client(container_url) blob = client.get_blob_client(str(pathlib.Path(prefix) / bundle_type / filename)) if message_json is not None: blob.upload_blob(json.dumps(message_json).encode("utf-8"), overwrite=True) elif message is not None: blob.upload_blob(bytes(message, "utf-8"), overwrite=True) class AzureFhirserverCredentialManager: """Manager for handling Azure credentials for access to the FHIR server""" def __init__(self, fhir_url): """Credential manager constructor""" self.access_token = None self.fhir_url = fhir_url def get_fhir_url(self): """Get FHIR URL""" return self.fhir_url def get_access_token(self, token_reuse_tolerance: float = 10.0) -> AccessToken: """If the token is already set for this object and is not about to expire (within token_reuse_tolerance parameter), then return the existing token. Otherwise, request a new one. :param str token_reuse_tolerance: Number of seconds before expiration it is OK to reuse the currently assigned token""" if not self._need_new_token(token_reuse_tolerance): return self.access_token creds = self._get_azure_credentials() scope = f"{self.fhir_url}/.default" self.access_token = creds.get_token(scope) return self.access_token def _get_azure_credentials(self): """Get default Azure Credentials from login context and related Azure configuration.""" return DefaultAzureCredential() def _need_new_token(self, token_reuse_tolerance: float = 10.0) -> bool: """Determine whether the token already stored for this object can be reused, or if it needs to be re-requested. :param str token_reuse_tolerance: Number of seconds before expiration it is OK to reuse the currently assigned token""" try: current_time_utc = datetime.now(timezone.utc).timestamp() return ( self.access_token.expires_on - token_reuse_tolerance ) < current_time_utc except AttributeError: # access_token not set return True def get_fhirserver_cred_manager(fhir_url: str): """Get an instance of the Azure FHIR Server credential manager.""" return AzureFhirserverCredentialManager(fhir_url) def upload_bundle_to_fhir_server(bundle: dict, access_token: str, fhir_url: str): """Import a FHIR resource to the FHIR server. The submissions may be Bundles or individual FHIR resources. :param AzureFhirserverCredentialManager fhirserver_cred_manager: Credential manager. :param dict fhir_json: FHIR resource in json format. :param str method: HTTP method to use (currently PUT or POST supported) """ retry_strategy = Retry( total=3, status_forcelist=[429, 500, 502, 503, 504], allowed_methods=["HEAD", "PUT", "POST", "OPTIONS"], ) adapter = HTTPAdapter(max_retries=retry_strategy) http = requests.Session() http.mount("https://", adapter) try: requests.post( fhir_url, headers={ "Authorization": f"Bearer {access_token}", "Accept": "application/fhir+json", "Content-Type": "application/fhir+json", }, data=json.dumps(bundle), ) except Exception: logging.exception("Request to post Bundle failed for json: " + str(bundle)) return
36.398438
93
0.68255
from datetime import datetime, timezone import json import logging import pathlib import requests from requests.adapters import HTTPAdapter from urllib3 import Retry from azure.core.credentials import AccessToken from azure.identity import DefaultAzureCredential from azure.storage.blob import ContainerClient def get_blob_client(container_url: str) -> ContainerClient: creds = DefaultAzureCredential() return ContainerClient.from_container_url(container_url, credential=creds) def generate_filename(blob_name: str, message_index: int) -> str: fname = blob_name.split("/")[-1] fname, _ = fname.rsplit(".", 1) return f"{fname}-{message_index}" def store_data( container_url: str, prefix: str, filename: str, bundle_type: str, message_json: dict = None, message: str = None, ) -> None: client = get_blob_client(container_url) blob = client.get_blob_client(str(pathlib.Path(prefix) / bundle_type / filename)) if message_json is not None: blob.upload_blob(json.dumps(message_json).encode("utf-8"), overwrite=True) elif message is not None: blob.upload_blob(bytes(message, "utf-8"), overwrite=True) class AzureFhirserverCredentialManager: def __init__(self, fhir_url): self.access_token = None self.fhir_url = fhir_url def get_fhir_url(self): return self.fhir_url def get_access_token(self, token_reuse_tolerance: float = 10.0) -> AccessToken: if not self._need_new_token(token_reuse_tolerance): return self.access_token creds = self._get_azure_credentials() scope = f"{self.fhir_url}/.default" self.access_token = creds.get_token(scope) return self.access_token def _get_azure_credentials(self): return DefaultAzureCredential() def _need_new_token(self, token_reuse_tolerance: float = 10.0) -> bool: try: current_time_utc = datetime.now(timezone.utc).timestamp() return ( self.access_token.expires_on - token_reuse_tolerance ) < current_time_utc except AttributeError: return True def get_fhirserver_cred_manager(fhir_url: str): return AzureFhirserverCredentialManager(fhir_url) def upload_bundle_to_fhir_server(bundle: dict, access_token: str, fhir_url: str): retry_strategy = Retry( total=3, status_forcelist=[429, 500, 502, 503, 504], allowed_methods=["HEAD", "PUT", "POST", "OPTIONS"], ) adapter = HTTPAdapter(max_retries=retry_strategy) http = requests.Session() http.mount("https://", adapter) try: requests.post( fhir_url, headers={ "Authorization": f"Bearer {access_token}", "Accept": "application/fhir+json", "Content-Type": "application/fhir+json", }, data=json.dumps(bundle), ) except Exception: logging.exception("Request to post Bundle failed for json: " + str(bundle)) return
true
true
1c2ce642c0b84948b0a1c1957666b41eb9af6cfb
468
py
Python
corehq/apps/data_dictionary/migrations/0006_caseproperty_group.py
kkrampa/commcare-hq
d64d7cad98b240325ad669ccc7effb07721b4d44
[ "BSD-3-Clause" ]
1
2020-05-05T13:10:01.000Z
2020-05-05T13:10:01.000Z
corehq/apps/data_dictionary/migrations/0006_caseproperty_group.py
kkrampa/commcare-hq
d64d7cad98b240325ad669ccc7effb07721b4d44
[ "BSD-3-Clause" ]
1
2019-12-09T14:00:14.000Z
2019-12-09T14:00:14.000Z
corehq/apps/data_dictionary/migrations/0006_caseproperty_group.py
MaciejChoromanski/commcare-hq
fd7f65362d56d73b75a2c20d2afeabbc70876867
[ "BSD-3-Clause" ]
5
2015-11-30T13:12:45.000Z
2019-07-01T19:27:07.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absolute_import from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('data_dictionary', '0005_casetype_fully_generated'), ] operations = [ migrations.AddField( model_name='caseproperty', name='group', field=models.TextField(default=b'', blank=True), ), ]
22.285714
61
0.641026
from __future__ import unicode_literals from __future__ import absolute_import from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('data_dictionary', '0005_casetype_fully_generated'), ] operations = [ migrations.AddField( model_name='caseproperty', name='group', field=models.TextField(default=b'', blank=True), ), ]
true
true
1c2ce6bfac193cc81e3a31decba1d40c981bad46
14,385
py
Python
test/functional/mempool_accept.py
Bits-Coin/bits-coin
dd8220018f5582e76d43e8c52bd323524e495d8c
[ "MIT" ]
2
2021-11-17T23:05:13.000Z
2021-11-17T23:05:32.000Z
test/functional/mempool_accept.py
Bits-Coin/bits-coin
dd8220018f5582e76d43e8c52bd323524e495d8c
[ "MIT" ]
null
null
null
test/functional/mempool_accept.py
Bits-Coin/bits-coin
dd8220018f5582e76d43e8c52bd323524e495d8c
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2017 The BitsCoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool acceptance of raw transactions.""" from io import BytesIO from test_framework.test_framework import BitsCoinTestFramework from test_framework.messages import ( BIP125_SEQUENCE_NUMBER, COIN, COutPoint, CTransaction, CTxOut, MAX_BLOCK_BASE_SIZE, ) from test_framework.script import ( hash160, CScript, OP_0, OP_EQUAL, OP_HASH160, OP_RETURN, ) from test_framework.util import ( assert_equal, assert_raises_rpc_error, bytes_to_hex_str, hex_str_to_bytes, wait_until, ) class MempoolAcceptanceTest(BitsCoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.extra_args = [[ '-txindex', '-reindex', # Need reindex for txindex '-acceptnonstdtxn=0', # Try to mimic main-net ]] * self.num_nodes def skip_test_if_missing_module(self): self.skip_if_no_wallet() def check_mempool_result(self, result_expected, *args, **kwargs): """Wrapper to check result of testmempoolaccept on node_0's mempool""" result_test = self.nodes[0].testmempoolaccept(*args, **kwargs) assert_equal(result_expected, result_test) assert_equal(self.nodes[0].getmempoolinfo()['size'], self.mempool_size) # Must not change mempool state def run_test(self): node = self.nodes[0] self.log.info('Start with empty mempool, and 200 blocks') self.mempool_size = 0 wait_until(lambda: node.getblockcount() == 200) assert_equal(node.getmempoolinfo()['size'], self.mempool_size) self.log.info('Should not accept garbage to testmempoolaccept') assert_raises_rpc_error(-3, 'Expected type array, got string', lambda: node.testmempoolaccept(rawtxs='ff00baar')) assert_raises_rpc_error(-8, 'Array must contain exactly one raw transaction for now', lambda: node.testmempoolaccept(rawtxs=['ff00baar', 'ff22'])) assert_raises_rpc_error(-22, 'TX decode failed', lambda: node.testmempoolaccept(rawtxs=['ff00baar'])) self.log.info('A transaction already in the blockchain') coin = node.listunspent()[0] # Pick a random coin(base) to spend raw_tx_in_block = node.signrawtransactionwithwallet(node.createrawtransaction( inputs=[{'txid': coin['txid'], 'vout': coin['vout']}], outputs=[{node.getnewaddress(): 0.3}, {node.getnewaddress(): 49}], ))['hex'] txid_in_block = node.sendrawtransaction(hexstring=raw_tx_in_block, allowhighfees=True) node.generate(1) self.check_mempool_result( result_expected=[{'txid': txid_in_block, 'allowed': False, 'reject-reason': '18: txn-already-known'}], rawtxs=[raw_tx_in_block], ) self.log.info('A transaction not in the mempool') fee = 0.00000700 raw_tx_0 = node.signrawtransactionwithwallet(node.createrawtransaction( inputs=[{"txid": txid_in_block, "vout": 0, "sequence": BIP125_SEQUENCE_NUMBER}], # RBF is used later outputs=[{node.getnewaddress(): 0.3 - fee}], ))['hex'] tx = CTransaction() tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) txid_0 = tx.rehash() self.check_mempool_result( result_expected=[{'txid': txid_0, 'allowed': True}], rawtxs=[raw_tx_0], ) self.log.info('A transaction in the mempool') node.sendrawtransaction(hexstring=raw_tx_0) self.mempool_size = 1 self.check_mempool_result( result_expected=[{'txid': txid_0, 'allowed': False, 'reject-reason': '18: txn-already-in-mempool'}], rawtxs=[raw_tx_0], ) self.log.info('A transaction that replaces a mempool transaction') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) tx.vout[0].nValue -= int(fee * COIN) # Double the fee tx.vin[0].nSequence = BIP125_SEQUENCE_NUMBER + 1 # Now, opt out of RBF raw_tx_0 = node.signrawtransactionwithwallet(bytes_to_hex_str(tx.serialize()))['hex'] tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) txid_0 = tx.rehash() self.check_mempool_result( result_expected=[{'txid': txid_0, 'allowed': True}], rawtxs=[raw_tx_0], ) self.log.info('A transaction that conflicts with an unconfirmed tx') # Send the transaction that replaces the mempool transaction and opts out of replaceability node.sendrawtransaction(hexstring=bytes_to_hex_str(tx.serialize()), allowhighfees=True) # take original raw_tx_0 tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) tx.vout[0].nValue -= int(4 * fee * COIN) # Set more fee # skip re-signing the tx self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '18: txn-mempool-conflict'}], rawtxs=[bytes_to_hex_str(tx.serialize())], allowhighfees=True, ) self.log.info('A transaction with missing inputs, that never existed') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) tx.vin[0].prevout = COutPoint(hash=int('ff' * 32, 16), n=14) # skip re-signing the tx self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'missing-inputs'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction with missing inputs, that existed once in the past') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) tx.vin[0].prevout.n = 1 # Set vout to 1, to spend the other outpoint (49 coins) of the in-chain-tx we want to double spend raw_tx_1 = node.signrawtransactionwithwallet(bytes_to_hex_str(tx.serialize()))['hex'] txid_1 = node.sendrawtransaction(hexstring=raw_tx_1, allowhighfees=True) # Now spend both to "clearly hide" the outputs, ie. remove the coins from the utxo set by spending them raw_tx_spend_both = node.signrawtransactionwithwallet(node.createrawtransaction( inputs=[ {'txid': txid_0, 'vout': 0}, {'txid': txid_1, 'vout': 0}, ], outputs=[{node.getnewaddress(): 0.1}] ))['hex'] txid_spend_both = node.sendrawtransaction(hexstring=raw_tx_spend_both, allowhighfees=True) node.generate(1) self.mempool_size = 0 # Now see if we can add the coins back to the utxo set by sending the exact txs again self.check_mempool_result( result_expected=[{'txid': txid_0, 'allowed': False, 'reject-reason': 'missing-inputs'}], rawtxs=[raw_tx_0], ) self.check_mempool_result( result_expected=[{'txid': txid_1, 'allowed': False, 'reject-reason': 'missing-inputs'}], rawtxs=[raw_tx_1], ) self.log.info('Create a signed "reference" tx for later use') raw_tx_reference = node.signrawtransactionwithwallet(node.createrawtransaction( inputs=[{'txid': txid_spend_both, 'vout': 0}], outputs=[{node.getnewaddress(): 0.05}], ))['hex'] tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) # Reference tx should be valid on itself self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': True}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction with no outputs') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout = [] # Skip re-signing the transaction for context independent checks from now on # tx.deserialize(BytesIO(hex_str_to_bytes(node.signrawtransactionwithwallet(bytes_to_hex_str(tx.serialize()))['hex']))) self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-vout-empty'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A really large transaction') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vin = [tx.vin[0]] * (MAX_BLOCK_BASE_SIZE // len(tx.vin[0].serialize())) self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-oversize'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction with negative output value') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout[0].nValue *= -1 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-vout-negative'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction with too large output value') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout[0].nValue = 21000000 * COIN + 1 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-vout-toolarge'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction with too large sum of output values') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout = [tx.vout[0]] * 2 tx.vout[0].nValue = 21000000 * COIN self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-txouttotal-toolarge'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction with duplicate inputs') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vin = [tx.vin[0]] * 2 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-inputs-duplicate'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A coinbase transaction') # Pick the input of the first tx we signed, so it has to be a coinbase tx raw_tx_coinbase_spent = node.getrawtransaction(txid=node.decoderawtransaction(hexstring=raw_tx_in_block)['vin'][0]['txid']) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_coinbase_spent))) self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: coinbase'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('Some nonstandard transactions') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.nVersion = 3 # A version currently non-standard self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: version'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout[0].scriptPubKey = CScript([OP_0]) # Some non-standard script self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: scriptpubkey'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vin[0].scriptSig = CScript([OP_HASH160]) # Some not-pushonly scriptSig self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: scriptsig-not-pushonly'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) output_p2sh_burn = CTxOut(nValue=540, scriptPubKey=CScript([OP_HASH160, hash160(b'burn'), OP_EQUAL])) num_scripts = 100000 // len(output_p2sh_burn.serialize()) # Use enough outputs to make the tx too large for our policy tx.vout = [output_p2sh_burn] * num_scripts self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: tx-size'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout[0] = output_p2sh_burn tx.vout[0].nValue -= 1 # Make output smaller, such that it is dust for our policy self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: dust'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout[0].scriptPubKey = CScript([OP_RETURN, b'\xff']) tx.vout = [tx.vout[0]] * 2 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: multi-op-return'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A timelocked transaction') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vin[0].nSequence -= 1 # Should be non-max, so locktime is not ignored tx.nLockTime = node.getblockcount() + 1 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: non-final'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction that is locked by BIP68 sequence logic') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vin[0].nSequence = 2 # We could include it in the second block mined from now, but not the very next one # Can skip re-signing the tx because of early rejection self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: non-BIP68-final'}], rawtxs=[bytes_to_hex_str(tx.serialize())], allowhighfees=True, ) if __name__ == '__main__': MempoolAcceptanceTest().main()
48.597973
154
0.64456
from io import BytesIO from test_framework.test_framework import BitsCoinTestFramework from test_framework.messages import ( BIP125_SEQUENCE_NUMBER, COIN, COutPoint, CTransaction, CTxOut, MAX_BLOCK_BASE_SIZE, ) from test_framework.script import ( hash160, CScript, OP_0, OP_EQUAL, OP_HASH160, OP_RETURN, ) from test_framework.util import ( assert_equal, assert_raises_rpc_error, bytes_to_hex_str, hex_str_to_bytes, wait_until, ) class MempoolAcceptanceTest(BitsCoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.extra_args = [[ '-txindex', '-reindex', '-acceptnonstdtxn=0', ]] * self.num_nodes def skip_test_if_missing_module(self): self.skip_if_no_wallet() def check_mempool_result(self, result_expected, *args, **kwargs): result_test = self.nodes[0].testmempoolaccept(*args, **kwargs) assert_equal(result_expected, result_test) assert_equal(self.nodes[0].getmempoolinfo()['size'], self.mempool_size) def run_test(self): node = self.nodes[0] self.log.info('Start with empty mempool, and 200 blocks') self.mempool_size = 0 wait_until(lambda: node.getblockcount() == 200) assert_equal(node.getmempoolinfo()['size'], self.mempool_size) self.log.info('Should not accept garbage to testmempoolaccept') assert_raises_rpc_error(-3, 'Expected type array, got string', lambda: node.testmempoolaccept(rawtxs='ff00baar')) assert_raises_rpc_error(-8, 'Array must contain exactly one raw transaction for now', lambda: node.testmempoolaccept(rawtxs=['ff00baar', 'ff22'])) assert_raises_rpc_error(-22, 'TX decode failed', lambda: node.testmempoolaccept(rawtxs=['ff00baar'])) self.log.info('A transaction already in the blockchain') coin = node.listunspent()[0] raw_tx_in_block = node.signrawtransactionwithwallet(node.createrawtransaction( inputs=[{'txid': coin['txid'], 'vout': coin['vout']}], outputs=[{node.getnewaddress(): 0.3}, {node.getnewaddress(): 49}], ))['hex'] txid_in_block = node.sendrawtransaction(hexstring=raw_tx_in_block, allowhighfees=True) node.generate(1) self.check_mempool_result( result_expected=[{'txid': txid_in_block, 'allowed': False, 'reject-reason': '18: txn-already-known'}], rawtxs=[raw_tx_in_block], ) self.log.info('A transaction not in the mempool') fee = 0.00000700 raw_tx_0 = node.signrawtransactionwithwallet(node.createrawtransaction( inputs=[{"txid": txid_in_block, "vout": 0, "sequence": BIP125_SEQUENCE_NUMBER}], outputs=[{node.getnewaddress(): 0.3 - fee}], ))['hex'] tx = CTransaction() tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) txid_0 = tx.rehash() self.check_mempool_result( result_expected=[{'txid': txid_0, 'allowed': True}], rawtxs=[raw_tx_0], ) self.log.info('A transaction in the mempool') node.sendrawtransaction(hexstring=raw_tx_0) self.mempool_size = 1 self.check_mempool_result( result_expected=[{'txid': txid_0, 'allowed': False, 'reject-reason': '18: txn-already-in-mempool'}], rawtxs=[raw_tx_0], ) self.log.info('A transaction that replaces a mempool transaction') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) tx.vout[0].nValue -= int(fee * COIN) tx.vin[0].nSequence = BIP125_SEQUENCE_NUMBER + 1 raw_tx_0 = node.signrawtransactionwithwallet(bytes_to_hex_str(tx.serialize()))['hex'] tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) txid_0 = tx.rehash() self.check_mempool_result( result_expected=[{'txid': txid_0, 'allowed': True}], rawtxs=[raw_tx_0], ) self.log.info('A transaction that conflicts with an unconfirmed tx') node.sendrawtransaction(hexstring=bytes_to_hex_str(tx.serialize()), allowhighfees=True) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) tx.vout[0].nValue -= int(4 * fee * COIN) self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '18: txn-mempool-conflict'}], rawtxs=[bytes_to_hex_str(tx.serialize())], allowhighfees=True, ) self.log.info('A transaction with missing inputs, that never existed') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) tx.vin[0].prevout = COutPoint(hash=int('ff' * 32, 16), n=14) self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'missing-inputs'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction with missing inputs, that existed once in the past') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) tx.vin[0].prevout.n = 1 raw_tx_1 = node.signrawtransactionwithwallet(bytes_to_hex_str(tx.serialize()))['hex'] txid_1 = node.sendrawtransaction(hexstring=raw_tx_1, allowhighfees=True) raw_tx_spend_both = node.signrawtransactionwithwallet(node.createrawtransaction( inputs=[ {'txid': txid_0, 'vout': 0}, {'txid': txid_1, 'vout': 0}, ], outputs=[{node.getnewaddress(): 0.1}] ))['hex'] txid_spend_both = node.sendrawtransaction(hexstring=raw_tx_spend_both, allowhighfees=True) node.generate(1) self.mempool_size = 0 self.check_mempool_result( result_expected=[{'txid': txid_0, 'allowed': False, 'reject-reason': 'missing-inputs'}], rawtxs=[raw_tx_0], ) self.check_mempool_result( result_expected=[{'txid': txid_1, 'allowed': False, 'reject-reason': 'missing-inputs'}], rawtxs=[raw_tx_1], ) self.log.info('Create a signed "reference" tx for later use') raw_tx_reference = node.signrawtransactionwithwallet(node.createrawtransaction( inputs=[{'txid': txid_spend_both, 'vout': 0}], outputs=[{node.getnewaddress(): 0.05}], ))['hex'] tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': True}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction with no outputs') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout = [] self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-vout-empty'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A really large transaction') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vin = [tx.vin[0]] * (MAX_BLOCK_BASE_SIZE // len(tx.vin[0].serialize())) self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-oversize'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction with negative output value') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout[0].nValue *= -1 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-vout-negative'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction with too large output value') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout[0].nValue = 21000000 * COIN + 1 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-vout-toolarge'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction with too large sum of output values') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout = [tx.vout[0]] * 2 tx.vout[0].nValue = 21000000 * COIN self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-txouttotal-toolarge'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction with duplicate inputs') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vin = [tx.vin[0]] * 2 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-inputs-duplicate'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A coinbase transaction') raw_tx_coinbase_spent = node.getrawtransaction(txid=node.decoderawtransaction(hexstring=raw_tx_in_block)['vin'][0]['txid']) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_coinbase_spent))) self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: coinbase'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('Some nonstandard transactions') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.nVersion = 3 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: version'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout[0].scriptPubKey = CScript([OP_0]) self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: scriptpubkey'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vin[0].scriptSig = CScript([OP_HASH160]) self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: scriptsig-not-pushonly'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) output_p2sh_burn = CTxOut(nValue=540, scriptPubKey=CScript([OP_HASH160, hash160(b'burn'), OP_EQUAL])) num_scripts = 100000 // len(output_p2sh_burn.serialize()) tx.vout = [output_p2sh_burn] * num_scripts self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: tx-size'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout[0] = output_p2sh_burn tx.vout[0].nValue -= 1 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: dust'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout[0].scriptPubKey = CScript([OP_RETURN, b'\xff']) tx.vout = [tx.vout[0]] * 2 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: multi-op-return'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A timelocked transaction') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vin[0].nSequence -= 1 tx.nLockTime = node.getblockcount() + 1 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: non-final'}], rawtxs=[bytes_to_hex_str(tx.serialize())], ) self.log.info('A transaction that is locked by BIP68 sequence logic') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vin[0].nSequence = 2 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: non-BIP68-final'}], rawtxs=[bytes_to_hex_str(tx.serialize())], allowhighfees=True, ) if __name__ == '__main__': MempoolAcceptanceTest().main()
true
true
1c2ce766f24df8bf11f59ac9a48bcb2d11b81e6b
24,493
py
Python
src/ros_robodk_post_processors/robodk_post_processors/Comau_C5G_Joints.py
jeritgeorge/ros_robodk_post_processors
dd6fda231c5bcf964bf177b1737dc4b06c27cd33
[ "BSD-3-Clause" ]
null
null
null
src/ros_robodk_post_processors/robodk_post_processors/Comau_C5G_Joints.py
jeritgeorge/ros_robodk_post_processors
dd6fda231c5bcf964bf177b1737dc4b06c27cd33
[ "BSD-3-Clause" ]
null
null
null
src/ros_robodk_post_processors/robodk_post_processors/Comau_C5G_Joints.py
jeritgeorge/ros_robodk_post_processors
dd6fda231c5bcf964bf177b1737dc4b06c27cd33
[ "BSD-3-Clause" ]
null
null
null
# Copyright 2017 - RoboDK Software S.L. - http://www.robodk.com/ # 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. # ---------------------------------------------------- # This file is a POST PROCESSOR for Robot Offline Programming to generate programs # for Comau C5G robots # # To edit/test this POST PROCESSOR script file: # Select "Program"->"Add/Edit Post Processor", then select your post or create a new one. # You can edit this file using any text editor or Python editor. Using a Python editor allows to quickly evaluate a sample program at the end of this file. # Python should be automatically installed with RoboDK # # You can also edit the POST PROCESSOR manually: # 1- Open the *.py file with Python IDLE (right click -> Edit with IDLE) # 2- Make the necessary changes # 3- Run the file to open Python Shell: Run -> Run module (F5 by default) # 4- The "test_post()" function is called automatically # Alternatively, you can edit this file using a text editor and run it with Python # # To use a POST PROCESSOR file you must place the *.py file in "C:/RoboDK/Posts/" # To select one POST PROCESSOR for your robot in RoboDK you must follow these steps: # 1- Open the robot panel (double click a robot) # 2- Select "Parameters" # 3- Select "Unlock advanced options" # 4- Select your post as the file name in the "Robot brand" box # # To delete an existing POST PROCESSOR script, simply delete this file (.py file) # # ---------------------------------------------------- # More information about RoboDK Post Processors and Offline Programming here: # http://www.robodk.com/help#PostProcessor # http://www.robodk.com/doc/en/PythonAPI/postprocessor.html # ---------------------------------------------------- MACRO_MESSAGE_TP = '''-- Display message on the teach pendant: WIN_DEL ('menu:') -- popup window over window USR1 WIN_POPUP('POP1:', 'USR1:') -- open a lun on window POP1 OPEN FILE lun ('POP1:', 'rw') WRITE lun ('%s', NL) CLOSE FILE lun -- let user read the message DELAY 5000 -- Remove and delete window POP1 from user screen WIN_REMOVE('POP1:') WIN_DEL('POP1:') ------------------''' # ---------------------------------------------------- # Import RoboDK tools from robodk import * # gearbox ratio for external axes RATIO_EXTAX = [1,1,1,1,1,1] #[10.6/360.0, 1, 1, 1, 1, 1] # ---------------------------------------------------- # Object class that handles the robot instructions/syntax class RobotPost(object): """Robot post processor class""" PROG_EXT = 'pdl' # set the program extension MAX_LINES_X_PROG = 5000 # maximum number of lines per program. It will then generate multiple "pages (files)" INCLUDE_SUB_PROGRAMS = True #INCLUDE_SUB_PROGRAMS = False # other variables ROBOT_POST = '' ROBOT_NAME = '' # Multiple program files variables PROG_NAME = 'unknown' # single program name PROG_NAMES = [] PROG_FILES = [] PROG_LIST = [] PROG_VARS = [] SPEED_MMS = 1000 ACCEL_MMSS = 100 FLY_DIST = -1 # set to >0 to use MOVEFLY IMPORTS = [] PROG = '' ROUTINES = '' nLines = 0 nProgs = 0 LOG = '' nAxes = 6 TAB = '' LAST_POSE = None LAST_E_LENGTH = 0 NEW_E_LENGTH = 0 # --------------------------------------------------- def joints_2_str(self, joints): """Contverts a joint target to a string""" if joints is not None and len(joints) > 6: joints[6] = joints[6]*RATIO_EXTAX[0] return '{%s}' % (','.join(format(ji, ".5f") for ji in joints)) def pose_2_str(self, pose,joints=None,conf_RLF=None): """Converts a pose target to a string""" [x,y,z,w,p,r] = Pose_2_Comau(pose) config = [] # WARNING: Config only available for SMART type of contollers if conf_RLF is not None: if conf_RLF[0] > 0: config.append('S') if conf_RLF[1] > 0: config.append('E') if joints is not None: #self.addline('cnfg_str := POS_GET_CNFG(%s)' % self.joints_2_str(joints)) #config = 'cnfg_str' if len(joints) >= 5 and joints[4] < 0: config.append('W') if len(joints) >= 4: t1 = round((joints[3]+180) // 360) config.append('T1:%i' % t1) if len(joints) >= 6: t2 = round((joints[5]+180) // 360) config.append('T2:%i' % t2) t3 = round((joints[2]+180) // 360) config.append('T3:%i' % t3) pos_str = "POS(%.4f, %.4f, %.4f, %.4f, %.4f, %.4f, '%s')" % (x,y,z,w,p,r, ' '.join(config)) if joints is None or len(joints) <= 6: return pos_str #return ('XTNDPOS(POS(%.4f,%.4f,%.4f,%.4f,%.4f,%.4f), , , (%.4f))' % (x,y,z,w,p,r,j7)) else: self.addline('pxtn.POS := ' + pos_str) for i in range(6,len(joints)): self.addline('pxtn.AUX[%i] := %.5f' % (i-6+1, joints[i]*RATIO_EXTAX[i-6])) return 'pxtn' def __init__(self, robotpost=None, robotname=None, robot_axes = 6, **kwargs): self.ROBOT_POST = robotpost self.ROBOT_NAME = robotname self.PROG = '' self.LOG = '' self.nAxes = robot_axes for k,v in kwargs.items(): if k == 'lines_x_prog': self.MAX_LINES_X_PROG = v def ProgStart(self, progname, new_page = False): progname_i = progname if new_page: if self.INCLUDE_SUB_PROGRAMS: raise Exception("Multiple pages per program is not supported when adding routines in the main program") nPages = len(self.PROG_LIST) if nPages == 0: progname_i = progname else: progname_i = "%s%i" % (self.PROG_NAME, nPages) else: self.PROG_NAME = progname self.nProgs = self.nProgs + 1 self.PROG_NAMES = [] if self.nProgs > 1: if not self.INCLUDE_SUB_PROGRAMS: return else: if progname_i in self.IMPORTS: self.IMPORTS.remove(progname_i) self.addline('ROUTINE R_%s' % progname_i) self.addline('VAR') self.addline('BEGIN') self.TAB = ' ' return self.PROG_NAMES.append(progname_i) self.addline('PROGRAM %s' % progname_i) self.addline('-- IMPORTS --') #self.addline('CONST') self.addline('VAR') self.addline('ROUTINE R_%s EXPORTED FROM %s GLOBAL' % (progname_i, progname_i)) self.addline('') self.addline('-- ROUTINES --') #self.addline('BEGIN R_%s' % progname_i) self.addline('ROUTINE R_%s' % progname_i) self.addline('VAR') #self.addline(' cnfg_str: STRING') # PROG_VARS if self.nAxes > 6: self.addline(' pxtn: XTNDPOS') self.addline('-- VARIABLES --') # PROG_VARS self.addline('BEGIN') self.TAB = ' ' self.addline('$ORNT_TYPE := RS_WORLD') self.addline('$MOVE_TYPE := JOINT') self.addline('$JNT_MTURN := TRUE') self.addline('$CNFG_CARE := TRUE') self.addline('$TURN_CARE := TRUE') self.addline('$SING_CARE := FALSE') self.addline('$TERM_TYPE := NOSETTLE') # Use MOVEFLY (rounding) self.addline('$FLY_TYPE := FLY_CART') self.addline('$FLY_TRAJ := FLY_PASS') self.setZoneData(self.FLY_DIST) #self.addline('$FLY_DIST := 1') self.addline('$STRESS_PER:= 65') def ProgFinish(self, progname, new_page = False): variables = '' for line in self.PROG_VARS: variables = ' %s\n' % line self.PROG = self.PROG.replace('-- VARIABLES --\n', variables,1) self.PROG_VARS = [] if self.nProgs > 1 and not self.INCLUDE_SUB_PROGRAMS: return self.TAB = '' if self.nProgs <= 1: self.PROG = self.PROG + "END R_%s\n\n" % progname # Create a the main program which call the main routine self.PROG = self.PROG + "BEGIN\n R_%s\nEND %s\n\n" % (progname, progname) else: self.ROUTINES = self.ROUTINES + "END R_%s\n\n" % progname if new_page: self.PROG_LIST.append(self.PROG) self.PROG = '' self.nLines = 0 def progsave(self, folder, progname, ask_user = False, show_result = False): progname = progname + '.' + self.PROG_EXT if ask_user or not DirExists(folder): filesave = getSaveFile(folder, progname, 'Save program as...') if filesave is not None: filesave = filesave.name else: return else: filesave = folder + '/' + progname self.FILE_SAVED = filesave # save imports imports = '' for i in range(len(self.IMPORTS)): imports = imports + "IMPORT '%s'\n" % self.IMPORTS[i] self.PROG = self.PROG.replace("-- IMPORTS --\n", imports, 1) # save routines self.PROG = self.PROG.replace("-- ROUTINES --\n", self.ROUTINES, 1) fid = open(filesave, "w") fid.write(self.PROG) fid.close() print('SAVED: %s\n' % filesave) # tell RoboDK the path of the saved file self.PROG_FILES.append(filesave) # open file with default application if show_result: if type(show_result) is str: # Open file with provided application import subprocess p = subprocess.Popen([show_result, filesave]) elif type(show_result) is list: import subprocess p = subprocess.Popen(show_result + [filesave]) else: # open file with default application import os os.startfile(filesave) if len(self.LOG) > 0: mbox('Program generation LOG:\n\n' + self.LOG) def ProgSave(self, folder, progname, ask_user = False, show_result = False): if len(self.PROG_LIST) >= 1: if self.nLines > 0: self.PROG_LIST.append(self.PROG) self.PROG = '' self.nLines = 0 npages = len(self.PROG_LIST) progname_main = progname + "Main" mainprog = "PROGRAM %s\n" % progname_main for i in range(npages): mainprog += "IMPORT '%s'\n" % self.PROG_NAMES[i] mainprog += "CONST\nVAR\n" mainprog += "BEGIN\n" for i in range(npages): mainprog += " R_%s()\n" % self.PROG_NAMES[i] mainprog += "END %s\n" % progname_main self.PROG = mainprog self.progsave(folder, progname_main, ask_user, show_result) self.LOG = '' folder_user = getFileDir(self.FILE_SAVED) # progname_user = getFileName(self.FILE_SAVED) for i in range(npages): self.PROG = self.PROG_LIST[i] self.progsave(folder_user, self.PROG_NAMES[i], False, show_result) else: self.progsave(folder, progname, ask_user, show_result) def ProgSendRobot(self, robot_ip, remote_path, ftp_user, ftp_pass): """Send a program to the robot using the provided parameters. This method is executed right after ProgSave if we selected the option "Send Program to Robot". The connection parameters must be provided in the robot connection menu of RoboDK""" UploadFTP(self.PROG_FILES, robot_ip, remote_path, ftp_user, ftp_pass) def MoveJ(self, pose, joints, conf_RLF=None): """Add a joint movement""" #self.addline('MOVE JOINT TO ' + joints_2_str(joints))# MOVE JOINT TO: won't use absolute axis position self.addline('MOVE TO ' + self.joints_2_str(joints)) # MOVE TO: absolute axis position def new_move(self, pose1, pose2): if pose1 is None: return def Calculate_Time(Dist, Vmax, Amax): '''Calculate the time it takes to move a distance Dist at Amax acceleration and Vmax speed''' tacc = Vmax/Amax; Xacc = 0.5*Amax*tacc*tacc; if Dist <= 2*Xacc: # Vmax is not reached tacc = sqrt(Dist/Amax) Ttot = tacc*2 else: # Vmax is reached Xvmax = Dist - 2*Xacc Tvmax = Xvmax/Vmax Ttot = 2*tacc + Tvmax return Ttot add_material = self.NEW_E_LENGTH - self.LAST_E_LENGTH self.LAST_E_LENGTH = self.NEW_E_LENGTH if add_material > 0: distance_mm = norm(subs3(pose1.Pos(), pose2.Pos())) # calculate movement time in seconds time_s = Calculate_Time(distance_mm, self.SPEED_MMS, self.ACCEL_MMSS) # add material self.addline("$AOUT[5] := %.3f" % (add_material/time_s)) else: # DO not add material self.addline("$AOUT[5] := 0") def new_movec(self, pose1, pose2, pose3): return def MoveL(self, pose, joints, conf_RLF=None): """Add a linear movement""" pose = None # Filter sending the same movement twice if self.LAST_POSE is not None and pose is not None: # Skip adding a new movement if the new position is the same as the last one if distance(pose.Pos(), self.LAST_POSE.Pos()) < 0.001 and pose_angle_between(pose, self.LAST_POSE) < 0.01: return target = '' if pose is None: target = self.joints_2_str(joints) else: target = self.pose_2_str(pose,joints) #self.new_move(self.LAST_POSE, pose) #used for 3D printing if self.FLY_DIST > 0: self.addline('MOVEFLY LINEAR TO %s ADVANCE' % target) else: self.addline('MOVE LINEAR TO ' + target) self.LAST_POSE = pose def MoveC(self, pose1, joints1, pose2, joints2, conf_RLF_1=None, conf_RLF_2=None): """Add a circular movement""" #self.new_movec(self.LAST_POSE, pose1, pose2) #used for 3D printing if self.FLY_DIST > 0: self.addline('MOVEFLY CIRCULAR TO %s VIA %s ADVANCE' % (self.pose_2_str(pose2,joints2), self.pose_2_str(pose1,joints1))) else: self.addline('MOVE CIRCULAR TO %s VIA %s' % (self.pose_2_str(pose2,joints2), self.pose_2_str(pose1,joints1))) self.LAST_POSE = pose2 def setFrame(self, pose, frame_id=None, frame_name=None): """Change the robot reference frame""" self.addline('$UFRAME := ' + self.pose_2_str(pose)) def setTool(self, pose, tool_id=None, tool_name=None): """Change the robot TCP""" self.addline('$TOOL := ' + self.pose_2_str(pose)) def Pause(self, time_ms): """Pause the robot program""" if time_ms <= 0: self.addline('PAUSE') else: self.addline('DELAY %.0f' % (time_ms)) def setSpeed(self, speed_mms): """Changes the robot speed (in mm/s)""" self.SPEED_MMS = speed_mms self.addline('$SPD_OPT := SPD_LIN') self.addline('$LIN_SPD := %.3f' % (speed_mms*0.001)) def setAcceleration(self, accel_mmss): """Changes the robot acceleration (in mm/s2)""" self.ACCEL_MMSS = accel_mmss self.addlog('setAcceleration not defined') def setSpeedJoints(self, speed_degs): """Changes the robot joint speed (in deg/s)""" self.addline('$ROT_SPD := %.3f' % (speed_degs*pi/180.0)) def setAccelerationJoints(self, accel_degss): """Changes the robot joint acceleration (in deg/s2)""" self.addlog('setAccelerationJoints not defined') def setZoneData(self, zone_mm): """Changes the zone data approach (makes the movement more smooth)""" #self.addlog('setZoneData not defined (%.1f mm)' % zone_mm) self.FLY_DIST = zone_mm self.addline('$FLY_DIST := %.3f' % zone_mm) def setDO(self, io_var, io_value): """Sets a variable (output) to a given value""" if type(io_var) != str: # set default variable name if io_var is a number io_var = '$DOUT[%s]' % str(io_var) if type(io_value) != str: # set default variable value if io_value is a number if io_value > 0: io_value = 'ON' else: io_value = 'OFF' # at this point, io_var and io_value must be string values self.addline('%s := %s' % (io_var, io_value)) def waitDI(self, io_var, io_value, timeout_ms=-1): """Waits for an input io_var to attain a given value io_value. Optionally, a timeout can be provided.""" if type(io_var) != str: # set default variable name if io_var is a number io_var = '$DIN[%s]' % str(io_var) if type(io_value) != str: # set default variable value if io_value is a number if io_value > 0: io_value = 'ON' else: io_value = 'OFF' # at this point, io_var and io_value must be string values if timeout_ms < 0: #self.addline('WAIT FOR %s==%s' % (io_var, io_value)) self.addline('$TIMER[1] := 0') self.addline('REPEAT') self.addline(' DELAY 1') self.addline('UNTIL (%s = %s)' % (io_var, io_value)) else: self.addline('$TIMER[1] := 0') self.addline('REPEAT') self.addline(' DELAY 1') self.addline('UNTIL (%s = %s) OR ($TIMER[1] > %.1f)' % (io_var, io_value, timeout_ms)) self.addline('IF $TIMER[1] > %.1f THEN' % timeout_ms) self.addline('-- TIMED OUT! Important: This section must be updated accordingly') self.addline(' DELAY 2000') #self.addline(' PAUSE')#Important, this must be updated to perform a specific action self.addline('ENDIF') def RunCode(self, code, is_function_call = False): """Adds code or a function call""" if self.nProgs > 1 and not self.INCLUDE_SUB_PROGRAMS: return if is_function_call: if code.startswith("Extruder("): # if the program call is Extruder(123.56), we extract the number as a string and convert it to a number self.NEW_E_LENGTH = float(code[9:-1]) # it needs to retrieve the extruder length from the program call # Do not generate program call return code.replace(' ','_') bracket_id = code.find('(') import_prog = None if bracket_id < 0: # no brackets import_prog = code #code = code + '()' else: # brackets import_prog = code[:bracket_id] # Add import directive only if we have not added it before if not import_prog in self.IMPORTS: self.IMPORTS.append(import_prog) self.addline('R_' + code) else: self.addline(code) def RunMessage(self, message, iscomment = False): """Add a joint movement""" if iscomment: self.addline('-- ' + message) else: #self.addline('TYPE "' + message + '"') #-------- Option 1: Show message on the teach pendant: Important! Fails if there is no teach pendant #self.PROG_VARS.append('lun: INTEGER') #self.addline(MACRO_MESSAGE_TP % message) #-------- Option 2: Just comment the message self.addline('-- ' + message) # ------------------ private ---------------------- def addline(self, newline): """Add a program line""" if self.nProgs > 1 and not self.INCLUDE_SUB_PROGRAMS: return if not self.INCLUDE_SUB_PROGRAMS and self.nLines > self.MAX_LINES_X_PROG: self.nLines = 0 self.ProgFinish(self.PROG_NAME, True) self.ProgStart(self.PROG_NAME, True) if self.nProgs > 1: self.ROUTINES = self.ROUTINES + self.TAB + newline + '\n' else: self.PROG = self.PROG + self.TAB + newline + '\n' self.nLines = self.nLines + 1 def addlog(self, newline): """Add a log message""" if self.nProgs > 1 and not self.INCLUDE_SUB_PROGRAMS: return self.LOG = self.LOG + newline + '\n' # ------------------------------------------------- # ------------ For testing purposes --------------- def Pose(xyzrpw): [x,y,z,r,p,w] = xyzrpw a = r*math.pi/180 b = p*math.pi/180 c = w*math.pi/180 ca = math.cos(a) sa = math.sin(a) cb = math.cos(b) sb = math.sin(b) cc = math.cos(c) sc = math.sin(c) return Mat([[cb*ca, ca*sc*sb - cc*sa, sc*sa + cc*ca*sb, x],[cb*sa, cc*ca + sc*sb*sa, cc*sb*sa - ca*sc, y],[-sb, cb*sc, cc*cb, z],[0,0,0,1]]) def test_post(): """Test the post with a basic program""" robot = RobotPost('Comau_custom', 'Generic Comau robot') robot.ProgStart("Program") robot.RunMessage("Program generated by RoboDK", True) robot.setFrame(Pose([807.766544, -963.699898, 41.478944, 0, 0, 0])) robot.setTool(Pose([62.5, -108.253175, 100, -60, 90, 0])) robot.MoveJ(Pose([200, 200, 500, 180, 0, 180]), [-46.18419, -6.77518, -20.54925, 71.38674, 49.58727, -302.54752] ) robot.MoveL(Pose([200, 250, 348.734575, 180, 0, -150]), [-41.62707, -8.89064, -30.01809, 60.62329, 49.66749, -258.98418] ) robot.MoveL(Pose([200, 200, 262.132034, 180, 0, -150]), [-43.73892, -3.91728, -35.77935, 58.57566, 54.11615, -253.81122] ) robot.RunMessage("Setting air valve 1 on") robot.RunCode("TCP_On", True) robot.Pause(1000) robot.MoveL(Pose([200, 250, 348.734575, 180, 0, -150]), [-41.62707, -8.89064, -30.01809, 60.62329, 49.66749, -258.98418] ) robot.MoveL(Pose([250, 300, 278.023897, 180, 0, -150]), [-37.52588, -6.32628, -34.59693, 53.52525, 49.24426, -251.44677] ) robot.MoveL(Pose([250, 250, 191.421356, 180, 0, -150]), [-39.75778, -1.04537, -40.37883, 52.09118, 54.15317, -246.94403] ) robot.RunMessage("Setting air valve off") robot.RunCode("TCP_Off(55)", True) robot.Pause(1000) robot.MoveL(Pose([250, 300, 278.023897, 180, 0, -150]), [-37.52588, -6.32628, -34.59693, 53.52525, 49.24426, -251.44677] ) robot.MoveL(Pose([250, 200, 278.023897, 180, 0, -150]), [-41.85389, -1.95619, -34.89154, 57.43912, 52.34162, -253.73403] ) robot.MoveL(Pose([250, 150, 191.421356, 180, 0, -150]), [-43.82111, 3.29703, -40.29493, 56.02402, 56.61169, -249.23532] ) robot.ProgFinish("Program") # robot.ProgSave(".","Program",True) print(robot.PROG) if len(robot.LOG) > 0: mbox('Program generation LOG:\n\n' + robot.LOG) input("Press Enter to close...") if __name__ == "__main__": """Function to call when the module is executed by itself: test""" test_post()
41.164706
165
0.548565
SAGE_TP = '''-- Display message on the teach pendant: WIN_DEL ('menu:') -- popup window over window USR1 WIN_POPUP('POP1:', 'USR1:') -- open a lun on window POP1 OPEN FILE lun ('POP1:', 'rw') WRITE lun ('%s', NL) CLOSE FILE lun -- let user read the message DELAY 5000 -- Remove and delete window POP1 from user screen WIN_REMOVE('POP1:') WIN_DEL('POP1:') ------------------''' from robodk import * RATIO_EXTAX = [1,1,1,1,1,1] class RobotPost(object): PROG_EXT = 'pdl' MAX_LINES_X_PROG = 5000 INCLUDE_SUB_PROGRAMS = True ROBOT_POST = '' ROBOT_NAME = '' PROG_NAME = 'unknown' PROG_NAMES = [] PROG_FILES = [] PROG_LIST = [] PROG_VARS = [] SPEED_MMS = 1000 ACCEL_MMSS = 100 FLY_DIST = -1 IMPORTS = [] PROG = '' ROUTINES = '' nLines = 0 nProgs = 0 LOG = '' nAxes = 6 TAB = '' LAST_POSE = None LAST_E_LENGTH = 0 NEW_E_LENGTH = 0 def joints_2_str(self, joints): if joints is not None and len(joints) > 6: joints[6] = joints[6]*RATIO_EXTAX[0] return '{%s}' % (','.join(format(ji, ".5f") for ji in joints)) def pose_2_str(self, pose,joints=None,conf_RLF=None): [x,y,z,w,p,r] = Pose_2_Comau(pose) config = [] if conf_RLF is not None: if conf_RLF[0] > 0: config.append('S') if conf_RLF[1] > 0: config.append('E') if joints is not None: if len(joints) >= 5 and joints[4] < 0: config.append('W') if len(joints) >= 4: t1 = round((joints[3]+180) // 360) config.append('T1:%i' % t1) if len(joints) >= 6: t2 = round((joints[5]+180) // 360) config.append('T2:%i' % t2) t3 = round((joints[2]+180) // 360) config.append('T3:%i' % t3) pos_str = "POS(%.4f, %.4f, %.4f, %.4f, %.4f, %.4f, '%s')" % (x,y,z,w,p,r, ' '.join(config)) if joints is None or len(joints) <= 6: return pos_str else: self.addline('pxtn.POS := ' + pos_str) for i in range(6,len(joints)): self.addline('pxtn.AUX[%i] := %.5f' % (i-6+1, joints[i]*RATIO_EXTAX[i-6])) return 'pxtn' def __init__(self, robotpost=None, robotname=None, robot_axes = 6, **kwargs): self.ROBOT_POST = robotpost self.ROBOT_NAME = robotname self.PROG = '' self.LOG = '' self.nAxes = robot_axes for k,v in kwargs.items(): if k == 'lines_x_prog': self.MAX_LINES_X_PROG = v def ProgStart(self, progname, new_page = False): progname_i = progname if new_page: if self.INCLUDE_SUB_PROGRAMS: raise Exception("Multiple pages per program is not supported when adding routines in the main program") nPages = len(self.PROG_LIST) if nPages == 0: progname_i = progname else: progname_i = "%s%i" % (self.PROG_NAME, nPages) else: self.PROG_NAME = progname self.nProgs = self.nProgs + 1 self.PROG_NAMES = [] if self.nProgs > 1: if not self.INCLUDE_SUB_PROGRAMS: return else: if progname_i in self.IMPORTS: self.IMPORTS.remove(progname_i) self.addline('ROUTINE R_%s' % progname_i) self.addline('VAR') self.addline('BEGIN') self.TAB = ' ' return self.PROG_NAMES.append(progname_i) self.addline('PROGRAM %s' % progname_i) self.addline('-- IMPORTS --') self.addline('VAR') self.addline('ROUTINE R_%s EXPORTED FROM %s GLOBAL' % (progname_i, progname_i)) self.addline('') self.addline('-- ROUTINES --') self.addline('ROUTINE R_%s' % progname_i) self.addline('VAR') self.nAxes > 6: self.addline(' pxtn: XTNDPOS') self.addline('-- VARIABLES --') self.addline('BEGIN') self.TAB = ' ' self.addline('$ORNT_TYPE := RS_WORLD') self.addline('$MOVE_TYPE := JOINT') self.addline('$JNT_MTURN := TRUE') self.addline('$CNFG_CARE := TRUE') self.addline('$TURN_CARE := TRUE') self.addline('$SING_CARE := FALSE') self.addline('$TERM_TYPE := NOSETTLE') self.addline('$FLY_TYPE := FLY_CART') self.addline('$FLY_TRAJ := FLY_PASS') self.setZoneData(self.FLY_DIST) self.addline('$STRESS_PER:= 65') def ProgFinish(self, progname, new_page = False): variables = '' for line in self.PROG_VARS: variables = ' %s\n' % line self.PROG = self.PROG.replace('-- VARIABLES --\n', variables,1) self.PROG_VARS = [] if self.nProgs > 1 and not self.INCLUDE_SUB_PROGRAMS: return self.TAB = '' if self.nProgs <= 1: self.PROG = self.PROG + "END R_%s\n\n" % progname self.PROG = self.PROG + "BEGIN\n R_%s\nEND %s\n\n" % (progname, progname) else: self.ROUTINES = self.ROUTINES + "END R_%s\n\n" % progname if new_page: self.PROG_LIST.append(self.PROG) self.PROG = '' self.nLines = 0 def progsave(self, folder, progname, ask_user = False, show_result = False): progname = progname + '.' + self.PROG_EXT if ask_user or not DirExists(folder): filesave = getSaveFile(folder, progname, 'Save program as...') if filesave is not None: filesave = filesave.name else: return else: filesave = folder + '/' + progname self.FILE_SAVED = filesave imports = '' for i in range(len(self.IMPORTS)): imports = imports + "IMPORT '%s'\n" % self.IMPORTS[i] self.PROG = self.PROG.replace("-- IMPORTS --\n", imports, 1) self.PROG = self.PROG.replace("-- ROUTINES --\n", self.ROUTINES, 1) fid = open(filesave, "w") fid.write(self.PROG) fid.close() print('SAVED: %s\n' % filesave) self.PROG_FILES.append(filesave) if show_result: if type(show_result) is str: import subprocess p = subprocess.Popen([show_result, filesave]) elif type(show_result) is list: import subprocess p = subprocess.Popen(show_result + [filesave]) else: import os os.startfile(filesave) if len(self.LOG) > 0: mbox('Program generation LOG:\n\n' + self.LOG) def ProgSave(self, folder, progname, ask_user = False, show_result = False): if len(self.PROG_LIST) >= 1: if self.nLines > 0: self.PROG_LIST.append(self.PROG) self.PROG = '' self.nLines = 0 npages = len(self.PROG_LIST) progname_main = progname + "Main" mainprog = "PROGRAM %s\n" % progname_main for i in range(npages): mainprog += "IMPORT '%s'\n" % self.PROG_NAMES[i] mainprog += "CONST\nVAR\n" mainprog += "BEGIN\n" for i in range(npages): mainprog += " R_%s()\n" % self.PROG_NAMES[i] mainprog += "END %s\n" % progname_main self.PROG = mainprog self.progsave(folder, progname_main, ask_user, show_result) self.LOG = '' folder_user = getFileDir(self.FILE_SAVED) for i in range(npages): self.PROG = self.PROG_LIST[i] self.progsave(folder_user, self.PROG_NAMES[i], False, show_result) else: self.progsave(folder, progname, ask_user, show_result) def ProgSendRobot(self, robot_ip, remote_path, ftp_user, ftp_pass): UploadFTP(self.PROG_FILES, robot_ip, remote_path, ftp_user, ftp_pass) def MoveJ(self, pose, joints, conf_RLF=None): str(joints)) # MOVE TO: absolute axis position def new_move(self, pose1, pose2): if pose1 is None: return def Calculate_Time(Dist, Vmax, Amax): tacc = Vmax/Amax; Xacc = 0.5*Amax*tacc*tacc; if Dist <= 2*Xacc: # Vmax is not reached tacc = sqrt(Dist/Amax) Ttot = tacc*2 else: # Vmax is reached Xvmax = Dist - 2*Xacc Tvmax = Xvmax/Vmax Ttot = 2*tacc + Tvmax return Ttot add_material = self.NEW_E_LENGTH - self.LAST_E_LENGTH self.LAST_E_LENGTH = self.NEW_E_LENGTH if add_material > 0: distance_mm = norm(subs3(pose1.Pos(), pose2.Pos())) # calculate movement time in seconds time_s = Calculate_Time(distance_mm, self.SPEED_MMS, self.ACCEL_MMSS) # add material self.addline("$AOUT[5] := %.3f" % (add_material/time_s)) else: # DO not add material self.addline("$AOUT[5] := 0") def new_movec(self, pose1, pose2, pose3): return def MoveL(self, pose, joints, conf_RLF=None): pose = None # Filter sending the same movement twice if self.LAST_POSE is not None and pose is not None: # Skip adding a new movement if the new position is the same as the last one if distance(pose.Pos(), self.LAST_POSE.Pos()) < 0.001 and pose_angle_between(pose, self.LAST_POSE) < 0.01: return target = '' if pose is None: target = self.joints_2_str(joints) else: target = self.pose_2_str(pose,joints) #self.new_move(self.LAST_POSE, pose) #used for 3D printing if self.FLY_DIST > 0: self.addline('MOVEFLY LINEAR TO %s ADVANCE' % target) else: self.addline('MOVE LINEAR TO ' + target) self.LAST_POSE = pose def MoveC(self, pose1, joints1, pose2, joints2, conf_RLF_1=None, conf_RLF_2=None): #self.new_movec(self.LAST_POSE, pose1, pose2) #used for 3D printing if self.FLY_DIST > 0: self.addline('MOVEFLY CIRCULAR TO %s VIA %s ADVANCE' % (self.pose_2_str(pose2,joints2), self.pose_2_str(pose1,joints1))) else: self.addline('MOVE CIRCULAR TO %s VIA %s' % (self.pose_2_str(pose2,joints2), self.pose_2_str(pose1,joints1))) self.LAST_POSE = pose2 def setFrame(self, pose, frame_id=None, frame_name=None): self.addline('$UFRAME := ' + self.pose_2_str(pose)) def setTool(self, pose, tool_id=None, tool_name=None): self.addline('$TOOL := ' + self.pose_2_str(pose)) def Pause(self, time_ms): if time_ms <= 0: self.addline('PAUSE') else: self.addline('DELAY %.0f' % (time_ms)) def setSpeed(self, speed_mms): self.SPEED_MMS = speed_mms self.addline('$SPD_OPT := SPD_LIN') self.addline('$LIN_SPD := %.3f' % (speed_mms*0.001)) def setAcceleration(self, accel_mmss): self.ACCEL_MMSS = accel_mmss self.addlog('setAcceleration not defined') def setSpeedJoints(self, speed_degs): self.addline('$ROT_SPD := %.3f' % (speed_degs*pi/180.0)) def setAccelerationJoints(self, accel_degss): self.addlog('setAccelerationJoints not defined') def setZoneData(self, zone_mm): #self.addlog('setZoneData not defined (%.1f mm)' % zone_mm) self.FLY_DIST = zone_mm self.addline('$FLY_DIST := %.3f' % zone_mm) def setDO(self, io_var, io_value): if type(io_var) != str: # set default variable name if io_var is a number io_var = '$DOUT[%s]' % str(io_var) if type(io_value) != str: # set default variable value if io_value is a number if io_value > 0: io_value = 'ON' else: io_value = 'OFF' # at this point, io_var and io_value must be string values self.addline('%s := %s' % (io_var, io_value)) def waitDI(self, io_var, io_value, timeout_ms=-1): if type(io_var) != str: # set default variable name if io_var is a number io_var = '$DIN[%s]' % str(io_var) if type(io_value) != str: # set default variable value if io_value is a number if io_value > 0: io_value = 'ON' else: io_value = 'OFF' # at this point, io_var and io_value must be string values if timeout_ms < 0: #self.addline('WAIT FOR %s==%s' % (io_var, io_value)) self.addline('$TIMER[1] := 0') self.addline('REPEAT') self.addline(' DELAY 1') self.addline('UNTIL (%s = %s)' % (io_var, io_value)) else: self.addline('$TIMER[1] := 0') self.addline('REPEAT') self.addline(' DELAY 1') self.addline('UNTIL (%s = %s) OR ($TIMER[1] > %.1f)' % (io_var, io_value, timeout_ms)) self.addline('IF $TIMER[1] > %.1f THEN' % timeout_ms) self.addline('-- TIMED OUT! Important: This section must be updated accordingly') self.addline(' DELAY 2000') #self.addline(' PAUSE')#Important, this must be updated to perform a specific action self.addline('ENDIF') def RunCode(self, code, is_function_call = False): if self.nProgs > 1 and not self.INCLUDE_SUB_PROGRAMS: return if is_function_call: if code.startswith("Extruder("): # if the program call is Extruder(123.56), we extract the number as a string and convert it to a number self.NEW_E_LENGTH = float(code[9:-1]) # it needs to retrieve the extruder length from the program call # Do not generate program call return code.replace(' ','_') bracket_id = code.find('(') import_prog = None if bracket_id < 0: # no brackets import_prog = code #code = code + '()' else: # brackets import_prog = code[:bracket_id] # Add import directive only if we have not added it before if not import_prog in self.IMPORTS: self.IMPORTS.append(import_prog) self.addline('R_' + code) else: self.addline(code) def RunMessage(self, message, iscomment = False): if iscomment: self.addline('-- ' + message) else: #self.addline('TYPE "' + message + '"') #-------- Option 1: Show message on the teach pendant: Important! Fails if there is no teach pendant #self.PROG_VARS.append('lun: INTEGER') #self.addline(MACRO_MESSAGE_TP % message) #-------- Option 2: Just comment the message self.addline('-- ' + message) # ------------------ private ---------------------- def addline(self, newline): if self.nProgs > 1 and not self.INCLUDE_SUB_PROGRAMS: return if not self.INCLUDE_SUB_PROGRAMS and self.nLines > self.MAX_LINES_X_PROG: self.nLines = 0 self.ProgFinish(self.PROG_NAME, True) self.ProgStart(self.PROG_NAME, True) if self.nProgs > 1: self.ROUTINES = self.ROUTINES + self.TAB + newline + '\n' else: self.PROG = self.PROG + self.TAB + newline + '\n' self.nLines = self.nLines + 1 def addlog(self, newline): if self.nProgs > 1 and not self.INCLUDE_SUB_PROGRAMS: return self.LOG = self.LOG + newline + '\n' # ------------------------------------------------- # ------------ For testing purposes --------------- def Pose(xyzrpw): [x,y,z,r,p,w] = xyzrpw a = r*math.pi/180 b = p*math.pi/180 c = w*math.pi/180 ca = math.cos(a) sa = math.sin(a) cb = math.cos(b) sb = math.sin(b) cc = math.cos(c) sc = math.sin(c) return Mat([[cb*ca, ca*sc*sb - cc*sa, sc*sa + cc*ca*sb, x],[cb*sa, cc*ca + sc*sb*sa, cc*sb*sa - ca*sc, y],[-sb, cb*sc, cc*cb, z],[0,0,0,1]]) def test_post(): robot = RobotPost('Comau_custom', 'Generic Comau robot') robot.ProgStart("Program") robot.RunMessage("Program generated by RoboDK", True) robot.setFrame(Pose([807.766544, -963.699898, 41.478944, 0, 0, 0])) robot.setTool(Pose([62.5, -108.253175, 100, -60, 90, 0])) robot.MoveJ(Pose([200, 200, 500, 180, 0, 180]), [-46.18419, -6.77518, -20.54925, 71.38674, 49.58727, -302.54752] ) robot.MoveL(Pose([200, 250, 348.734575, 180, 0, -150]), [-41.62707, -8.89064, -30.01809, 60.62329, 49.66749, -258.98418] ) robot.MoveL(Pose([200, 200, 262.132034, 180, 0, -150]), [-43.73892, -3.91728, -35.77935, 58.57566, 54.11615, -253.81122] ) robot.RunMessage("Setting air valve 1 on") robot.RunCode("TCP_On", True) robot.Pause(1000) robot.MoveL(Pose([200, 250, 348.734575, 180, 0, -150]), [-41.62707, -8.89064, -30.01809, 60.62329, 49.66749, -258.98418] ) robot.MoveL(Pose([250, 300, 278.023897, 180, 0, -150]), [-37.52588, -6.32628, -34.59693, 53.52525, 49.24426, -251.44677] ) robot.MoveL(Pose([250, 250, 191.421356, 180, 0, -150]), [-39.75778, -1.04537, -40.37883, 52.09118, 54.15317, -246.94403] ) robot.RunMessage("Setting air valve off") robot.RunCode("TCP_Off(55)", True) robot.Pause(1000) robot.MoveL(Pose([250, 300, 278.023897, 180, 0, -150]), [-37.52588, -6.32628, -34.59693, 53.52525, 49.24426, -251.44677] ) robot.MoveL(Pose([250, 200, 278.023897, 180, 0, -150]), [-41.85389, -1.95619, -34.89154, 57.43912, 52.34162, -253.73403] ) robot.MoveL(Pose([250, 150, 191.421356, 180, 0, -150]), [-43.82111, 3.29703, -40.29493, 56.02402, 56.61169, -249.23532] ) robot.ProgFinish("Program") # robot.ProgSave(".","Program",True) print(robot.PROG) if len(robot.LOG) > 0: mbox('Program generation LOG:\n\n' + robot.LOG) input("Press Enter to close...") if __name__ == "__main__": test_post()
true
true
1c2ce77bb97a40c4ab8829fd4394cd5dbd6f7523
373
py
Python
core/migrations/0003_alter_address_options.py
Gandabh/E-commerce-Site
8bc4ca85c9cd6f3ed1435e5767aef4ab315df559
[ "MIT" ]
1
2022-01-01T21:46:48.000Z
2022-01-01T21:46:48.000Z
core/migrations/0003_alter_address_options.py
Gandabh/E-commerce-Site
8bc4ca85c9cd6f3ed1435e5767aef4ab315df559
[ "MIT" ]
null
null
null
core/migrations/0003_alter_address_options.py
Gandabh/E-commerce-Site
8bc4ca85c9cd6f3ed1435e5767aef4ab315df559
[ "MIT" ]
null
null
null
# Generated by Django 3.2.4 on 2021-08-20 15:53 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0002_address'), ] operations = [ migrations.AlterModelOptions( name='address', options={'verbose_name': 'Address', 'verbose_name_plural': 'Addresses'}, ), ]
20.722222
84
0.603217
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0002_address'), ] operations = [ migrations.AlterModelOptions( name='address', options={'verbose_name': 'Address', 'verbose_name_plural': 'Addresses'}, ), ]
true
true
1c2ce7b37f5d8879fdad3b05ee37439372f0f157
6,635
py
Python
lib/notetaker/days.py
Ghalko/noteTaker
f294dbc5fe0c9073837562e0466292d18fafc1ff
[ "MIT" ]
null
null
null
lib/notetaker/days.py
Ghalko/noteTaker
f294dbc5fe0c9073837562e0466292d18fafc1ff
[ "MIT" ]
null
null
null
lib/notetaker/days.py
Ghalko/noteTaker
f294dbc5fe0c9073837562e0466292d18fafc1ff
[ "MIT" ]
1
2019-09-07T05:31:15.000Z
2019-09-07T05:31:15.000Z
"""Creates a scrolling canvas in which days are separated into their own text boxes of varying sizes for easier date reading and fewer days loaded.""" from Tkinter import (Tk, Frame, Scrollbar, Canvas, Button, Text, WORD, BOTH, VERTICAL, END, Y, NW, RIGHT, LEFT, FALSE, TRUE) import notetaker.ncore as ncore import notetaker.utils as utils import datetime class VerticalScrolledFrame(Frame): """A pure Tkinter scrollable frame that actually works! * Use the 'interior' attribute to place widgets inside the scrollable frame * Construct and pack/place/grid normally * This frame only allows vertical scrolling http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame """ def __init__(self, parent, *args, **kw): Frame.__init__(self, parent, *args, **kw) # create a canvas object and a vertical scrollbar for scrolling it vscrollbar = Scrollbar(self, orient=VERTICAL) vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) vscrollbar.config(command=canvas.yview) # reset the view canvas.xview_moveto(0) canvas.yview_moveto(0) # create a frame inside the canvas which will be scrolled with it self.interior = interior = Frame(canvas) interior_id = canvas.create_window(0, 0, window=interior, anchor=NW) # track changes to the canvas and frame width and sync them, # also updating the scrollbar def _configure_interior(event=None): # update the scrollbars to match the size of the inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) canvas.config(scrollregion="0 0 %s %s" % size) if interior.winfo_reqwidth() != canvas.winfo_width(): # update the canvas's width to fit the inner frame canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event=None): if interior.winfo_reqwidth() != canvas.winfo_width(): # update the inner frame's width to fill the canvas canvas.itemconfigure(interior_id, width=canvas.winfo_width()) canvas.bind('<Configure>', _configure_canvas) class Days(object): def __init__(self, master=None, ncore=None, project=None, limit=2): self.master = master self.ncore = ncore self.project = project self.frame = None self.gui_fill() self.days = [] self.limit = limit limit = (limit+1) *-1 #Gets the previous two days and this one. list_ = sorted(self.ncore.get_all_dates(project))[limit:] if list_ == []: day = int(datetime.datetime.now().strftime("%Y%m%d")) self.append(day) for day in list_: self.append(day) #uses Days append self._repack() def gui_fill(self): """Creates the vertical scrolled frame""" self.frame = VerticalScrolledFrame(self.master) self.frame.pack() tempf = Frame(self.frame.interior) tempf.pack() Button(tempf, text="More", command=self._more).pack(side=LEFT) Button(tempf, text="Less", command=self._less).pack(side=RIGHT) def append(self, date): """Appends a new Day instance and repacks.""" self.days.append(Day(self, date)) self._repack() def get_current(self): """Returns current day at the end of the list.""" return self.days[-1] def _more(self, event=None): """Adds 3 more days to the beginning of the list.""" tlist = [] limit = (self.limit+4) *-1 oldlimit = (self.limit+1) * -1 self.limit += 3 list_ = sorted(self.ncore.get_all_dates(self.project))[limit:oldlimit] for day in self.days: day.gui_forget() for day in list_: tlist.append(Day(self, day)) self.days = tlist + self.days self._repack() def _less(self, event=None): if len(self.days) < 4: return for day in self.days: day.gui_forget() self.limit -= 3 self.days = self.days[3:] self._repack() def _repack(self): """Repacks the list of Day objects""" for day in self.days: day.gui_pack() self.days[-1].text.config(height=10) #For better entry. self.days[-1].text.yview(END) #maybe make these two statements #a decorator class Day(object): """Text displayed in text boxes.""" def __init__(self, parent=None, date=None): self.date = date self.parent = parent self.entry = 0 self.text = None self.gui_fill() def gui_fill(self): """Fills gui.""" self.text = Text(self.parent.frame.interior, height=10, width=77, wrap=WORD, bg='light blue', spacing1=5) lines = 0 for row in self.parent.ncore.print_project_day(self.parent.project, self.date): str_ = str(row[0]) + ' ' + str(row[1]) + ' ' + str(row[2]) + '\n' self.text.insert(END, str_) lines += utils.count_lines(str_) if lines < 10: self.text.config(height=lines+1) def gui_forget(self): """For pack forgetting""" self.text.pack_forget() def gui_pack(self): """For packing""" self.text.pack() def gui_refresh(self, event=None): """Reloads the day's text""" self.text.delete('1.0', END) for row in self.parent.ncore.print_project_day(self.parent.project, self.date): str_ = str(row[0]) + ' ' + str(row[1]) + ' ' + str(row[2]) + '\n' self.text.insert(END, str_) self.text.yview(END) class Test(Frame): """Basically just a class to be called if module is not imported.""" def __init__(self, master=None, ncore=None, project="Other", limit=2): self.frame = Frame.__init__(self, master) self.pack() Days(master=master, ncore=ncore, project=project, limit=limit) if __name__ == "__main__": PATH = "/home/bgorges/Tools/noteTaker" ROOT = Tk() NOTECORE = ncore.NoteCore(dbpath=PATH) APP = Test(master=ROOT, ncore=NOTECORE, project="Other", limit=2) APP.mainloop()
37.914286
79
0.593971
from Tkinter import (Tk, Frame, Scrollbar, Canvas, Button, Text, WORD, BOTH, VERTICAL, END, Y, NW, RIGHT, LEFT, FALSE, TRUE) import notetaker.ncore as ncore import notetaker.utils as utils import datetime class VerticalScrolledFrame(Frame): def __init__(self, parent, *args, **kw): Frame.__init__(self, parent, *args, **kw) vscrollbar = Scrollbar(self, orient=VERTICAL) vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) vscrollbar.config(command=canvas.yview) canvas.xview_moveto(0) canvas.yview_moveto(0) self.interior = interior = Frame(canvas) interior_id = canvas.create_window(0, 0, window=interior, anchor=NW) def _configure_interior(event=None): size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) canvas.config(scrollregion="0 0 %s %s" % size) if interior.winfo_reqwidth() != canvas.winfo_width(): canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event=None): if interior.winfo_reqwidth() != canvas.winfo_width(): # update the inner frame's width to fill the canvas canvas.itemconfigure(interior_id, width=canvas.winfo_width()) canvas.bind('<Configure>', _configure_canvas) class Days(object): def __init__(self, master=None, ncore=None, project=None, limit=2): self.master = master self.ncore = ncore self.project = project self.frame = None self.gui_fill() self.days = [] self.limit = limit limit = (limit+1) *-1 list_ = sorted(self.ncore.get_all_dates(project))[limit:] if list_ == []: day = int(datetime.datetime.now().strftime("%Y%m%d")) self.append(day) for day in list_: self.append(day) self._repack() def gui_fill(self): self.frame = VerticalScrolledFrame(self.master) self.frame.pack() tempf = Frame(self.frame.interior) tempf.pack() Button(tempf, text="More", command=self._more).pack(side=LEFT) Button(tempf, text="Less", command=self._less).pack(side=RIGHT) def append(self, date): self.days.append(Day(self, date)) self._repack() def get_current(self): return self.days[-1] def _more(self, event=None): tlist = [] limit = (self.limit+4) *-1 oldlimit = (self.limit+1) * -1 self.limit += 3 list_ = sorted(self.ncore.get_all_dates(self.project))[limit:oldlimit] for day in self.days: day.gui_forget() for day in list_: tlist.append(Day(self, day)) self.days = tlist + self.days self._repack() def _less(self, event=None): if len(self.days) < 4: return for day in self.days: day.gui_forget() self.limit -= 3 self.days = self.days[3:] self._repack() def _repack(self): for day in self.days: day.gui_pack() self.days[-1].text.config(height=10) self.days[-1].text.yview(END) class Day(object): def __init__(self, parent=None, date=None): self.date = date self.parent = parent self.entry = 0 self.text = None self.gui_fill() def gui_fill(self): self.text = Text(self.parent.frame.interior, height=10, width=77, wrap=WORD, bg='light blue', spacing1=5) lines = 0 for row in self.parent.ncore.print_project_day(self.parent.project, self.date): str_ = str(row[0]) + ' ' + str(row[1]) + ' ' + str(row[2]) + '\n' self.text.insert(END, str_) lines += utils.count_lines(str_) if lines < 10: self.text.config(height=lines+1) def gui_forget(self): self.text.pack_forget() def gui_pack(self): self.text.pack() def gui_refresh(self, event=None): self.text.delete('1.0', END) for row in self.parent.ncore.print_project_day(self.parent.project, self.date): str_ = str(row[0]) + ' ' + str(row[1]) + ' ' + str(row[2]) + '\n' self.text.insert(END, str_) self.text.yview(END) class Test(Frame): def __init__(self, master=None, ncore=None, project="Other", limit=2): self.frame = Frame.__init__(self, master) self.pack() Days(master=master, ncore=ncore, project=project, limit=limit) if __name__ == "__main__": PATH = "/home/bgorges/Tools/noteTaker" ROOT = Tk() NOTECORE = ncore.NoteCore(dbpath=PATH) APP = Test(master=ROOT, ncore=NOTECORE, project="Other", limit=2) APP.mainloop()
true
true
1c2ce7e1672b943bb64dd2c1a67898c7f6b659b8
3,629
py
Python
examples/colors.py
Doradx/luma.examples
d4641281fe18ffc5cfd6c307c79e7d7fefc36ffa
[ "MIT" ]
null
null
null
examples/colors.py
Doradx/luma.examples
d4641281fe18ffc5cfd6c307c79e7d7fefc36ffa
[ "MIT" ]
null
null
null
examples/colors.py
Doradx/luma.examples
d4641281fe18ffc5cfd6c307c79e7d7fefc36ffa
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-18 Richard Hull and contributors # See LICENSE.rst for details. # PYTHON_ARGCOMPLETE_OK """ Color rendering demo. """ import math import time import random import os.path from demo_opts import get_device from luma.core.render import canvas from PIL import Image def main(): img_path = os.path.abspath(os.path.join( os.path.dirname(__file__), 'images', 'balloon.png')) balloon = Image.open(img_path) \ .transform(device.size, Image.AFFINE, (1, 0, 0, 0, 1, 0), Image.BILINEAR) \ .convert(device.mode) while True: # Image display device.display(balloon) time.sleep(5) # Cycle through some primary colours for color in ["black", "white", "red", "orange", "yellow", "green", "blue", "indigo", "violet"]: with canvas(device, dither=True) as draw: draw.rectangle(device.bounding_box, fill=color) size = draw.textsize(color) left = (device.width - size[0]) // 2 top = (device.height - size[1]) // 2 right = left + size[0] bottom = top + size[1] draw.rectangle((left - 1, top, right, bottom), fill="black") draw.text((left, top), text=color, fill="white") time.sleep(3) # Rainbow w = 4 with canvas(device, dither=True) as draw: for i in range(device.width // w): r = int(math.sin(0.3 * i + 0) * 127) + 128 g = int(math.sin(0.3 * i + 2) * 127) + 128 b = int(math.sin(0.3 * i + 4) * 127) + 128 rgb = (r << 16) | (g << 8) | b draw.rectangle((i * w, 0, (i + 1) * w, device.height), fill=rgb) size = draw.textsize("rainbow") left = (device.width - size[0]) // 2 top = (device.height - size[1]) // 2 right = left + size[0] bottom = top + size[1] draw.rectangle((left - 1, top, right, bottom), fill="black") draw.text((left, top), text="rainbow", fill="white") time.sleep(5) # Gradient with canvas(device, dither=True) as draw: for y in range(device.height): for x in range(device.width): r = int(min(x / (device.width / 256), 255)) g = int(min(y / (device.height / 256), 255)) b = 0 draw.point((x, y), fill=(r, g, b)) size = draw.textsize("gradient") left = (device.width - size[0]) // 2 top = (device.height - size[1]) // 2 right = left + size[0] bottom = top + size[1] draw.rectangle((left - 1, top, right, bottom), fill="black") draw.text((left, top), text="gradient", fill="white") time.sleep(5) # Random blocks w = device.width // 12 h = device.height // 8 for _ in range(40): with canvas(device, dither=True) as draw: for x in range(12): for y in range(8): color = random.randint(0, 2 ** 24) left = x * w right = (x + 1) * w top = y * h bottom = (y + 1) * h draw.rectangle((left, top, right - 2, bottom - 2), fill=color) time.sleep(0.25) if __name__ == "__main__": try: device = get_device() main() except KeyboardInterrupt: pass
33.601852
104
0.488013
import math import time import random import os.path from demo_opts import get_device from luma.core.render import canvas from PIL import Image def main(): img_path = os.path.abspath(os.path.join( os.path.dirname(__file__), 'images', 'balloon.png')) balloon = Image.open(img_path) \ .transform(device.size, Image.AFFINE, (1, 0, 0, 0, 1, 0), Image.BILINEAR) \ .convert(device.mode) while True: device.display(balloon) time.sleep(5) for color in ["black", "white", "red", "orange", "yellow", "green", "blue", "indigo", "violet"]: with canvas(device, dither=True) as draw: draw.rectangle(device.bounding_box, fill=color) size = draw.textsize(color) left = (device.width - size[0]) // 2 top = (device.height - size[1]) // 2 right = left + size[0] bottom = top + size[1] draw.rectangle((left - 1, top, right, bottom), fill="black") draw.text((left, top), text=color, fill="white") time.sleep(3) w = 4 with canvas(device, dither=True) as draw: for i in range(device.width // w): r = int(math.sin(0.3 * i + 0) * 127) + 128 g = int(math.sin(0.3 * i + 2) * 127) + 128 b = int(math.sin(0.3 * i + 4) * 127) + 128 rgb = (r << 16) | (g << 8) | b draw.rectangle((i * w, 0, (i + 1) * w, device.height), fill=rgb) size = draw.textsize("rainbow") left = (device.width - size[0]) // 2 top = (device.height - size[1]) // 2 right = left + size[0] bottom = top + size[1] draw.rectangle((left - 1, top, right, bottom), fill="black") draw.text((left, top), text="rainbow", fill="white") time.sleep(5) with canvas(device, dither=True) as draw: for y in range(device.height): for x in range(device.width): r = int(min(x / (device.width / 256), 255)) g = int(min(y / (device.height / 256), 255)) b = 0 draw.point((x, y), fill=(r, g, b)) size = draw.textsize("gradient") left = (device.width - size[0]) // 2 top = (device.height - size[1]) // 2 right = left + size[0] bottom = top + size[1] draw.rectangle((left - 1, top, right, bottom), fill="black") draw.text((left, top), text="gradient", fill="white") time.sleep(5) w = device.width // 12 h = device.height // 8 for _ in range(40): with canvas(device, dither=True) as draw: for x in range(12): for y in range(8): color = random.randint(0, 2 ** 24) left = x * w right = (x + 1) * w top = y * h bottom = (y + 1) * h draw.rectangle((left, top, right - 2, bottom - 2), fill=color) time.sleep(0.25) if __name__ == "__main__": try: device = get_device() main() except KeyboardInterrupt: pass
true
true
1c2ce7feb96ee701287ac30e62477274a15affa0
58,647
py
Python
chia/wallet/wallet_state_manager.py
Hydrangea-Network/hydrangea-blockchain
d15662329958dbdaa9cbd99733ba729f0e74ce54
[ "Apache-2.0" ]
1
2022-03-15T06:41:49.000Z
2022-03-15T06:41:49.000Z
chia/wallet/wallet_state_manager.py
Hydrangea-Network/hydrangea-blockchain
d15662329958dbdaa9cbd99733ba729f0e74ce54
[ "Apache-2.0" ]
null
null
null
chia/wallet/wallet_state_manager.py
Hydrangea-Network/hydrangea-blockchain
d15662329958dbdaa9cbd99733ba729f0e74ce54
[ "Apache-2.0" ]
null
null
null
import asyncio import json import logging import multiprocessing import multiprocessing.context import time from collections import defaultdict from pathlib import Path from secrets import token_bytes from typing import Any, Callable, Dict, List, Optional, Set, Tuple import aiosqlite from blspy import G1Element, PrivateKey from chia.consensus.coinbase import pool_parent_id, farmer_parent_id, timelord_parent_id from chia.consensus.constants import ConsensusConstants from chia.pools.pool_puzzles import SINGLETON_LAUNCHER_HASH, solution_to_pool_state from chia.pools.pool_wallet import PoolWallet from chia.protocols import wallet_protocol from chia.protocols.wallet_protocol import PuzzleSolutionResponse, RespondPuzzleSolution, CoinState from chia.server.ws_connection import WSChiaConnection from chia.types.blockchain_format.coin import Coin from chia.types.blockchain_format.program import Program from chia.types.blockchain_format.sized_bytes import bytes32 from chia.types.coin_spend import CoinSpend from chia.types.full_block import FullBlock from chia.types.mempool_inclusion_status import MempoolInclusionStatus from chia.util.byte_types import hexstr_to_bytes from chia.util.config import process_config_start_method from chia.util.db_wrapper import DBWrapper from chia.util.errors import Err from chia.util.ints import uint32, uint64, uint128, uint8 from chia.util.db_synchronous import db_synchronous_on from chia.wallet.cat_wallet.cat_utils import match_cat_puzzle, construct_cat_puzzle from chia.wallet.cat_wallet.cat_wallet import CATWallet from chia.wallet.cat_wallet.cat_constants import DEFAULT_CATS from chia.wallet.derivation_record import DerivationRecord from chia.wallet.derive_keys import master_sk_to_wallet_sk, master_sk_to_wallet_sk_unhardened from chia.wallet.key_val_store import KeyValStore from chia.wallet.puzzles.cat_loader import CAT_MOD from chia.wallet.rl_wallet.rl_wallet import RLWallet from chia.wallet.settings.user_settings import UserSettings from chia.wallet.trade_manager import TradeManager from chia.wallet.transaction_record import TransactionRecord from chia.wallet.util.compute_hints import compute_coin_hints from chia.wallet.util.transaction_type import TransactionType from chia.wallet.util.wallet_sync_utils import last_change_height_cs from chia.wallet.util.wallet_types import WalletType from chia.wallet.wallet import Wallet from chia.wallet.wallet_action import WalletAction from chia.wallet.wallet_action_store import WalletActionStore from chia.wallet.wallet_blockchain import WalletBlockchain from chia.wallet.wallet_coin_record import WalletCoinRecord from chia.wallet.wallet_coin_store import WalletCoinStore from chia.wallet.wallet_info import WalletInfo from chia.wallet.wallet_interested_store import WalletInterestedStore from chia.wallet.wallet_pool_store import WalletPoolStore from chia.wallet.wallet_puzzle_store import WalletPuzzleStore from chia.wallet.wallet_sync_store import WalletSyncStore from chia.wallet.wallet_transaction_store import WalletTransactionStore from chia.wallet.wallet_user_store import WalletUserStore from chia.server.server import ChiaServer from chia.wallet.did_wallet.did_wallet import DIDWallet from chia.wallet.wallet_weight_proof_handler import WalletWeightProofHandler class WalletStateManager: constants: ConsensusConstants config: Dict tx_store: WalletTransactionStore puzzle_store: WalletPuzzleStore user_store: WalletUserStore action_store: WalletActionStore basic_store: KeyValStore start_index: int # Makes sure only one asyncio thread is changing the blockchain state at one time lock: asyncio.Lock log: logging.Logger # TODO Don't allow user to send tx until wallet is synced sync_mode: bool sync_target: uint32 genesis: FullBlock state_changed_callback: Optional[Callable] pending_tx_callback: Optional[Callable] puzzle_hash_created_callbacks: Dict = defaultdict(lambda *x: None) db_path: Path db_connection: aiosqlite.Connection db_wrapper: DBWrapper main_wallet: Wallet wallets: Dict[uint32, Any] private_key: PrivateKey trade_manager: TradeManager new_wallet: bool user_settings: UserSettings blockchain: WalletBlockchain coin_store: WalletCoinStore sync_store: WalletSyncStore finished_sync_up_to: uint32 interested_store: WalletInterestedStore multiprocessing_context: multiprocessing.context.BaseContext weight_proof_handler: WalletWeightProofHandler server: ChiaServer root_path: Path wallet_node: Any pool_store: WalletPoolStore default_cats: Dict[str, Any] @staticmethod async def create( private_key: PrivateKey, config: Dict, db_path: Path, constants: ConsensusConstants, server: ChiaServer, root_path: Path, wallet_node, name: str = None, ): self = WalletStateManager() self.new_wallet = False self.config = config self.constants = constants self.server = server self.root_path = root_path self.log = logging.getLogger(name if name else __name__) self.lock = asyncio.Lock() self.log.debug(f"Starting in db path: {db_path}") self.db_connection = await aiosqlite.connect(db_path) await self.db_connection.execute("pragma journal_mode=wal") await self.db_connection.execute( "pragma synchronous={}".format(db_synchronous_on(self.config.get("db_sync", "auto"), db_path)) ) self.db_wrapper = DBWrapper(self.db_connection) self.coin_store = await WalletCoinStore.create(self.db_wrapper) self.tx_store = await WalletTransactionStore.create(self.db_wrapper) self.puzzle_store = await WalletPuzzleStore.create(self.db_wrapper) self.user_store = await WalletUserStore.create(self.db_wrapper) self.action_store = await WalletActionStore.create(self.db_wrapper) self.basic_store = await KeyValStore.create(self.db_wrapper) self.trade_manager = await TradeManager.create(self, self.db_wrapper) self.user_settings = await UserSettings.create(self.basic_store) self.pool_store = await WalletPoolStore.create(self.db_wrapper) self.interested_store = await WalletInterestedStore.create(self.db_wrapper) self.default_cats = DEFAULT_CATS self.wallet_node = wallet_node self.sync_mode = False self.sync_target = uint32(0) self.finished_sync_up_to = uint32(0) multiprocessing_start_method = process_config_start_method(config=self.config, log=self.log) self.multiprocessing_context = multiprocessing.get_context(method=multiprocessing_start_method) self.weight_proof_handler = WalletWeightProofHandler( constants=self.constants, multiprocessing_context=self.multiprocessing_context, ) self.blockchain = await WalletBlockchain.create(self.basic_store, self.constants, self.weight_proof_handler) self.state_changed_callback = None self.pending_tx_callback = None self.db_path = db_path main_wallet_info = await self.user_store.get_wallet_by_id(1) assert main_wallet_info is not None self.private_key = private_key self.main_wallet = await Wallet.create(self, main_wallet_info) self.wallets = {main_wallet_info.id: self.main_wallet} wallet = None for wallet_info in await self.get_all_wallet_info_entries(): if wallet_info.type == WalletType.STANDARD_WALLET: if wallet_info.id == 1: continue wallet = await Wallet.create(self, wallet_info) elif wallet_info.type == WalletType.CAT: wallet = await CATWallet.create( self, self.main_wallet, wallet_info, ) elif wallet_info.type == WalletType.RATE_LIMITED: wallet = await RLWallet.create(self, wallet_info) elif wallet_info.type == WalletType.DISTRIBUTED_ID: wallet = await DIDWallet.create( self, self.main_wallet, wallet_info, ) elif wallet_info.type == WalletType.POOLING_WALLET: wallet = await PoolWallet.create_from_db( self, self.main_wallet, wallet_info, ) if wallet is not None: self.wallets[wallet_info.id] = wallet return self def get_derivation_index(self, pubkey: G1Element, max_depth: int = 1000) -> int: for i in range(0, max_depth): derived = self.get_public_key(uint32(i)) if derived == pubkey: return i derived = self.get_public_key_unhardened(uint32(i)) if derived == pubkey: return i return -1 def get_public_key(self, index: uint32) -> G1Element: return master_sk_to_wallet_sk(self.private_key, index).get_g1() def get_public_key_unhardened(self, index: uint32) -> G1Element: return master_sk_to_wallet_sk_unhardened(self.private_key, index).get_g1() async def get_keys(self, puzzle_hash: bytes32) -> Optional[Tuple[G1Element, PrivateKey]]: record = await self.puzzle_store.record_for_puzzle_hash(puzzle_hash) if record is None: raise ValueError(f"No key for this puzzlehash {puzzle_hash})") if record.hardened: private = master_sk_to_wallet_sk(self.private_key, record.index) pubkey = private.get_g1() return pubkey, private private = master_sk_to_wallet_sk_unhardened(self.private_key, record.index) pubkey = private.get_g1() return pubkey, private async def create_more_puzzle_hashes(self, from_zero: bool = False, in_transaction=False): """ For all wallets in the user store, generates the first few puzzle hashes so that we can restore the wallet from only the private keys. """ targets = list(self.wallets.keys()) unused: Optional[uint32] = await self.puzzle_store.get_unused_derivation_path() if unused is None: # This handles the case where the database has entries but they have all been used unused = await self.puzzle_store.get_last_derivation_path() if unused is None: # This handles the case where the database is empty unused = uint32(0) to_generate = self.config["initial_num_public_keys"] for wallet_id in targets: target_wallet = self.wallets[wallet_id] last: Optional[uint32] = await self.puzzle_store.get_last_derivation_path_for_wallet(wallet_id) start_index = 0 derivation_paths: List[DerivationRecord] = [] if last is not None: start_index = last + 1 # If the key was replaced (from_zero=True), we should generate the puzzle hashes for the new key if from_zero: start_index = 0 last_index = unused + to_generate if start_index >= last_index: self.log.debug(f"Nothing to create for for wallet_id: {wallet_id}, index: {start_index}") else: creating_msg = f"Creating puzzle hashes from {start_index} to {last_index} for wallet_id: {wallet_id}" self.log.info(f"Start: {creating_msg}") for index in range(start_index, last_index): if WalletType(target_wallet.type()) == WalletType.POOLING_WALLET: continue # Hardened pubkey: G1Element = self.get_public_key(uint32(index)) puzzle: Program = target_wallet.puzzle_for_pk(bytes(pubkey)) if puzzle is None: self.log.error(f"Unable to create puzzles with wallet {target_wallet}") break puzzlehash: bytes32 = puzzle.get_tree_hash() self.log.debug(f"Puzzle at index {index} wallet ID {wallet_id} puzzle hash {puzzlehash.hex()}") derivation_paths.append( DerivationRecord( uint32(index), puzzlehash, pubkey, target_wallet.type(), uint32(target_wallet.id()), True ) ) # Unhardened pubkey_unhardened: G1Element = self.get_public_key_unhardened(uint32(index)) puzzle_unhardened: Program = target_wallet.puzzle_for_pk(bytes(pubkey_unhardened)) if puzzle_unhardened is None: self.log.error(f"Unable to create puzzles with wallet {target_wallet}") break puzzlehash_unhardened: bytes32 = puzzle_unhardened.get_tree_hash() self.log.debug( f"Puzzle at index {index} wallet ID {wallet_id} puzzle hash {puzzlehash_unhardened.hex()}" ) derivation_paths.append( DerivationRecord( uint32(index), puzzlehash_unhardened, pubkey_unhardened, target_wallet.type(), uint32(target_wallet.id()), False, ) ) self.log.info(f"Done: {creating_msg}") await self.puzzle_store.add_derivation_paths(derivation_paths, in_transaction) await self.add_interested_puzzle_hashes( [record.puzzle_hash for record in derivation_paths], [record.wallet_id for record in derivation_paths], in_transaction, ) if unused > 0: await self.puzzle_store.set_used_up_to(uint32(unused - 1), in_transaction) async def update_wallet_puzzle_hashes(self, wallet_id): derivation_paths: List[DerivationRecord] = [] target_wallet = self.wallets[wallet_id] last: Optional[uint32] = await self.puzzle_store.get_last_derivation_path_for_wallet(wallet_id) unused: Optional[uint32] = await self.puzzle_store.get_unused_derivation_path() if unused is None: # This handles the case where the database has entries but they have all been used unused = await self.puzzle_store.get_last_derivation_path() if unused is None: # This handles the case where the database is empty unused = uint32(0) for index in range(unused, last): # Since DID are not released yet we can assume they are only using unhardened keys derivation pubkey: G1Element = self.get_public_key_unhardened(uint32(index)) puzzle: Program = target_wallet.puzzle_for_pk(bytes(pubkey)) puzzlehash: bytes32 = puzzle.get_tree_hash() self.log.info(f"Generating public key at index {index} puzzle hash {puzzlehash.hex()}") derivation_paths.append( DerivationRecord( uint32(index), puzzlehash, pubkey, target_wallet.wallet_info.type, uint32(target_wallet.wallet_info.id), False, ) ) await self.puzzle_store.add_derivation_paths(derivation_paths) async def get_unused_derivation_record( self, wallet_id: uint32, in_transaction=False, hardened=False ) -> DerivationRecord: """ Creates a puzzle hash for the given wallet, and then makes more puzzle hashes for every wallet to ensure we always have more in the database. Never reusue the same public key more than once (for privacy). """ async with self.puzzle_store.lock: # If we have no unused public keys, we will create new ones unused: Optional[uint32] = await self.puzzle_store.get_unused_derivation_path() if unused is None: await self.create_more_puzzle_hashes() # Now we must have unused public keys unused = await self.puzzle_store.get_unused_derivation_path() assert unused is not None record: Optional[DerivationRecord] = await self.puzzle_store.get_derivation_record( unused, wallet_id, hardened ) assert record is not None # Set this key to used so we never use it again await self.puzzle_store.set_used_up_to(record.index, in_transaction=in_transaction) # Create more puzzle hashes / keys await self.create_more_puzzle_hashes(in_transaction=in_transaction) return record async def get_current_derivation_record_for_wallet(self, wallet_id: uint32) -> Optional[DerivationRecord]: async with self.puzzle_store.lock: # If we have no unused public keys, we will create new ones current: Optional[DerivationRecord] = await self.puzzle_store.get_current_derivation_record_for_wallet( wallet_id ) return current def set_callback(self, callback: Callable): """ Callback to be called when the state of the wallet changes. """ self.state_changed_callback = callback def set_pending_callback(self, callback: Callable): """ Callback to be called when new pending transaction enters the store """ self.pending_tx_callback = callback def set_coin_with_puzzlehash_created_callback(self, puzzlehash: bytes32, callback: Callable): """ Callback to be called when new coin is seen with specified puzzlehash """ self.puzzle_hash_created_callbacks[puzzlehash] = callback async def puzzle_hash_created(self, coin: Coin): callback = self.puzzle_hash_created_callbacks[coin.puzzle_hash] if callback is None: return None await callback(coin) def state_changed(self, state: str, wallet_id: int = None, data_object=None): """ Calls the callback if it's present. """ if data_object is None: data_object = {} if self.state_changed_callback is None: return None self.state_changed_callback(state, wallet_id, data_object) def tx_pending_changed(self) -> None: """ Notifies the wallet node that there's new tx pending """ if self.pending_tx_callback is None: return None self.pending_tx_callback() async def synced(self): latest = await self.blockchain.get_peak_block() if latest is None: return False if latest.height - await self.blockchain.get_finished_sync_up_to() > 1: return False latest_timestamp = self.blockchain.get_latest_timestamp() if latest_timestamp > int(time.time()) - 10 * 60: return True return False def set_sync_mode(self, mode: bool, sync_height: uint32 = uint32(0)): """ Sets the sync mode. This changes the behavior of the wallet node. """ self.sync_mode = mode self.sync_target = sync_height self.state_changed("sync_changed") async def get_confirmed_spendable_balance_for_wallet(self, wallet_id: int, unspent_records=None) -> uint128: """ Returns the balance amount of all coins that are spendable. """ spendable: Set[WalletCoinRecord] = await self.get_spendable_coins_for_wallet(wallet_id, unspent_records) spendable_amount: uint128 = uint128(0) for record in spendable: spendable_amount = uint128(spendable_amount + record.coin.amount) return spendable_amount async def does_coin_belong_to_wallet(self, coin: Coin, wallet_id: int) -> bool: """ Returns true if we have the key for this coin. """ info = await self.puzzle_store.wallet_info_for_puzzle_hash(coin.puzzle_hash) if info is None: return False coin_wallet_id, wallet_type = info if wallet_id == coin_wallet_id: return True return False async def get_confirmed_balance_for_wallet( self, wallet_id: int, unspent_coin_records: Optional[Set[WalletCoinRecord]] = None, ) -> uint128: """ Returns the confirmed balance, including coinbase rewards that are not spendable. """ # lock only if unspent_coin_records is None if unspent_coin_records is None: unspent_coin_records = await self.coin_store.get_unspent_coins_for_wallet(wallet_id) return uint128(sum(cr.coin.amount for cr in unspent_coin_records)) async def get_unconfirmed_balance( self, wallet_id: int, unspent_coin_records: Optional[Set[WalletCoinRecord]] = None ) -> uint128: """ Returns the balance, including coinbase rewards that are not spendable, and unconfirmed transactions. """ # This API should change so that get_balance_from_coin_records is called for Set[WalletCoinRecord] # and this method is called only for the unspent_coin_records==None case. if unspent_coin_records is None: unspent_coin_records = await self.coin_store.get_unspent_coins_for_wallet(wallet_id) unconfirmed_tx: List[TransactionRecord] = await self.tx_store.get_unconfirmed_for_wallet(wallet_id) all_unspent_coins: Set[Coin] = {cr.coin for cr in unspent_coin_records} for record in unconfirmed_tx: for addition in record.additions: # This change or a self transaction if await self.does_coin_belong_to_wallet(addition, wallet_id): all_unspent_coins.add(addition) for removal in record.removals: if await self.does_coin_belong_to_wallet(removal, wallet_id) and removal in all_unspent_coins: all_unspent_coins.remove(removal) return uint128(sum(coin.amount for coin in all_unspent_coins)) async def unconfirmed_removals_for_wallet(self, wallet_id: int) -> Dict[bytes32, Coin]: """ Returns new removals transactions that have not been confirmed yet. """ removals: Dict[bytes32, Coin] = {} unconfirmed_tx = await self.tx_store.get_unconfirmed_for_wallet(wallet_id) for record in unconfirmed_tx: for coin in record.removals: removals[coin.name()] = coin return removals async def fetch_parent_and_check_for_cat( self, peer: WSChiaConnection, coin_state: CoinState, fork_height: Optional[uint32] ) -> Tuple[Optional[uint32], Optional[WalletType]]: if self.is_pool_reward(coin_state.created_height, coin_state.coin.parent_coin_info) or self.is_farmer_reward( coin_state.created_height, coin_state.coin.parent_coin_info ): return None, None response: List[CoinState] = await self.wallet_node.get_coin_state( [coin_state.coin.parent_coin_info], fork_height, peer ) if len(response) == 0: self.log.warning(f"Could not find a parent coin with ID: {coin_state.coin.parent_coin_info}") return None, None parent_coin_state = response[0] assert parent_coin_state.spent_height == coin_state.created_height wallet_id = None wallet_type = None cs: Optional[CoinSpend] = await self.wallet_node.fetch_puzzle_solution( peer, parent_coin_state.spent_height, parent_coin_state.coin ) if cs is None: return None, None matched, curried_args = match_cat_puzzle(Program.from_bytes(bytes(cs.puzzle_reveal))) if matched: mod_hash, tail_hash, inner_puzzle = curried_args inner_puzzle_hash = inner_puzzle.get_tree_hash() self.log.info( f"parent: {parent_coin_state.coin.name()} inner_puzzle_hash for parent is {inner_puzzle_hash}" ) hint_list = compute_coin_hints(cs) derivation_record = None for hint in hint_list: derivation_record = await self.puzzle_store.get_derivation_record_for_puzzle_hash(bytes32(hint)) if derivation_record is not None: break if derivation_record is None: self.log.info(f"Received state for the coin that doesn't belong to us {coin_state}") else: our_inner_puzzle: Program = self.main_wallet.puzzle_for_pk(bytes(derivation_record.pubkey)) asset_id: bytes32 = bytes32(bytes(tail_hash)[1:]) cat_puzzle = construct_cat_puzzle(CAT_MOD, asset_id, our_inner_puzzle) if cat_puzzle.get_tree_hash() != coin_state.coin.puzzle_hash: return None, None if bytes(tail_hash).hex()[2:] in self.default_cats or self.config.get( "automatically_add_unknown_cats", False ): cat_wallet = await CATWallet.create_wallet_for_cat( self, self.main_wallet, bytes(tail_hash).hex()[2:], in_transaction=True ) wallet_id = cat_wallet.id() wallet_type = WalletType(cat_wallet.type()) self.state_changed("wallet_created") else: # Found unacknowledged CAT, save it in the database. await self.interested_store.add_unacknowledged_token( asset_id, CATWallet.default_wallet_name_for_unknown_cat(asset_id.hex()), parent_coin_state.spent_height, parent_coin_state.coin.puzzle_hash, ) self.state_changed("added_stray_cat") return wallet_id, wallet_type async def new_coin_state( self, coin_states: List[CoinState], peer: WSChiaConnection, fork_height: Optional[uint32] ) -> None: # TODO: add comment about what this method does # Input states should already be sorted by cs_height, with reorgs at the beginning curr_h = -1 for c_state in coin_states: last_change_height = last_change_height_cs(c_state) if last_change_height < curr_h: raise ValueError("Input coin_states is not sorted properly") curr_h = last_change_height all_txs_per_wallet: Dict[int, List[TransactionRecord]] = {} trade_removals = await self.trade_manager.get_coins_of_interest() all_unconfirmed: List[TransactionRecord] = await self.tx_store.get_all_unconfirmed() trade_coin_removed: List[CoinState] = [] for coin_state_idx, coin_state in enumerate(coin_states): wallet_info: Optional[Tuple[uint32, WalletType]] = await self.get_wallet_id_for_puzzle_hash( coin_state.coin.puzzle_hash ) local_record: Optional[WalletCoinRecord] = await self.coin_store.get_coin_record(coin_state.coin.name()) self.log.debug(f"{coin_state.coin.name()}: {coin_state}") # If we already have this coin, and it was spent and confirmed at the same heights, then we return (done) if local_record is not None: local_spent = None if local_record.spent_block_height != 0: local_spent = local_record.spent_block_height if ( local_spent == coin_state.spent_height and local_record.confirmed_block_height == coin_state.created_height ): continue wallet_id: Optional[uint32] = None wallet_type: Optional[WalletType] = None if wallet_info is not None: wallet_id, wallet_type = wallet_info elif local_record is not None: wallet_id = uint32(local_record.wallet_id) wallet_type = local_record.wallet_type elif coin_state.created_height is not None: wallet_id, wallet_type = await self.fetch_parent_and_check_for_cat(peer, coin_state, fork_height) if wallet_id is None or wallet_type is None: self.log.info(f"No wallet for coin state: {coin_state}") continue if wallet_id in all_txs_per_wallet: all_txs = all_txs_per_wallet[wallet_id] else: all_txs = await self.tx_store.get_all_transactions_for_wallet(wallet_id) all_txs_per_wallet[wallet_id] = all_txs all_outgoing = [tx for tx in all_txs if "OUTGOING" in TransactionType(tx.type).name] derivation_index = await self.puzzle_store.index_for_puzzle_hash(coin_state.coin.puzzle_hash) if derivation_index is not None: await self.puzzle_store.set_used_up_to(derivation_index, True) if coin_state.created_height is None: # TODO implements this coin got reorged # TODO: we need to potentially roll back the pool wallet here pass elif coin_state.created_height is not None and coin_state.spent_height is None: await self.coin_added(coin_state.coin, coin_state.created_height, all_txs, wallet_id, wallet_type) elif coin_state.created_height is not None and coin_state.spent_height is not None: self.log.info(f"Coin Removed: {coin_state}") record = await self.coin_store.get_coin_record(coin_state.coin.name()) if coin_state.coin.name() in trade_removals: trade_coin_removed.append(coin_state) children: Optional[List[CoinState]] = None if record is None: timelord_reward = False farmer_reward = False pool_reward = False tx_type: int if self.is_farmer_reward(coin_state.created_height, coin_state.coin.parent_coin_info): farmer_reward = True tx_type = TransactionType.FEE_REWARD.value elif self.is_pool_reward(coin_state.created_height, coin_state.coin.parent_coin_info): pool_reward = True tx_type = TransactionType.COINBASE_REWARD.value else: tx_type = TransactionType.INCOMING_TX.value record = WalletCoinRecord( coin_state.coin, coin_state.created_height, coin_state.spent_height, True, farmer_reward or pool_reward, wallet_type, wallet_id, ) await self.coin_store.add_coin_record(record) # Coin first received coin_record: Optional[WalletCoinRecord] = await self.coin_store.get_coin_record( coin_state.coin.parent_coin_info ) if coin_record is not None and wallet_type.value == coin_record.wallet_type: change = True else: change = False if not change: created_timestamp = await self.wallet_node.get_timestamp_for_height(coin_state.created_height) tx_record = TransactionRecord( confirmed_at_height=coin_state.created_height, created_at_time=uint64(created_timestamp), to_puzzle_hash=(await self.convert_puzzle_hash(wallet_id, coin_state.coin.puzzle_hash)), amount=uint64(coin_state.coin.amount), fee_amount=uint64(0), confirmed=True, sent=uint32(0), spend_bundle=None, additions=[coin_state.coin], removals=[], wallet_id=wallet_id, sent_to=[], trade_id=None, type=uint32(tx_type), name=bytes32(token_bytes()), memos=[], ) await self.tx_store.add_transaction_record(tx_record, True) children = await self.wallet_node.fetch_children(peer, coin_state.coin.name(), fork_height) assert children is not None additions = [state.coin for state in children] if len(children) > 0: fee = 0 to_puzzle_hash = None # Find coin that doesn't belong to us amount = 0 for coin in additions: derivation_record = await self.puzzle_store.get_derivation_record_for_puzzle_hash( coin.puzzle_hash ) if derivation_record is None: to_puzzle_hash = coin.puzzle_hash amount += coin.amount if to_puzzle_hash is None: to_puzzle_hash = additions[0].puzzle_hash spent_timestamp = await self.wallet_node.get_timestamp_for_height(coin_state.spent_height) # Reorg rollback adds reorged transactions so it's possible there is tx_record already # Even though we are just adding coin record to the db (after reorg) tx_records: List[TransactionRecord] = [] for out_tx_record in all_outgoing: for rem_coin in out_tx_record.removals: if rem_coin.name() == coin_state.coin.name(): tx_records.append(out_tx_record) if len(tx_records) > 0: for tx_record in tx_records: await self.tx_store.set_confirmed(tx_record.name, coin_state.spent_height) else: tx_record = TransactionRecord( confirmed_at_height=coin_state.spent_height, created_at_time=uint64(spent_timestamp), to_puzzle_hash=(await self.convert_puzzle_hash(wallet_id, to_puzzle_hash)), amount=uint64(int(amount)), fee_amount=uint64(fee), confirmed=True, sent=uint32(0), spend_bundle=None, additions=additions, removals=[coin_state.coin], wallet_id=wallet_id, sent_to=[], trade_id=None, type=uint32(TransactionType.OUTGOING_TX.value), name=bytes32(token_bytes()), memos=[], ) await self.tx_store.add_transaction_record(tx_record, True) else: await self.coin_store.set_spent(coin_state.coin.name(), coin_state.spent_height) rem_tx_records: List[TransactionRecord] = [] for out_tx_record in all_outgoing: for rem_coin in out_tx_record.removals: if rem_coin.name() == coin_state.coin.name(): rem_tx_records.append(out_tx_record) for tx_record in rem_tx_records: await self.tx_store.set_confirmed(tx_record.name, coin_state.spent_height) for unconfirmed_record in all_unconfirmed: for rem_coin in unconfirmed_record.removals: if rem_coin.name() == coin_state.coin.name(): self.log.info(f"Setting tx_id: {unconfirmed_record.name} to confirmed") await self.tx_store.set_confirmed(unconfirmed_record.name, coin_state.spent_height) if record.wallet_type == WalletType.POOLING_WALLET: if coin_state.spent_height is not None and coin_state.coin.amount == uint64(1): wallet = self.wallets[uint32(record.wallet_id)] curr_coin_state: CoinState = coin_state while curr_coin_state.spent_height is not None: cs: CoinSpend = await self.wallet_node.fetch_puzzle_solution( peer, curr_coin_state.spent_height, curr_coin_state.coin ) success = await wallet.apply_state_transition(cs, curr_coin_state.spent_height) if not success: break new_singleton_coin: Optional[Coin] = wallet.get_next_interesting_coin(cs) if new_singleton_coin is None: # No more singleton (maybe destroyed?) break await self.coin_added( new_singleton_coin, coin_state.spent_height, [], uint32(record.wallet_id), record.wallet_type, ) await self.coin_store.set_spent(curr_coin_state.coin.name(), curr_coin_state.spent_height) await self.add_interested_coin_ids([new_singleton_coin.name()], True) new_coin_state: List[CoinState] = await self.wallet_node.get_coin_state( [new_singleton_coin.name()], fork_height, peer ) assert len(new_coin_state) == 1 curr_coin_state = new_coin_state[0] # Check if a child is a singleton launcher if children is None: children = await self.wallet_node.fetch_children(peer, coin_state.coin.name(), fork_height) assert children is not None for child in children: if child.coin.puzzle_hash != SINGLETON_LAUNCHER_HASH: continue if await self.have_a_pool_wallet_with_launched_id(child.coin.name()): continue if child.spent_height is None: # TODO handle spending launcher later block continue launcher_spend: Optional[CoinSpend] = await self.wallet_node.fetch_puzzle_solution( peer, coin_state.spent_height, child.coin ) if launcher_spend is None: continue try: pool_state = solution_to_pool_state(launcher_spend) except Exception as e: self.log.debug(f"Not a pool wallet launcher {e}") continue # solution_to_pool_state may return None but this may not be an error if pool_state is None: self.log.debug("solution_to_pool_state returned None, ignore and continue") continue assert child.spent_height is not None pool_wallet = await PoolWallet.create( self, self.main_wallet, child.coin.name(), [launcher_spend], child.spent_height, in_transaction=True, name="pool_wallet", ) launcher_spend_additions = launcher_spend.additions() assert len(launcher_spend_additions) == 1 coin_added = launcher_spend_additions[0] await self.coin_added( coin_added, coin_state.spent_height, [], pool_wallet.id(), WalletType(pool_wallet.type()) ) await self.add_interested_coin_ids([coin_added.name()], True) else: raise RuntimeError("All cases already handled") # Logic error, all cases handled for coin_state_removed in trade_coin_removed: await self.trade_manager.coins_of_interest_farmed(coin_state_removed, fork_height) async def have_a_pool_wallet_with_launched_id(self, launcher_id: bytes32) -> bool: for wallet_id, wallet in self.wallets.items(): if ( wallet.type() == WalletType.POOLING_WALLET and (await wallet.get_current_state()).launcher_id == launcher_id ): self.log.warning("Already have, not recreating") return True return False def is_pool_reward(self, created_height, parent_id): for i in range(0, 30): try_height = created_height - i if try_height < 0: break calculated = pool_parent_id(try_height, self.constants.GENESIS_CHALLENGE) if calculated == parent_id: return True return False def is_farmer_reward(self, created_height, parent_id): for i in range(0, 30): try_height = created_height - i if try_height < 0: break calculated = farmer_parent_id(try_height, self.constants.GENESIS_CHALLENGE) if calculated == parent_id: return True return False def is_timelord_reward(self, created_height, parent_id): for i in range(0, 30): try_height = created_height - i if try_height < 0: break calculated = timelord_parent_id(try_height, self.constants.GENESIS_CHALLENGE) if calculated == parent_id: return True return False async def get_wallet_id_for_puzzle_hash(self, puzzle_hash: bytes32) -> Optional[Tuple[uint32, WalletType]]: info = await self.puzzle_store.wallet_info_for_puzzle_hash(puzzle_hash) if info is not None: wallet_id, wallet_type = info return uint32(wallet_id), wallet_type interested_wallet_id = await self.interested_store.get_interested_puzzle_hash_wallet_id(puzzle_hash=puzzle_hash) if interested_wallet_id is not None: wallet_id = uint32(interested_wallet_id) if wallet_id not in self.wallets.keys(): self.log.warning(f"Do not have wallet {wallet_id} for puzzle_hash {puzzle_hash}") return None wallet_type = WalletType(self.wallets[uint32(wallet_id)].type()) return uint32(wallet_id), wallet_type return None async def coin_added( self, coin: Coin, height: uint32, all_outgoing_transaction_records: List[TransactionRecord], wallet_id: uint32, wallet_type: WalletType, ) -> Optional[WalletCoinRecord]: """ Adding coin to DB, return wallet coin record if it get's added """ existing: Optional[WalletCoinRecord] = await self.coin_store.get_coin_record(coin.name()) if existing is not None: return None self.log.info(f"Adding coin: {coin} at {height} wallet_id:{wallet_id}") farmer_reward = False pool_reward = False if self.is_farmer_reward(height, coin.parent_coin_info): farmer_reward = True elif self.is_pool_reward(height, coin.parent_coin_info): pool_reward = True farm_reward = False coin_record: Optional[WalletCoinRecord] = await self.coin_store.get_coin_record(coin.parent_coin_info) if coin_record is not None and wallet_type.value == coin_record.wallet_type: change = True else: change = False if farmer_reward or pool_reward: farm_reward = True if pool_reward: tx_type: int = TransactionType.COINBASE_REWARD.value else: tx_type = TransactionType.FEE_REWARD.value timestamp = await self.wallet_node.get_timestamp_for_height(height) tx_record = TransactionRecord( confirmed_at_height=uint32(height), created_at_time=timestamp, to_puzzle_hash=(await self.convert_puzzle_hash(wallet_id, coin.puzzle_hash)), amount=coin.amount, fee_amount=uint64(0), confirmed=True, sent=uint32(0), spend_bundle=None, additions=[coin], removals=[], wallet_id=wallet_id, sent_to=[], trade_id=None, type=uint32(tx_type), name=coin.name(), memos=[], ) await self.tx_store.add_transaction_record(tx_record, True) else: records: List[TransactionRecord] = [] for record in all_outgoing_transaction_records: for add_coin in record.additions: if add_coin.name() == coin.name(): records.append(record) if len(records) > 0: for record in records: if record.confirmed is False: await self.tx_store.set_confirmed(record.name, height) elif not change: timestamp = await self.wallet_node.get_timestamp_for_height(height) tx_record = TransactionRecord( confirmed_at_height=uint32(height), created_at_time=timestamp, to_puzzle_hash=(await self.convert_puzzle_hash(wallet_id, coin.puzzle_hash)), amount=coin.amount, fee_amount=uint64(0), confirmed=True, sent=uint32(0), spend_bundle=None, additions=[coin], removals=[], wallet_id=wallet_id, sent_to=[], trade_id=None, type=uint32(TransactionType.INCOMING_TX.value), name=coin.name(), memos=[], ) if coin.amount > 0: await self.tx_store.add_transaction_record(tx_record, True) coin_record_1: WalletCoinRecord = WalletCoinRecord( coin, height, uint32(0), False, farm_reward, wallet_type, wallet_id ) await self.coin_store.add_coin_record(coin_record_1) if wallet_type == WalletType.CAT or wallet_type == WalletType.DISTRIBUTED_ID: wallet = self.wallets[wallet_id] await wallet.coin_added(coin, height) await self.create_more_puzzle_hashes(in_transaction=True) return coin_record_1 async def add_pending_transaction(self, tx_record: TransactionRecord): """ Called from wallet before new transaction is sent to the full_node """ # Wallet node will use this queue to retry sending this transaction until full nodes receives it await self.tx_store.add_transaction_record(tx_record, False) all_coins_names = [] all_coins_names.extend([coin.name() for coin in tx_record.additions]) all_coins_names.extend([coin.name() for coin in tx_record.removals]) await self.add_interested_coin_ids(all_coins_names, False) self.tx_pending_changed() self.state_changed("pending_transaction", tx_record.wallet_id) async def add_transaction(self, tx_record: TransactionRecord, in_transaction=False): """ Called from wallet to add transaction that is not being set to full_node """ await self.tx_store.add_transaction_record(tx_record, in_transaction) self.state_changed("pending_transaction", tx_record.wallet_id) async def remove_from_queue( self, spendbundle_id: bytes32, name: str, send_status: MempoolInclusionStatus, error: Optional[Err], ): """ Full node received our transaction, no need to keep it in queue anymore """ updated = await self.tx_store.increment_sent(spendbundle_id, name, send_status, error) if updated: tx: Optional[TransactionRecord] = await self.get_transaction(spendbundle_id) if tx is not None: self.state_changed("tx_update", tx.wallet_id, {"transaction": tx}) async def get_all_transactions(self, wallet_id: int) -> List[TransactionRecord]: """ Retrieves all confirmed and pending transactions """ records = await self.tx_store.get_all_transactions_for_wallet(wallet_id) return records async def get_transaction(self, tx_id: bytes32) -> Optional[TransactionRecord]: return await self.tx_store.get_transaction_record(tx_id) async def is_addition_relevant(self, addition: Coin): """ Check whether we care about a new addition (puzzle_hash). Returns true if we control this puzzle hash. """ result = await self.puzzle_store.puzzle_hash_exists(addition.puzzle_hash) return result async def get_wallet_for_coin(self, coin_id: bytes32) -> Any: coin_record = await self.coin_store.get_coin_record(coin_id) if coin_record is None: return None wallet_id = uint32(coin_record.wallet_id) wallet = self.wallets[wallet_id] return wallet async def reorg_rollback(self, height: int): """ Rolls back and updates the coin_store and transaction store. It's possible this height is the tip, or even beyond the tip. """ await self.coin_store.rollback_to_block(height) reorged: List[TransactionRecord] = await self.tx_store.get_transaction_above(height) await self.tx_store.rollback_to_block(height) for record in reorged: if record.type in [ TransactionType.OUTGOING_TX, TransactionType.OUTGOING_TRADE, TransactionType.INCOMING_TRADE, ]: await self.tx_store.tx_reorged(record, in_transaction=True) self.tx_pending_changed() # Removes wallets that were created from a blockchain transaction which got reorged. remove_ids = [] for wallet_id, wallet in self.wallets.items(): if wallet.type() == WalletType.POOLING_WALLET.value: remove: bool = await wallet.rewind(height, in_transaction=True) if remove: remove_ids.append(wallet_id) for wallet_id in remove_ids: await self.user_store.delete_wallet(wallet_id, in_transaction=True) self.wallets.pop(wallet_id) async def _await_closed(self) -> None: await self.db_connection.close() if self.weight_proof_handler is not None: self.weight_proof_handler.cancel_weight_proof_tasks() def unlink_db(self): Path(self.db_path).unlink() async def get_all_wallet_info_entries(self, wallet_type: Optional[WalletType] = None) -> List[WalletInfo]: return await self.user_store.get_all_wallet_info_entries(wallet_type) async def get_start_height(self): """ If we have coin use that as starting height next time, otherwise use the peak """ return 0 async def get_wallet_for_asset_id(self, asset_id: str): for wallet_id in self.wallets: wallet = self.wallets[wallet_id] if wallet.type() == WalletType.CAT: if bytes(wallet.cat_info.limitations_program_hash).hex() == asset_id: return wallet return None async def add_new_wallet(self, wallet: Any, wallet_id: int, create_puzzle_hashes=True, in_transaction=False): self.wallets[uint32(wallet_id)] = wallet if create_puzzle_hashes: await self.create_more_puzzle_hashes(in_transaction=in_transaction) self.state_changed("wallet_created") async def get_spendable_coins_for_wallet(self, wallet_id: int, records=None) -> Set[WalletCoinRecord]: if records is None: records = await self.coin_store.get_unspent_coins_for_wallet(wallet_id) # Coins that are currently part of a transaction unconfirmed_tx: List[TransactionRecord] = await self.tx_store.get_unconfirmed_for_wallet(wallet_id) removal_dict: Dict[bytes32, Coin] = {} for tx in unconfirmed_tx: for coin in tx.removals: # TODO, "if" might not be necessary once unconfirmed tx doesn't contain coins for other wallets if await self.does_coin_belong_to_wallet(coin, wallet_id): removal_dict[coin.name()] = coin # Coins that are part of the trade offer_locked_coins: Dict[bytes32, WalletCoinRecord] = await self.trade_manager.get_locked_coins() filtered = set() for record in records: if record.coin.name() in offer_locked_coins: continue if record.coin.name() in removal_dict: continue filtered.add(record) return filtered async def create_action( self, name: str, wallet_id: int, wallet_type: int, callback: str, done: bool, data: str, in_transaction: bool ): await self.action_store.create_action(name, wallet_id, wallet_type, callback, done, data, in_transaction) self.tx_pending_changed() async def generator_received(self, height: uint32, header_hash: uint32, program: Program): actions: List[WalletAction] = await self.action_store.get_all_pending_actions() for action in actions: data = json.loads(action.data) action_data = data["data"]["action_data"] if action.name == "request_generator": stored_header_hash = bytes32(hexstr_to_bytes(action_data["header_hash"])) stored_height = uint32(action_data["height"]) if stored_header_hash == header_hash and stored_height == height: if action.done: return None wallet = self.wallets[uint32(action.wallet_id)] callback_str = action.wallet_callback if callback_str is not None: callback = getattr(wallet, callback_str) await callback(height, header_hash, program, action.id) async def puzzle_solution_received(self, response: RespondPuzzleSolution): unwrapped: PuzzleSolutionResponse = response.response actions: List[WalletAction] = await self.action_store.get_all_pending_actions() for action in actions: data = json.loads(action.data) action_data = data["data"]["action_data"] if action.name == "request_puzzle_solution": stored_coin_name = bytes32(hexstr_to_bytes(action_data["coin_name"])) height = uint32(action_data["height"]) if stored_coin_name == unwrapped.coin_name and height == unwrapped.height: if action.done: return None wallet = self.wallets[uint32(action.wallet_id)] callback_str = action.wallet_callback if callback_str is not None: callback = getattr(wallet, callback_str) await callback(unwrapped, action.id) async def new_peak(self, peak: wallet_protocol.NewPeakWallet): for wallet_id, wallet in self.wallets.items(): if wallet.type() == uint8(WalletType.POOLING_WALLET): await wallet.new_peak(peak.height) async def add_interested_puzzle_hashes( self, puzzle_hashes: List[bytes32], wallet_ids: List[int], in_transaction: bool = False ) -> None: for puzzle_hash, wallet_id in zip(puzzle_hashes, wallet_ids): await self.interested_store.add_interested_puzzle_hash(puzzle_hash, wallet_id, in_transaction) if len(puzzle_hashes) > 0: await self.wallet_node.new_peak_queue.subscribe_to_puzzle_hashes(puzzle_hashes) async def add_interested_coin_ids(self, coin_ids: List[bytes32], in_transaction: bool = False) -> None: for coin_id in coin_ids: await self.interested_store.add_interested_coin_id(coin_id, in_transaction) if len(coin_ids) > 0: await self.wallet_node.new_peak_queue.subscribe_to_coin_ids(coin_ids) async def delete_trade_transactions(self, trade_id: bytes32): txs: List[TransactionRecord] = await self.tx_store.get_transactions_by_trade_id(trade_id) for tx in txs: await self.tx_store.delete_transaction_record(tx.name) async def convert_puzzle_hash(self, wallet_id: uint32, puzzle_hash: bytes32) -> bytes32: wallet = self.wallets[wallet_id] # This should be general to wallets but for right now this is just for CATs so we'll add this if if wallet.type() == WalletType.CAT.value: return await wallet.convert_puzzle_hash(puzzle_hash) return puzzle_hash
46.471474
120
0.615939
import asyncio import json import logging import multiprocessing import multiprocessing.context import time from collections import defaultdict from pathlib import Path from secrets import token_bytes from typing import Any, Callable, Dict, List, Optional, Set, Tuple import aiosqlite from blspy import G1Element, PrivateKey from chia.consensus.coinbase import pool_parent_id, farmer_parent_id, timelord_parent_id from chia.consensus.constants import ConsensusConstants from chia.pools.pool_puzzles import SINGLETON_LAUNCHER_HASH, solution_to_pool_state from chia.pools.pool_wallet import PoolWallet from chia.protocols import wallet_protocol from chia.protocols.wallet_protocol import PuzzleSolutionResponse, RespondPuzzleSolution, CoinState from chia.server.ws_connection import WSChiaConnection from chia.types.blockchain_format.coin import Coin from chia.types.blockchain_format.program import Program from chia.types.blockchain_format.sized_bytes import bytes32 from chia.types.coin_spend import CoinSpend from chia.types.full_block import FullBlock from chia.types.mempool_inclusion_status import MempoolInclusionStatus from chia.util.byte_types import hexstr_to_bytes from chia.util.config import process_config_start_method from chia.util.db_wrapper import DBWrapper from chia.util.errors import Err from chia.util.ints import uint32, uint64, uint128, uint8 from chia.util.db_synchronous import db_synchronous_on from chia.wallet.cat_wallet.cat_utils import match_cat_puzzle, construct_cat_puzzle from chia.wallet.cat_wallet.cat_wallet import CATWallet from chia.wallet.cat_wallet.cat_constants import DEFAULT_CATS from chia.wallet.derivation_record import DerivationRecord from chia.wallet.derive_keys import master_sk_to_wallet_sk, master_sk_to_wallet_sk_unhardened from chia.wallet.key_val_store import KeyValStore from chia.wallet.puzzles.cat_loader import CAT_MOD from chia.wallet.rl_wallet.rl_wallet import RLWallet from chia.wallet.settings.user_settings import UserSettings from chia.wallet.trade_manager import TradeManager from chia.wallet.transaction_record import TransactionRecord from chia.wallet.util.compute_hints import compute_coin_hints from chia.wallet.util.transaction_type import TransactionType from chia.wallet.util.wallet_sync_utils import last_change_height_cs from chia.wallet.util.wallet_types import WalletType from chia.wallet.wallet import Wallet from chia.wallet.wallet_action import WalletAction from chia.wallet.wallet_action_store import WalletActionStore from chia.wallet.wallet_blockchain import WalletBlockchain from chia.wallet.wallet_coin_record import WalletCoinRecord from chia.wallet.wallet_coin_store import WalletCoinStore from chia.wallet.wallet_info import WalletInfo from chia.wallet.wallet_interested_store import WalletInterestedStore from chia.wallet.wallet_pool_store import WalletPoolStore from chia.wallet.wallet_puzzle_store import WalletPuzzleStore from chia.wallet.wallet_sync_store import WalletSyncStore from chia.wallet.wallet_transaction_store import WalletTransactionStore from chia.wallet.wallet_user_store import WalletUserStore from chia.server.server import ChiaServer from chia.wallet.did_wallet.did_wallet import DIDWallet from chia.wallet.wallet_weight_proof_handler import WalletWeightProofHandler class WalletStateManager: constants: ConsensusConstants config: Dict tx_store: WalletTransactionStore puzzle_store: WalletPuzzleStore user_store: WalletUserStore action_store: WalletActionStore basic_store: KeyValStore start_index: int lock: asyncio.Lock log: logging.Logger sync_mode: bool sync_target: uint32 genesis: FullBlock state_changed_callback: Optional[Callable] pending_tx_callback: Optional[Callable] puzzle_hash_created_callbacks: Dict = defaultdict(lambda *x: None) db_path: Path db_connection: aiosqlite.Connection db_wrapper: DBWrapper main_wallet: Wallet wallets: Dict[uint32, Any] private_key: PrivateKey trade_manager: TradeManager new_wallet: bool user_settings: UserSettings blockchain: WalletBlockchain coin_store: WalletCoinStore sync_store: WalletSyncStore finished_sync_up_to: uint32 interested_store: WalletInterestedStore multiprocessing_context: multiprocessing.context.BaseContext weight_proof_handler: WalletWeightProofHandler server: ChiaServer root_path: Path wallet_node: Any pool_store: WalletPoolStore default_cats: Dict[str, Any] @staticmethod async def create( private_key: PrivateKey, config: Dict, db_path: Path, constants: ConsensusConstants, server: ChiaServer, root_path: Path, wallet_node, name: str = None, ): self = WalletStateManager() self.new_wallet = False self.config = config self.constants = constants self.server = server self.root_path = root_path self.log = logging.getLogger(name if name else __name__) self.lock = asyncio.Lock() self.log.debug(f"Starting in db path: {db_path}") self.db_connection = await aiosqlite.connect(db_path) await self.db_connection.execute("pragma journal_mode=wal") await self.db_connection.execute( "pragma synchronous={}".format(db_synchronous_on(self.config.get("db_sync", "auto"), db_path)) ) self.db_wrapper = DBWrapper(self.db_connection) self.coin_store = await WalletCoinStore.create(self.db_wrapper) self.tx_store = await WalletTransactionStore.create(self.db_wrapper) self.puzzle_store = await WalletPuzzleStore.create(self.db_wrapper) self.user_store = await WalletUserStore.create(self.db_wrapper) self.action_store = await WalletActionStore.create(self.db_wrapper) self.basic_store = await KeyValStore.create(self.db_wrapper) self.trade_manager = await TradeManager.create(self, self.db_wrapper) self.user_settings = await UserSettings.create(self.basic_store) self.pool_store = await WalletPoolStore.create(self.db_wrapper) self.interested_store = await WalletInterestedStore.create(self.db_wrapper) self.default_cats = DEFAULT_CATS self.wallet_node = wallet_node self.sync_mode = False self.sync_target = uint32(0) self.finished_sync_up_to = uint32(0) multiprocessing_start_method = process_config_start_method(config=self.config, log=self.log) self.multiprocessing_context = multiprocessing.get_context(method=multiprocessing_start_method) self.weight_proof_handler = WalletWeightProofHandler( constants=self.constants, multiprocessing_context=self.multiprocessing_context, ) self.blockchain = await WalletBlockchain.create(self.basic_store, self.constants, self.weight_proof_handler) self.state_changed_callback = None self.pending_tx_callback = None self.db_path = db_path main_wallet_info = await self.user_store.get_wallet_by_id(1) assert main_wallet_info is not None self.private_key = private_key self.main_wallet = await Wallet.create(self, main_wallet_info) self.wallets = {main_wallet_info.id: self.main_wallet} wallet = None for wallet_info in await self.get_all_wallet_info_entries(): if wallet_info.type == WalletType.STANDARD_WALLET: if wallet_info.id == 1: continue wallet = await Wallet.create(self, wallet_info) elif wallet_info.type == WalletType.CAT: wallet = await CATWallet.create( self, self.main_wallet, wallet_info, ) elif wallet_info.type == WalletType.RATE_LIMITED: wallet = await RLWallet.create(self, wallet_info) elif wallet_info.type == WalletType.DISTRIBUTED_ID: wallet = await DIDWallet.create( self, self.main_wallet, wallet_info, ) elif wallet_info.type == WalletType.POOLING_WALLET: wallet = await PoolWallet.create_from_db( self, self.main_wallet, wallet_info, ) if wallet is not None: self.wallets[wallet_info.id] = wallet return self def get_derivation_index(self, pubkey: G1Element, max_depth: int = 1000) -> int: for i in range(0, max_depth): derived = self.get_public_key(uint32(i)) if derived == pubkey: return i derived = self.get_public_key_unhardened(uint32(i)) if derived == pubkey: return i return -1 def get_public_key(self, index: uint32) -> G1Element: return master_sk_to_wallet_sk(self.private_key, index).get_g1() def get_public_key_unhardened(self, index: uint32) -> G1Element: return master_sk_to_wallet_sk_unhardened(self.private_key, index).get_g1() async def get_keys(self, puzzle_hash: bytes32) -> Optional[Tuple[G1Element, PrivateKey]]: record = await self.puzzle_store.record_for_puzzle_hash(puzzle_hash) if record is None: raise ValueError(f"No key for this puzzlehash {puzzle_hash})") if record.hardened: private = master_sk_to_wallet_sk(self.private_key, record.index) pubkey = private.get_g1() return pubkey, private private = master_sk_to_wallet_sk_unhardened(self.private_key, record.index) pubkey = private.get_g1() return pubkey, private async def create_more_puzzle_hashes(self, from_zero: bool = False, in_transaction=False): targets = list(self.wallets.keys()) unused: Optional[uint32] = await self.puzzle_store.get_unused_derivation_path() if unused is None: # This handles the case where the database has entries but they have all been used unused = await self.puzzle_store.get_last_derivation_path() if unused is None: # This handles the case where the database is empty unused = uint32(0) to_generate = self.config["initial_num_public_keys"] for wallet_id in targets: target_wallet = self.wallets[wallet_id] last: Optional[uint32] = await self.puzzle_store.get_last_derivation_path_for_wallet(wallet_id) start_index = 0 derivation_paths: List[DerivationRecord] = [] if last is not None: start_index = last + 1 # If the key was replaced (from_zero=True), we should generate the puzzle hashes for the new key if from_zero: start_index = 0 last_index = unused + to_generate if start_index >= last_index: self.log.debug(f"Nothing to create for for wallet_id: {wallet_id}, index: {start_index}") else: creating_msg = f"Creating puzzle hashes from {start_index} to {last_index} for wallet_id: {wallet_id}" self.log.info(f"Start: {creating_msg}") for index in range(start_index, last_index): if WalletType(target_wallet.type()) == WalletType.POOLING_WALLET: continue # Hardened pubkey: G1Element = self.get_public_key(uint32(index)) puzzle: Program = target_wallet.puzzle_for_pk(bytes(pubkey)) if puzzle is None: self.log.error(f"Unable to create puzzles with wallet {target_wallet}") break puzzlehash: bytes32 = puzzle.get_tree_hash() self.log.debug(f"Puzzle at index {index} wallet ID {wallet_id} puzzle hash {puzzlehash.hex()}") derivation_paths.append( DerivationRecord( uint32(index), puzzlehash, pubkey, target_wallet.type(), uint32(target_wallet.id()), True ) ) # Unhardened pubkey_unhardened: G1Element = self.get_public_key_unhardened(uint32(index)) puzzle_unhardened: Program = target_wallet.puzzle_for_pk(bytes(pubkey_unhardened)) if puzzle_unhardened is None: self.log.error(f"Unable to create puzzles with wallet {target_wallet}") break puzzlehash_unhardened: bytes32 = puzzle_unhardened.get_tree_hash() self.log.debug( f"Puzzle at index {index} wallet ID {wallet_id} puzzle hash {puzzlehash_unhardened.hex()}" ) derivation_paths.append( DerivationRecord( uint32(index), puzzlehash_unhardened, pubkey_unhardened, target_wallet.type(), uint32(target_wallet.id()), False, ) ) self.log.info(f"Done: {creating_msg}") await self.puzzle_store.add_derivation_paths(derivation_paths, in_transaction) await self.add_interested_puzzle_hashes( [record.puzzle_hash for record in derivation_paths], [record.wallet_id for record in derivation_paths], in_transaction, ) if unused > 0: await self.puzzle_store.set_used_up_to(uint32(unused - 1), in_transaction) async def update_wallet_puzzle_hashes(self, wallet_id): derivation_paths: List[DerivationRecord] = [] target_wallet = self.wallets[wallet_id] last: Optional[uint32] = await self.puzzle_store.get_last_derivation_path_for_wallet(wallet_id) unused: Optional[uint32] = await self.puzzle_store.get_unused_derivation_path() if unused is None: # This handles the case where the database has entries but they have all been used unused = await self.puzzle_store.get_last_derivation_path() if unused is None: # This handles the case where the database is empty unused = uint32(0) for index in range(unused, last): # Since DID are not released yet we can assume they are only using unhardened keys derivation pubkey: G1Element = self.get_public_key_unhardened(uint32(index)) puzzle: Program = target_wallet.puzzle_for_pk(bytes(pubkey)) puzzlehash: bytes32 = puzzle.get_tree_hash() self.log.info(f"Generating public key at index {index} puzzle hash {puzzlehash.hex()}") derivation_paths.append( DerivationRecord( uint32(index), puzzlehash, pubkey, target_wallet.wallet_info.type, uint32(target_wallet.wallet_info.id), False, ) ) await self.puzzle_store.add_derivation_paths(derivation_paths) async def get_unused_derivation_record( self, wallet_id: uint32, in_transaction=False, hardened=False ) -> DerivationRecord: async with self.puzzle_store.lock: # If we have no unused public keys, we will create new ones unused: Optional[uint32] = await self.puzzle_store.get_unused_derivation_path() if unused is None: await self.create_more_puzzle_hashes() # Now we must have unused public keys unused = await self.puzzle_store.get_unused_derivation_path() assert unused is not None record: Optional[DerivationRecord] = await self.puzzle_store.get_derivation_record( unused, wallet_id, hardened ) assert record is not None # Set this key to used so we never use it again await self.puzzle_store.set_used_up_to(record.index, in_transaction=in_transaction) # Create more puzzle hashes / keys await self.create_more_puzzle_hashes(in_transaction=in_transaction) return record async def get_current_derivation_record_for_wallet(self, wallet_id: uint32) -> Optional[DerivationRecord]: async with self.puzzle_store.lock: # If we have no unused public keys, we will create new ones current: Optional[DerivationRecord] = await self.puzzle_store.get_current_derivation_record_for_wallet( wallet_id ) return current def set_callback(self, callback: Callable): self.state_changed_callback = callback def set_pending_callback(self, callback: Callable): self.pending_tx_callback = callback def set_coin_with_puzzlehash_created_callback(self, puzzlehash: bytes32, callback: Callable): self.puzzle_hash_created_callbacks[puzzlehash] = callback async def puzzle_hash_created(self, coin: Coin): callback = self.puzzle_hash_created_callbacks[coin.puzzle_hash] if callback is None: return None await callback(coin) def state_changed(self, state: str, wallet_id: int = None, data_object=None): if data_object is None: data_object = {} if self.state_changed_callback is None: return None self.state_changed_callback(state, wallet_id, data_object) def tx_pending_changed(self) -> None: if self.pending_tx_callback is None: return None self.pending_tx_callback() async def synced(self): latest = await self.blockchain.get_peak_block() if latest is None: return False if latest.height - await self.blockchain.get_finished_sync_up_to() > 1: return False latest_timestamp = self.blockchain.get_latest_timestamp() if latest_timestamp > int(time.time()) - 10 * 60: return True return False def set_sync_mode(self, mode: bool, sync_height: uint32 = uint32(0)): self.sync_mode = mode self.sync_target = sync_height self.state_changed("sync_changed") async def get_confirmed_spendable_balance_for_wallet(self, wallet_id: int, unspent_records=None) -> uint128: spendable: Set[WalletCoinRecord] = await self.get_spendable_coins_for_wallet(wallet_id, unspent_records) spendable_amount: uint128 = uint128(0) for record in spendable: spendable_amount = uint128(spendable_amount + record.coin.amount) return spendable_amount async def does_coin_belong_to_wallet(self, coin: Coin, wallet_id: int) -> bool: info = await self.puzzle_store.wallet_info_for_puzzle_hash(coin.puzzle_hash) if info is None: return False coin_wallet_id, wallet_type = info if wallet_id == coin_wallet_id: return True return False async def get_confirmed_balance_for_wallet( self, wallet_id: int, unspent_coin_records: Optional[Set[WalletCoinRecord]] = None, ) -> uint128: # lock only if unspent_coin_records is None if unspent_coin_records is None: unspent_coin_records = await self.coin_store.get_unspent_coins_for_wallet(wallet_id) return uint128(sum(cr.coin.amount for cr in unspent_coin_records)) async def get_unconfirmed_balance( self, wallet_id: int, unspent_coin_records: Optional[Set[WalletCoinRecord]] = None ) -> uint128: # This API should change so that get_balance_from_coin_records is called for Set[WalletCoinRecord] # and this method is called only for the unspent_coin_records==None case. if unspent_coin_records is None: unspent_coin_records = await self.coin_store.get_unspent_coins_for_wallet(wallet_id) unconfirmed_tx: List[TransactionRecord] = await self.tx_store.get_unconfirmed_for_wallet(wallet_id) all_unspent_coins: Set[Coin] = {cr.coin for cr in unspent_coin_records} for record in unconfirmed_tx: for addition in record.additions: # This change or a self transaction if await self.does_coin_belong_to_wallet(addition, wallet_id): all_unspent_coins.add(addition) for removal in record.removals: if await self.does_coin_belong_to_wallet(removal, wallet_id) and removal in all_unspent_coins: all_unspent_coins.remove(removal) return uint128(sum(coin.amount for coin in all_unspent_coins)) async def unconfirmed_removals_for_wallet(self, wallet_id: int) -> Dict[bytes32, Coin]: removals: Dict[bytes32, Coin] = {} unconfirmed_tx = await self.tx_store.get_unconfirmed_for_wallet(wallet_id) for record in unconfirmed_tx: for coin in record.removals: removals[coin.name()] = coin return removals async def fetch_parent_and_check_for_cat( self, peer: WSChiaConnection, coin_state: CoinState, fork_height: Optional[uint32] ) -> Tuple[Optional[uint32], Optional[WalletType]]: if self.is_pool_reward(coin_state.created_height, coin_state.coin.parent_coin_info) or self.is_farmer_reward( coin_state.created_height, coin_state.coin.parent_coin_info ): return None, None response: List[CoinState] = await self.wallet_node.get_coin_state( [coin_state.coin.parent_coin_info], fork_height, peer ) if len(response) == 0: self.log.warning(f"Could not find a parent coin with ID: {coin_state.coin.parent_coin_info}") return None, None parent_coin_state = response[0] assert parent_coin_state.spent_height == coin_state.created_height wallet_id = None wallet_type = None cs: Optional[CoinSpend] = await self.wallet_node.fetch_puzzle_solution( peer, parent_coin_state.spent_height, parent_coin_state.coin ) if cs is None: return None, None matched, curried_args = match_cat_puzzle(Program.from_bytes(bytes(cs.puzzle_reveal))) if matched: mod_hash, tail_hash, inner_puzzle = curried_args inner_puzzle_hash = inner_puzzle.get_tree_hash() self.log.info( f"parent: {parent_coin_state.coin.name()} inner_puzzle_hash for parent is {inner_puzzle_hash}" ) hint_list = compute_coin_hints(cs) derivation_record = None for hint in hint_list: derivation_record = await self.puzzle_store.get_derivation_record_for_puzzle_hash(bytes32(hint)) if derivation_record is not None: break if derivation_record is None: self.log.info(f"Received state for the coin that doesn't belong to us {coin_state}") else: our_inner_puzzle: Program = self.main_wallet.puzzle_for_pk(bytes(derivation_record.pubkey)) asset_id: bytes32 = bytes32(bytes(tail_hash)[1:]) cat_puzzle = construct_cat_puzzle(CAT_MOD, asset_id, our_inner_puzzle) if cat_puzzle.get_tree_hash() != coin_state.coin.puzzle_hash: return None, None if bytes(tail_hash).hex()[2:] in self.default_cats or self.config.get( "automatically_add_unknown_cats", False ): cat_wallet = await CATWallet.create_wallet_for_cat( self, self.main_wallet, bytes(tail_hash).hex()[2:], in_transaction=True ) wallet_id = cat_wallet.id() wallet_type = WalletType(cat_wallet.type()) self.state_changed("wallet_created") else: await self.interested_store.add_unacknowledged_token( asset_id, CATWallet.default_wallet_name_for_unknown_cat(asset_id.hex()), parent_coin_state.spent_height, parent_coin_state.coin.puzzle_hash, ) self.state_changed("added_stray_cat") return wallet_id, wallet_type async def new_coin_state( self, coin_states: List[CoinState], peer: WSChiaConnection, fork_height: Optional[uint32] ) -> None: curr_h = -1 for c_state in coin_states: last_change_height = last_change_height_cs(c_state) if last_change_height < curr_h: raise ValueError("Input coin_states is not sorted properly") curr_h = last_change_height all_txs_per_wallet: Dict[int, List[TransactionRecord]] = {} trade_removals = await self.trade_manager.get_coins_of_interest() all_unconfirmed: List[TransactionRecord] = await self.tx_store.get_all_unconfirmed() trade_coin_removed: List[CoinState] = [] for coin_state_idx, coin_state in enumerate(coin_states): wallet_info: Optional[Tuple[uint32, WalletType]] = await self.get_wallet_id_for_puzzle_hash( coin_state.coin.puzzle_hash ) local_record: Optional[WalletCoinRecord] = await self.coin_store.get_coin_record(coin_state.coin.name()) self.log.debug(f"{coin_state.coin.name()}: {coin_state}") if local_record is not None: local_spent = None if local_record.spent_block_height != 0: local_spent = local_record.spent_block_height if ( local_spent == coin_state.spent_height and local_record.confirmed_block_height == coin_state.created_height ): continue wallet_id: Optional[uint32] = None wallet_type: Optional[WalletType] = None if wallet_info is not None: wallet_id, wallet_type = wallet_info elif local_record is not None: wallet_id = uint32(local_record.wallet_id) wallet_type = local_record.wallet_type elif coin_state.created_height is not None: wallet_id, wallet_type = await self.fetch_parent_and_check_for_cat(peer, coin_state, fork_height) if wallet_id is None or wallet_type is None: self.log.info(f"No wallet for coin state: {coin_state}") continue if wallet_id in all_txs_per_wallet: all_txs = all_txs_per_wallet[wallet_id] else: all_txs = await self.tx_store.get_all_transactions_for_wallet(wallet_id) all_txs_per_wallet[wallet_id] = all_txs all_outgoing = [tx for tx in all_txs if "OUTGOING" in TransactionType(tx.type).name] derivation_index = await self.puzzle_store.index_for_puzzle_hash(coin_state.coin.puzzle_hash) if derivation_index is not None: await self.puzzle_store.set_used_up_to(derivation_index, True) if coin_state.created_height is None: pass elif coin_state.created_height is not None and coin_state.spent_height is None: await self.coin_added(coin_state.coin, coin_state.created_height, all_txs, wallet_id, wallet_type) elif coin_state.created_height is not None and coin_state.spent_height is not None: self.log.info(f"Coin Removed: {coin_state}") record = await self.coin_store.get_coin_record(coin_state.coin.name()) if coin_state.coin.name() in trade_removals: trade_coin_removed.append(coin_state) children: Optional[List[CoinState]] = None if record is None: timelord_reward = False farmer_reward = False pool_reward = False tx_type: int if self.is_farmer_reward(coin_state.created_height, coin_state.coin.parent_coin_info): farmer_reward = True tx_type = TransactionType.FEE_REWARD.value elif self.is_pool_reward(coin_state.created_height, coin_state.coin.parent_coin_info): pool_reward = True tx_type = TransactionType.COINBASE_REWARD.value else: tx_type = TransactionType.INCOMING_TX.value record = WalletCoinRecord( coin_state.coin, coin_state.created_height, coin_state.spent_height, True, farmer_reward or pool_reward, wallet_type, wallet_id, ) await self.coin_store.add_coin_record(record) coin_record: Optional[WalletCoinRecord] = await self.coin_store.get_coin_record( coin_state.coin.parent_coin_info ) if coin_record is not None and wallet_type.value == coin_record.wallet_type: change = True else: change = False if not change: created_timestamp = await self.wallet_node.get_timestamp_for_height(coin_state.created_height) tx_record = TransactionRecord( confirmed_at_height=coin_state.created_height, created_at_time=uint64(created_timestamp), to_puzzle_hash=(await self.convert_puzzle_hash(wallet_id, coin_state.coin.puzzle_hash)), amount=uint64(coin_state.coin.amount), fee_amount=uint64(0), confirmed=True, sent=uint32(0), spend_bundle=None, additions=[coin_state.coin], removals=[], wallet_id=wallet_id, sent_to=[], trade_id=None, type=uint32(tx_type), name=bytes32(token_bytes()), memos=[], ) await self.tx_store.add_transaction_record(tx_record, True) children = await self.wallet_node.fetch_children(peer, coin_state.coin.name(), fork_height) assert children is not None additions = [state.coin for state in children] if len(children) > 0: fee = 0 to_puzzle_hash = None amount = 0 for coin in additions: derivation_record = await self.puzzle_store.get_derivation_record_for_puzzle_hash( coin.puzzle_hash ) if derivation_record is None: to_puzzle_hash = coin.puzzle_hash amount += coin.amount if to_puzzle_hash is None: to_puzzle_hash = additions[0].puzzle_hash spent_timestamp = await self.wallet_node.get_timestamp_for_height(coin_state.spent_height) # Reorg rollback adds reorged transactions so it's possible there is tx_record already tx_records: List[TransactionRecord] = [] for out_tx_record in all_outgoing: for rem_coin in out_tx_record.removals: if rem_coin.name() == coin_state.coin.name(): tx_records.append(out_tx_record) if len(tx_records) > 0: for tx_record in tx_records: await self.tx_store.set_confirmed(tx_record.name, coin_state.spent_height) else: tx_record = TransactionRecord( confirmed_at_height=coin_state.spent_height, created_at_time=uint64(spent_timestamp), to_puzzle_hash=(await self.convert_puzzle_hash(wallet_id, to_puzzle_hash)), amount=uint64(int(amount)), fee_amount=uint64(fee), confirmed=True, sent=uint32(0), spend_bundle=None, additions=additions, removals=[coin_state.coin], wallet_id=wallet_id, sent_to=[], trade_id=None, type=uint32(TransactionType.OUTGOING_TX.value), name=bytes32(token_bytes()), memos=[], ) await self.tx_store.add_transaction_record(tx_record, True) else: await self.coin_store.set_spent(coin_state.coin.name(), coin_state.spent_height) rem_tx_records: List[TransactionRecord] = [] for out_tx_record in all_outgoing: for rem_coin in out_tx_record.removals: if rem_coin.name() == coin_state.coin.name(): rem_tx_records.append(out_tx_record) for tx_record in rem_tx_records: await self.tx_store.set_confirmed(tx_record.name, coin_state.spent_height) for unconfirmed_record in all_unconfirmed: for rem_coin in unconfirmed_record.removals: if rem_coin.name() == coin_state.coin.name(): self.log.info(f"Setting tx_id: {unconfirmed_record.name} to confirmed") await self.tx_store.set_confirmed(unconfirmed_record.name, coin_state.spent_height) if record.wallet_type == WalletType.POOLING_WALLET: if coin_state.spent_height is not None and coin_state.coin.amount == uint64(1): wallet = self.wallets[uint32(record.wallet_id)] curr_coin_state: CoinState = coin_state while curr_coin_state.spent_height is not None: cs: CoinSpend = await self.wallet_node.fetch_puzzle_solution( peer, curr_coin_state.spent_height, curr_coin_state.coin ) success = await wallet.apply_state_transition(cs, curr_coin_state.spent_height) if not success: break new_singleton_coin: Optional[Coin] = wallet.get_next_interesting_coin(cs) if new_singleton_coin is None: break await self.coin_added( new_singleton_coin, coin_state.spent_height, [], uint32(record.wallet_id), record.wallet_type, ) await self.coin_store.set_spent(curr_coin_state.coin.name(), curr_coin_state.spent_height) await self.add_interested_coin_ids([new_singleton_coin.name()], True) new_coin_state: List[CoinState] = await self.wallet_node.get_coin_state( [new_singleton_coin.name()], fork_height, peer ) assert len(new_coin_state) == 1 curr_coin_state = new_coin_state[0] if children is None: children = await self.wallet_node.fetch_children(peer, coin_state.coin.name(), fork_height) assert children is not None for child in children: if child.coin.puzzle_hash != SINGLETON_LAUNCHER_HASH: continue if await self.have_a_pool_wallet_with_launched_id(child.coin.name()): continue if child.spent_height is None: continue launcher_spend: Optional[CoinSpend] = await self.wallet_node.fetch_puzzle_solution( peer, coin_state.spent_height, child.coin ) if launcher_spend is None: continue try: pool_state = solution_to_pool_state(launcher_spend) except Exception as e: self.log.debug(f"Not a pool wallet launcher {e}") continue if pool_state is None: self.log.debug("solution_to_pool_state returned None, ignore and continue") continue assert child.spent_height is not None pool_wallet = await PoolWallet.create( self, self.main_wallet, child.coin.name(), [launcher_spend], child.spent_height, in_transaction=True, name="pool_wallet", ) launcher_spend_additions = launcher_spend.additions() assert len(launcher_spend_additions) == 1 coin_added = launcher_spend_additions[0] await self.coin_added( coin_added, coin_state.spent_height, [], pool_wallet.id(), WalletType(pool_wallet.type()) ) await self.add_interested_coin_ids([coin_added.name()], True) else: raise RuntimeError("All cases already handled") for coin_state_removed in trade_coin_removed: await self.trade_manager.coins_of_interest_farmed(coin_state_removed, fork_height) async def have_a_pool_wallet_with_launched_id(self, launcher_id: bytes32) -> bool: for wallet_id, wallet in self.wallets.items(): if ( wallet.type() == WalletType.POOLING_WALLET and (await wallet.get_current_state()).launcher_id == launcher_id ): self.log.warning("Already have, not recreating") return True return False def is_pool_reward(self, created_height, parent_id): for i in range(0, 30): try_height = created_height - i if try_height < 0: break calculated = pool_parent_id(try_height, self.constants.GENESIS_CHALLENGE) if calculated == parent_id: return True return False def is_farmer_reward(self, created_height, parent_id): for i in range(0, 30): try_height = created_height - i if try_height < 0: break calculated = farmer_parent_id(try_height, self.constants.GENESIS_CHALLENGE) if calculated == parent_id: return True return False def is_timelord_reward(self, created_height, parent_id): for i in range(0, 30): try_height = created_height - i if try_height < 0: break calculated = timelord_parent_id(try_height, self.constants.GENESIS_CHALLENGE) if calculated == parent_id: return True return False async def get_wallet_id_for_puzzle_hash(self, puzzle_hash: bytes32) -> Optional[Tuple[uint32, WalletType]]: info = await self.puzzle_store.wallet_info_for_puzzle_hash(puzzle_hash) if info is not None: wallet_id, wallet_type = info return uint32(wallet_id), wallet_type interested_wallet_id = await self.interested_store.get_interested_puzzle_hash_wallet_id(puzzle_hash=puzzle_hash) if interested_wallet_id is not None: wallet_id = uint32(interested_wallet_id) if wallet_id not in self.wallets.keys(): self.log.warning(f"Do not have wallet {wallet_id} for puzzle_hash {puzzle_hash}") return None wallet_type = WalletType(self.wallets[uint32(wallet_id)].type()) return uint32(wallet_id), wallet_type return None async def coin_added( self, coin: Coin, height: uint32, all_outgoing_transaction_records: List[TransactionRecord], wallet_id: uint32, wallet_type: WalletType, ) -> Optional[WalletCoinRecord]: existing: Optional[WalletCoinRecord] = await self.coin_store.get_coin_record(coin.name()) if existing is not None: return None self.log.info(f"Adding coin: {coin} at {height} wallet_id:{wallet_id}") farmer_reward = False pool_reward = False if self.is_farmer_reward(height, coin.parent_coin_info): farmer_reward = True elif self.is_pool_reward(height, coin.parent_coin_info): pool_reward = True farm_reward = False coin_record: Optional[WalletCoinRecord] = await self.coin_store.get_coin_record(coin.parent_coin_info) if coin_record is not None and wallet_type.value == coin_record.wallet_type: change = True else: change = False if farmer_reward or pool_reward: farm_reward = True if pool_reward: tx_type: int = TransactionType.COINBASE_REWARD.value else: tx_type = TransactionType.FEE_REWARD.value timestamp = await self.wallet_node.get_timestamp_for_height(height) tx_record = TransactionRecord( confirmed_at_height=uint32(height), created_at_time=timestamp, to_puzzle_hash=(await self.convert_puzzle_hash(wallet_id, coin.puzzle_hash)), amount=coin.amount, fee_amount=uint64(0), confirmed=True, sent=uint32(0), spend_bundle=None, additions=[coin], removals=[], wallet_id=wallet_id, sent_to=[], trade_id=None, type=uint32(tx_type), name=coin.name(), memos=[], ) await self.tx_store.add_transaction_record(tx_record, True) else: records: List[TransactionRecord] = [] for record in all_outgoing_transaction_records: for add_coin in record.additions: if add_coin.name() == coin.name(): records.append(record) if len(records) > 0: for record in records: if record.confirmed is False: await self.tx_store.set_confirmed(record.name, height) elif not change: timestamp = await self.wallet_node.get_timestamp_for_height(height) tx_record = TransactionRecord( confirmed_at_height=uint32(height), created_at_time=timestamp, to_puzzle_hash=(await self.convert_puzzle_hash(wallet_id, coin.puzzle_hash)), amount=coin.amount, fee_amount=uint64(0), confirmed=True, sent=uint32(0), spend_bundle=None, additions=[coin], removals=[], wallet_id=wallet_id, sent_to=[], trade_id=None, type=uint32(TransactionType.INCOMING_TX.value), name=coin.name(), memos=[], ) if coin.amount > 0: await self.tx_store.add_transaction_record(tx_record, True) coin_record_1: WalletCoinRecord = WalletCoinRecord( coin, height, uint32(0), False, farm_reward, wallet_type, wallet_id ) await self.coin_store.add_coin_record(coin_record_1) if wallet_type == WalletType.CAT or wallet_type == WalletType.DISTRIBUTED_ID: wallet = self.wallets[wallet_id] await wallet.coin_added(coin, height) await self.create_more_puzzle_hashes(in_transaction=True) return coin_record_1 async def add_pending_transaction(self, tx_record: TransactionRecord): await self.tx_store.add_transaction_record(tx_record, False) all_coins_names = [] all_coins_names.extend([coin.name() for coin in tx_record.additions]) all_coins_names.extend([coin.name() for coin in tx_record.removals]) await self.add_interested_coin_ids(all_coins_names, False) self.tx_pending_changed() self.state_changed("pending_transaction", tx_record.wallet_id) async def add_transaction(self, tx_record: TransactionRecord, in_transaction=False): await self.tx_store.add_transaction_record(tx_record, in_transaction) self.state_changed("pending_transaction", tx_record.wallet_id) async def remove_from_queue( self, spendbundle_id: bytes32, name: str, send_status: MempoolInclusionStatus, error: Optional[Err], ): updated = await self.tx_store.increment_sent(spendbundle_id, name, send_status, error) if updated: tx: Optional[TransactionRecord] = await self.get_transaction(spendbundle_id) if tx is not None: self.state_changed("tx_update", tx.wallet_id, {"transaction": tx}) async def get_all_transactions(self, wallet_id: int) -> List[TransactionRecord]: records = await self.tx_store.get_all_transactions_for_wallet(wallet_id) return records async def get_transaction(self, tx_id: bytes32) -> Optional[TransactionRecord]: return await self.tx_store.get_transaction_record(tx_id) async def is_addition_relevant(self, addition: Coin): result = await self.puzzle_store.puzzle_hash_exists(addition.puzzle_hash) return result async def get_wallet_for_coin(self, coin_id: bytes32) -> Any: coin_record = await self.coin_store.get_coin_record(coin_id) if coin_record is None: return None wallet_id = uint32(coin_record.wallet_id) wallet = self.wallets[wallet_id] return wallet async def reorg_rollback(self, height: int): await self.coin_store.rollback_to_block(height) reorged: List[TransactionRecord] = await self.tx_store.get_transaction_above(height) await self.tx_store.rollback_to_block(height) for record in reorged: if record.type in [ TransactionType.OUTGOING_TX, TransactionType.OUTGOING_TRADE, TransactionType.INCOMING_TRADE, ]: await self.tx_store.tx_reorged(record, in_transaction=True) self.tx_pending_changed() remove_ids = [] for wallet_id, wallet in self.wallets.items(): if wallet.type() == WalletType.POOLING_WALLET.value: remove: bool = await wallet.rewind(height, in_transaction=True) if remove: remove_ids.append(wallet_id) for wallet_id in remove_ids: await self.user_store.delete_wallet(wallet_id, in_transaction=True) self.wallets.pop(wallet_id) async def _await_closed(self) -> None: await self.db_connection.close() if self.weight_proof_handler is not None: self.weight_proof_handler.cancel_weight_proof_tasks() def unlink_db(self): Path(self.db_path).unlink() async def get_all_wallet_info_entries(self, wallet_type: Optional[WalletType] = None) -> List[WalletInfo]: return await self.user_store.get_all_wallet_info_entries(wallet_type) async def get_start_height(self): return 0 async def get_wallet_for_asset_id(self, asset_id: str): for wallet_id in self.wallets: wallet = self.wallets[wallet_id] if wallet.type() == WalletType.CAT: if bytes(wallet.cat_info.limitations_program_hash).hex() == asset_id: return wallet return None async def add_new_wallet(self, wallet: Any, wallet_id: int, create_puzzle_hashes=True, in_transaction=False): self.wallets[uint32(wallet_id)] = wallet if create_puzzle_hashes: await self.create_more_puzzle_hashes(in_transaction=in_transaction) self.state_changed("wallet_created") async def get_spendable_coins_for_wallet(self, wallet_id: int, records=None) -> Set[WalletCoinRecord]: if records is None: records = await self.coin_store.get_unspent_coins_for_wallet(wallet_id) unconfirmed_tx: List[TransactionRecord] = await self.tx_store.get_unconfirmed_for_wallet(wallet_id) removal_dict: Dict[bytes32, Coin] = {} for tx in unconfirmed_tx: for coin in tx.removals: if await self.does_coin_belong_to_wallet(coin, wallet_id): removal_dict[coin.name()] = coin # Coins that are part of the trade offer_locked_coins: Dict[bytes32, WalletCoinRecord] = await self.trade_manager.get_locked_coins() filtered = set() for record in records: if record.coin.name() in offer_locked_coins: continue if record.coin.name() in removal_dict: continue filtered.add(record) return filtered async def create_action( self, name: str, wallet_id: int, wallet_type: int, callback: str, done: bool, data: str, in_transaction: bool ): await self.action_store.create_action(name, wallet_id, wallet_type, callback, done, data, in_transaction) self.tx_pending_changed() async def generator_received(self, height: uint32, header_hash: uint32, program: Program): actions: List[WalletAction] = await self.action_store.get_all_pending_actions() for action in actions: data = json.loads(action.data) action_data = data["data"]["action_data"] if action.name == "request_generator": stored_header_hash = bytes32(hexstr_to_bytes(action_data["header_hash"])) stored_height = uint32(action_data["height"]) if stored_header_hash == header_hash and stored_height == height: if action.done: return None wallet = self.wallets[uint32(action.wallet_id)] callback_str = action.wallet_callback if callback_str is not None: callback = getattr(wallet, callback_str) await callback(height, header_hash, program, action.id) async def puzzle_solution_received(self, response: RespondPuzzleSolution): unwrapped: PuzzleSolutionResponse = response.response actions: List[WalletAction] = await self.action_store.get_all_pending_actions() for action in actions: data = json.loads(action.data) action_data = data["data"]["action_data"] if action.name == "request_puzzle_solution": stored_coin_name = bytes32(hexstr_to_bytes(action_data["coin_name"])) height = uint32(action_data["height"]) if stored_coin_name == unwrapped.coin_name and height == unwrapped.height: if action.done: return None wallet = self.wallets[uint32(action.wallet_id)] callback_str = action.wallet_callback if callback_str is not None: callback = getattr(wallet, callback_str) await callback(unwrapped, action.id) async def new_peak(self, peak: wallet_protocol.NewPeakWallet): for wallet_id, wallet in self.wallets.items(): if wallet.type() == uint8(WalletType.POOLING_WALLET): await wallet.new_peak(peak.height) async def add_interested_puzzle_hashes( self, puzzle_hashes: List[bytes32], wallet_ids: List[int], in_transaction: bool = False ) -> None: for puzzle_hash, wallet_id in zip(puzzle_hashes, wallet_ids): await self.interested_store.add_interested_puzzle_hash(puzzle_hash, wallet_id, in_transaction) if len(puzzle_hashes) > 0: await self.wallet_node.new_peak_queue.subscribe_to_puzzle_hashes(puzzle_hashes) async def add_interested_coin_ids(self, coin_ids: List[bytes32], in_transaction: bool = False) -> None: for coin_id in coin_ids: await self.interested_store.add_interested_coin_id(coin_id, in_transaction) if len(coin_ids) > 0: await self.wallet_node.new_peak_queue.subscribe_to_coin_ids(coin_ids) async def delete_trade_transactions(self, trade_id: bytes32): txs: List[TransactionRecord] = await self.tx_store.get_transactions_by_trade_id(trade_id) for tx in txs: await self.tx_store.delete_transaction_record(tx.name) async def convert_puzzle_hash(self, wallet_id: uint32, puzzle_hash: bytes32) -> bytes32: wallet = self.wallets[wallet_id] # This should be general to wallets but for right now this is just for CATs so we'll add this if if wallet.type() == WalletType.CAT.value: return await wallet.convert_puzzle_hash(puzzle_hash) return puzzle_hash
true
true
1c2ce85606808bea6bdcd71ee1e5b60922899ec9
6,190
py
Python
src/examples/VRGameFog-IFogSim-WL/testConvergence.py
vyk1/YAFS
514f8362c90923fa28f871fcf179b755a9315c47
[ "MIT" ]
58
2018-09-19T12:00:01.000Z
2022-03-28T12:14:32.000Z
src/examples/VRGameFog-IFogSim-WL/testConvergence.py
vyk1/YAFS
514f8362c90923fa28f871fcf179b755a9315c47
[ "MIT" ]
55
2018-03-18T09:58:27.000Z
2022-02-19T16:40:02.000Z
src/examples/VRGameFog-IFogSim-WL/testConvergence.py
vyk1/YAFS
514f8362c90923fa28f871fcf179b755a9315c47
[ "MIT" ]
51
2018-05-30T11:33:10.000Z
2022-03-14T15:37:01.000Z
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 6 16:48:57 2018 @author: isaaclera """ import numpy as np YFAS4 = [11.270442, 11.270623, 11.270012, 11.270021, 11.270031, 11.269538, 11.269547, 11.268429, 11.270591, 11.269940, 11.268374, 11.270021, 11.268418, 11.268944, 11.268985, 11.269444, 11.270576, 11.270090, 11.268944, 11.269489, 11.269405, 11.268916, 11.269418, 11.270576, 11.268837, 11.269988, 11.268969, 11.270012, 11.269471, 11.270623, 11.269921, 11.269926, 11.270655, 11.269552, 11.269983, 11.270422, 11.269480, 11.268385, 11.270002, 11.269427, 11.270660, 11.270036, 11.269861, 11.270591, 11.268504, 11.270493, 11.269964, 11.269488, 11.270031, 11.270581] YAFS8 = [11.265525, 11.266339, 11.266815, 11.266855, 11.266066, 11.266793, 11.266837, 11.266059, 11.266313, 11.266814, 11.266597, 11.266853, 11.266819, 11.266840, 11.266598, 11.266553, 11.266891, 11.266056, 11.266781, 11.266583, 11.266566, 11.266300, 11.266042, 11.266070, 11.266315, 11.266567, 11.266575, 11.266032, 11.266579, 11.266357, 11.266556, 11.266026, 11.266585, 11.266874, 11.266852, 11.266317, 11.266556, 11.266585, 11.266068, 11.266295, 11.266595, 11.266322, 11.266562, 11.266813, 11.266328, 11.266572, 11.266858, 11.266055, 11.266320, 11.266334] YAFS12 = [11.265424, 11.265598, 11.265620, 11.265262, 11.265421, 11.265447, 11.265605, 11.265604, 11.265599, 11.265603, 11.265615, 11.265617, 11.265598, 11.265611, 11.265435, 11.265603, 11.265604, 11.264904, 11.265612, 11.265434, 11.265609, 11.265102, 11.265423, 11.265266, 11.265425, 11.265250, 11.265427, 11.265452, 11.265432, 11.265456, 11.265073, 11.265626, 11.265082, 11.265417, 11.265081, 11.265090, 11.265265, 11.265614, 11.265094, 11.265259, 11.265436, 11.265610, 11.265619, 11.265598, 11.265281, 11.265595, 11.265083, 11.265441, 11.265621, 11.265591] YAFS16 =[11.264981, 11.264608, 11.264860, 11.264854, 11.264883, 11.264875, 11.264857, 11.264865, 11.264863, 11.264857, 11.264860, 11.264999, 11.264733, 11.264727, 11.264738, 11.264731, 11.264991, 11.264994, 11.264860, 11.264999, 11.265000, 11.264991, 11.264983, 11.264748, 11.264866, 11.264988, 11.264999, 11.264995, 11.265004, 11.264867, 11.264997, 11.264882, 11.264995, 11.264859, 11.264741, 11.264730, 11.264740, 11.264865, 11.264717, 11.264725, 11.264734, 11.264207, 11.264864, 11.264866, 11.264613, 11.264729, 11.264743, 11.264859, 11.264850, 11.264727] iFOG4 = [31.567014877440677, 31.2096085700963, 31.572940602513007, 32.09846731216869, 31.792375613564243, 31.424621004232844, 32.04335456925575, 31.64746479672535, 31.864294659944616, 31.953031858836283, 31.494672286834362, 31.39366324536594, 31.9330291330959, 31.624966442944583, 31.351483395614157, 31.360150842367922, 31.946874707666186, 31.46681646446987, 31.725400313292727, 31.878630822078588, 31.450552934872057, 31.561696751665966, 31.760980953726737, 31.61584410211693, 31.85765037646526, 31.588118685691732, 31.538965103047765, 31.875204878212468, 32.04039882134873, 31.974034757361743, 31.825800952238026, 31.860045585250894, 31.74689429856358, 31.595326959974482, 31.567728517075153, 31.67316165064918, 31.734033481104987, 31.747852362825974, 31.697831781669656, 31.449777335693597, 31.633845469419953, 31.261946244207035, 31.512462484441933, 31.738540845661536, 31.829588718812303, 31.61758201414952, 31.755117403160344, 31.684510700310877, 31.663332103705088, 31.59112414160327, 31.736744614282188] iFOG8 = [31.824870005152544, 31.308233878305664, 31.63140903918994, 31.607322598441506, 31.797154459140017, 31.60744992813196, 31.78501672169974, 31.313537275709574, 31.556893939936433, 31.813897687958356, 31.546548077781956, 31.54571365545189, 31.7610100755262, 31.657092962150408, 31.811162052815273, 31.87786253393602, 31.733055897530978, 31.66802107358438, 31.86733314438995, 31.60201939019151, 31.856532456020354, 31.593935385166244, 31.91018849931251, 31.741217704968758, 31.71168869299696, 31.68676569379744, 31.654600237926505, 31.634309962315537, 31.78376537464453, 31.523910842992237, 31.344856954660475, 31.802250975942954, 31.49838544019412, 31.71671805331793, 31.681395720312402, 31.873480122111538, 31.842035466656807, 31.60424413680737, 31.677882323684667, 31.60865151246418, 31.605794410152583, 31.7091690924313, 31.586701523045587, 31.67643022244788, 31.65827077853141, 31.51779854040955] iFOG12 = [31.527656135037645, 31.566542875429953, 31.583142226513335, 31.7183597304816, 31.617750133241476, 31.885462498982793, 31.539747456559475, 31.657806149276933, 31.65879173721966, 31.60788495755312, 31.75726587500943, 31.712496136707237, 31.499593245681424, 31.508957387495002, 31.761966259831276, 31.698547661932345, 31.801609867084004, 31.6381053991471, 31.6363948406526, 31.67585787825071, 31.66730693446405, 31.68694412821118, 31.804783015645324, 31.597311537070794, 31.57325161001325, 31.587005485736235, 31.757460511381755, 31.693234605929035, 31.674055061553943, 31.64761152308104, 31.54117279204224, 31.54233248362793, 31.569759110769073, 31.486255820595197, 31.609553939297612, 31.85137358126173, 32.01635987575208, 31.65992722412061, 31.593333594011373, 31.692828648641054, 31.71146206016865, 31.38862252584211, 31.897913580557333, 31.830566331867267, 31.426588863591125, 31.63415020297928] iFOG16 = [31.44319878979343, 31.552334454736133, 31.682084871564953, 31.761914523261304, 31.810926207188768, 31.561097434192455, 31.779844957414298, 31.392378353361043, 31.873843235026225, 31.744376676391745, 31.625968801049037, 31.602215698677004, 31.813225776124753, 31.562337244472484, 31.696847808168243, 31.903286751887627, 31.519814582748293, 31.54366633216892, 31.58841433840935, 31.4630381792411, 31.874078090902373, 31.690547620132648, 31.59378772837774, 31.612639941031595, 31.568692958222847, 31.532164860225638, 31.726651022826655, 31.802570700370133, 31.735676103172228, 31.6413832499989, 31.59990847806666, 31.5974415806301, 31.592421292125856, 31.700416447580768, 31.76237040195895, 31.669176402727306, 31.741612269184262, 31.772092793236496, 31.49199967976739, 31.88103118845454, 31.57354311237185, 31.478132563277104, 31.847975187719452, 31.57405712508705, 31.810763820819652, 31.55968399736258] ttt = np.array(iFOG16) from scipy import stats print(stats.describe(ttt))
15.097561
35
0.794507
import numpy as np YFAS4 = [11.270442, 11.270623, 11.270012, 11.270021, 11.270031, 11.269538, 11.269547, 11.268429, 11.270591, 11.269940, 11.268374, 11.270021, 11.268418, 11.268944, 11.268985, 11.269444, 11.270576, 11.270090, 11.268944, 11.269489, 11.269405, 11.268916, 11.269418, 11.270576, 11.268837, 11.269988, 11.268969, 11.270012, 11.269471, 11.270623, 11.269921, 11.269926, 11.270655, 11.269552, 11.269983, 11.270422, 11.269480, 11.268385, 11.270002, 11.269427, 11.270660, 11.270036, 11.269861, 11.270591, 11.268504, 11.270493, 11.269964, 11.269488, 11.270031, 11.270581] YAFS8 = [11.265525, 11.266339, 11.266815, 11.266855, 11.266066, 11.266793, 11.266837, 11.266059, 11.266313, 11.266814, 11.266597, 11.266853, 11.266819, 11.266840, 11.266598, 11.266553, 11.266891, 11.266056, 11.266781, 11.266583, 11.266566, 11.266300, 11.266042, 11.266070, 11.266315, 11.266567, 11.266575, 11.266032, 11.266579, 11.266357, 11.266556, 11.266026, 11.266585, 11.266874, 11.266852, 11.266317, 11.266556, 11.266585, 11.266068, 11.266295, 11.266595, 11.266322, 11.266562, 11.266813, 11.266328, 11.266572, 11.266858, 11.266055, 11.266320, 11.266334] YAFS12 = [11.265424, 11.265598, 11.265620, 11.265262, 11.265421, 11.265447, 11.265605, 11.265604, 11.265599, 11.265603, 11.265615, 11.265617, 11.265598, 11.265611, 11.265435, 11.265603, 11.265604, 11.264904, 11.265612, 11.265434, 11.265609, 11.265102, 11.265423, 11.265266, 11.265425, 11.265250, 11.265427, 11.265452, 11.265432, 11.265456, 11.265073, 11.265626, 11.265082, 11.265417, 11.265081, 11.265090, 11.265265, 11.265614, 11.265094, 11.265259, 11.265436, 11.265610, 11.265619, 11.265598, 11.265281, 11.265595, 11.265083, 11.265441, 11.265621, 11.265591] YAFS16 =[11.264981, 11.264608, 11.264860, 11.264854, 11.264883, 11.264875, 11.264857, 11.264865, 11.264863, 11.264857, 11.264860, 11.264999, 11.264733, 11.264727, 11.264738, 11.264731, 11.264991, 11.264994, 11.264860, 11.264999, 11.265000, 11.264991, 11.264983, 11.264748, 11.264866, 11.264988, 11.264999, 11.264995, 11.265004, 11.264867, 11.264997, 11.264882, 11.264995, 11.264859, 11.264741, 11.264730, 11.264740, 11.264865, 11.264717, 11.264725, 11.264734, 11.264207, 11.264864, 11.264866, 11.264613, 11.264729, 11.264743, 11.264859, 11.264850, 11.264727] iFOG4 = [31.567014877440677, 31.2096085700963, 31.572940602513007, 32.09846731216869, 31.792375613564243, 31.424621004232844, 32.04335456925575, 31.64746479672535, 31.864294659944616, 31.953031858836283, 31.494672286834362, 31.39366324536594, 31.9330291330959, 31.624966442944583, 31.351483395614157, 31.360150842367922, 31.946874707666186, 31.46681646446987, 31.725400313292727, 31.878630822078588, 31.450552934872057, 31.561696751665966, 31.760980953726737, 31.61584410211693, 31.85765037646526, 31.588118685691732, 31.538965103047765, 31.875204878212468, 32.04039882134873, 31.974034757361743, 31.825800952238026, 31.860045585250894, 31.74689429856358, 31.595326959974482, 31.567728517075153, 31.67316165064918, 31.734033481104987, 31.747852362825974, 31.697831781669656, 31.449777335693597, 31.633845469419953, 31.261946244207035, 31.512462484441933, 31.738540845661536, 31.829588718812303, 31.61758201414952, 31.755117403160344, 31.684510700310877, 31.663332103705088, 31.59112414160327, 31.736744614282188] iFOG8 = [31.824870005152544, 31.308233878305664, 31.63140903918994, 31.607322598441506, 31.797154459140017, 31.60744992813196, 31.78501672169974, 31.313537275709574, 31.556893939936433, 31.813897687958356, 31.546548077781956, 31.54571365545189, 31.7610100755262, 31.657092962150408, 31.811162052815273, 31.87786253393602, 31.733055897530978, 31.66802107358438, 31.86733314438995, 31.60201939019151, 31.856532456020354, 31.593935385166244, 31.91018849931251, 31.741217704968758, 31.71168869299696, 31.68676569379744, 31.654600237926505, 31.634309962315537, 31.78376537464453, 31.523910842992237, 31.344856954660475, 31.802250975942954, 31.49838544019412, 31.71671805331793, 31.681395720312402, 31.873480122111538, 31.842035466656807, 31.60424413680737, 31.677882323684667, 31.60865151246418, 31.605794410152583, 31.7091690924313, 31.586701523045587, 31.67643022244788, 31.65827077853141, 31.51779854040955] iFOG12 = [31.527656135037645, 31.566542875429953, 31.583142226513335, 31.7183597304816, 31.617750133241476, 31.885462498982793, 31.539747456559475, 31.657806149276933, 31.65879173721966, 31.60788495755312, 31.75726587500943, 31.712496136707237, 31.499593245681424, 31.508957387495002, 31.761966259831276, 31.698547661932345, 31.801609867084004, 31.6381053991471, 31.6363948406526, 31.67585787825071, 31.66730693446405, 31.68694412821118, 31.804783015645324, 31.597311537070794, 31.57325161001325, 31.587005485736235, 31.757460511381755, 31.693234605929035, 31.674055061553943, 31.64761152308104, 31.54117279204224, 31.54233248362793, 31.569759110769073, 31.486255820595197, 31.609553939297612, 31.85137358126173, 32.01635987575208, 31.65992722412061, 31.593333594011373, 31.692828648641054, 31.71146206016865, 31.38862252584211, 31.897913580557333, 31.830566331867267, 31.426588863591125, 31.63415020297928] iFOG16 = [31.44319878979343, 31.552334454736133, 31.682084871564953, 31.761914523261304, 31.810926207188768, 31.561097434192455, 31.779844957414298, 31.392378353361043, 31.873843235026225, 31.744376676391745, 31.625968801049037, 31.602215698677004, 31.813225776124753, 31.562337244472484, 31.696847808168243, 31.903286751887627, 31.519814582748293, 31.54366633216892, 31.58841433840935, 31.4630381792411, 31.874078090902373, 31.690547620132648, 31.59378772837774, 31.612639941031595, 31.568692958222847, 31.532164860225638, 31.726651022826655, 31.802570700370133, 31.735676103172228, 31.6413832499989, 31.59990847806666, 31.5974415806301, 31.592421292125856, 31.700416447580768, 31.76237040195895, 31.669176402727306, 31.741612269184262, 31.772092793236496, 31.49199967976739, 31.88103118845454, 31.57354311237185, 31.478132563277104, 31.847975187719452, 31.57405712508705, 31.810763820819652, 31.55968399736258] ttt = np.array(iFOG16) from scipy import stats print(stats.describe(ttt))
true
true
1c2ceabba4122f488ae08dc526fe1f465bea18a9
1,302
py
Python
src/ucar/unidata/idv/resources/python/image.py
slclark/IDV
2d4b857b0f4b42e4cd1059bca2c8a5485baeab57
[ "CNRI-Jython" ]
48
2015-02-22T05:05:01.000Z
2022-03-14T14:23:41.000Z
src/ucar/unidata/idv/resources/python/image.py
slclark/IDV
2d4b857b0f4b42e4cd1059bca2c8a5485baeab57
[ "CNRI-Jython" ]
40
2015-02-09T19:25:29.000Z
2022-02-16T00:21:08.000Z
src/ucar/unidata/idv/resources/python/image.py
slclark/IDV
2d4b857b0f4b42e4cd1059bca2c8a5485baeab57
[ "CNRI-Jython" ]
28
2015-04-03T05:43:00.000Z
2022-01-31T23:41:20.000Z
def makeNavigatedImage (d,ulLat,ulLon,lrLat,lrLon): """This takes a image data object and a lat/lon bounding box and adds a lat/lon domain to the data. Use it in conjunction with a formula: """ from visad import Linear2DSet from visad import RealTupleType ulLat=float(ulLat) ulLon=float(ulLon) lrLat=float(lrLat) lrLon=float(lrLon) domain = d.getDomainSet() newDomain = Linear2DSet(RealTupleType.SpatialEarth2DTuple,ulLon,lrLon,domain.getX().getLength(),ulLat,lrLat,domain.getY().getLength()) return GridUtil.setSpatialDomain(d, newDomain) def combineRGB(red, green, blue): """ combine 3 images as an RGB image """ red=GridUtil.setParamType(red,makeRealType("redimage"), 0) green=GridUtil.setParamType(green,makeRealType("greenimage"), 0) blue=GridUtil.setParamType(blue,makeRealType("blueimage"), 0) return DerivedGridFactory.combineGrids((red,green,blue),1) def combineABIRGB(chP64,chP86,chP47): """ GOES16/17 combine 3 images as an RGB image """ green = 0.45*chP64 + 0.45*chP47 + 0.1*chP86 red = GridUtil.setParamType(chP64,makeRealType("redimage"), 0) blue = GridUtil.setParamType(chP47,makeRealType("blueimage"), 0) grn = GridUtil.setParamType(green,makeRealType("greenimage"), 0) return DerivedGridFactory.combineGrids((red,grn,blue),1)
37.2
136
0.745776
def makeNavigatedImage (d,ulLat,ulLon,lrLat,lrLon): from visad import Linear2DSet from visad import RealTupleType ulLat=float(ulLat) ulLon=float(ulLon) lrLat=float(lrLat) lrLon=float(lrLon) domain = d.getDomainSet() newDomain = Linear2DSet(RealTupleType.SpatialEarth2DTuple,ulLon,lrLon,domain.getX().getLength(),ulLat,lrLat,domain.getY().getLength()) return GridUtil.setSpatialDomain(d, newDomain) def combineRGB(red, green, blue): red=GridUtil.setParamType(red,makeRealType("redimage"), 0) green=GridUtil.setParamType(green,makeRealType("greenimage"), 0) blue=GridUtil.setParamType(blue,makeRealType("blueimage"), 0) return DerivedGridFactory.combineGrids((red,green,blue),1) def combineABIRGB(chP64,chP86,chP47): green = 0.45*chP64 + 0.45*chP47 + 0.1*chP86 red = GridUtil.setParamType(chP64,makeRealType("redimage"), 0) blue = GridUtil.setParamType(chP47,makeRealType("blueimage"), 0) grn = GridUtil.setParamType(green,makeRealType("greenimage"), 0) return DerivedGridFactory.combineGrids((red,grn,blue),1)
true
true
1c2ceacbabd17b9b013f7be8a942911c72c4a22a
19,513
py
Python
google/ads/googleads/v4/services/services/conversion_adjustment_upload_service/client.py
batardo/google-ads-python
a39748521847e85138fca593f3be2681352ad024
[ "Apache-2.0" ]
null
null
null
google/ads/googleads/v4/services/services/conversion_adjustment_upload_service/client.py
batardo/google-ads-python
a39748521847e85138fca593f3be2681352ad024
[ "Apache-2.0" ]
null
null
null
google/ads/googleads/v4/services/services/conversion_adjustment_upload_service/client.py
batardo/google-ads-python
a39748521847e85138fca593f3be2681352ad024
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from collections import OrderedDict from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.ads.googleads.v4.services.types import ( conversion_adjustment_upload_service, ) from google.rpc import status_pb2 as status # type: ignore from .transports.base import ( ConversionAdjustmentUploadServiceTransport, DEFAULT_CLIENT_INFO, ) from .transports.grpc import ConversionAdjustmentUploadServiceGrpcTransport class ConversionAdjustmentUploadServiceClientMeta(type): """Metaclass for the ConversionAdjustmentUploadService client. This provides class-level methods for building and retrieving support objects (e.g. transport) without polluting the client instance objects. """ _transport_registry = ( OrderedDict() ) # type: Dict[str, Type[ConversionAdjustmentUploadServiceTransport]] _transport_registry["grpc"] = ConversionAdjustmentUploadServiceGrpcTransport def get_transport_class( cls, label: str = None, ) -> Type[ConversionAdjustmentUploadServiceTransport]: """Return an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values())) class ConversionAdjustmentUploadServiceClient( metaclass=ConversionAdjustmentUploadServiceClientMeta ): """Service to upload conversion adjustments.""" @staticmethod def _get_default_mtls_endpoint(api_endpoint): """Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint mtls_endpoint_re = re.compile( r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" ) m = mtls_endpoint_re.match(api_endpoint) name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint if sandbox: return api_endpoint.replace( "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" ) return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") DEFAULT_ENDPOINT = "googleads.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials info. Args: info (dict): The service account private key info. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: ConversionAdjustmentUploadServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_info( info ) kwargs["credentials"] = credentials return cls(*args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: ConversionAdjustmentUploadServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename ) kwargs["credentials"] = credentials return cls(*args, **kwargs) from_service_account_json = from_service_account_file @property def transport(self) -> ConversionAdjustmentUploadServiceTransport: """Return the transport used by the client instance. Returns: ConversionAdjustmentUploadServiceTransport: The transport used by the client instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: """Return a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @staticmethod def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_folder_path(folder: str,) -> str: """Return a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P<folder>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_organization_path(organization: str,) -> str: """Return a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P<organization>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_project_path(project: str,) -> str: """Return a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_location_path(project: str, location: str,) -> str: """Return a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @staticmethod def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match( r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path ) return m.groupdict() if m else {} def __init__( self, *, credentials: Optional[credentials.Credentials] = None, transport: Union[ str, ConversionAdjustmentUploadServiceTransport, None ] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the conversion adjustment upload service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, ~.ConversionAdjustmentUploadServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint) and "auto" (auto switch to the default mTLS endpoint if client certificate is present, this is the default value). However, the ``api_endpoint`` property takes precedence if provided. (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used to provide client certificate for mutual TLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. use_client_cert = bool( util.strtobool( os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") ) ) ssl_credentials = None is_mtls = False if use_client_cert: if client_options.client_cert_source: import grpc # type: ignore cert, key = client_options.client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) is_mtls = True else: creds = SslCredentials() is_mtls = creds.is_mtls ssl_credentials = creds.ssl_credentials if is_mtls else None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint else: use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": api_endpoint = ( self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, ConversionAdjustmentUploadServiceTransport): # transport is a ConversionAdjustmentUploadServiceTransport instance. if credentials: raise ValueError( "When providing a transport instance, " "provide its credentials directly." ) self._transport = transport elif isinstance(transport, str): Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, host=self.DEFAULT_ENDPOINT ) else: self._transport = ConversionAdjustmentUploadServiceGrpcTransport( credentials=credentials, host=api_endpoint, ssl_channel_credentials=ssl_credentials, client_info=client_info, ) def upload_conversion_adjustments( self, request: conversion_adjustment_upload_service.UploadConversionAdjustmentsRequest = None, *, customer_id: str = None, conversion_adjustments: Sequence[ conversion_adjustment_upload_service.ConversionAdjustment ] = None, partial_failure: bool = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> conversion_adjustment_upload_service.UploadConversionAdjustmentsResponse: r"""Processes the given conversion adjustments. Args: request (:class:`google.ads.googleads.v4.services.types.UploadConversionAdjustmentsRequest`): The request object. Request message for [ConversionAdjustmentUploadService.UploadConversionAdjustments][google.ads.googleads.v4.services.ConversionAdjustmentUploadService.UploadConversionAdjustments]. customer_id (:class:`str`): Required. The ID of the customer performing the upload. This corresponds to the ``customer_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. conversion_adjustments (:class:`Sequence[google.ads.googleads.v4.services.types.ConversionAdjustment]`): Required. The conversion adjustments that are being uploaded. This corresponds to the ``conversion_adjustments`` field on the ``request`` instance; if ``request`` is provided, this should not be set. partial_failure (:class:`bool`): Required. If true, successful operations will be carried out and invalid operations will return errors. If false, all operations will be carried out in one transaction if and only if they are all valid. This should always be set to true. See https://developers.google.com/google- ads/api/docs/best-practices/partial- failures for more information about partial failure. This corresponds to the ``partial_failure`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v4.services.types.UploadConversionAdjustmentsResponse: Response message for [ConversionAdjustmentUploadService.UploadConversionAdjustments][google.ads.googleads.v4.services.ConversionAdjustmentUploadService.UploadConversionAdjustments]. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any( [customer_id, conversion_adjustments, partial_failure] ): raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a conversion_adjustment_upload_service.UploadConversionAdjustmentsRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance( request, conversion_adjustment_upload_service.UploadConversionAdjustmentsRequest, ): request = conversion_adjustment_upload_service.UploadConversionAdjustmentsRequest( request ) # If we have keyword arguments corresponding to fields on the # request, apply these. if customer_id is not None: request.customer_id = customer_id if conversion_adjustments is not None: request.conversion_adjustments = conversion_adjustments if partial_failure is not None: request.partial_failure = partial_failure # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ self._transport.upload_conversion_adjustments ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( (("customer_id", request.customer_id),) ), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response __all__ = ("ConversionAdjustmentUploadServiceClient",)
41.694444
179
0.641982
from collections import OrderedDict from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union from google.api_core import client_options as client_options_lib from google.api_core import exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials from google.auth.transport import mtls from google.auth.transport.grpc import SslCredentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account from google.ads.googleads.v4.services.types import ( conversion_adjustment_upload_service, ) from google.rpc import status_pb2 as status from .transports.base import ( ConversionAdjustmentUploadServiceTransport, DEFAULT_CLIENT_INFO, ) from .transports.grpc import ConversionAdjustmentUploadServiceGrpcTransport class ConversionAdjustmentUploadServiceClientMeta(type): _transport_registry = ( OrderedDict() ) _transport_registry["grpc"] = ConversionAdjustmentUploadServiceGrpcTransport def get_transport_class( cls, label: str = None, ) -> Type[ConversionAdjustmentUploadServiceTransport]: if label: return cls._transport_registry[label] return next(iter(cls._transport_registry.values())) class ConversionAdjustmentUploadServiceClient( metaclass=ConversionAdjustmentUploadServiceClientMeta ): @staticmethod def _get_default_mtls_endpoint(api_endpoint): if not api_endpoint: return api_endpoint mtls_endpoint_re = re.compile( r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" ) m = mtls_endpoint_re.match(api_endpoint) name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint if sandbox: return api_endpoint.replace( "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" ) return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") DEFAULT_ENDPOINT = "googleads.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( DEFAULT_ENDPOINT ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): credentials = service_account.Credentials.from_service_account_info( info ) kwargs["credentials"] = credentials return cls(*args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): credentials = service_account.Credentials.from_service_account_file( filename ) kwargs["credentials"] = credentials return cls(*args, **kwargs) from_service_account_json = from_service_account_file @property def transport(self) -> ConversionAdjustmentUploadServiceTransport: return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @staticmethod def parse_common_billing_account_path(path: str) -> Dict[str, str]: m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_folder_path(folder: str,) -> str: return "folders/{folder}".format(folder=folder,) @staticmethod def parse_common_folder_path(path: str) -> Dict[str, str]: m = re.match(r"^folders/(?P<folder>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_organization_path(organization: str,) -> str: return "organizations/{organization}".format(organization=organization,) @staticmethod def parse_common_organization_path(path: str) -> Dict[str, str]: m = re.match(r"^organizations/(?P<organization>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_project_path(project: str,) -> str: return "projects/{project}".format(project=project,) @staticmethod def parse_common_project_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P<project>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_location_path(project: str, location: str,) -> str: return "projects/{project}/locations/{location}".format( project=project, location=location, ) @staticmethod def parse_common_location_path(path: str) -> Dict[str, str]: m = re.match( r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path ) return m.groupdict() if m else {} def __init__( self, *, credentials: Optional[credentials.Credentials] = None, transport: Union[ str, ConversionAdjustmentUploadServiceTransport, None ] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: if isinstance(client_options, dict): client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = bool( util.strtobool( os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") ) ) ssl_credentials = None is_mtls = False if use_client_cert: if client_options.client_cert_source: import grpc cert, key = client_options.client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) is_mtls = True else: creds = SslCredentials() is_mtls = creds.is_mtls ssl_credentials = creds.ssl_credentials if is_mtls else None if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint else: use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": api_endpoint = ( self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) if isinstance(transport, ConversionAdjustmentUploadServiceTransport): if credentials: raise ValueError( "When providing a transport instance, " "provide its credentials directly." ) self._transport = transport elif isinstance(transport, str): Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, host=self.DEFAULT_ENDPOINT ) else: self._transport = ConversionAdjustmentUploadServiceGrpcTransport( credentials=credentials, host=api_endpoint, ssl_channel_credentials=ssl_credentials, client_info=client_info, ) def upload_conversion_adjustments( self, request: conversion_adjustment_upload_service.UploadConversionAdjustmentsRequest = None, *, customer_id: str = None, conversion_adjustments: Sequence[ conversion_adjustment_upload_service.ConversionAdjustment ] = None, partial_failure: bool = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> conversion_adjustment_upload_service.UploadConversionAdjustmentsResponse: if request is not None and any( [customer_id, conversion_adjustments, partial_failure] ): raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) if not isinstance( request, conversion_adjustment_upload_service.UploadConversionAdjustmentsRequest, ): request = conversion_adjustment_upload_service.UploadConversionAdjustmentsRequest( request ) if customer_id is not None: request.customer_id = customer_id if conversion_adjustments is not None: request.conversion_adjustments = conversion_adjustments if partial_failure is not None: request.partial_failure = partial_failure rpc = self._transport._wrapped_methods[ self._transport.upload_conversion_adjustments ] metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( (("customer_id", request.customer_id),) ), ) response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) return response __all__ = ("ConversionAdjustmentUploadServiceClient",)
true
true
1c2ceb47acf990e1976742cdc5fdc40fc0cdd355
9,879
py
Python
tools/analysis_tools/confusion_matrix.py
PhilippMarquardt/mmdetection
5979e13f7faea90f4b80079320b93585300c6a4f
[ "Apache-2.0" ]
1
2019-08-18T18:04:21.000Z
2019-08-18T18:04:21.000Z
tools/analysis_tools/confusion_matrix.py
PhilippMarquardt/mmdetection
5979e13f7faea90f4b80079320b93585300c6a4f
[ "Apache-2.0" ]
1
2022-01-06T14:58:44.000Z
2022-01-06T14:58:44.000Z
tools/analysis_tools/confusion_matrix.py
PhilippMarquardt/mmdetection
5979e13f7faea90f4b80079320b93585300c6a4f
[ "Apache-2.0" ]
1
2021-12-13T02:37:50.000Z
2021-12-13T02:37:50.000Z
import argparse import os import matplotlib.pyplot as plt import mmcv import numpy as np from matplotlib.ticker import MultipleLocator from mmcv import Config, DictAction from mmcv.ops import nms from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps from mmdet.datasets import build_dataset from mmdet.utils import update_data_root def parse_args(): parser = argparse.ArgumentParser( description='Generate confusion matrix from detection results') parser.add_argument('config', help='test config file path') parser.add_argument( 'prediction_path', help='prediction path where test .pkl result') parser.add_argument( 'save_dir', help='directory where confusion matrix will be saved') parser.add_argument( '--show', action='store_true', help='show confusion matrix') parser.add_argument( '--color-theme', default='plasma', help='theme of the matrix color map') parser.add_argument( '--score-thr', type=float, default=0.3, help='score threshold to filter detection bboxes') parser.add_argument( '--tp-iou-thr', type=float, default=0.5, help='IoU threshold to be considered as matched') parser.add_argument( '--nms-iou-thr', type=float, default=None, help='nms IoU threshold, only applied when users want to change the' 'nms IoU threshold.') parser.add_argument( '--cfg-options', nargs='+', action=DictAction, help='override some settings in the used config, the key-value pair ' 'in xxx=yyy format will be merged into config file. If the value to ' 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' 'Note that the quotation marks are necessary and that no white space ' 'is allowed.') args = parser.parse_args() return args def calculate_confusion_matrix(dataset, results, score_thr=0, nms_iou_thr=None, tp_iou_thr=0.5): """Calculate the confusion matrix. Args: dataset (Dataset): Test or val dataset. results (list[ndarray]): A list of detection results in each image. score_thr (float|optional): Score threshold to filter bboxes. Default: 0. nms_iou_thr (float|optional): nms IoU threshold, the detection results have done nms in the detector, only applied when users want to change the nms IoU threshold. Default: None. tp_iou_thr (float|optional): IoU threshold to be considered as matched. Default: 0.5. """ num_classes = len(dataset.CLASSES) confusion_matrix = np.zeros(shape=[num_classes + 1, num_classes + 1]) assert len(dataset) == len(results) prog_bar = mmcv.ProgressBar(len(results)) for idx, per_img_res in enumerate(results): if isinstance(per_img_res, tuple): res_bboxes, _ = per_img_res else: res_bboxes = per_img_res ann = dataset.get_ann_info(idx) gt_bboxes = ann['bboxes'] labels = ann['labels'] analyze_per_img_dets(confusion_matrix, gt_bboxes, labels, res_bboxes, score_thr, tp_iou_thr, nms_iou_thr) prog_bar.update() return confusion_matrix def analyze_per_img_dets(confusion_matrix, gt_bboxes, gt_labels, result, score_thr=0, tp_iou_thr=0.5, nms_iou_thr=None): """Analyze detection results on each image. Args: confusion_matrix (ndarray): The confusion matrix, has shape (num_classes + 1, num_classes + 1). gt_bboxes (ndarray): Ground truth bboxes, has shape (num_gt, 4). gt_labels (ndarray): Ground truth labels, has shape (num_gt). result (ndarray): Detection results, has shape (num_classes, num_bboxes, 5). score_thr (float): Score threshold to filter bboxes. Default: 0. tp_iou_thr (float): IoU threshold to be considered as matched. Default: 0.5. nms_iou_thr (float|optional): nms IoU threshold, the detection results have done nms in the detector, only applied when users want to change the nms IoU threshold. Default: None. """ true_positives = np.zeros_like(gt_labels) for det_label, det_bboxes in enumerate(result): if nms_iou_thr: det_bboxes, _ = nms( det_bboxes[:, :4], det_bboxes[:, -1], nms_iou_thr, score_threshold=score_thr) ious = bbox_overlaps(det_bboxes[:, :4], gt_bboxes) for i, det_bbox in enumerate(det_bboxes): score = det_bbox[4] det_match = 0 if score >= score_thr: for j, gt_label in enumerate(gt_labels): if ious[i, j] >= tp_iou_thr: det_match += 1 if gt_label == det_label: true_positives[j] += 1 # TP confusion_matrix[gt_label, det_label] += 1 if det_match == 0: # BG FP confusion_matrix[-1, det_label] += 1 for num_tp, gt_label in zip(true_positives, gt_labels): if num_tp == 0: # FN confusion_matrix[gt_label, -1] += 1 def plot_confusion_matrix(confusion_matrix, labels, save_dir=None, show=True, title='Normalized Confusion Matrix', color_theme='plasma'): """Draw confusion matrix with matplotlib. Args: confusion_matrix (ndarray): The confusion matrix. labels (list[str]): List of class names. save_dir (str|optional): If set, save the confusion matrix plot to the given path. Default: None. show (bool): Whether to show the plot. Default: True. title (str): Title of the plot. Default: `Normalized Confusion Matrix`. color_theme (str): Theme of the matrix color map. Default: `plasma`. """ # normalize the confusion matrix per_label_sums = confusion_matrix.sum(axis=1)[:, np.newaxis] confusion_matrix = \ confusion_matrix.astype(np.float32) / per_label_sums * 100 num_classes = len(labels) fig, ax = plt.subplots( figsize=(0.5 * num_classes, 0.5 * num_classes * 0.8), dpi=180) cmap = plt.get_cmap(color_theme) im = ax.imshow(confusion_matrix, cmap=cmap) plt.colorbar(mappable=im, ax=ax) title_font = {'weight': 'bold', 'size': 12} ax.set_title(title, fontdict=title_font) label_font = {'size': 10} plt.ylabel('Ground Truth Label', fontdict=label_font) plt.xlabel('Prediction Label', fontdict=label_font) # draw locator xmajor_locator = MultipleLocator(1) xminor_locator = MultipleLocator(0.5) ax.xaxis.set_major_locator(xmajor_locator) ax.xaxis.set_minor_locator(xminor_locator) ymajor_locator = MultipleLocator(1) yminor_locator = MultipleLocator(0.5) ax.yaxis.set_major_locator(ymajor_locator) ax.yaxis.set_minor_locator(yminor_locator) # draw grid ax.grid(True, which='minor', linestyle='-') # draw label ax.set_xticks(np.arange(num_classes)) ax.set_yticks(np.arange(num_classes)) ax.set_xticklabels(labels) ax.set_yticklabels(labels) ax.tick_params( axis='x', bottom=False, top=True, labelbottom=False, labeltop=True) plt.setp( ax.get_xticklabels(), rotation=45, ha='left', rotation_mode='anchor') # draw confution matrix value for i in range(num_classes): for j in range(num_classes): ax.text( j, i, '{}%'.format( int(confusion_matrix[ i, j]) if not np.isnan(confusion_matrix[i, j]) else -1), ha='center', va='center', color='w', size=7) ax.set_ylim(len(confusion_matrix) - 0.5, -0.5) # matplotlib>3.1.1 fig.tight_layout() if save_dir is not None: plt.savefig( os.path.join(save_dir, 'confusion_matrix.png'), format='png') if show: plt.show() def main(): args = parse_args() cfg = Config.fromfile(args.config) # update data root according to MMDET_DATASETS update_data_root(cfg) if args.cfg_options is not None: cfg.merge_from_dict(args.cfg_options) results = mmcv.load(args.prediction_path) assert isinstance(results, list) if isinstance(results[0], list): pass elif isinstance(results[0], tuple): results = [result[0] for result in results] else: raise TypeError('invalid type of prediction results') if isinstance(cfg.data.test, dict): cfg.data.test.test_mode = True elif isinstance(cfg.data.test, list): for ds_cfg in cfg.data.test: ds_cfg.test_mode = True dataset = build_dataset(cfg.data.test) confusion_matrix = calculate_confusion_matrix(dataset, results, args.score_thr, args.nms_iou_thr, args.tp_iou_thr) plot_confusion_matrix( confusion_matrix, dataset.CLASSES + ('background', ), save_dir=args.save_dir, show=args.show, color_theme=args.color_theme) if __name__ == '__main__': main()
36.453875
79
0.596012
import argparse import os import matplotlib.pyplot as plt import mmcv import numpy as np from matplotlib.ticker import MultipleLocator from mmcv import Config, DictAction from mmcv.ops import nms from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps from mmdet.datasets import build_dataset from mmdet.utils import update_data_root def parse_args(): parser = argparse.ArgumentParser( description='Generate confusion matrix from detection results') parser.add_argument('config', help='test config file path') parser.add_argument( 'prediction_path', help='prediction path where test .pkl result') parser.add_argument( 'save_dir', help='directory where confusion matrix will be saved') parser.add_argument( '--show', action='store_true', help='show confusion matrix') parser.add_argument( '--color-theme', default='plasma', help='theme of the matrix color map') parser.add_argument( '--score-thr', type=float, default=0.3, help='score threshold to filter detection bboxes') parser.add_argument( '--tp-iou-thr', type=float, default=0.5, help='IoU threshold to be considered as matched') parser.add_argument( '--nms-iou-thr', type=float, default=None, help='nms IoU threshold, only applied when users want to change the' 'nms IoU threshold.') parser.add_argument( '--cfg-options', nargs='+', action=DictAction, help='override some settings in the used config, the key-value pair ' 'in xxx=yyy format will be merged into config file. If the value to ' 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' 'Note that the quotation marks are necessary and that no white space ' 'is allowed.') args = parser.parse_args() return args def calculate_confusion_matrix(dataset, results, score_thr=0, nms_iou_thr=None, tp_iou_thr=0.5): num_classes = len(dataset.CLASSES) confusion_matrix = np.zeros(shape=[num_classes + 1, num_classes + 1]) assert len(dataset) == len(results) prog_bar = mmcv.ProgressBar(len(results)) for idx, per_img_res in enumerate(results): if isinstance(per_img_res, tuple): res_bboxes, _ = per_img_res else: res_bboxes = per_img_res ann = dataset.get_ann_info(idx) gt_bboxes = ann['bboxes'] labels = ann['labels'] analyze_per_img_dets(confusion_matrix, gt_bboxes, labels, res_bboxes, score_thr, tp_iou_thr, nms_iou_thr) prog_bar.update() return confusion_matrix def analyze_per_img_dets(confusion_matrix, gt_bboxes, gt_labels, result, score_thr=0, tp_iou_thr=0.5, nms_iou_thr=None): true_positives = np.zeros_like(gt_labels) for det_label, det_bboxes in enumerate(result): if nms_iou_thr: det_bboxes, _ = nms( det_bboxes[:, :4], det_bboxes[:, -1], nms_iou_thr, score_threshold=score_thr) ious = bbox_overlaps(det_bboxes[:, :4], gt_bboxes) for i, det_bbox in enumerate(det_bboxes): score = det_bbox[4] det_match = 0 if score >= score_thr: for j, gt_label in enumerate(gt_labels): if ious[i, j] >= tp_iou_thr: det_match += 1 if gt_label == det_label: true_positives[j] += 1 confusion_matrix[gt_label, det_label] += 1 if det_match == 0: confusion_matrix[-1, det_label] += 1 for num_tp, gt_label in zip(true_positives, gt_labels): if num_tp == 0: confusion_matrix[gt_label, -1] += 1 def plot_confusion_matrix(confusion_matrix, labels, save_dir=None, show=True, title='Normalized Confusion Matrix', color_theme='plasma'): per_label_sums = confusion_matrix.sum(axis=1)[:, np.newaxis] confusion_matrix = \ confusion_matrix.astype(np.float32) / per_label_sums * 100 num_classes = len(labels) fig, ax = plt.subplots( figsize=(0.5 * num_classes, 0.5 * num_classes * 0.8), dpi=180) cmap = plt.get_cmap(color_theme) im = ax.imshow(confusion_matrix, cmap=cmap) plt.colorbar(mappable=im, ax=ax) title_font = {'weight': 'bold', 'size': 12} ax.set_title(title, fontdict=title_font) label_font = {'size': 10} plt.ylabel('Ground Truth Label', fontdict=label_font) plt.xlabel('Prediction Label', fontdict=label_font) xmajor_locator = MultipleLocator(1) xminor_locator = MultipleLocator(0.5) ax.xaxis.set_major_locator(xmajor_locator) ax.xaxis.set_minor_locator(xminor_locator) ymajor_locator = MultipleLocator(1) yminor_locator = MultipleLocator(0.5) ax.yaxis.set_major_locator(ymajor_locator) ax.yaxis.set_minor_locator(yminor_locator) ax.grid(True, which='minor', linestyle='-') ax.set_xticks(np.arange(num_classes)) ax.set_yticks(np.arange(num_classes)) ax.set_xticklabels(labels) ax.set_yticklabels(labels) ax.tick_params( axis='x', bottom=False, top=True, labelbottom=False, labeltop=True) plt.setp( ax.get_xticklabels(), rotation=45, ha='left', rotation_mode='anchor') for i in range(num_classes): for j in range(num_classes): ax.text( j, i, '{}%'.format( int(confusion_matrix[ i, j]) if not np.isnan(confusion_matrix[i, j]) else -1), ha='center', va='center', color='w', size=7) ax.set_ylim(len(confusion_matrix) - 0.5, -0.5) fig.tight_layout() if save_dir is not None: plt.savefig( os.path.join(save_dir, 'confusion_matrix.png'), format='png') if show: plt.show() def main(): args = parse_args() cfg = Config.fromfile(args.config) update_data_root(cfg) if args.cfg_options is not None: cfg.merge_from_dict(args.cfg_options) results = mmcv.load(args.prediction_path) assert isinstance(results, list) if isinstance(results[0], list): pass elif isinstance(results[0], tuple): results = [result[0] for result in results] else: raise TypeError('invalid type of prediction results') if isinstance(cfg.data.test, dict): cfg.data.test.test_mode = True elif isinstance(cfg.data.test, list): for ds_cfg in cfg.data.test: ds_cfg.test_mode = True dataset = build_dataset(cfg.data.test) confusion_matrix = calculate_confusion_matrix(dataset, results, args.score_thr, args.nms_iou_thr, args.tp_iou_thr) plot_confusion_matrix( confusion_matrix, dataset.CLASSES + ('background', ), save_dir=args.save_dir, show=args.show, color_theme=args.color_theme) if __name__ == '__main__': main()
true
true
1c2cebd45c1f366750dccf8309f4ff80526353ad
129
py
Python
mfi_customization/mfi/patch/set_issue_attachment.py
anuradha-88/mfi_customization
eb19ed43d0178b461f1d9914d2f7b6b55c9d030c
[ "MIT" ]
null
null
null
mfi_customization/mfi/patch/set_issue_attachment.py
anuradha-88/mfi_customization
eb19ed43d0178b461f1d9914d2f7b6b55c9d030c
[ "MIT" ]
null
null
null
mfi_customization/mfi/patch/set_issue_attachment.py
anuradha-88/mfi_customization
eb19ed43d0178b461f1d9914d2f7b6b55c9d030c
[ "MIT" ]
null
null
null
import frappe def execute(): for d in frappe.get_all("Task"): task=frappe.get_doc("Task",d.name) task.save()
21.5
42
0.612403
import frappe def execute(): for d in frappe.get_all("Task"): task=frappe.get_doc("Task",d.name) task.save()
true
true
1c2cecb6c89ff9713fb2f8396b5b557db3191585
9,196
py
Python
tests/python/pants_test/backend/jvm/tasks/jvm_compile/java/test_cache_compile_integration.py
lahosken/pants
1b0340987c9b2eab9411416803c75b80736716e4
[ "Apache-2.0" ]
1
2021-11-11T14:04:24.000Z
2021-11-11T14:04:24.000Z
tests/python/pants_test/backend/jvm/tasks/jvm_compile/java/test_cache_compile_integration.py
lahosken/pants
1b0340987c9b2eab9411416803c75b80736716e4
[ "Apache-2.0" ]
null
null
null
tests/python/pants_test/backend/jvm/tasks/jvm_compile/java/test_cache_compile_integration.py
lahosken/pants
1b0340987c9b2eab9411416803c75b80736716e4
[ "Apache-2.0" ]
1
2021-11-11T14:04:12.000Z
2021-11-11T14:04:12.000Z
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from collections import namedtuple from textwrap import dedent from pants.backend.jvm.tasks.jvm_compile.zinc.zinc_compile import ZincCompile from pants.base.build_environment import get_buildroot from pants.util.contextutil import temporary_dir from pants.util.dirutil import safe_mkdir, safe_open, safe_rmtree from pants_test.backend.jvm.tasks.jvm_compile.base_compile_integration_test import BaseCompileIT class Compile(namedtuple('Compile', ['srcfiles', 'config', 'artifact_count'])): pass class CacheCompileIntegrationTest(BaseCompileIT): def run_compile(self, target_spec, config, workdir): args = ['compile', target_spec] pants_run = self.run_pants_with_workdir(args, workdir, config) self.assert_success(pants_run) def create_file(self, path, value): with safe_open(path, 'w') as f: f.write(value) def test_transitive_invalid_target_is_dep(self): with temporary_dir() as cache_dir, \ temporary_dir(root_dir=get_buildroot()) as src_dir: config = { 'cache.compile.zinc': {'write_to': [cache_dir], 'read_from': [cache_dir]}, 'compile.zinc': {'incremental_caching': True}, 'java': {'strict_deps': False}, } target_dir = os.path.join(src_dir, 'org', 'pantsbuild', 'cachetest') a_srcfile = os.path.join(target_dir, 'A.java') b_srcfile = os.path.join(target_dir, 'B.java') c_srcfile = os.path.join(target_dir, 'C.java') buildfile = os.path.join(target_dir, 'BUILD') self.create_file(a_srcfile, dedent("""package org.pantsbuild.cachetest; class A {} """)) self.create_file(b_srcfile, dedent("""package org.pantsbuild.cachetest; class B { A a; } """)) self.create_file(c_srcfile, dedent("""package org.pantsbuild.cachetest; class C { A a; } """)) self.create_file(buildfile, dedent(""" java_library(name='a', sources=['A.java'] ) java_library(name='b', sources=['B.java'], dependencies=[':a'] ) java_library(name='c', sources=['C.java'], dependencies=[':b'] ) """)) c_spec = os.path.join(os.path.basename(src_dir), 'org', 'pantsbuild', 'cachetest:c') with self.temporary_workdir() as workdir: self.run_compile(c_spec, config, workdir) # clean workdir # rm cache entries for a and b cache_dir_entries = os.listdir(os.path.join(cache_dir)) zinc_dir = os.path.join(cache_dir, cache_dir_entries[0]) c_or_a_cache_dirs = [subdir for subdir in os.listdir(zinc_dir) if subdir.endswith('cachetest.a') or subdir.endswith('cachetest.c')] for subdir in c_or_a_cache_dirs: safe_rmtree(os.path.join(zinc_dir, subdir)) # run compile with self.temporary_workdir() as workdir: self.run_compile(c_spec, config, workdir) def test_stale_artifacts_rmd_when_cache_used_with_zinc(self): with temporary_dir() as cache_dir, \ self.temporary_workdir() as workdir, \ temporary_dir(root_dir=get_buildroot()) as src_dir: config = { 'cache.compile.zinc': {'write_to': [cache_dir], 'read_from': [cache_dir]}, 'compile.zinc': {'incremental_caching': True }, } srcfile = os.path.join(src_dir, 'org', 'pantsbuild', 'cachetest', 'A.java') buildfile = os.path.join(src_dir, 'org', 'pantsbuild', 'cachetest', 'BUILD') self.create_file(srcfile, dedent("""package org.pantsbuild.cachetest; class A {} class Main {}""")) self.create_file(buildfile, dedent("""java_library(name='cachetest', sources=['A.java'] )""")) cachetest_spec = os.path.join(os.path.basename(src_dir), 'org', 'pantsbuild', 'cachetest:cachetest') # Caches values A.class, Main.class self.run_compile(cachetest_spec, config, workdir) self.create_file(srcfile, dedent("""package org.pantsbuild.cachetest; class A {} class NotMain {}""")) # Caches values A.class, NotMain.class and leaves them on the filesystem self.run_compile(cachetest_spec, config, workdir) self.create_file(srcfile, dedent("""package org.pantsbuild.cachetest; class A {} class Main {}""")) # Should cause NotMain.class to be removed self.run_compile(cachetest_spec, config, workdir) root = os.path.join(workdir, 'compile', 'zinc') task_versions = [p for p in os.listdir(root) if p != 'current'] self.assertEqual(len(task_versions), 1, 'Expected 1 task version.') versioned_root = os.path.join(root, task_versions[0]) per_target_dirs = os.listdir(versioned_root) self.assertEqual(len(per_target_dirs), 1, 'Expected 1 target.') target_workdir_root = os.path.join(versioned_root, per_target_dirs[0]) target_workdirs = os.listdir(target_workdir_root) self.assertEqual(len(target_workdirs), 3, 'Expected 3 workdirs (current, and two versioned).') self.assertIn('current', target_workdirs) def classfiles(d): cd = os.path.join(target_workdir_root, d, 'classes', 'org', 'pantsbuild', 'cachetest') return sorted(os.listdir(cd)) # One workdir should contain NotMain, and the other should contain Main. self.assertEquals(sorted(classfiles(w) for w in target_workdirs if w != 'current'), sorted([['A.class', 'Main.class'], ['A.class', 'NotMain.class']])) def test_incremental_caching(self): """Tests that with --no-incremental-caching, we don't write incremental artifacts.""" srcfile = 'A.java' def config(incremental_caching): return { 'compile.zinc': {'incremental_caching': incremental_caching} } self._do_test_caching( Compile({srcfile: "class A {}"}, config(False), 1), Compile({srcfile: "final class A {}"}, config(False), 1), Compile({srcfile: "public final class A {}"}, config(True), 2), ) def test_incremental(self): """Tests that with --no-incremental and --no-incremental-caching, we always write artifacts.""" srcfile = 'A.java' config = {'compile.zinc': {'incremental': False, 'incremental_caching': False}} self._do_test_caching( Compile({srcfile: "class A {}"}, config, 1), Compile({srcfile: "final class A {}"}, config, 2), Compile({srcfile: "public final class A {}"}, config, 3), ) def _do_test_caching(self, *compiles): """Tests that the given compiles within the same workspace produce the given artifact counts.""" with temporary_dir() as cache_dir, \ self.temporary_workdir() as workdir, \ temporary_dir(root_dir=get_buildroot()) as src_dir: def complete_config(config): # Clone the input config and add cache settings. cache_settings = {'write_to': [cache_dir], 'read_from': [cache_dir]} return dict(config.items() + [('cache.compile.zinc', cache_settings)]) buildfile = os.path.join(src_dir, 'BUILD') spec = os.path.join(src_dir, ':cachetest') artifact_dir = os.path.join(cache_dir, ZincCompile.stable_name(), '{}.cachetest'.format(os.path.basename(src_dir))) for c in compiles: # Clear the src directory and recreate the files. safe_mkdir(src_dir, clean=True) self.create_file(buildfile, """java_library(name='cachetest', sources=rglobs('*.java', '*.scala'))""") for name, content in c.srcfiles.items(): self.create_file(os.path.join(src_dir, name), content) # Compile, and confirm that we have the right count of artifacts. self.run_compile(spec, complete_config(c.config), workdir) self.assertEquals(c.artifact_count, len(os.listdir(artifact_dir))) class CacheCompileIntegrationWithZjarsTest(CacheCompileIntegrationTest): _EXTRA_TASK_ARGS = ['--compile-zinc-use-classpath-jars']
41.053571
100
0.591453
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from collections import namedtuple from textwrap import dedent from pants.backend.jvm.tasks.jvm_compile.zinc.zinc_compile import ZincCompile from pants.base.build_environment import get_buildroot from pants.util.contextutil import temporary_dir from pants.util.dirutil import safe_mkdir, safe_open, safe_rmtree from pants_test.backend.jvm.tasks.jvm_compile.base_compile_integration_test import BaseCompileIT class Compile(namedtuple('Compile', ['srcfiles', 'config', 'artifact_count'])): pass class CacheCompileIntegrationTest(BaseCompileIT): def run_compile(self, target_spec, config, workdir): args = ['compile', target_spec] pants_run = self.run_pants_with_workdir(args, workdir, config) self.assert_success(pants_run) def create_file(self, path, value): with safe_open(path, 'w') as f: f.write(value) def test_transitive_invalid_target_is_dep(self): with temporary_dir() as cache_dir, \ temporary_dir(root_dir=get_buildroot()) as src_dir: config = { 'cache.compile.zinc': {'write_to': [cache_dir], 'read_from': [cache_dir]}, 'compile.zinc': {'incremental_caching': True}, 'java': {'strict_deps': False}, } target_dir = os.path.join(src_dir, 'org', 'pantsbuild', 'cachetest') a_srcfile = os.path.join(target_dir, 'A.java') b_srcfile = os.path.join(target_dir, 'B.java') c_srcfile = os.path.join(target_dir, 'C.java') buildfile = os.path.join(target_dir, 'BUILD') self.create_file(a_srcfile, dedent("""package org.pantsbuild.cachetest; class A {} """)) self.create_file(b_srcfile, dedent("""package org.pantsbuild.cachetest; class B { A a; } """)) self.create_file(c_srcfile, dedent("""package org.pantsbuild.cachetest; class C { A a; } """)) self.create_file(buildfile, dedent(""" java_library(name='a', sources=['A.java'] ) java_library(name='b', sources=['B.java'], dependencies=[':a'] ) java_library(name='c', sources=['C.java'], dependencies=[':b'] ) """)) c_spec = os.path.join(os.path.basename(src_dir), 'org', 'pantsbuild', 'cachetest:c') with self.temporary_workdir() as workdir: self.run_compile(c_spec, config, workdir) cache_dir_entries = os.listdir(os.path.join(cache_dir)) zinc_dir = os.path.join(cache_dir, cache_dir_entries[0]) c_or_a_cache_dirs = [subdir for subdir in os.listdir(zinc_dir) if subdir.endswith('cachetest.a') or subdir.endswith('cachetest.c')] for subdir in c_or_a_cache_dirs: safe_rmtree(os.path.join(zinc_dir, subdir)) with self.temporary_workdir() as workdir: self.run_compile(c_spec, config, workdir) def test_stale_artifacts_rmd_when_cache_used_with_zinc(self): with temporary_dir() as cache_dir, \ self.temporary_workdir() as workdir, \ temporary_dir(root_dir=get_buildroot()) as src_dir: config = { 'cache.compile.zinc': {'write_to': [cache_dir], 'read_from': [cache_dir]}, 'compile.zinc': {'incremental_caching': True }, } srcfile = os.path.join(src_dir, 'org', 'pantsbuild', 'cachetest', 'A.java') buildfile = os.path.join(src_dir, 'org', 'pantsbuild', 'cachetest', 'BUILD') self.create_file(srcfile, dedent("""package org.pantsbuild.cachetest; class A {} class Main {}""")) self.create_file(buildfile, dedent("""java_library(name='cachetest', sources=['A.java'] )""")) cachetest_spec = os.path.join(os.path.basename(src_dir), 'org', 'pantsbuild', 'cachetest:cachetest') self.run_compile(cachetest_spec, config, workdir) self.create_file(srcfile, dedent("""package org.pantsbuild.cachetest; class A {} class NotMain {}""")) self.run_compile(cachetest_spec, config, workdir) self.create_file(srcfile, dedent("""package org.pantsbuild.cachetest; class A {} class Main {}""")) self.run_compile(cachetest_spec, config, workdir) root = os.path.join(workdir, 'compile', 'zinc') task_versions = [p for p in os.listdir(root) if p != 'current'] self.assertEqual(len(task_versions), 1, 'Expected 1 task version.') versioned_root = os.path.join(root, task_versions[0]) per_target_dirs = os.listdir(versioned_root) self.assertEqual(len(per_target_dirs), 1, 'Expected 1 target.') target_workdir_root = os.path.join(versioned_root, per_target_dirs[0]) target_workdirs = os.listdir(target_workdir_root) self.assertEqual(len(target_workdirs), 3, 'Expected 3 workdirs (current, and two versioned).') self.assertIn('current', target_workdirs) def classfiles(d): cd = os.path.join(target_workdir_root, d, 'classes', 'org', 'pantsbuild', 'cachetest') return sorted(os.listdir(cd)) self.assertEquals(sorted(classfiles(w) for w in target_workdirs if w != 'current'), sorted([['A.class', 'Main.class'], ['A.class', 'NotMain.class']])) def test_incremental_caching(self): srcfile = 'A.java' def config(incremental_caching): return { 'compile.zinc': {'incremental_caching': incremental_caching} } self._do_test_caching( Compile({srcfile: "class A {}"}, config(False), 1), Compile({srcfile: "final class A {}"}, config(False), 1), Compile({srcfile: "public final class A {}"}, config(True), 2), ) def test_incremental(self): srcfile = 'A.java' config = {'compile.zinc': {'incremental': False, 'incremental_caching': False}} self._do_test_caching( Compile({srcfile: "class A {}"}, config, 1), Compile({srcfile: "final class A {}"}, config, 2), Compile({srcfile: "public final class A {}"}, config, 3), ) def _do_test_caching(self, *compiles): with temporary_dir() as cache_dir, \ self.temporary_workdir() as workdir, \ temporary_dir(root_dir=get_buildroot()) as src_dir: def complete_config(config): cache_settings = {'write_to': [cache_dir], 'read_from': [cache_dir]} return dict(config.items() + [('cache.compile.zinc', cache_settings)]) buildfile = os.path.join(src_dir, 'BUILD') spec = os.path.join(src_dir, ':cachetest') artifact_dir = os.path.join(cache_dir, ZincCompile.stable_name(), '{}.cachetest'.format(os.path.basename(src_dir))) for c in compiles: safe_mkdir(src_dir, clean=True) self.create_file(buildfile, """java_library(name='cachetest', sources=rglobs('*.java', '*.scala'))""") for name, content in c.srcfiles.items(): self.create_file(os.path.join(src_dir, name), content) self.run_compile(spec, complete_config(c.config), workdir) self.assertEquals(c.artifact_count, len(os.listdir(artifact_dir))) class CacheCompileIntegrationWithZjarsTest(CacheCompileIntegrationTest): _EXTRA_TASK_ARGS = ['--compile-zinc-use-classpath-jars']
true
true
1c2cee02a210635e110ba3cbe538ddc3b51710dd
6,958
py
Python
os_vif/objects/vif.py
mail2nsrajesh/os-vif
6a9017d1dcf2a0a4ab8bf35f39d4bfb7cb56027d
[ "Apache-2.0" ]
null
null
null
os_vif/objects/vif.py
mail2nsrajesh/os-vif
6a9017d1dcf2a0a4ab8bf35f39d4bfb7cb56027d
[ "Apache-2.0" ]
null
null
null
os_vif/objects/vif.py
mail2nsrajesh/os-vif
6a9017d1dcf2a0a4ab8bf35f39d4bfb7cb56027d
[ "Apache-2.0" ]
null
null
null
# 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 oslo_utils import versionutils from oslo_versionedobjects import base from oslo_versionedobjects import fields from os_vif.objects import base as osv_base from os_vif.objects import fields as osv_fields @base.VersionedObjectRegistry.register class VIFBase(osv_base.VersionedObject, base.ComparableVersionedObject): """Represents a virtual network interface.""" # Version 1.0: Initial version VERSION = '1.0' fields = { # Unique identifier of the VIF port 'id': fields.UUIDField(), # The guest MAC address 'address': fields.MACAddressField(nullable=True), # The network to which the VIF is connected 'network': fields.ObjectField('Network', nullable=True), # Name of the registered os_vif plugin 'plugin': fields.StringField(), # Whether the VIF is initially online 'active': fields.BooleanField(default=True), # Whether the host VIF should be preserved on unplug 'preserve_on_delete': fields.BooleanField(default=False), # Whether the network service has provided traffic filtering 'has_traffic_filtering': fields.BooleanField(default=False), # The virtual port profile metadata 'port_profile': fields.ObjectField('VIFPortProfileBase', subclasses=True) } @base.VersionedObjectRegistry.register class VIFGeneric(VIFBase): # For libvirt drivers, this maps to type="ethernet" which # just implies a bare TAP device, all setup delegated to # the plugin VERSION = '1.0' fields = { # Name of the device to create 'vif_name': fields.StringField() } @base.VersionedObjectRegistry.register class VIFBridge(VIFBase): # For libvirt drivers, this maps to type='bridge' VERSION = '1.0' fields = { # Name of the virtual device to create 'vif_name': fields.StringField(), # Name of the physical device to connect to (eg br0) 'bridge_name': fields.StringField(), } @base.VersionedObjectRegistry.register class VIFOpenVSwitch(VIFBase): # For libvirt drivers, this also maps to type='bridge' VERSION = '1.0' fields = { # Name of the virtual device to create 'vif_name': fields.StringField(), # Name of the physical device to connect to (eg br0) 'bridge_name': fields.StringField(), } @base.VersionedObjectRegistry.register class VIFDirect(VIFBase): # For libvirt drivers, this maps to type='direct' VERSION = '1.0' fields = { # Name of the device to create 'vif_name': fields.StringField(), # The PCI address of the host device 'dev_address': fields.PCIAddressField(), # Port connection mode 'mode': osv_fields.VIFDirectModeField(), # The VLAN device name to use 'vlan_name': fields.StringField(), } @base.VersionedObjectRegistry.register class VIFVHostUser(VIFBase): # For libvirt drivers, this maps to type='vhostuser' VERSION = '1.1' fields = { # Name of the vhostuser port to create 'vif_name': fields.StringField(), # UNIX socket path 'path': fields.StringField(), # UNIX socket access permissions 'mode': osv_fields.VIFVHostUserModeField(), } def obj_make_compatible(self, primitive, target_version): super(VIFVHostUser, self).obj_make_compatible(primitive, target_version) target_version = versionutils.convert_version_to_tuple(target_version) if target_version < (1, 1) and 'vif_name' in primitive: del primitive['vif_name'] @base.VersionedObjectRegistry.register class VIFHostDevice(VIFBase): # For libvirt drivers, this maps to type='hostdev' VERSION = '1.0' fields = { # The type of the host device. # Valid values are ethernet and generic. # Ethernet is <interface type='hostdev'> # Generic is <hostdev mode='subsystem' type='pci'> 'dev_type': osv_fields.VIFHostDeviceDevTypeField(), # The PCI address of the host device 'dev_address': fields.PCIAddressField(), } @base.VersionedObjectRegistry.register class VIFPortProfileBase(osv_base.VersionedObject, base.ComparableVersionedObject): # Base class for all types of port profile VERSION = '1.0' @base.VersionedObjectRegistry.register class VIFPortProfileOpenVSwitch(VIFPortProfileBase): # Port profile info for OpenVSwitch networks VERSION = '1.0' fields = { 'interface_id': fields.UUIDField(), 'profile_id': fields.StringField(), } @base.VersionedObjectRegistry.register class VIFPortProfileFPOpenVSwitch(VIFPortProfileOpenVSwitch): # Port profile info for OpenVSwitch networks using fastpath VERSION = '1.0' fields = { # Name of the bridge (managed by fast path) to connect to 'bridge_name': fields.StringField(), # Whether the OpenVSwitch network is using hybrid plug 'hybrid_plug': fields.BooleanField(default=False), } @base.VersionedObjectRegistry.register class VIFPortProfileFPBridge(VIFPortProfileBase): # Port profile info for LinuxBridge networks using fastpath VERSION = '1.0' fields = { # Name of the bridge (managed by fast path) to connect to 'bridge_name': fields.StringField(), } @base.VersionedObjectRegistry.register class VIFPortProfileFPTap(VIFPortProfileBase): # Port profile info for Calico networks using fastpath VERSION = '1.0' fields = { # The mac address of the host vhostuser port 'mac_address': fields.MACAddressField(nullable=True), } @base.VersionedObjectRegistry.register class VIFPortProfile8021Qbg(VIFPortProfileBase): # Port profile info for VEPA 802.1qbg networks VERSION = '1.0' fields = { 'manager_id': fields.IntegerField(), 'type_id': fields.IntegerField(), 'type_id_version': fields.IntegerField(), 'instance_id': fields.UUIDField(), } @base.VersionedObjectRegistry.register class VIFPortProfile8021Qbh(VIFPortProfileBase): # Port profile info for VEPA 802.1qbh networks VERSION = '1.0' fields = { 'profile_id': fields.StringField() }
28.4
78
0.672032
from oslo_utils import versionutils from oslo_versionedobjects import base from oslo_versionedobjects import fields from os_vif.objects import base as osv_base from os_vif.objects import fields as osv_fields @base.VersionedObjectRegistry.register class VIFBase(osv_base.VersionedObject, base.ComparableVersionedObject): VERSION = '1.0' fields = { 'id': fields.UUIDField(), 'address': fields.MACAddressField(nullable=True), 'network': fields.ObjectField('Network', nullable=True), 'plugin': fields.StringField(), 'active': fields.BooleanField(default=True), 'preserve_on_delete': fields.BooleanField(default=False), 'has_traffic_filtering': fields.BooleanField(default=False), 'port_profile': fields.ObjectField('VIFPortProfileBase', subclasses=True) } @base.VersionedObjectRegistry.register class VIFGeneric(VIFBase): VERSION = '1.0' fields = { 'vif_name': fields.StringField() } @base.VersionedObjectRegistry.register class VIFBridge(VIFBase): VERSION = '1.0' fields = { 'vif_name': fields.StringField(), 'bridge_name': fields.StringField(), } @base.VersionedObjectRegistry.register class VIFOpenVSwitch(VIFBase): VERSION = '1.0' fields = { 'vif_name': fields.StringField(), 'bridge_name': fields.StringField(), } @base.VersionedObjectRegistry.register class VIFDirect(VIFBase): VERSION = '1.0' fields = { 'vif_name': fields.StringField(), 'dev_address': fields.PCIAddressField(), 'mode': osv_fields.VIFDirectModeField(), 'vlan_name': fields.StringField(), } @base.VersionedObjectRegistry.register class VIFVHostUser(VIFBase): VERSION = '1.1' fields = { 'vif_name': fields.StringField(), 'path': fields.StringField(), 'mode': osv_fields.VIFVHostUserModeField(), } def obj_make_compatible(self, primitive, target_version): super(VIFVHostUser, self).obj_make_compatible(primitive, target_version) target_version = versionutils.convert_version_to_tuple(target_version) if target_version < (1, 1) and 'vif_name' in primitive: del primitive['vif_name'] @base.VersionedObjectRegistry.register class VIFHostDevice(VIFBase): VERSION = '1.0' fields = { 'dev_type': osv_fields.VIFHostDeviceDevTypeField(), 'dev_address': fields.PCIAddressField(), } @base.VersionedObjectRegistry.register class VIFPortProfileBase(osv_base.VersionedObject, base.ComparableVersionedObject): VERSION = '1.0' @base.VersionedObjectRegistry.register class VIFPortProfileOpenVSwitch(VIFPortProfileBase): VERSION = '1.0' fields = { 'interface_id': fields.UUIDField(), 'profile_id': fields.StringField(), } @base.VersionedObjectRegistry.register class VIFPortProfileFPOpenVSwitch(VIFPortProfileOpenVSwitch): VERSION = '1.0' fields = { 'bridge_name': fields.StringField(), 'hybrid_plug': fields.BooleanField(default=False), } @base.VersionedObjectRegistry.register class VIFPortProfileFPBridge(VIFPortProfileBase): VERSION = '1.0' fields = { 'bridge_name': fields.StringField(), } @base.VersionedObjectRegistry.register class VIFPortProfileFPTap(VIFPortProfileBase): VERSION = '1.0' fields = { 'mac_address': fields.MACAddressField(nullable=True), } @base.VersionedObjectRegistry.register class VIFPortProfile8021Qbg(VIFPortProfileBase): VERSION = '1.0' fields = { 'manager_id': fields.IntegerField(), 'type_id': fields.IntegerField(), 'type_id_version': fields.IntegerField(), 'instance_id': fields.UUIDField(), } @base.VersionedObjectRegistry.register class VIFPortProfile8021Qbh(VIFPortProfileBase): VERSION = '1.0' fields = { 'profile_id': fields.StringField() }
true
true
1c2cee8f013fa85696748e87d47cd717f7fc700c
328
py
Python
posts/migrations/0006_remove_like_likenumber.py
Joe-Sin7h/melodiam
756996464a79a1e2066004d2bcc05c10fbbf3e8e
[ "MIT" ]
null
null
null
posts/migrations/0006_remove_like_likenumber.py
Joe-Sin7h/melodiam
756996464a79a1e2066004d2bcc05c10fbbf3e8e
[ "MIT" ]
null
null
null
posts/migrations/0006_remove_like_likenumber.py
Joe-Sin7h/melodiam
756996464a79a1e2066004d2bcc05c10fbbf3e8e
[ "MIT" ]
null
null
null
# Generated by Django 3.0.7 on 2020-10-30 17:39 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('posts', '0005_auto_20201006_1833'), ] operations = [ migrations.RemoveField( model_name='like', name='likenumber', ), ]
18.222222
47
0.591463
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('posts', '0005_auto_20201006_1833'), ] operations = [ migrations.RemoveField( model_name='like', name='likenumber', ), ]
true
true
1c2ceea6f34c2496fa1ab5886b8a377f67f00059
11,085
py
Python
nova/api/ec2/ec2utils.py
bopopescu/nova_vmware_compute_driver
60d3936b68030647b9f11970c9e0d060fc286dd9
[ "Apache-2.0" ]
null
null
null
nova/api/ec2/ec2utils.py
bopopescu/nova_vmware_compute_driver
60d3936b68030647b9f11970c9e0d060fc286dd9
[ "Apache-2.0" ]
null
null
null
nova/api/ec2/ec2utils.py
bopopescu/nova_vmware_compute_driver
60d3936b68030647b9f11970c9e0d060fc286dd9
[ "Apache-2.0" ]
2
2019-07-08T22:12:35.000Z
2020-07-24T08:27:24.000Z
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import re from nova import context from nova import db from nova import exception from nova.network import model as network_model from nova.openstack.common import log as logging from nova.openstack.common import timeutils from nova.openstack.common import uuidutils LOG = logging.getLogger(__name__) def image_type(image_type): """Converts to a three letter image type. aki, kernel => aki ari, ramdisk => ari anything else => ami """ if image_type == 'kernel': return 'aki' if image_type == 'ramdisk': return 'ari' if image_type not in ['aki', 'ari']: return 'ami' return image_type def id_to_glance_id(context, image_id): """Convert an internal (db) id to a glance id.""" return db.s3_image_get(context, image_id)['uuid'] def glance_id_to_id(context, glance_id): """Convert a glance id to an internal (db) id.""" if glance_id is None: return try: return db.s3_image_get_by_uuid(context, glance_id)['id'] except exception.NotFound: return db.s3_image_create(context, glance_id)['id'] def ec2_id_to_glance_id(context, ec2_id): image_id = ec2_id_to_id(ec2_id) return id_to_glance_id(context, image_id) def glance_id_to_ec2_id(context, glance_id, image_type='ami'): image_id = glance_id_to_id(context, glance_id) return image_ec2_id(image_id, image_type=image_type) def ec2_id_to_id(ec2_id): """Convert an ec2 ID (i-[base 16 number]) to an instance id (int)""" try: return int(ec2_id.split('-')[-1], 16) except ValueError: raise exception.InvalidEc2Id(ec2_id=ec2_id) def image_ec2_id(image_id, image_type='ami'): """Returns image ec2_id using id and three letter type.""" template = image_type + '-%08x' try: return id_to_ec2_id(image_id, template=template) except ValueError: #TODO(wwolf): once we have ec2_id -> glance_id mapping # in place, this wont be necessary return "ami-00000000" def get_ip_info_for_instance_from_nw_info(nw_info): ip_info = {} fixed_ips = nw_info.fixed_ips() ip_info['fixed_ips'] = [ip['address'] for ip in fixed_ips if ip['version'] == 4] ip_info['fixed_ip6s'] = [ip['address'] for ip in fixed_ips if ip['version'] == 6] ip_info['floating_ips'] = [ip['address'] for ip in nw_info.floating_ips()] return ip_info def get_ip_info_for_instance(context, instance): """Return a dictionary of IP information for an instance""" info_cache = instance['info_cache'] or {} cached_nwinfo = info_cache.get('network_info') # Make sure empty response is turned into [] if not cached_nwinfo: cached_nwinfo = [] nw_info = network_model.NetworkInfo.hydrate(cached_nwinfo) return get_ip_info_for_instance_from_nw_info(nw_info) def get_availability_zone_by_host(services, host): if len(services) > 0: return services[0]['availability_zone'] return 'unknown zone' def id_to_ec2_id(instance_id, template='i-%08x'): """Convert an instance ID (int) to an ec2 ID (i-[base 16 number])""" return template % int(instance_id) def id_to_ec2_inst_id(instance_id): """Get or create an ec2 instance ID (i-[base 16 number]) from uuid.""" if instance_id is None: return None elif uuidutils.is_uuid_like(instance_id): ctxt = context.get_admin_context() int_id = get_int_id_from_instance_uuid(ctxt, instance_id) return id_to_ec2_id(int_id) else: return id_to_ec2_id(instance_id) def ec2_inst_id_to_uuid(context, ec2_id): """"Convert an instance id to uuid.""" int_id = ec2_id_to_id(ec2_id) return get_instance_uuid_from_int_id(context, int_id) def get_instance_uuid_from_int_id(context, int_id): return db.get_instance_uuid_by_ec2_id(context, int_id) def id_to_ec2_snap_id(snapshot_id): """Get or create an ec2 volume ID (vol-[base 16 number]) from uuid.""" if uuidutils.is_uuid_like(snapshot_id): ctxt = context.get_admin_context() int_id = get_int_id_from_snapshot_uuid(ctxt, snapshot_id) return id_to_ec2_id(int_id, 'snap-%08x') else: return id_to_ec2_id(snapshot_id, 'snap-%08x') def id_to_ec2_vol_id(volume_id): """Get or create an ec2 volume ID (vol-[base 16 number]) from uuid.""" if uuidutils.is_uuid_like(volume_id): ctxt = context.get_admin_context() int_id = get_int_id_from_volume_uuid(ctxt, volume_id) return id_to_ec2_id(int_id, 'vol-%08x') else: return id_to_ec2_id(volume_id, 'vol-%08x') def ec2_vol_id_to_uuid(ec2_id): """Get the corresponding UUID for the given ec2-id.""" ctxt = context.get_admin_context() # NOTE(jgriffith) first strip prefix to get just the numeric int_id = ec2_id_to_id(ec2_id) return get_volume_uuid_from_int_id(ctxt, int_id) def is_ec2_timestamp_expired(request, expires=None): """Checks the timestamp or expiry time included in a EC2 request and returns true if the request is expired """ query_time = None timestamp = request.get('Timestamp') expiry_time = request.get('Expires') try: if timestamp and expiry_time: msg = _("Request must include either Timestamp or Expires," " but cannot contain both") LOG.error(msg) raise exception.InvalidRequest(msg) elif expiry_time: query_time = timeutils.parse_strtime(expiry_time, "%Y-%m-%dT%H:%M:%SZ") return timeutils.is_older_than(query_time, -1) elif timestamp: query_time = timeutils.parse_strtime(timestamp, "%Y-%m-%dT%H:%M:%SZ") # Check if the difference between the timestamp in the request # and the time on our servers is larger than 5 minutes, the # request is too old (or too new). if query_time and expires: return timeutils.is_older_than(query_time, expires) or \ timeutils.is_newer_than(query_time, expires) return False except ValueError: LOG.audit(_("Timestamp is invalid.")) return True def get_int_id_from_instance_uuid(context, instance_uuid): if instance_uuid is None: return try: return db.get_ec2_instance_id_by_uuid(context, instance_uuid) except exception.NotFound: return db.ec2_instance_create(context, instance_uuid)['id'] def get_int_id_from_volume_uuid(context, volume_uuid): if volume_uuid is None: return try: return db.get_ec2_volume_id_by_uuid(context, volume_uuid) except exception.NotFound: return db.ec2_volume_create(context, volume_uuid)['id'] def get_volume_uuid_from_int_id(context, int_id): return db.get_volume_uuid_by_ec2_id(context, int_id) def ec2_snap_id_to_uuid(ec2_id): """Get the corresponding UUID for the given ec2-id.""" ctxt = context.get_admin_context() # NOTE(jgriffith) first strip prefix to get just the numeric int_id = ec2_id_to_id(ec2_id) return get_snapshot_uuid_from_int_id(ctxt, int_id) def get_int_id_from_snapshot_uuid(context, snapshot_uuid): if snapshot_uuid is None: return try: return db.get_ec2_snapshot_id_by_uuid(context, snapshot_uuid) except exception.NotFound: return db.ec2_snapshot_create(context, snapshot_uuid)['id'] def get_snapshot_uuid_from_int_id(context, int_id): return db.get_snapshot_uuid_by_ec2_id(context, int_id) _c2u = re.compile('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))') def camelcase_to_underscore(str): return _c2u.sub(r'_\1', str).lower().strip('_') def _try_convert(value): """Return a non-string from a string or unicode, if possible. ============= ===================================================== When value is returns ============= ===================================================== zero-length '' 'None' None 'True' True case insensitive 'False' False case insensitive '0', '-0' 0 0xN, -0xN int from hex (positive) (N is any number) 0bN, -0bN int from binary (positive) (N is any number) * try conversion to int, float, complex, fallback value """ def _negative_zero(value): epsilon = 1e-7 return 0 if abs(value) < epsilon else value if len(value) == 0: return '' if value == 'None': return None lowered_value = value.lower() if lowered_value == 'true': return True if lowered_value == 'false': return False for prefix, base in [('0x', 16), ('0b', 2), ('0', 8), ('', 10)]: try: if lowered_value.startswith((prefix, "-" + prefix)): return int(lowered_value, base) except ValueError: pass try: return _negative_zero(float(value)) except ValueError: return value def dict_from_dotted_str(items): """parse multi dot-separated argument into dict. EBS boot uses multi dot-separated arguments like BlockDeviceMapping.1.DeviceName=snap-id Convert the above into {'block_device_mapping': {'1': {'device_name': snap-id}}} """ args = {} for key, value in items: parts = key.split(".") key = str(camelcase_to_underscore(parts[0])) if isinstance(value, str) or isinstance(value, unicode): # NOTE(vish): Automatically convert strings back # into their respective values value = _try_convert(value) if len(parts) > 1: d = args.get(key, {}) args[key] = d for k in parts[1:-1]: k = camelcase_to_underscore(k) v = d.get(k, {}) d[k] = v d = v d[camelcase_to_underscore(parts[-1])] = value else: args[key] = value return args def search_opts_from_filters(filters): return dict((f['name'].replace('-', '_'), f['value']['1']) for f in filters if f['value']['1']) if filters else {}
32.795858
78
0.642129
import re from nova import context from nova import db from nova import exception from nova.network import model as network_model from nova.openstack.common import log as logging from nova.openstack.common import timeutils from nova.openstack.common import uuidutils LOG = logging.getLogger(__name__) def image_type(image_type): if image_type == 'kernel': return 'aki' if image_type == 'ramdisk': return 'ari' if image_type not in ['aki', 'ari']: return 'ami' return image_type def id_to_glance_id(context, image_id): return db.s3_image_get(context, image_id)['uuid'] def glance_id_to_id(context, glance_id): if glance_id is None: return try: return db.s3_image_get_by_uuid(context, glance_id)['id'] except exception.NotFound: return db.s3_image_create(context, glance_id)['id'] def ec2_id_to_glance_id(context, ec2_id): image_id = ec2_id_to_id(ec2_id) return id_to_glance_id(context, image_id) def glance_id_to_ec2_id(context, glance_id, image_type='ami'): image_id = glance_id_to_id(context, glance_id) return image_ec2_id(image_id, image_type=image_type) def ec2_id_to_id(ec2_id): try: return int(ec2_id.split('-')[-1], 16) except ValueError: raise exception.InvalidEc2Id(ec2_id=ec2_id) def image_ec2_id(image_id, image_type='ami'): template = image_type + '-%08x' try: return id_to_ec2_id(image_id, template=template) except ValueError: return "ami-00000000" def get_ip_info_for_instance_from_nw_info(nw_info): ip_info = {} fixed_ips = nw_info.fixed_ips() ip_info['fixed_ips'] = [ip['address'] for ip in fixed_ips if ip['version'] == 4] ip_info['fixed_ip6s'] = [ip['address'] for ip in fixed_ips if ip['version'] == 6] ip_info['floating_ips'] = [ip['address'] for ip in nw_info.floating_ips()] return ip_info def get_ip_info_for_instance(context, instance): info_cache = instance['info_cache'] or {} cached_nwinfo = info_cache.get('network_info') if not cached_nwinfo: cached_nwinfo = [] nw_info = network_model.NetworkInfo.hydrate(cached_nwinfo) return get_ip_info_for_instance_from_nw_info(nw_info) def get_availability_zone_by_host(services, host): if len(services) > 0: return services[0]['availability_zone'] return 'unknown zone' def id_to_ec2_id(instance_id, template='i-%08x'): return template % int(instance_id) def id_to_ec2_inst_id(instance_id): if instance_id is None: return None elif uuidutils.is_uuid_like(instance_id): ctxt = context.get_admin_context() int_id = get_int_id_from_instance_uuid(ctxt, instance_id) return id_to_ec2_id(int_id) else: return id_to_ec2_id(instance_id) def ec2_inst_id_to_uuid(context, ec2_id): int_id = ec2_id_to_id(ec2_id) return get_instance_uuid_from_int_id(context, int_id) def get_instance_uuid_from_int_id(context, int_id): return db.get_instance_uuid_by_ec2_id(context, int_id) def id_to_ec2_snap_id(snapshot_id): if uuidutils.is_uuid_like(snapshot_id): ctxt = context.get_admin_context() int_id = get_int_id_from_snapshot_uuid(ctxt, snapshot_id) return id_to_ec2_id(int_id, 'snap-%08x') else: return id_to_ec2_id(snapshot_id, 'snap-%08x') def id_to_ec2_vol_id(volume_id): if uuidutils.is_uuid_like(volume_id): ctxt = context.get_admin_context() int_id = get_int_id_from_volume_uuid(ctxt, volume_id) return id_to_ec2_id(int_id, 'vol-%08x') else: return id_to_ec2_id(volume_id, 'vol-%08x') def ec2_vol_id_to_uuid(ec2_id): ctxt = context.get_admin_context() int_id = ec2_id_to_id(ec2_id) return get_volume_uuid_from_int_id(ctxt, int_id) def is_ec2_timestamp_expired(request, expires=None): query_time = None timestamp = request.get('Timestamp') expiry_time = request.get('Expires') try: if timestamp and expiry_time: msg = _("Request must include either Timestamp or Expires," " but cannot contain both") LOG.error(msg) raise exception.InvalidRequest(msg) elif expiry_time: query_time = timeutils.parse_strtime(expiry_time, "%Y-%m-%dT%H:%M:%SZ") return timeutils.is_older_than(query_time, -1) elif timestamp: query_time = timeutils.parse_strtime(timestamp, "%Y-%m-%dT%H:%M:%SZ") if query_time and expires: return timeutils.is_older_than(query_time, expires) or \ timeutils.is_newer_than(query_time, expires) return False except ValueError: LOG.audit(_("Timestamp is invalid.")) return True def get_int_id_from_instance_uuid(context, instance_uuid): if instance_uuid is None: return try: return db.get_ec2_instance_id_by_uuid(context, instance_uuid) except exception.NotFound: return db.ec2_instance_create(context, instance_uuid)['id'] def get_int_id_from_volume_uuid(context, volume_uuid): if volume_uuid is None: return try: return db.get_ec2_volume_id_by_uuid(context, volume_uuid) except exception.NotFound: return db.ec2_volume_create(context, volume_uuid)['id'] def get_volume_uuid_from_int_id(context, int_id): return db.get_volume_uuid_by_ec2_id(context, int_id) def ec2_snap_id_to_uuid(ec2_id): ctxt = context.get_admin_context() int_id = ec2_id_to_id(ec2_id) return get_snapshot_uuid_from_int_id(ctxt, int_id) def get_int_id_from_snapshot_uuid(context, snapshot_uuid): if snapshot_uuid is None: return try: return db.get_ec2_snapshot_id_by_uuid(context, snapshot_uuid) except exception.NotFound: return db.ec2_snapshot_create(context, snapshot_uuid)['id'] def get_snapshot_uuid_from_int_id(context, int_id): return db.get_snapshot_uuid_by_ec2_id(context, int_id) _c2u = re.compile('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))') def camelcase_to_underscore(str): return _c2u.sub(r'_\1', str).lower().strip('_') def _try_convert(value): def _negative_zero(value): epsilon = 1e-7 return 0 if abs(value) < epsilon else value if len(value) == 0: return '' if value == 'None': return None lowered_value = value.lower() if lowered_value == 'true': return True if lowered_value == 'false': return False for prefix, base in [('0x', 16), ('0b', 2), ('0', 8), ('', 10)]: try: if lowered_value.startswith((prefix, "-" + prefix)): return int(lowered_value, base) except ValueError: pass try: return _negative_zero(float(value)) except ValueError: return value def dict_from_dotted_str(items): args = {} for key, value in items: parts = key.split(".") key = str(camelcase_to_underscore(parts[0])) if isinstance(value, str) or isinstance(value, unicode): value = _try_convert(value) if len(parts) > 1: d = args.get(key, {}) args[key] = d for k in parts[1:-1]: k = camelcase_to_underscore(k) v = d.get(k, {}) d[k] = v d = v d[camelcase_to_underscore(parts[-1])] = value else: args[key] = value return args def search_opts_from_filters(filters): return dict((f['name'].replace('-', '_'), f['value']['1']) for f in filters if f['value']['1']) if filters else {}
true
true
1c2ceeb87282ee5345ebdfd72f7fea38d9e08d23
15,567
py
Python
Lib/test/test_ftplib.py
ystk/debian-python2.6
17d77164dc5d5748e54aeaa5adc89ac511fc71ae
[ "PSF-2.0" ]
3
2015-09-22T14:04:54.000Z
2021-07-15T07:07:11.000Z
Lib/test/test_ftplib.py
ystk/debian-python2.6
17d77164dc5d5748e54aeaa5adc89ac511fc71ae
[ "PSF-2.0" ]
1
2020-09-07T15:33:56.000Z
2020-09-07T15:33:56.000Z
Lib/test/test_ftplib.py
ystk/debian-python2.6
17d77164dc5d5748e54aeaa5adc89ac511fc71ae
[ "PSF-2.0" ]
2
2019-11-24T12:11:50.000Z
2020-12-26T19:00:20.000Z
"""Test script for ftplib module.""" # Modified by Giampaolo Rodola' to test FTP class and IPv6 environment import ftplib import threading import asyncore import asynchat import socket import StringIO from unittest import TestCase from test import test_support from test.test_support import HOST # the dummy data returned by server over the data channel when # RETR, LIST and NLST commands are issued RETR_DATA = 'abcde12345\r\n' * 1000 LIST_DATA = 'foo\r\nbar\r\n' NLST_DATA = 'foo\r\nbar\r\n' class DummyDTPHandler(asynchat.async_chat): def __init__(self, conn, baseclass): asynchat.async_chat.__init__(self, conn) self.baseclass = baseclass self.baseclass.last_received_data = '' def handle_read(self): self.baseclass.last_received_data += self.recv(1024) def handle_close(self): self.baseclass.push('226 transfer complete') self.close() class DummyFTPHandler(asynchat.async_chat): def __init__(self, conn): asynchat.async_chat.__init__(self, conn) self.set_terminator("\r\n") self.in_buffer = [] self.dtp = None self.last_received_cmd = None self.last_received_data = '' self.next_response = '' self.push('220 welcome') def collect_incoming_data(self, data): self.in_buffer.append(data) def found_terminator(self): line = ''.join(self.in_buffer) self.in_buffer = [] if self.next_response: self.push(self.next_response) self.next_response = '' cmd = line.split(' ')[0].lower() self.last_received_cmd = cmd space = line.find(' ') if space != -1: arg = line[space + 1:] else: arg = "" if hasattr(self, 'cmd_' + cmd): method = getattr(self, 'cmd_' + cmd) method(arg) else: self.push('550 command "%s" not understood.' %cmd) def handle_error(self): raise def push(self, data): asynchat.async_chat.push(self, data + '\r\n') def cmd_port(self, arg): addr = map(int, arg.split(',')) ip = '%d.%d.%d.%d' %tuple(addr[:4]) port = (addr[4] * 256) + addr[5] s = socket.create_connection((ip, port), timeout=2) self.dtp = DummyDTPHandler(s, baseclass=self) self.push('200 active data connection established') def cmd_pasv(self, arg): sock = socket.socket() sock.bind((self.socket.getsockname()[0], 0)) sock.listen(5) sock.settimeout(2) ip, port = sock.getsockname()[:2] ip = ip.replace('.', ',') p1, p2 = divmod(port, 256) self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2)) conn, addr = sock.accept() self.dtp = DummyDTPHandler(conn, baseclass=self) def cmd_eprt(self, arg): af, ip, port = arg.split(arg[0])[1:-1] port = int(port) s = socket.create_connection((ip, port), timeout=2) self.dtp = DummyDTPHandler(s, baseclass=self) self.push('200 active data connection established') def cmd_epsv(self, arg): sock = socket.socket(socket.AF_INET6) sock.bind((self.socket.getsockname()[0], 0)) sock.listen(5) sock.settimeout(2) port = sock.getsockname()[1] self.push('229 entering extended passive mode (|||%d|)' %port) conn, addr = sock.accept() self.dtp = DummyDTPHandler(conn, baseclass=self) def cmd_echo(self, arg): # sends back the received string (used by the test suite) self.push(arg) def cmd_user(self, arg): self.push('331 username ok') def cmd_pass(self, arg): self.push('230 password ok') def cmd_acct(self, arg): self.push('230 acct ok') def cmd_rnfr(self, arg): self.push('350 rnfr ok') def cmd_rnto(self, arg): self.push('250 rnto ok') def cmd_dele(self, arg): self.push('250 dele ok') def cmd_cwd(self, arg): self.push('250 cwd ok') def cmd_size(self, arg): self.push('250 1000') def cmd_mkd(self, arg): self.push('257 "%s"' %arg) def cmd_rmd(self, arg): self.push('250 rmd ok') def cmd_pwd(self, arg): self.push('257 "pwd ok"') def cmd_type(self, arg): self.push('200 type ok') def cmd_quit(self, arg): self.push('221 quit ok') self.close() def cmd_stor(self, arg): self.push('125 stor ok') def cmd_retr(self, arg): self.push('125 retr ok') self.dtp.push(RETR_DATA) self.dtp.close_when_done() def cmd_list(self, arg): self.push('125 list ok') self.dtp.push(LIST_DATA) self.dtp.close_when_done() def cmd_nlst(self, arg): self.push('125 nlst ok') self.dtp.push(NLST_DATA) self.dtp.close_when_done() class DummyFTPServer(asyncore.dispatcher, threading.Thread): handler = DummyFTPHandler def __init__(self, address, af=socket.AF_INET): threading.Thread.__init__(self) asyncore.dispatcher.__init__(self) self.create_socket(af, socket.SOCK_STREAM) self.bind(address) self.listen(5) self.active = False self.active_lock = threading.Lock() self.host, self.port = self.socket.getsockname()[:2] def start(self): assert not self.active self.__flag = threading.Event() threading.Thread.start(self) self.__flag.wait() def run(self): self.active = True self.__flag.set() while self.active and asyncore.socket_map: self.active_lock.acquire() asyncore.loop(timeout=0.1, count=1) self.active_lock.release() asyncore.close_all(ignore_all=True) def stop(self): assert self.active self.active = False self.join() def handle_accept(self): conn, addr = self.accept() self.handler = self.handler(conn) self.close() def handle_connect(self): self.close() handle_read = handle_connect def writable(self): return 0 def handle_error(self): raise class TestFTPClass(TestCase): def setUp(self): self.server = DummyFTPServer((HOST, 0)) self.server.start() self.client = ftplib.FTP(timeout=2) self.client.connect(self.server.host, self.server.port) def tearDown(self): self.client.close() self.server.stop() def test_getwelcome(self): self.assertEqual(self.client.getwelcome(), '220 welcome') def test_sanitize(self): self.assertEqual(self.client.sanitize('foo'), repr('foo')) self.assertEqual(self.client.sanitize('pass 12345'), repr('pass *****')) self.assertEqual(self.client.sanitize('PASS 12345'), repr('PASS *****')) def test_exceptions(self): self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 400') self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 499') self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 500') self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 599') self.assertRaises(ftplib.error_proto, self.client.sendcmd, 'echo 999') def test_all_errors(self): exceptions = (ftplib.error_reply, ftplib.error_temp, ftplib.error_perm, ftplib.error_proto, ftplib.Error, IOError, EOFError) for x in exceptions: try: raise x('exception not included in all_errors set') except ftplib.all_errors: pass def test_set_pasv(self): # passive mode is supposed to be enabled by default self.assertTrue(self.client.passiveserver) self.client.set_pasv(True) self.assertTrue(self.client.passiveserver) self.client.set_pasv(False) self.assertFalse(self.client.passiveserver) def test_voidcmd(self): self.client.voidcmd('echo 200') self.client.voidcmd('echo 299') self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 199') self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 300') def test_login(self): self.client.login() def test_acct(self): self.client.acct('passwd') def test_rename(self): self.client.rename('a', 'b') self.server.handler.next_response = '200' self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b') def test_delete(self): self.client.delete('foo') self.server.handler.next_response = '199' self.assertRaises(ftplib.error_reply, self.client.delete, 'foo') def test_size(self): self.client.size('foo') def test_mkd(self): dir = self.client.mkd('/foo') self.assertEqual(dir, '/foo') def test_rmd(self): self.client.rmd('foo') def test_pwd(self): dir = self.client.pwd() self.assertEqual(dir, 'pwd ok') def test_quit(self): self.assertEqual(self.client.quit(), '221 quit ok') # Ensure the connection gets closed; sock attribute should be None self.assertEqual(self.client.sock, None) def test_retrbinary(self): received = [] self.client.retrbinary('retr', received.append) self.assertEqual(''.join(received), RETR_DATA) def test_retrlines(self): received = [] self.client.retrlines('retr', received.append) self.assertEqual(''.join(received), RETR_DATA.replace('\r\n', '')) def test_storbinary(self): f = StringIO.StringIO(RETR_DATA) self.client.storbinary('stor', f) self.assertEqual(self.server.handler.last_received_data, RETR_DATA) # test new callback arg flag = [] f.seek(0) self.client.storbinary('stor', f, callback=lambda x: flag.append(None)) self.assertTrue(flag) def test_storlines(self): f = StringIO.StringIO(RETR_DATA.replace('\r\n', '\n')) self.client.storlines('stor', f) self.assertEqual(self.server.handler.last_received_data, RETR_DATA) # test new callback arg flag = [] f.seek(0) self.client.storlines('stor foo', f, callback=lambda x: flag.append(None)) self.assertTrue(flag) def test_nlst(self): self.client.nlst() self.assertEqual(self.client.nlst(), NLST_DATA.split('\r\n')[:-1]) def test_dir(self): l = [] self.client.dir(lambda x: l.append(x)) self.assertEqual(''.join(l), LIST_DATA.replace('\r\n', '')) def test_makeport(self): self.client.makeport() # IPv4 is in use, just make sure send_eprt has not been used self.assertEqual(self.server.handler.last_received_cmd, 'port') def test_makepasv(self): host, port = self.client.makepasv() conn = socket.create_connection((host, port), 2) conn.close() # IPv4 is in use, just make sure send_epsv has not been used self.assertEqual(self.server.handler.last_received_cmd, 'pasv') class TestIPv6Environment(TestCase): def setUp(self): self.server = DummyFTPServer((HOST, 0), af=socket.AF_INET6) self.server.start() self.client = ftplib.FTP() self.client.connect(self.server.host, self.server.port) def tearDown(self): self.client.close() self.server.stop() def test_af(self): self.assertEqual(self.client.af, socket.AF_INET6) def test_makeport(self): self.client.makeport() self.assertEqual(self.server.handler.last_received_cmd, 'eprt') def test_makepasv(self): host, port = self.client.makepasv() conn = socket.create_connection((host, port), 2) conn.close() self.assertEqual(self.server.handler.last_received_cmd, 'epsv') def test_transfer(self): def retr(): received = [] self.client.retrbinary('retr', received.append) self.assertEqual(''.join(received), RETR_DATA) self.client.set_pasv(True) retr() self.client.set_pasv(False) retr() class TestTimeouts(TestCase): def setUp(self): self.evt = threading.Event() self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(3) self.port = test_support.bind_port(self.sock) threading.Thread(target=self.server, args=(self.evt,self.sock)).start() # Wait for the server to be ready. self.evt.wait() self.evt.clear() ftplib.FTP.port = self.port def tearDown(self): self.evt.wait() def server(self, evt, serv): # This method sets the evt 3 times: # 1) when the connection is ready to be accepted. # 2) when it is safe for the caller to close the connection # 3) when we have closed the socket serv.listen(5) # (1) Signal the caller that we are ready to accept the connection. evt.set() try: conn, addr = serv.accept() except socket.timeout: pass else: conn.send("1 Hola mundo\n") # (2) Signal the caller that it is safe to close the socket. evt.set() conn.close() finally: serv.close() # (3) Signal the caller that we are done. evt.set() def testTimeoutDefault(self): # default -- use global socket timeout self.assert_(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) try: ftp = ftplib.FTP("localhost") finally: socket.setdefaulttimeout(None) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.close() def testTimeoutNone(self): # no timeout -- do not use global socket timeout self.assert_(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) try: ftp = ftplib.FTP("localhost", timeout=None) finally: socket.setdefaulttimeout(None) self.assertTrue(ftp.sock.gettimeout() is None) self.evt.wait() ftp.close() def testTimeoutValue(self): # a value ftp = ftplib.FTP(HOST, timeout=30) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.close() def testTimeoutConnect(self): ftp = ftplib.FTP() ftp.connect(HOST, timeout=30) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.close() def testTimeoutDifferentOrder(self): ftp = ftplib.FTP(timeout=30) ftp.connect(HOST) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.close() def testTimeoutDirectAccess(self): ftp = ftplib.FTP() ftp.timeout = 30 ftp.connect(HOST) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.close() def test_main(): tests = [TestFTPClass, TestTimeouts] if socket.has_ipv6: try: DummyFTPServer((HOST, 0), af=socket.AF_INET6) except socket.error: pass else: tests.append(TestIPv6Environment) thread_info = test_support.threading_setup() try: test_support.run_unittest(*tests) finally: test_support.threading_cleanup(*thread_info) if __name__ == '__main__': test_main()
30.404297
82
0.60821
import ftplib import threading import asyncore import asynchat import socket import StringIO from unittest import TestCase from test import test_support from test.test_support import HOST # the dummy data returned by server over the data channel when # RETR, LIST and NLST commands are issued RETR_DATA = 'abcde12345\r\n' * 1000 LIST_DATA = 'foo\r\nbar\r\n' NLST_DATA = 'foo\r\nbar\r\n' class DummyDTPHandler(asynchat.async_chat): def __init__(self, conn, baseclass): asynchat.async_chat.__init__(self, conn) self.baseclass = baseclass self.baseclass.last_received_data = '' def handle_read(self): self.baseclass.last_received_data += self.recv(1024) def handle_close(self): self.baseclass.push('226 transfer complete') self.close() class DummyFTPHandler(asynchat.async_chat): def __init__(self, conn): asynchat.async_chat.__init__(self, conn) self.set_terminator("\r\n") self.in_buffer = [] self.dtp = None self.last_received_cmd = None self.last_received_data = '' self.next_response = '' self.push('220 welcome') def collect_incoming_data(self, data): self.in_buffer.append(data) def found_terminator(self): line = ''.join(self.in_buffer) self.in_buffer = [] if self.next_response: self.push(self.next_response) self.next_response = '' cmd = line.split(' ')[0].lower() self.last_received_cmd = cmd space = line.find(' ') if space != -1: arg = line[space + 1:] else: arg = "" if hasattr(self, 'cmd_' + cmd): method = getattr(self, 'cmd_' + cmd) method(arg) else: self.push('550 command "%s" not understood.' %cmd) def handle_error(self): raise def push(self, data): asynchat.async_chat.push(self, data + '\r\n') def cmd_port(self, arg): addr = map(int, arg.split(',')) ip = '%d.%d.%d.%d' %tuple(addr[:4]) port = (addr[4] * 256) + addr[5] s = socket.create_connection((ip, port), timeout=2) self.dtp = DummyDTPHandler(s, baseclass=self) self.push('200 active data connection established') def cmd_pasv(self, arg): sock = socket.socket() sock.bind((self.socket.getsockname()[0], 0)) sock.listen(5) sock.settimeout(2) ip, port = sock.getsockname()[:2] ip = ip.replace('.', ',') p1, p2 = divmod(port, 256) self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2)) conn, addr = sock.accept() self.dtp = DummyDTPHandler(conn, baseclass=self) def cmd_eprt(self, arg): af, ip, port = arg.split(arg[0])[1:-1] port = int(port) s = socket.create_connection((ip, port), timeout=2) self.dtp = DummyDTPHandler(s, baseclass=self) self.push('200 active data connection established') def cmd_epsv(self, arg): sock = socket.socket(socket.AF_INET6) sock.bind((self.socket.getsockname()[0], 0)) sock.listen(5) sock.settimeout(2) port = sock.getsockname()[1] self.push('229 entering extended passive mode (|||%d|)' %port) conn, addr = sock.accept() self.dtp = DummyDTPHandler(conn, baseclass=self) def cmd_echo(self, arg): # sends back the received string (used by the test suite) self.push(arg) def cmd_user(self, arg): self.push('331 username ok') def cmd_pass(self, arg): self.push('230 password ok') def cmd_acct(self, arg): self.push('230 acct ok') def cmd_rnfr(self, arg): self.push('350 rnfr ok') def cmd_rnto(self, arg): self.push('250 rnto ok') def cmd_dele(self, arg): self.push('250 dele ok') def cmd_cwd(self, arg): self.push('250 cwd ok') def cmd_size(self, arg): self.push('250 1000') def cmd_mkd(self, arg): self.push('257 "%s"' %arg) def cmd_rmd(self, arg): self.push('250 rmd ok') def cmd_pwd(self, arg): self.push('257 "pwd ok"') def cmd_type(self, arg): self.push('200 type ok') def cmd_quit(self, arg): self.push('221 quit ok') self.close() def cmd_stor(self, arg): self.push('125 stor ok') def cmd_retr(self, arg): self.push('125 retr ok') self.dtp.push(RETR_DATA) self.dtp.close_when_done() def cmd_list(self, arg): self.push('125 list ok') self.dtp.push(LIST_DATA) self.dtp.close_when_done() def cmd_nlst(self, arg): self.push('125 nlst ok') self.dtp.push(NLST_DATA) self.dtp.close_when_done() class DummyFTPServer(asyncore.dispatcher, threading.Thread): handler = DummyFTPHandler def __init__(self, address, af=socket.AF_INET): threading.Thread.__init__(self) asyncore.dispatcher.__init__(self) self.create_socket(af, socket.SOCK_STREAM) self.bind(address) self.listen(5) self.active = False self.active_lock = threading.Lock() self.host, self.port = self.socket.getsockname()[:2] def start(self): assert not self.active self.__flag = threading.Event() threading.Thread.start(self) self.__flag.wait() def run(self): self.active = True self.__flag.set() while self.active and asyncore.socket_map: self.active_lock.acquire() asyncore.loop(timeout=0.1, count=1) self.active_lock.release() asyncore.close_all(ignore_all=True) def stop(self): assert self.active self.active = False self.join() def handle_accept(self): conn, addr = self.accept() self.handler = self.handler(conn) self.close() def handle_connect(self): self.close() handle_read = handle_connect def writable(self): return 0 def handle_error(self): raise class TestFTPClass(TestCase): def setUp(self): self.server = DummyFTPServer((HOST, 0)) self.server.start() self.client = ftplib.FTP(timeout=2) self.client.connect(self.server.host, self.server.port) def tearDown(self): self.client.close() self.server.stop() def test_getwelcome(self): self.assertEqual(self.client.getwelcome(), '220 welcome') def test_sanitize(self): self.assertEqual(self.client.sanitize('foo'), repr('foo')) self.assertEqual(self.client.sanitize('pass 12345'), repr('pass *****')) self.assertEqual(self.client.sanitize('PASS 12345'), repr('PASS *****')) def test_exceptions(self): self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 400') self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 499') self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 500') self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 599') self.assertRaises(ftplib.error_proto, self.client.sendcmd, 'echo 999') def test_all_errors(self): exceptions = (ftplib.error_reply, ftplib.error_temp, ftplib.error_perm, ftplib.error_proto, ftplib.Error, IOError, EOFError) for x in exceptions: try: raise x('exception not included in all_errors set') except ftplib.all_errors: pass def test_set_pasv(self): # passive mode is supposed to be enabled by default self.assertTrue(self.client.passiveserver) self.client.set_pasv(True) self.assertTrue(self.client.passiveserver) self.client.set_pasv(False) self.assertFalse(self.client.passiveserver) def test_voidcmd(self): self.client.voidcmd('echo 200') self.client.voidcmd('echo 299') self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 199') self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 300') def test_login(self): self.client.login() def test_acct(self): self.client.acct('passwd') def test_rename(self): self.client.rename('a', 'b') self.server.handler.next_response = '200' self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b') def test_delete(self): self.client.delete('foo') self.server.handler.next_response = '199' self.assertRaises(ftplib.error_reply, self.client.delete, 'foo') def test_size(self): self.client.size('foo') def test_mkd(self): dir = self.client.mkd('/foo') self.assertEqual(dir, '/foo') def test_rmd(self): self.client.rmd('foo') def test_pwd(self): dir = self.client.pwd() self.assertEqual(dir, 'pwd ok') def test_quit(self): self.assertEqual(self.client.quit(), '221 quit ok') # Ensure the connection gets closed; sock attribute should be None self.assertEqual(self.client.sock, None) def test_retrbinary(self): received = [] self.client.retrbinary('retr', received.append) self.assertEqual(''.join(received), RETR_DATA) def test_retrlines(self): received = [] self.client.retrlines('retr', received.append) self.assertEqual(''.join(received), RETR_DATA.replace('\r\n', '')) def test_storbinary(self): f = StringIO.StringIO(RETR_DATA) self.client.storbinary('stor', f) self.assertEqual(self.server.handler.last_received_data, RETR_DATA) # test new callback arg flag = [] f.seek(0) self.client.storbinary('stor', f, callback=lambda x: flag.append(None)) self.assertTrue(flag) def test_storlines(self): f = StringIO.StringIO(RETR_DATA.replace('\r\n', '\n')) self.client.storlines('stor', f) self.assertEqual(self.server.handler.last_received_data, RETR_DATA) # test new callback arg flag = [] f.seek(0) self.client.storlines('stor foo', f, callback=lambda x: flag.append(None)) self.assertTrue(flag) def test_nlst(self): self.client.nlst() self.assertEqual(self.client.nlst(), NLST_DATA.split('\r\n')[:-1]) def test_dir(self): l = [] self.client.dir(lambda x: l.append(x)) self.assertEqual(''.join(l), LIST_DATA.replace('\r\n', '')) def test_makeport(self): self.client.makeport() # IPv4 is in use, just make sure send_eprt has not been used self.assertEqual(self.server.handler.last_received_cmd, 'port') def test_makepasv(self): host, port = self.client.makepasv() conn = socket.create_connection((host, port), 2) conn.close() # IPv4 is in use, just make sure send_epsv has not been used self.assertEqual(self.server.handler.last_received_cmd, 'pasv') class TestIPv6Environment(TestCase): def setUp(self): self.server = DummyFTPServer((HOST, 0), af=socket.AF_INET6) self.server.start() self.client = ftplib.FTP() self.client.connect(self.server.host, self.server.port) def tearDown(self): self.client.close() self.server.stop() def test_af(self): self.assertEqual(self.client.af, socket.AF_INET6) def test_makeport(self): self.client.makeport() self.assertEqual(self.server.handler.last_received_cmd, 'eprt') def test_makepasv(self): host, port = self.client.makepasv() conn = socket.create_connection((host, port), 2) conn.close() self.assertEqual(self.server.handler.last_received_cmd, 'epsv') def test_transfer(self): def retr(): received = [] self.client.retrbinary('retr', received.append) self.assertEqual(''.join(received), RETR_DATA) self.client.set_pasv(True) retr() self.client.set_pasv(False) retr() class TestTimeouts(TestCase): def setUp(self): self.evt = threading.Event() self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(3) self.port = test_support.bind_port(self.sock) threading.Thread(target=self.server, args=(self.evt,self.sock)).start() # Wait for the server to be ready. self.evt.wait() self.evt.clear() ftplib.FTP.port = self.port def tearDown(self): self.evt.wait() def server(self, evt, serv): # This method sets the evt 3 times: # 1) when the connection is ready to be accepted. # 2) when it is safe for the caller to close the connection # 3) when we have closed the socket serv.listen(5) # (1) Signal the caller that we are ready to accept the connection. evt.set() try: conn, addr = serv.accept() except socket.timeout: pass else: conn.send("1 Hola mundo\n") # (2) Signal the caller that it is safe to close the socket. evt.set() conn.close() finally: serv.close() # (3) Signal the caller that we are done. evt.set() def testTimeoutDefault(self): # default -- use global socket timeout self.assert_(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) try: ftp = ftplib.FTP("localhost") finally: socket.setdefaulttimeout(None) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.close() def testTimeoutNone(self): # no timeout -- do not use global socket timeout self.assert_(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) try: ftp = ftplib.FTP("localhost", timeout=None) finally: socket.setdefaulttimeout(None) self.assertTrue(ftp.sock.gettimeout() is None) self.evt.wait() ftp.close() def testTimeoutValue(self): # a value ftp = ftplib.FTP(HOST, timeout=30) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.close() def testTimeoutConnect(self): ftp = ftplib.FTP() ftp.connect(HOST, timeout=30) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.close() def testTimeoutDifferentOrder(self): ftp = ftplib.FTP(timeout=30) ftp.connect(HOST) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.close() def testTimeoutDirectAccess(self): ftp = ftplib.FTP() ftp.timeout = 30 ftp.connect(HOST) self.assertEqual(ftp.sock.gettimeout(), 30) self.evt.wait() ftp.close() def test_main(): tests = [TestFTPClass, TestTimeouts] if socket.has_ipv6: try: DummyFTPServer((HOST, 0), af=socket.AF_INET6) except socket.error: pass else: tests.append(TestIPv6Environment) thread_info = test_support.threading_setup() try: test_support.run_unittest(*tests) finally: test_support.threading_cleanup(*thread_info) if __name__ == '__main__': test_main()
true
true
1c2cefc327815da69fad35455065f2b7f216bbf5
5,791
py
Python
test/functional/p2p_fingerprint.py
Kozisto/FreedomCoin-Core
ba4f6def338c58616ece13d890393552e657d3f0
[ "MIT" ]
null
null
null
test/functional/p2p_fingerprint.py
Kozisto/FreedomCoin-Core
ba4f6def338c58616ece13d890393552e657d3f0
[ "MIT" ]
1
2022-02-11T23:23:05.000Z
2022-02-11T23:23:05.000Z
test/functional/p2p_fingerprint.py
FreedomCoin-Project/FreedomCoin-Core
46e09320dd9903137433fc71aa9186fa3cdbe866
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test various fingerprinting protections. If an stale block more than a month old or its header are requested by a peer, the node should pretend that it does not have it to avoid fingerprinting. """ import time from test_framework.blocktools import (create_block, create_coinbase) from test_framework.messages import CInv from test_framework.mininode import ( P2PInterface, msg_headers, msg_block, msg_getdata, msg_getheaders, wait_until, ) from test_framework.test_framework import FreedomCoinTestFramework from test_framework.util import assert_equal class P2PFingerprintTest(FreedomCoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 # Build a chain of blocks on top of given one def build_chain(self, nblocks, prev_hash, prev_height, prev_median_time): blocks = [] for _ in range(nblocks): coinbase = create_coinbase(prev_height + 1) block_time = prev_median_time + 1 block = create_block(int(prev_hash, 16), coinbase, block_time) block.solve() blocks.append(block) prev_hash = block.hash prev_height += 1 prev_median_time = block_time return blocks # Send a getdata request for a given block hash def send_block_request(self, block_hash, node): msg = msg_getdata() msg.inv.append(CInv(2, block_hash)) # 2 == "Block" node.send_message(msg) # Send a getheaders request for a given single block hash def send_header_request(self, block_hash, node): msg = msg_getheaders() msg.hashstop = block_hash node.send_message(msg) # Check whether last block received from node has a given hash def last_block_equals(self, expected_hash, node): block_msg = node.last_message.get("block") return block_msg and block_msg.block.rehash() == expected_hash # Check whether last block header received from node has a given hash def last_header_equals(self, expected_hash, node): headers_msg = node.last_message.get("headers") return (headers_msg and headers_msg.headers and headers_msg.headers[0].rehash() == expected_hash) # Checks that stale blocks timestamped more than a month ago are not served # by the node while recent stale blocks and old active chain blocks are. # This does not currently test that stale blocks timestamped within the # last month but that have over a month's worth of work are also withheld. def run_test(self): node0 = self.nodes[0].add_p2p_connection(P2PInterface()) node0.wait_for_verack() # Set node time to 60 days ago self.nodes[0].setmocktime(int(time.time()) - 60 * 24 * 60 * 60) # Generating a chain of 10 blocks block_hashes = self.nodes[0].generate(10) # Create longer chain starting 2 blocks before current tip height = len(block_hashes) - 2 block_hash = block_hashes[height - 1] block_time = self.nodes[0].getblockheader(block_hash)["mediantime"] + 1 new_blocks = self.build_chain(5, block_hash, height, block_time) # Force reorg to a longer chain node0.send_message(msg_headers(new_blocks)) node0.wait_for_getdata() for block in new_blocks: node0.send_and_ping(msg_block(block)) # Check that reorg succeeded assert_equal(self.nodes[0].getblockcount(), 13) stale_hash = int(block_hashes[-1], 16) # Check that getdata request for stale block succeeds self.send_block_request(stale_hash, node0) test_function = lambda: self.last_block_equals(stale_hash, node0) wait_until(test_function, timeout=3) # Check that getheader request for stale block header succeeds self.send_header_request(stale_hash, node0) test_function = lambda: self.last_header_equals(stale_hash, node0) wait_until(test_function, timeout=3) # Longest chain is extended so stale is much older than chain tip self.nodes[0].setmocktime(0) tip = self.nodes[0].generate(nblocks=1)[0] assert_equal(self.nodes[0].getblockcount(), 14) # Send getdata & getheaders to refresh last received getheader message block_hash = int(tip, 16) self.send_block_request(block_hash, node0) self.send_header_request(block_hash, node0) node0.sync_with_ping() # Request for very old stale block should now fail self.send_block_request(stale_hash, node0) time.sleep(3) assert not self.last_block_equals(stale_hash, node0) # Request for very old stale block header should now fail self.send_header_request(stale_hash, node0) time.sleep(3) assert not self.last_header_equals(stale_hash, node0) # Verify we can fetch very old blocks and headers on the active chain block_hash = int(block_hashes[2], 16) self.send_block_request(block_hash, node0) self.send_header_request(block_hash, node0) node0.sync_with_ping() self.send_block_request(block_hash, node0) test_function = lambda: self.last_block_equals(block_hash, node0) wait_until(test_function, timeout=3) self.send_header_request(block_hash, node0) test_function = lambda: self.last_header_equals(block_hash, node0) wait_until(test_function, timeout=3) if __name__ == '__main__': P2PFingerprintTest().main()
38.865772
79
0.689
import time from test_framework.blocktools import (create_block, create_coinbase) from test_framework.messages import CInv from test_framework.mininode import ( P2PInterface, msg_headers, msg_block, msg_getdata, msg_getheaders, wait_until, ) from test_framework.test_framework import FreedomCoinTestFramework from test_framework.util import assert_equal class P2PFingerprintTest(FreedomCoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def build_chain(self, nblocks, prev_hash, prev_height, prev_median_time): blocks = [] for _ in range(nblocks): coinbase = create_coinbase(prev_height + 1) block_time = prev_median_time + 1 block = create_block(int(prev_hash, 16), coinbase, block_time) block.solve() blocks.append(block) prev_hash = block.hash prev_height += 1 prev_median_time = block_time return blocks def send_block_request(self, block_hash, node): msg = msg_getdata() msg.inv.append(CInv(2, block_hash)) node.send_message(msg) def send_header_request(self, block_hash, node): msg = msg_getheaders() msg.hashstop = block_hash node.send_message(msg) def last_block_equals(self, expected_hash, node): block_msg = node.last_message.get("block") return block_msg and block_msg.block.rehash() == expected_hash def last_header_equals(self, expected_hash, node): headers_msg = node.last_message.get("headers") return (headers_msg and headers_msg.headers and headers_msg.headers[0].rehash() == expected_hash) def run_test(self): node0 = self.nodes[0].add_p2p_connection(P2PInterface()) node0.wait_for_verack() # Set node time to 60 days ago self.nodes[0].setmocktime(int(time.time()) - 60 * 24 * 60 * 60) # Generating a chain of 10 blocks block_hashes = self.nodes[0].generate(10) # Create longer chain starting 2 blocks before current tip height = len(block_hashes) - 2 block_hash = block_hashes[height - 1] block_time = self.nodes[0].getblockheader(block_hash)["mediantime"] + 1 new_blocks = self.build_chain(5, block_hash, height, block_time) # Force reorg to a longer chain node0.send_message(msg_headers(new_blocks)) node0.wait_for_getdata() for block in new_blocks: node0.send_and_ping(msg_block(block)) # Check that reorg succeeded assert_equal(self.nodes[0].getblockcount(), 13) stale_hash = int(block_hashes[-1], 16) # Check that getdata request for stale block succeeds self.send_block_request(stale_hash, node0) test_function = lambda: self.last_block_equals(stale_hash, node0) wait_until(test_function, timeout=3) # Check that getheader request for stale block header succeeds self.send_header_request(stale_hash, node0) test_function = lambda: self.last_header_equals(stale_hash, node0) wait_until(test_function, timeout=3) # Longest chain is extended so stale is much older than chain tip self.nodes[0].setmocktime(0) tip = self.nodes[0].generate(nblocks=1)[0] assert_equal(self.nodes[0].getblockcount(), 14) # Send getdata & getheaders to refresh last received getheader message block_hash = int(tip, 16) self.send_block_request(block_hash, node0) self.send_header_request(block_hash, node0) node0.sync_with_ping() # Request for very old stale block should now fail self.send_block_request(stale_hash, node0) time.sleep(3) assert not self.last_block_equals(stale_hash, node0) # Request for very old stale block header should now fail self.send_header_request(stale_hash, node0) time.sleep(3) assert not self.last_header_equals(stale_hash, node0) # Verify we can fetch very old blocks and headers on the active chain block_hash = int(block_hashes[2], 16) self.send_block_request(block_hash, node0) self.send_header_request(block_hash, node0) node0.sync_with_ping() self.send_block_request(block_hash, node0) test_function = lambda: self.last_block_equals(block_hash, node0) wait_until(test_function, timeout=3) self.send_header_request(block_hash, node0) test_function = lambda: self.last_header_equals(block_hash, node0) wait_until(test_function, timeout=3) if __name__ == '__main__': P2PFingerprintTest().main()
true
true
1c2cf0936b8b0a5a65d83390990bd28f150f3bcd
3,645
py
Python
vfit/util.py
zorfling/vfit
50f2aec1be45ece00167107ec469a60564645ae0
[ "MIT" ]
17
2020-07-18T17:00:03.000Z
2022-03-13T13:03:09.000Z
vfit/util.py
zorfling/vfit
50f2aec1be45ece00167107ec469a60564645ae0
[ "MIT" ]
11
2020-11-02T19:10:30.000Z
2022-02-25T02:57:31.000Z
vfit/util.py
zorfling/vfit
50f2aec1be45ece00167107ec469a60564645ae0
[ "MIT" ]
6
2020-12-30T00:02:26.000Z
2022-02-25T02:45:01.000Z
PLAT_MAC = 1 PLAT_WINDOWS = 3 ENC_ROMAN = 0 ENC_UNICODE_11 = 1 LANG_ENGLISH = 1033 MACSTYLE = {'Regular': 0, 'Bold': 1, 'Italic': 2, 'Bold Italic': 3} OVERLAP_SIMPLE = 0x40 OVERLAP_COMPOUND = 0x0400 # Removes spaces from a string. def sanitize(string): return string.replace(" ", "") # Produces a unique ID for a style. def getUniqueStyleID(style): id = style["name"] if "subfamily" in style: id = f"{style['subfamily']}-{id}" return sanitize(id) def getFullName(style): familyName = style.get("prefFamily") if familyName == None: familyName = style.get("family") subfamilyName = style.get("prefSubfamily") if subfamilyName == None: subfamilyName = style.get("subfamily") return f"{familyName} {subfamilyName}" def getPostscriptName(style): familyName = style.get("prefFamily") if familyName == None: familyName = style.get("family") subfamilyName = style.get("prefSubfamily") if subfamilyName == None: subfamilyName = style.get("subfamily") familyName = familyName.replace(" ", "") subfamilyName = subfamilyName.replace(" ", "") return f"{familyName}-{subfamilyName}" # Rewrites the name table with new metadata. def updateNames(font, style): nameTable = font["name"] nameTable.names = [] family = style.get("family") subfamily = style.get("subfamily") prefFamily = style.get("prefFamily") prefSubfamily = style.get("prefSubfamily") fullName = getFullName(style) postscriptName = getPostscriptName(style) nameTable.setName(family, 1, PLAT_MAC, ENC_ROMAN, 0) nameTable.setName(family, 1, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) nameTable.setName(subfamily, 2, PLAT_MAC, ENC_ROMAN, 0) nameTable.setName(subfamily, 2, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) nameTable.setName(fullName, 3, PLAT_MAC, ENC_ROMAN, 0) nameTable.setName(fullName, 3, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) nameTable.setName(fullName, 4, PLAT_MAC, ENC_ROMAN, 0) nameTable.setName(fullName, 4, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) nameTable.setName("Version 1.000", 5, PLAT_MAC, ENC_ROMAN, 0) nameTable.setName("Version 1.000", 5, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) nameTable.setName(postscriptName, 6, PLAT_MAC, ENC_ROMAN, 0) nameTable.setName(postscriptName, 6, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) if prefFamily is not None: nameTable.setName(prefFamily, 16, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) if prefSubfamily is not None: nameTable.setName(prefSubfamily, 17, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) def makeSelection(bits, style): bits = bits ^ bits if style == 'Regular': bits |= 0b1000000 else: bits &= ~0b1000000 if style == 'Bold' or style == 'BoldItalic': bits |= 0b100000 else: bits &= ~0b100000 if style == 'Italic': bits |= 0b1 else: bits &= ~0b1 if not bits: bits = 0b1000000 return bits def getMacStyle(style): return MACSTYLE[style] def dropVariationTables(font): for tag in 'STAT cvar fvar gvar'.split(): if tag in font.keys(): del font[tag] def setOverlapFlags(font): glyf = font["glyf"] for glyph_name in glyf.keys(): glyph = glyf[glyph_name] if glyph.isComposite(): glyph.components[0].flags |= OVERLAP_COMPOUND elif glyph.numberOfContours > 0: glyph.flags[0] |= OVERLAP_SIMPLE
25.669014
79
0.65048
PLAT_MAC = 1 PLAT_WINDOWS = 3 ENC_ROMAN = 0 ENC_UNICODE_11 = 1 LANG_ENGLISH = 1033 MACSTYLE = {'Regular': 0, 'Bold': 1, 'Italic': 2, 'Bold Italic': 3} OVERLAP_SIMPLE = 0x40 OVERLAP_COMPOUND = 0x0400 def sanitize(string): return string.replace(" ", "") def getUniqueStyleID(style): id = style["name"] if "subfamily" in style: id = f"{style['subfamily']}-{id}" return sanitize(id) def getFullName(style): familyName = style.get("prefFamily") if familyName == None: familyName = style.get("family") subfamilyName = style.get("prefSubfamily") if subfamilyName == None: subfamilyName = style.get("subfamily") return f"{familyName} {subfamilyName}" def getPostscriptName(style): familyName = style.get("prefFamily") if familyName == None: familyName = style.get("family") subfamilyName = style.get("prefSubfamily") if subfamilyName == None: subfamilyName = style.get("subfamily") familyName = familyName.replace(" ", "") subfamilyName = subfamilyName.replace(" ", "") return f"{familyName}-{subfamilyName}" def updateNames(font, style): nameTable = font["name"] nameTable.names = [] family = style.get("family") subfamily = style.get("subfamily") prefFamily = style.get("prefFamily") prefSubfamily = style.get("prefSubfamily") fullName = getFullName(style) postscriptName = getPostscriptName(style) nameTable.setName(family, 1, PLAT_MAC, ENC_ROMAN, 0) nameTable.setName(family, 1, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) nameTable.setName(subfamily, 2, PLAT_MAC, ENC_ROMAN, 0) nameTable.setName(subfamily, 2, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) nameTable.setName(fullName, 3, PLAT_MAC, ENC_ROMAN, 0) nameTable.setName(fullName, 3, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) nameTable.setName(fullName, 4, PLAT_MAC, ENC_ROMAN, 0) nameTable.setName(fullName, 4, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) nameTable.setName("Version 1.000", 5, PLAT_MAC, ENC_ROMAN, 0) nameTable.setName("Version 1.000", 5, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) nameTable.setName(postscriptName, 6, PLAT_MAC, ENC_ROMAN, 0) nameTable.setName(postscriptName, 6, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) if prefFamily is not None: nameTable.setName(prefFamily, 16, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) if prefSubfamily is not None: nameTable.setName(prefSubfamily, 17, PLAT_WINDOWS, ENC_UNICODE_11, LANG_ENGLISH) def makeSelection(bits, style): bits = bits ^ bits if style == 'Regular': bits |= 0b1000000 else: bits &= ~0b1000000 if style == 'Bold' or style == 'BoldItalic': bits |= 0b100000 else: bits &= ~0b100000 if style == 'Italic': bits |= 0b1 else: bits &= ~0b1 if not bits: bits = 0b1000000 return bits def getMacStyle(style): return MACSTYLE[style] def dropVariationTables(font): for tag in 'STAT cvar fvar gvar'.split(): if tag in font.keys(): del font[tag] def setOverlapFlags(font): glyf = font["glyf"] for glyph_name in glyf.keys(): glyph = glyf[glyph_name] if glyph.isComposite(): glyph.components[0].flags |= OVERLAP_COMPOUND elif glyph.numberOfContours > 0: glyph.flags[0] |= OVERLAP_SIMPLE
true
true
1c2cf10d9603cf300c6a900634fd711d3689f71c
1,823
py
Python
tests/test_observable/test_fromiterable.py
samiur/RxPY
ea6b3554ab06cfc70e28b532c0a54b910b6ee470
[ "MIT" ]
null
null
null
tests/test_observable/test_fromiterable.py
samiur/RxPY
ea6b3554ab06cfc70e28b532c0a54b910b6ee470
[ "MIT" ]
null
null
null
tests/test_observable/test_fromiterable.py
samiur/RxPY
ea6b3554ab06cfc70e28b532c0a54b910b6ee470
[ "MIT" ]
null
null
null
import unittest import rx3 from rx3.testing import TestScheduler, ReactiveTest on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_completed on_error = ReactiveTest.on_error subscribe = ReactiveTest.subscribe subscribed = ReactiveTest.subscribed disposed = ReactiveTest.disposed created = ReactiveTest.created class RxException(Exception): pass # Helper function for raising exceptions within lambdas def _raise(ex): raise RxException(ex) class TestFromIterable(unittest.TestCase): def test_subscribe_to_iterable_finite(self): iterable_finite = [1, 2, 3, 4, 5] scheduler = TestScheduler() def create(): return rx3.from_(iterable_finite) results = scheduler.start(create) assert results.messages == [ on_next(200, 1), on_next(200, 2), on_next(200, 3), on_next(200, 4), on_next(200, 5), on_completed(200)] def test_subscribe_to_iterable_empty(self): iterable_finite = [] scheduler = TestScheduler() def create(): return rx3.from_(iterable_finite) results = scheduler.start(create) assert results.messages == [on_completed(200)] def test_double_subscribe_to_iterable(self): iterable_finite = [1, 2, 3] scheduler = TestScheduler() obs = rx3.from_(iterable_finite) results = scheduler.start(lambda: rx3.concat(obs, obs)) assert results.messages == [ on_next(200, 1), on_next(200, 2), on_next(200, 3), on_next(200, 1), on_next(200, 2), on_next(200, 3), on_completed(200)] def test_observer_throws(self): with self.assertRaises(RxException): rx3.from_iterable([1, 2, 3]).subscribe(lambda x: _raise('ex'))
26.808824
74
0.648382
import unittest import rx3 from rx3.testing import TestScheduler, ReactiveTest on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_completed on_error = ReactiveTest.on_error subscribe = ReactiveTest.subscribe subscribed = ReactiveTest.subscribed disposed = ReactiveTest.disposed created = ReactiveTest.created class RxException(Exception): pass def _raise(ex): raise RxException(ex) class TestFromIterable(unittest.TestCase): def test_subscribe_to_iterable_finite(self): iterable_finite = [1, 2, 3, 4, 5] scheduler = TestScheduler() def create(): return rx3.from_(iterable_finite) results = scheduler.start(create) assert results.messages == [ on_next(200, 1), on_next(200, 2), on_next(200, 3), on_next(200, 4), on_next(200, 5), on_completed(200)] def test_subscribe_to_iterable_empty(self): iterable_finite = [] scheduler = TestScheduler() def create(): return rx3.from_(iterable_finite) results = scheduler.start(create) assert results.messages == [on_completed(200)] def test_double_subscribe_to_iterable(self): iterable_finite = [1, 2, 3] scheduler = TestScheduler() obs = rx3.from_(iterable_finite) results = scheduler.start(lambda: rx3.concat(obs, obs)) assert results.messages == [ on_next(200, 1), on_next(200, 2), on_next(200, 3), on_next(200, 1), on_next(200, 2), on_next(200, 3), on_completed(200)] def test_observer_throws(self): with self.assertRaises(RxException): rx3.from_iterable([1, 2, 3]).subscribe(lambda x: _raise('ex'))
true
true
1c2cf128e3ee20ea0554308c2fc57970df75a721
22,701
py
Python
tests/test_periods.py
Mendybaeva/django-scheduler
eff7447993853d7d103995c6142b740aa4868ca5
[ "BSD-3-Clause" ]
null
null
null
tests/test_periods.py
Mendybaeva/django-scheduler
eff7447993853d7d103995c6142b740aa4868ca5
[ "BSD-3-Clause" ]
null
null
null
tests/test_periods.py
Mendybaeva/django-scheduler
eff7447993853d7d103995c6142b740aa4868ca5
[ "BSD-3-Clause" ]
null
null
null
import datetime import pytz from django.conf import settings from django.test import TestCase from django.test.utils import override_settings from django.utils.six.moves.builtins import range, zip from schedule.models import Calendar, Event, Rule from schedule.periods import Day, Month, Period, Week, Year class TestPeriod(TestCase): def setUp(self): rule = Rule.objects.create(frequency="WEEKLY") cal = Calendar.objects.create(name="MyCal") Event.objects.create( title='Recent Event', start=datetime.datetime(2008, 1, 5, 8, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc), end_recurring_period=datetime.datetime(2008, 5, 5, 0, 0, tzinfo=pytz.utc), rule=rule, calendar=cal, ) self.period = Period( events=Event.objects.all(), start=datetime.datetime(2008, 1, 4, 7, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 21, 7, 0, tzinfo=pytz.utc)) def test_get_occurrences(self): occurrence_list = self.period.occurrences self.assertEqual( ["%s to %s" % (o.start, o.end) for o in occurrence_list], [ '2008-01-05 08:00:00+00:00 to 2008-01-05 09:00:00+00:00', '2008-01-12 08:00:00+00:00 to 2008-01-12 09:00:00+00:00', '2008-01-19 08:00:00+00:00 to 2008-01-19 09:00:00+00:00', ] ) def test_get_occurrences_with_sorting_options(self): period = Period( events=Event.objects.all(), start=datetime.datetime(2008, 1, 4, 7, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 21, 7, 0, tzinfo=pytz.utc), sorting_options={"reverse": True}) occurrence_list = period.occurrences self.assertEqual( ["%s to %s" % (o.start, o.end) for o in occurrence_list], [ '2008-01-19 08:00:00+00:00 to 2008-01-19 09:00:00+00:00', '2008-01-12 08:00:00+00:00 to 2008-01-12 09:00:00+00:00', '2008-01-05 08:00:00+00:00 to 2008-01-05 09:00:00+00:00', ] ) def test_get_occurrence_partials(self): occurrence_dicts = self.period.get_occurrence_partials() self.assertEqual( [ (occ_dict["class"], occ_dict["occurrence"].start, occ_dict["occurrence"].end) for occ_dict in occurrence_dicts ], [ (1, datetime.datetime(2008, 1, 5, 8, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc)), (1, datetime.datetime(2008, 1, 12, 8, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 12, 9, 0, tzinfo=pytz.utc)), (1, datetime.datetime(2008, 1, 19, 8, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 19, 9, 0, tzinfo=pytz.utc)) ]) def test_has_occurrence(self): self.assertTrue(self.period.has_occurrences()) slot = self.period.get_time_slot( datetime.datetime(2008, 1, 4, 7, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 4, 7, 12, tzinfo=pytz.utc)) self.assertFalse(slot.has_occurrences()) class TestYear(TestCase): def setUp(self): self.year = Year(events=[], date=datetime.datetime(2008, 4, 1, tzinfo=pytz.utc)) def test_get_months(self): months = self.year.get_months() self.assertEqual( [month.start for month in months], [datetime.datetime(2008, i, 1, tzinfo=pytz.utc) for i in range(1, 13)]) class TestMonth(TestCase): def setUp(self): rule = Rule.objects.create(frequency="WEEKLY") cal = Calendar.objects.create(name="MyCal") Event.objects.create( title='Recent Event', start=datetime.datetime(2008, 1, 5, 8, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc), end_recurring_period=datetime.datetime(2008, 5, 5, 0, 0, tzinfo=pytz.utc), rule=rule, calendar=cal, ) self.month = Month(events=Event.objects.all(), date=datetime.datetime(2008, 2, 7, 9, 0, tzinfo=pytz.utc)) def test_get_weeks(self): weeks = self.month.get_weeks() actuals = [(week.start, week.end) for week in weeks] if settings.FIRST_DAY_OF_WEEK == 0: expecteds = [ (datetime.datetime(2008, 1, 27, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 3, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 3, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 10, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 10, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 17, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 17, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 24, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 24, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 3, 2, 0, 0, tzinfo=pytz.utc)) ] else: expecteds = [ (datetime.datetime(2008, 1, 28, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 4, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 4, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 11, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 11, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 18, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 18, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 25, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 25, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 3, 3, 0, 0, tzinfo=pytz.utc)) ] for actual, expected in zip(actuals, expecteds): self.assertEqual(actual, expected) def test_get_days(self): weeks = self.month.get_weeks() week = list(weeks)[0] days = week.get_days() actuals = [(len(day.occurrences), day.start, day.end) for day in days] if settings.FIRST_DAY_OF_WEEK == 0: expecteds = [ ( 0, datetime.datetime(2008, 1, 27, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 28, 0, 0, tzinfo=pytz.utc) ), ( 0, datetime.datetime(2008, 1, 28, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 29, 0, 0, tzinfo=pytz.utc) ), ( 0, datetime.datetime(2008, 1, 29, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 30, 0, 0, tzinfo=pytz.utc) ), ( 0, datetime.datetime(2008, 1, 30, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 31, 0, 0, tzinfo=pytz.utc) ), ( 0, datetime.datetime(2008, 1, 31, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 1, 0, 0, tzinfo=pytz.utc) ), ( 0, datetime.datetime(2008, 2, 1, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 2, 0, 0, tzinfo=pytz.utc) ), ( 1, datetime.datetime(2008, 2, 2, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 3, 0, 0, tzinfo=pytz.utc) ), ] else: expecteds = [ (0, datetime.datetime(2008, 1, 28, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 29, 0, 0, tzinfo=pytz.utc)), (0, datetime.datetime(2008, 1, 29, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 30, 0, 0, tzinfo=pytz.utc)), (0, datetime.datetime(2008, 1, 30, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 31, 0, 0, tzinfo=pytz.utc)), (0, datetime.datetime(2008, 1, 31, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 1, 0, 0, tzinfo=pytz.utc)), (0, datetime.datetime(2008, 2, 1, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 2, 0, 0, tzinfo=pytz.utc)), (1, datetime.datetime(2008, 2, 2, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 3, 0, 0, tzinfo=pytz.utc)), (0, datetime.datetime(2008, 2, 3, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 4, 0, 0, tzinfo=pytz.utc)) ] for actual, expected in zip(actuals, expecteds): self.assertEqual(actual, expected) def test_month_convenience_functions(self): self.assertEqual(self.month.prev_month().start, datetime.datetime(2008, 1, 1, 0, 0, tzinfo=pytz.utc)) self.assertEqual(self.month.next_month().start, datetime.datetime(2008, 3, 1, 0, 0, tzinfo=pytz.utc)) self.assertEqual(self.month.current_year().start, datetime.datetime(2008, 1, 1, 0, 0, tzinfo=pytz.utc)) self.assertEqual(self.month.prev_year().start, datetime.datetime(2007, 1, 1, 0, 0, tzinfo=pytz.utc)) self.assertEqual(self.month.next_year().start, datetime.datetime(2009, 1, 1, 0, 0, tzinfo=pytz.utc)) class TestDay(TestCase): def setUp(self): self.day = Day( events=Event.objects.all(), date=datetime.datetime(2008, 2, 7, 9, 0, tzinfo=pytz.utc)) def test_day_setup(self): self.assertEqual(self.day.start, datetime.datetime(2008, 2, 7, 0, 0, tzinfo=pytz.utc)) self.assertEqual(self.day.end, datetime.datetime(2008, 2, 8, 0, 0, tzinfo=pytz.utc)) def test_day_convenience_functions(self): self.assertEqual(self.day.prev_day().start, datetime.datetime(2008, 2, 6, 0, 0, tzinfo=pytz.utc)) self.assertEqual(self.day.next_day().start, datetime.datetime(2008, 2, 8, 0, 0, tzinfo=pytz.utc)) def test_time_slot(self): slot_start = datetime.datetime(2008, 2, 7, 13, 30, tzinfo=pytz.utc) slot_end = datetime.datetime(2008, 2, 7, 15, 0, tzinfo=pytz.utc) period = self.day.get_time_slot(slot_start, slot_end) self.assertEqual(period.start, slot_start) self.assertEqual(period.end, slot_end) def test_time_slot_with_dst(self): tzinfo = pytz.timezone('America/Vancouver') slot_start = datetime.datetime(2016, 3, 13, 0, 0, tzinfo=tzinfo) slot_end = datetime.datetime(2016, 3, 14, 0, 0, tzinfo=tzinfo) period = self.day.get_time_slot(slot_start, slot_end) self.assertEqual(period.start, slot_start) self.assertEqual(period.end, slot_end) def test_get_day_range(self): # This test exercises the case where a Day object is initiatized with # no date, which causes the Day constructor to call timezone.now(), # which always uses UTC. This can cause a problem if the desired TZ # is not UTC, because the _get_day_range method typecasts the # tz-aware datetime to a naive datetime. # To simulate this case, we will create a NY tz date, localize that # date to UTC, then create a Day object with the UTC date and NY TZ NY = pytz.timezone('America/New_York') user_wall_time = datetime.datetime(2015, 11, 4, 21, 30, tzinfo=NY) timezone_now = user_wall_time.astimezone(pytz.utc) test_day = Day( events=Event.objects.all(), date=timezone_now, tzinfo=NY) expected_start = datetime.datetime(2015, 11, 4, 5, 00, tzinfo=pytz.utc) expected_end = datetime.datetime(2015, 11, 5, 5, 00, tzinfo=pytz.utc) self.assertEqual(test_day.start, expected_start) self.assertEqual(test_day.end, expected_end) class TestOccurrencePool(TestCase): def setUp(self): rule = Rule.objects.create(frequency="WEEKLY") cal = Calendar.objects.create(name="MyCal") self.recurring_event = Event.objects.create( title='Recent Event', start=datetime.datetime(2008, 1, 5, 8, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc), end_recurring_period=datetime.datetime(2008, 5, 5, 0, 0, tzinfo=pytz.utc), rule=rule, calendar=cal, ) def testPeriodFromPool(self): """ Test that period initiated with occurrence_pool returns the same occurrences as "straigh" period in a corner case whereby a period's start date is equal to the occurrence's end date """ start = datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc) end = datetime.datetime(2008, 1, 5, 10, 0, tzinfo=pytz.utc) parent_period = Period(Event.objects.all(), start, end) period = Period(parent_period.events, start, end, parent_period.get_persisted_occurrences(), parent_period.occurrences) self.assertEqual(parent_period.occurrences, period.occurrences) class TestOccurrencesInTimezone(TestCase): def setUp(self): self.MVD = pytz.timezone('America/Montevideo') cal = Calendar.objects.create(name="MyCal") rule = Rule.objects.create(frequency="DAILY", params="byweekday:SA", name="Saturdays") Event.objects.create( title='Every Saturday Event', start=self.MVD.localize(datetime.datetime(2017, 1, 7, 22, 0)), end=self.MVD.localize(datetime.datetime(2017, 1, 7, 23, 0)), end_recurring_period=self.MVD.localize(datetime.datetime(2017, 2, 1)), rule=rule, calendar=cal, ) @override_settings(TIME_ZONE='America/Montevideo') def test_occurrences_with_TZ(self): start = self.MVD.localize(datetime.datetime(2017, 1, 13)) end = self.MVD.localize(datetime.datetime(2017, 1, 23)) period = Period(Event.objects.all(), start, end, tzinfo=self.MVD) self.assertEqual( ["%s to %s" % (o.start, o.end) for o in period.occurrences], [ '2017-01-14 22:00:00-03:00 to 2017-01-14 23:00:00-03:00', '2017-01-21 22:00:00-03:00 to 2017-01-21 23:00:00-03:00', ] ) @override_settings(TIME_ZONE='America/Montevideo') def test_occurrences_sub_period_with_TZ(self): start = self.MVD.localize(datetime.datetime(2017, 1, 13)) end = self.MVD.localize(datetime.datetime(2017, 1, 23)) period = Period(Event.objects.all(), start, end, tzinfo=self.MVD) sub_start = self.MVD.localize(datetime.datetime(2017, 1, 13)) sub_end = self.MVD.localize(datetime.datetime(2017, 1, 15)) sub_period = period.get_time_slot(sub_start, sub_end) self.assertEqual( ["%s to %s" % (o.start, o.end) for o in sub_period.occurrences], ['2017-01-14 22:00:00-03:00 to 2017-01-14 23:00:00-03:00']) class TestWeeklyOccurrences(TestCase): def setUp(self): self.MVD = pytz.timezone('America/Montevideo') # UTC-3 cal = Calendar.objects.create(name="MyCal") rule = Rule.objects.create(frequency="DAILY", name="daily") Event.objects.create( title='Test event', start=self.MVD.localize(datetime.datetime(2017, 1, 13, 15, 0)), end=self.MVD.localize(datetime.datetime(2017, 1, 14, 15, 0)), end_recurring_period=self.MVD.localize(datetime.datetime(2017, 1, 20)), rule=rule, calendar=cal, ) def test_occurrences_inside_recurrence_period(self): start = self.MVD.localize(datetime.datetime(2017, 1, 13)) period = Week(Event.objects.all(), start, tzinfo=self.MVD) self.assertEqual( ["%s to %s" % (o.start, o.end) for o in period.occurrences], [ '2017-01-13 15:00:00-03:00 to 2017-01-14 15:00:00-03:00', '2017-01-14 15:00:00-03:00 to 2017-01-15 15:00:00-03:00', ] ) def test_occurrences_outside_recurrence_period(self): start = self.MVD.localize(datetime.datetime(2017, 1, 23)) period = Week(Event.objects.all(), start, tzinfo=self.MVD) self.assertEqual(["%s to %s" % (o.start, o.end) for o in period.occurrences], []) def test_occurrences_no_end(self): event = Event.objects.filter(title='Test event').get() event.end_recurring_period = None start = self.MVD.localize(datetime.datetime(2018, 1, 13)) period = Week([event], start, tzinfo=self.MVD) self.assertEqual( ["%s to %s" % (o.start, o.end) for o in period.occurrences], [ '2018-01-06 15:00:00-03:00 to 2018-01-07 15:00:00-03:00', '2018-01-07 15:00:00-03:00 to 2018-01-08 15:00:00-03:00', '2018-01-08 15:00:00-03:00 to 2018-01-09 15:00:00-03:00', '2018-01-09 15:00:00-03:00 to 2018-01-10 15:00:00-03:00', '2018-01-10 15:00:00-03:00 to 2018-01-11 15:00:00-03:00', '2018-01-11 15:00:00-03:00 to 2018-01-12 15:00:00-03:00', '2018-01-12 15:00:00-03:00 to 2018-01-13 15:00:00-03:00', '2018-01-13 15:00:00-03:00 to 2018-01-14 15:00:00-03:00', ] ) def test_occurrences_end_in_diff_tz(self): event = Event.objects.filter(title='Test event').get() AMSTERDAM = pytz.timezone('Europe/Amsterdam') # 2017-01-14 00:00 CET = 2017-01-13 21:00 UYT event.end_recurring_period = AMSTERDAM.localize(datetime.datetime(2017, 1, 14, 0, 0)) start = self.MVD.localize(datetime.datetime(2017, 1, 13)) period = Week([event], start, tzinfo=self.MVD) self.assertEqual( ["%s to %s" % (o.start, o.end) for o in period.occurrences], ['2017-01-13 15:00:00-03:00 to 2017-01-14 15:00:00-03:00']) class TestAwareDay(TestCase): def setUp(self): self.timezone = pytz.timezone('Europe/Amsterdam') start = self.timezone.localize(datetime.datetime(2008, 2, 7, 0, 20)) end = self.timezone.localize(datetime.datetime(2008, 2, 7, 0, 21)) self.event = Event.objects.create( title='One minute long event on january seventh 2008 at 00:20 in Amsterdam.', start=start, end=end) self.day = Day( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2008, 2, 7, 9, 0)), tzinfo=self.timezone, ) def test_day_range(self): start = datetime.datetime(2008, 2, 6, 23, 0, tzinfo=pytz.utc) end = datetime.datetime(2008, 2, 7, 23, 0, tzinfo=pytz.utc) self.assertEqual(start, self.day.start) self.assertEqual(end, self.day.end) def test_occurrence(self): self.assertEqual(self.event in [o.event for o in self.day.occurrences], True) class TestTzInfoPersistence(TestCase): def setUp(self): self.timezone = pytz.timezone('Europe/Amsterdam') self.day = Day( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 12, 17, 9, 0)), tzinfo=self.timezone ) self.week = Week( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 12, 17, 9, 0)), tzinfo=self.timezone, ) self.month = Month( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 12, 17, 9, 0)), tzinfo=self.timezone, ) self.year = Year( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 12, 17, 9, 0)), tzinfo=self.timezone, ) def test_persistence(self): self.assertEqual(self.day.tzinfo, self.timezone) self.assertEqual(self.week.tzinfo, self.timezone) self.assertEqual(self.month.tzinfo, self.timezone) self.assertEqual(self.year.tzinfo, self.timezone) class TestAwareWeek(TestCase): def setUp(self): self.timezone = pytz.timezone('Europe/Amsterdam') self.week = Week( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 12, 17, 9, 0)), tzinfo=self.timezone, ) def test_week_range(self): start = self.timezone.localize(datetime.datetime(2013, 12, 15, 0, 0)) end = self.timezone.localize(datetime.datetime(2013, 12, 22, 0, 0)) self.assertEqual(self.week.tzinfo, self.timezone) self.assertEqual(start, self.week.start) self.assertEqual(end, self.week.end) class TestAwareMonth(TestCase): def setUp(self): self.timezone = pytz.timezone('Europe/Amsterdam') self.month = Month( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 11, 17, 9, 0)), tzinfo=self.timezone, ) def test_month_range(self): start = self.timezone.localize(datetime.datetime(2013, 11, 1, 0, 0)) end = self.timezone.localize(datetime.datetime(2013, 12, 1, 0, 0)) self.assertEqual(self.month.tzinfo, self.timezone) self.assertEqual(start, self.month.start) self.assertEqual(end, self.month.end) class TestAwareYear(TestCase): def setUp(self): self.timezone = pytz.timezone('Europe/Amsterdam') self.year = Year( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 12, 17, 9, 0)), tzinfo=self.timezone, ) def test_year_range(self): start = self.timezone.localize(datetime.datetime(2013, 1, 1, 0, 0)) end = self.timezone.localize(datetime.datetime(2014, 1, 1, 0, 0)) self.assertEqual(self.year.tzinfo, self.timezone) self.assertEqual(start, self.year.start) self.assertEqual(end, self.year.end) class TestStrftimeRefactor(TestCase): """ Test for the refactor of strftime """ def test_years_before_1900(self): d = datetime.date(year=1899, month=1, day=1) m = Month([], d) try: m.name() except ValueError as value_error: self.fail(value_error)
41.883764
127
0.580944
import datetime import pytz from django.conf import settings from django.test import TestCase from django.test.utils import override_settings from django.utils.six.moves.builtins import range, zip from schedule.models import Calendar, Event, Rule from schedule.periods import Day, Month, Period, Week, Year class TestPeriod(TestCase): def setUp(self): rule = Rule.objects.create(frequency="WEEKLY") cal = Calendar.objects.create(name="MyCal") Event.objects.create( title='Recent Event', start=datetime.datetime(2008, 1, 5, 8, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc), end_recurring_period=datetime.datetime(2008, 5, 5, 0, 0, tzinfo=pytz.utc), rule=rule, calendar=cal, ) self.period = Period( events=Event.objects.all(), start=datetime.datetime(2008, 1, 4, 7, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 21, 7, 0, tzinfo=pytz.utc)) def test_get_occurrences(self): occurrence_list = self.period.occurrences self.assertEqual( ["%s to %s" % (o.start, o.end) for o in occurrence_list], [ '2008-01-05 08:00:00+00:00 to 2008-01-05 09:00:00+00:00', '2008-01-12 08:00:00+00:00 to 2008-01-12 09:00:00+00:00', '2008-01-19 08:00:00+00:00 to 2008-01-19 09:00:00+00:00', ] ) def test_get_occurrences_with_sorting_options(self): period = Period( events=Event.objects.all(), start=datetime.datetime(2008, 1, 4, 7, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 21, 7, 0, tzinfo=pytz.utc), sorting_options={"reverse": True}) occurrence_list = period.occurrences self.assertEqual( ["%s to %s" % (o.start, o.end) for o in occurrence_list], [ '2008-01-19 08:00:00+00:00 to 2008-01-19 09:00:00+00:00', '2008-01-12 08:00:00+00:00 to 2008-01-12 09:00:00+00:00', '2008-01-05 08:00:00+00:00 to 2008-01-05 09:00:00+00:00', ] ) def test_get_occurrence_partials(self): occurrence_dicts = self.period.get_occurrence_partials() self.assertEqual( [ (occ_dict["class"], occ_dict["occurrence"].start, occ_dict["occurrence"].end) for occ_dict in occurrence_dicts ], [ (1, datetime.datetime(2008, 1, 5, 8, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc)), (1, datetime.datetime(2008, 1, 12, 8, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 12, 9, 0, tzinfo=pytz.utc)), (1, datetime.datetime(2008, 1, 19, 8, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 19, 9, 0, tzinfo=pytz.utc)) ]) def test_has_occurrence(self): self.assertTrue(self.period.has_occurrences()) slot = self.period.get_time_slot( datetime.datetime(2008, 1, 4, 7, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 4, 7, 12, tzinfo=pytz.utc)) self.assertFalse(slot.has_occurrences()) class TestYear(TestCase): def setUp(self): self.year = Year(events=[], date=datetime.datetime(2008, 4, 1, tzinfo=pytz.utc)) def test_get_months(self): months = self.year.get_months() self.assertEqual( [month.start for month in months], [datetime.datetime(2008, i, 1, tzinfo=pytz.utc) for i in range(1, 13)]) class TestMonth(TestCase): def setUp(self): rule = Rule.objects.create(frequency="WEEKLY") cal = Calendar.objects.create(name="MyCal") Event.objects.create( title='Recent Event', start=datetime.datetime(2008, 1, 5, 8, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc), end_recurring_period=datetime.datetime(2008, 5, 5, 0, 0, tzinfo=pytz.utc), rule=rule, calendar=cal, ) self.month = Month(events=Event.objects.all(), date=datetime.datetime(2008, 2, 7, 9, 0, tzinfo=pytz.utc)) def test_get_weeks(self): weeks = self.month.get_weeks() actuals = [(week.start, week.end) for week in weeks] if settings.FIRST_DAY_OF_WEEK == 0: expecteds = [ (datetime.datetime(2008, 1, 27, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 3, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 3, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 10, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 10, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 17, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 17, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 24, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 24, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 3, 2, 0, 0, tzinfo=pytz.utc)) ] else: expecteds = [ (datetime.datetime(2008, 1, 28, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 4, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 4, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 11, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 11, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 18, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 18, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 25, 0, 0, tzinfo=pytz.utc)), (datetime.datetime(2008, 2, 25, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 3, 3, 0, 0, tzinfo=pytz.utc)) ] for actual, expected in zip(actuals, expecteds): self.assertEqual(actual, expected) def test_get_days(self): weeks = self.month.get_weeks() week = list(weeks)[0] days = week.get_days() actuals = [(len(day.occurrences), day.start, day.end) for day in days] if settings.FIRST_DAY_OF_WEEK == 0: expecteds = [ ( 0, datetime.datetime(2008, 1, 27, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 28, 0, 0, tzinfo=pytz.utc) ), ( 0, datetime.datetime(2008, 1, 28, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 29, 0, 0, tzinfo=pytz.utc) ), ( 0, datetime.datetime(2008, 1, 29, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 30, 0, 0, tzinfo=pytz.utc) ), ( 0, datetime.datetime(2008, 1, 30, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 31, 0, 0, tzinfo=pytz.utc) ), ( 0, datetime.datetime(2008, 1, 31, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 1, 0, 0, tzinfo=pytz.utc) ), ( 0, datetime.datetime(2008, 2, 1, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 2, 0, 0, tzinfo=pytz.utc) ), ( 1, datetime.datetime(2008, 2, 2, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 3, 0, 0, tzinfo=pytz.utc) ), ] else: expecteds = [ (0, datetime.datetime(2008, 1, 28, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 29, 0, 0, tzinfo=pytz.utc)), (0, datetime.datetime(2008, 1, 29, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 30, 0, 0, tzinfo=pytz.utc)), (0, datetime.datetime(2008, 1, 30, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 31, 0, 0, tzinfo=pytz.utc)), (0, datetime.datetime(2008, 1, 31, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 1, 0, 0, tzinfo=pytz.utc)), (0, datetime.datetime(2008, 2, 1, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 2, 0, 0, tzinfo=pytz.utc)), (1, datetime.datetime(2008, 2, 2, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 3, 0, 0, tzinfo=pytz.utc)), (0, datetime.datetime(2008, 2, 3, 0, 0, tzinfo=pytz.utc), datetime.datetime(2008, 2, 4, 0, 0, tzinfo=pytz.utc)) ] for actual, expected in zip(actuals, expecteds): self.assertEqual(actual, expected) def test_month_convenience_functions(self): self.assertEqual(self.month.prev_month().start, datetime.datetime(2008, 1, 1, 0, 0, tzinfo=pytz.utc)) self.assertEqual(self.month.next_month().start, datetime.datetime(2008, 3, 1, 0, 0, tzinfo=pytz.utc)) self.assertEqual(self.month.current_year().start, datetime.datetime(2008, 1, 1, 0, 0, tzinfo=pytz.utc)) self.assertEqual(self.month.prev_year().start, datetime.datetime(2007, 1, 1, 0, 0, tzinfo=pytz.utc)) self.assertEqual(self.month.next_year().start, datetime.datetime(2009, 1, 1, 0, 0, tzinfo=pytz.utc)) class TestDay(TestCase): def setUp(self): self.day = Day( events=Event.objects.all(), date=datetime.datetime(2008, 2, 7, 9, 0, tzinfo=pytz.utc)) def test_day_setup(self): self.assertEqual(self.day.start, datetime.datetime(2008, 2, 7, 0, 0, tzinfo=pytz.utc)) self.assertEqual(self.day.end, datetime.datetime(2008, 2, 8, 0, 0, tzinfo=pytz.utc)) def test_day_convenience_functions(self): self.assertEqual(self.day.prev_day().start, datetime.datetime(2008, 2, 6, 0, 0, tzinfo=pytz.utc)) self.assertEqual(self.day.next_day().start, datetime.datetime(2008, 2, 8, 0, 0, tzinfo=pytz.utc)) def test_time_slot(self): slot_start = datetime.datetime(2008, 2, 7, 13, 30, tzinfo=pytz.utc) slot_end = datetime.datetime(2008, 2, 7, 15, 0, tzinfo=pytz.utc) period = self.day.get_time_slot(slot_start, slot_end) self.assertEqual(period.start, slot_start) self.assertEqual(period.end, slot_end) def test_time_slot_with_dst(self): tzinfo = pytz.timezone('America/Vancouver') slot_start = datetime.datetime(2016, 3, 13, 0, 0, tzinfo=tzinfo) slot_end = datetime.datetime(2016, 3, 14, 0, 0, tzinfo=tzinfo) period = self.day.get_time_slot(slot_start, slot_end) self.assertEqual(period.start, slot_start) self.assertEqual(period.end, slot_end) def test_get_day_range(self): NY = pytz.timezone('America/New_York') user_wall_time = datetime.datetime(2015, 11, 4, 21, 30, tzinfo=NY) timezone_now = user_wall_time.astimezone(pytz.utc) test_day = Day( events=Event.objects.all(), date=timezone_now, tzinfo=NY) expected_start = datetime.datetime(2015, 11, 4, 5, 00, tzinfo=pytz.utc) expected_end = datetime.datetime(2015, 11, 5, 5, 00, tzinfo=pytz.utc) self.assertEqual(test_day.start, expected_start) self.assertEqual(test_day.end, expected_end) class TestOccurrencePool(TestCase): def setUp(self): rule = Rule.objects.create(frequency="WEEKLY") cal = Calendar.objects.create(name="MyCal") self.recurring_event = Event.objects.create( title='Recent Event', start=datetime.datetime(2008, 1, 5, 8, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc), end_recurring_period=datetime.datetime(2008, 5, 5, 0, 0, tzinfo=pytz.utc), rule=rule, calendar=cal, ) def testPeriodFromPool(self): start = datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc) end = datetime.datetime(2008, 1, 5, 10, 0, tzinfo=pytz.utc) parent_period = Period(Event.objects.all(), start, end) period = Period(parent_period.events, start, end, parent_period.get_persisted_occurrences(), parent_period.occurrences) self.assertEqual(parent_period.occurrences, period.occurrences) class TestOccurrencesInTimezone(TestCase): def setUp(self): self.MVD = pytz.timezone('America/Montevideo') cal = Calendar.objects.create(name="MyCal") rule = Rule.objects.create(frequency="DAILY", params="byweekday:SA", name="Saturdays") Event.objects.create( title='Every Saturday Event', start=self.MVD.localize(datetime.datetime(2017, 1, 7, 22, 0)), end=self.MVD.localize(datetime.datetime(2017, 1, 7, 23, 0)), end_recurring_period=self.MVD.localize(datetime.datetime(2017, 2, 1)), rule=rule, calendar=cal, ) @override_settings(TIME_ZONE='America/Montevideo') def test_occurrences_with_TZ(self): start = self.MVD.localize(datetime.datetime(2017, 1, 13)) end = self.MVD.localize(datetime.datetime(2017, 1, 23)) period = Period(Event.objects.all(), start, end, tzinfo=self.MVD) self.assertEqual( ["%s to %s" % (o.start, o.end) for o in period.occurrences], [ '2017-01-14 22:00:00-03:00 to 2017-01-14 23:00:00-03:00', '2017-01-21 22:00:00-03:00 to 2017-01-21 23:00:00-03:00', ] ) @override_settings(TIME_ZONE='America/Montevideo') def test_occurrences_sub_period_with_TZ(self): start = self.MVD.localize(datetime.datetime(2017, 1, 13)) end = self.MVD.localize(datetime.datetime(2017, 1, 23)) period = Period(Event.objects.all(), start, end, tzinfo=self.MVD) sub_start = self.MVD.localize(datetime.datetime(2017, 1, 13)) sub_end = self.MVD.localize(datetime.datetime(2017, 1, 15)) sub_period = period.get_time_slot(sub_start, sub_end) self.assertEqual( ["%s to %s" % (o.start, o.end) for o in sub_period.occurrences], ['2017-01-14 22:00:00-03:00 to 2017-01-14 23:00:00-03:00']) class TestWeeklyOccurrences(TestCase): def setUp(self): self.MVD = pytz.timezone('America/Montevideo') cal = Calendar.objects.create(name="MyCal") rule = Rule.objects.create(frequency="DAILY", name="daily") Event.objects.create( title='Test event', start=self.MVD.localize(datetime.datetime(2017, 1, 13, 15, 0)), end=self.MVD.localize(datetime.datetime(2017, 1, 14, 15, 0)), end_recurring_period=self.MVD.localize(datetime.datetime(2017, 1, 20)), rule=rule, calendar=cal, ) def test_occurrences_inside_recurrence_period(self): start = self.MVD.localize(datetime.datetime(2017, 1, 13)) period = Week(Event.objects.all(), start, tzinfo=self.MVD) self.assertEqual( ["%s to %s" % (o.start, o.end) for o in period.occurrences], [ '2017-01-13 15:00:00-03:00 to 2017-01-14 15:00:00-03:00', '2017-01-14 15:00:00-03:00 to 2017-01-15 15:00:00-03:00', ] ) def test_occurrences_outside_recurrence_period(self): start = self.MVD.localize(datetime.datetime(2017, 1, 23)) period = Week(Event.objects.all(), start, tzinfo=self.MVD) self.assertEqual(["%s to %s" % (o.start, o.end) for o in period.occurrences], []) def test_occurrences_no_end(self): event = Event.objects.filter(title='Test event').get() event.end_recurring_period = None start = self.MVD.localize(datetime.datetime(2018, 1, 13)) period = Week([event], start, tzinfo=self.MVD) self.assertEqual( ["%s to %s" % (o.start, o.end) for o in period.occurrences], [ '2018-01-06 15:00:00-03:00 to 2018-01-07 15:00:00-03:00', '2018-01-07 15:00:00-03:00 to 2018-01-08 15:00:00-03:00', '2018-01-08 15:00:00-03:00 to 2018-01-09 15:00:00-03:00', '2018-01-09 15:00:00-03:00 to 2018-01-10 15:00:00-03:00', '2018-01-10 15:00:00-03:00 to 2018-01-11 15:00:00-03:00', '2018-01-11 15:00:00-03:00 to 2018-01-12 15:00:00-03:00', '2018-01-12 15:00:00-03:00 to 2018-01-13 15:00:00-03:00', '2018-01-13 15:00:00-03:00 to 2018-01-14 15:00:00-03:00', ] ) def test_occurrences_end_in_diff_tz(self): event = Event.objects.filter(title='Test event').get() AMSTERDAM = pytz.timezone('Europe/Amsterdam') event.end_recurring_period = AMSTERDAM.localize(datetime.datetime(2017, 1, 14, 0, 0)) start = self.MVD.localize(datetime.datetime(2017, 1, 13)) period = Week([event], start, tzinfo=self.MVD) self.assertEqual( ["%s to %s" % (o.start, o.end) for o in period.occurrences], ['2017-01-13 15:00:00-03:00 to 2017-01-14 15:00:00-03:00']) class TestAwareDay(TestCase): def setUp(self): self.timezone = pytz.timezone('Europe/Amsterdam') start = self.timezone.localize(datetime.datetime(2008, 2, 7, 0, 20)) end = self.timezone.localize(datetime.datetime(2008, 2, 7, 0, 21)) self.event = Event.objects.create( title='One minute long event on january seventh 2008 at 00:20 in Amsterdam.', start=start, end=end) self.day = Day( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2008, 2, 7, 9, 0)), tzinfo=self.timezone, ) def test_day_range(self): start = datetime.datetime(2008, 2, 6, 23, 0, tzinfo=pytz.utc) end = datetime.datetime(2008, 2, 7, 23, 0, tzinfo=pytz.utc) self.assertEqual(start, self.day.start) self.assertEqual(end, self.day.end) def test_occurrence(self): self.assertEqual(self.event in [o.event for o in self.day.occurrences], True) class TestTzInfoPersistence(TestCase): def setUp(self): self.timezone = pytz.timezone('Europe/Amsterdam') self.day = Day( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 12, 17, 9, 0)), tzinfo=self.timezone ) self.week = Week( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 12, 17, 9, 0)), tzinfo=self.timezone, ) self.month = Month( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 12, 17, 9, 0)), tzinfo=self.timezone, ) self.year = Year( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 12, 17, 9, 0)), tzinfo=self.timezone, ) def test_persistence(self): self.assertEqual(self.day.tzinfo, self.timezone) self.assertEqual(self.week.tzinfo, self.timezone) self.assertEqual(self.month.tzinfo, self.timezone) self.assertEqual(self.year.tzinfo, self.timezone) class TestAwareWeek(TestCase): def setUp(self): self.timezone = pytz.timezone('Europe/Amsterdam') self.week = Week( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 12, 17, 9, 0)), tzinfo=self.timezone, ) def test_week_range(self): start = self.timezone.localize(datetime.datetime(2013, 12, 15, 0, 0)) end = self.timezone.localize(datetime.datetime(2013, 12, 22, 0, 0)) self.assertEqual(self.week.tzinfo, self.timezone) self.assertEqual(start, self.week.start) self.assertEqual(end, self.week.end) class TestAwareMonth(TestCase): def setUp(self): self.timezone = pytz.timezone('Europe/Amsterdam') self.month = Month( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 11, 17, 9, 0)), tzinfo=self.timezone, ) def test_month_range(self): start = self.timezone.localize(datetime.datetime(2013, 11, 1, 0, 0)) end = self.timezone.localize(datetime.datetime(2013, 12, 1, 0, 0)) self.assertEqual(self.month.tzinfo, self.timezone) self.assertEqual(start, self.month.start) self.assertEqual(end, self.month.end) class TestAwareYear(TestCase): def setUp(self): self.timezone = pytz.timezone('Europe/Amsterdam') self.year = Year( events=Event.objects.all(), date=self.timezone.localize(datetime.datetime(2013, 12, 17, 9, 0)), tzinfo=self.timezone, ) def test_year_range(self): start = self.timezone.localize(datetime.datetime(2013, 1, 1, 0, 0)) end = self.timezone.localize(datetime.datetime(2014, 1, 1, 0, 0)) self.assertEqual(self.year.tzinfo, self.timezone) self.assertEqual(start, self.year.start) self.assertEqual(end, self.year.end) class TestStrftimeRefactor(TestCase): def test_years_before_1900(self): d = datetime.date(year=1899, month=1, day=1) m = Month([], d) try: m.name() except ValueError as value_error: self.fail(value_error)
true
true
1c2cf18d17ed5498a5d84cc94afa5ffe58a79da3
530
py
Python
bibbutler_web/migrations/0003_bibliography_addition.py
dolonnen/bibbuttler
a9f672d0321fa6d060e204ecc952ed333edc1d81
[ "MIT" ]
null
null
null
bibbutler_web/migrations/0003_bibliography_addition.py
dolonnen/bibbuttler
a9f672d0321fa6d060e204ecc952ed333edc1d81
[ "MIT" ]
null
null
null
bibbutler_web/migrations/0003_bibliography_addition.py
dolonnen/bibbuttler
a9f672d0321fa6d060e204ecc952ed333edc1d81
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-04 12:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bibbutler_web', '0002_auto_20160601_2103'), ] operations = [ migrations.AddField( model_name='bibliography', name='addition', field=models.CharField(blank=True, help_text='additional infos like version or something', max_length=20), ), ]
25.238095
118
0.649057
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bibbutler_web', '0002_auto_20160601_2103'), ] operations = [ migrations.AddField( model_name='bibliography', name='addition', field=models.CharField(blank=True, help_text='additional infos like version or something', max_length=20), ), ]
true
true
1c2cf3a169030dcfe3159a2340d5dcc68743c019
147
py
Python
ajunivel/apps.py
HumbertoDiego/django-ajustamento-redes-nivelamento
47912ccb4ba9fc29709add18bab688af50cfb582
[ "MIT" ]
1
2022-03-06T01:10:43.000Z
2022-03-06T01:10:43.000Z
ajunivel/apps.py
HumbertoDiego/django-ajustamento-redes-nivelamento
47912ccb4ba9fc29709add18bab688af50cfb582
[ "MIT" ]
null
null
null
ajunivel/apps.py
HumbertoDiego/django-ajustamento-redes-nivelamento
47912ccb4ba9fc29709add18bab688af50cfb582
[ "MIT" ]
null
null
null
from django.apps import AppConfig class AjunivelConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'ajunivel'
24.5
56
0.768707
from django.apps import AppConfig class AjunivelConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'ajunivel'
true
true
1c2cf665aa832a0cb1e917a9d43fe054bd1b9894
24,204
py
Python
gcloudc/db/backends/datastore/query.py
potatolondon/django-gcloud-connectors
99ac93c618a5bb8c4200fff14d13b0bff868aa94
[ "BSD-3-Clause" ]
10
2019-03-12T15:01:59.000Z
2021-12-14T02:06:21.000Z
gcloudc/db/backends/datastore/query.py
potatolondon/django-gcloud-connectors
99ac93c618a5bb8c4200fff14d13b0bff868aa94
[ "BSD-3-Clause" ]
9
2019-07-25T14:35:04.000Z
2019-12-19T11:35:49.000Z
gcloudc/db/backends/datastore/query.py
potatolondon/django-gcloud-connectors
99ac93c618a5bb8c4200fff14d13b0bff868aa94
[ "BSD-3-Clause" ]
2
2019-11-08T16:37:20.000Z
2020-05-27T15:10:27.000Z
import datetime import json import logging import re from itertools import chain from django.db import ( NotSupportedError, connections, ) from django.db.models import AutoField from django.core.exceptions import EmptyResultSet from . import POLYMODEL_CLASS_ATTRIBUTE from .indexing import ( add_special_index, get_indexer, ) from .utils import ( ensure_datetime, get_field_from_column, get_top_concrete_parent, has_concrete_parents, ) logger = logging.getLogger(__name__) VALID_QUERY_KINDS = ("SELECT", "UPDATE", "INSERT", "DELETE", "COUNT", "AVERAGE") VALID_ANNOTATIONS = {"MIN": min, "MAX": max, "SUM": sum, "COUNT": len, "AVG": lambda x: (sum(x) / len(x))} VALID_CONNECTORS = ("AND", "OR") VALID_OPERATORS = ("=", "<", ">", "<=", ">=", "IN") def convert_operator(operator): if operator == "exact": return "=" elif operator == "gt": return ">" elif operator == "lt": return "<" elif operator == "gte": return ">=" elif operator == "lte": return "<=" return operator.upper() class WhereNode(object): def __init__(self, using): self.using = using self.column = None self.operator = None self.value = None self.output_field = None self.will_never_return_results = False self.lookup_name = None self.children = [] self.connector = "AND" self.negated = False @property def is_leaf(self): return bool(self.column and self.operator) def set_connector(self, connector): self.connector = connector def append_child(self, node): self.children.append(node) def set_leaf(self, column, operator, value, is_pk_field, negated, lookup_name, namespace, target_field=None): # We need access to the Datastore client to access the Key factory wrapper = connections[self.using] wrapper.ensure_connection() gclient = wrapper.connection.gclient assert column assert operator assert isinstance(is_pk_field, bool) assert isinstance(negated, bool) if operator == "iexact" and isinstance(target_field, AutoField): # When new instance is created, automatic primary key 'id' # does not generate '_idx_iexact_id'. # As the primary key 'id' (AutoField) is integer and is always case insensitive, # we can deal with 'id_iexact=' query by using 'exact' rather than 'iexact'. operator = "exact" value = int(value) if is_pk_field: # If this is a primary key, we need to make sure that the value # we pass to the query is a datastore Key. We have to deal with IN queries here # because they aren't flattened until the DNF stage model = get_top_concrete_parent(target_field.model) table = model._meta.db_table if isinstance(value, (list, tuple)): value = [gclient.key(table, x, namespace=namespace) for x in value if x] else: # Django 1.11 has operators as symbols, earlier versions use "exact" etc. if (operator == "isnull" and value is True) or ( operator in ("exact", "lt", "lte", "<", "<=", "=") and not value ): # id=None will never return anything and # Empty strings and 0 are forbidden as keys self.will_never_return_results = True elif operator in ("gt", "gte", ">", ">=") and not value: # If the value is 0 or "", then we need to manipulate the value and operator here to # get the right result (given that both are invalid keys) so for both we return # >= 1 or >= "\0" for strings if isinstance(value, int): value = 1 else: value = "\0" value = gclient.key(table, value, namespace=namespace) operator = "gte" else: value = gclient.key(table, value, namespace=namespace) column = "__key__" # Do any special index conversions necessary to perform this lookup special_indexer = get_indexer(target_field, operator) if special_indexer: if is_pk_field: column = model._meta.pk.column value = str(value.id_or_name) add_special_index(connections[self.using], target_field.model, column, special_indexer, operator, value) index_type = special_indexer.prepare_index_type(operator, value) value = special_indexer.prep_value_for_query( value, model=target_field.model, column=column, connection=connections[self.using] ) column = special_indexer.indexed_column_name(column, value, index_type) operator = special_indexer.prep_query_operator(operator) self.column = column self.operator = convert_operator(operator) self.value = value self.lookup_name = lookup_name def __iter__(self): for child in chain(*map(iter, self.children)): yield child yield self def __repr__(self): if self.is_leaf: return "[%s%s%s]" % (self.column, self.operator, self.value) else: return "(%s:%s%s)" % ( self.connector, "!" if self.negated else "", ",".join([repr(x) for x in self.children]), ) def __eq__(self, rhs): if self.is_leaf != rhs.is_leaf: return False if self.is_leaf: return self.column == rhs.column and self.value == rhs.value and self.operator == rhs.operator else: return self.connector == rhs.connector and self.children == rhs.children def __hash__(self): if self.is_leaf: return hash((self.column, self.value, self.operator)) else: return hash((self.connector,) + tuple([hash(x) for x in self.children])) class Query(object): def __init__(self, model, kind): assert kind in VALID_QUERY_KINDS self.model = model self.concrete_model = get_top_concrete_parent(model) self.kind = kind self.projection_possible = True self.tables = [] self.columns = None # None means all fields self.init_list = [] self.distinct = False self.order_by = [] self.row_data = [] # For insert/updates self._where = None self.low_mark = self.high_mark = None self.annotations = [] self.per_entity_annotations = [] self.extra_selects = [] self.polymodel_filter_added = False # A list of PKs that should be excluded from the resultset self.excluded_pks = set() @property def is_normalized(self): """ Returns True if this query has a normalized where tree """ if not self.where: return True # Only a leaf node, return True if not self.where.is_leaf: return True # If we have children, and they are all leaf nodes then this is a normalized # query return self.where.connector == "OR" and self.where.children and all(x.is_leaf for x in self.where.children) def add_extra_select(self, column, lookup): if lookup.lower().startswith("select "): raise ValueError("SQL statements aren't supported with extra(select=)") # Boolean expression test bool_expr = r"(?P<lhs>[a-zA-Z0-9_]+)\s?(?P<op>[=|>|<]{1,2})\s?(?P<rhs>[\w+|']+)" # Operator expression test op_expr = r"(?P<lhs>[a-zA-Z0-9_]+)\s?(?P<op>[+|-|/|*])\s?(?P<rhs>[\w+|']+)" OP_LOOKUP = { "=": lambda x, y: x == y, "is": lambda x, y: x == y, "<": lambda x, y: x < y, ">": lambda x, y: x > y, ">=": lambda x, y: x >= y, "<=": lambda x, y: x <= y, "+": lambda x, y: x + y, "-": lambda x, y: x - y, "/": lambda x, y: x / y, "*": lambda x, y: x * y, } for regex in (bool_expr, op_expr): match = re.match(regex, lookup) if match: lhs = match.group("lhs") rhs = match.group("rhs") op = match.group("op").lower() if op in OP_LOOKUP: self.extra_selects.append((column, (OP_LOOKUP[op], (lhs, rhs)))) else: raise ValueError("Unsupported operator") return # Assume literal self.extra_selects.append((column, (lambda x: x, [lookup]))) def add_source_table(self, table): if table in self.tables: return self.tables.append(table) def set_distinct(self, distinct_fields): self.distinct = True if distinct_fields: for field in distinct_fields: self.add_projected_column(field) elif not self.columns: for field in self.model._meta.fields: self.add_projected_column(field.column) def add_order_by(self, column): self.order_by.append(column) def add_annotation(self, column, annotation): # The Trunc annotation class doesn't exist in Django 1.8, hence we compare by # strings, rather than importing the class to compare it name = annotation.__class__.__name__ if name == "Count": return # Handled elsewhere if name not in ("Trunc", "Col", "Date", "DateTime"): raise NotSupportedError("Unsupported annotation %s" % name) def process_date(value, lookup_type): value = ensure_datetime(value) ret = datetime.datetime.utcfromtimestamp(0) POSSIBLE_LOOKUPS = ("year", "month", "day", "hour", "minute", "second") ret = ret.replace( value.year, value.month if lookup_type in POSSIBLE_LOOKUPS[1:] else ret.month, value.day if lookup_type in POSSIBLE_LOOKUPS[2:] else ret.day, value.hour if lookup_type in POSSIBLE_LOOKUPS[3:] else ret.hour, value.minute if lookup_type in POSSIBLE_LOOKUPS[4:] else ret.minute, value.second if lookup_type in POSSIBLE_LOOKUPS[5:] else ret.second, ) return ret # Abuse the extra_select functionality if name == "Col": self.extra_selects.append((column, (lambda x: x, [column]))) elif name in ("Trunc", "Date", "DateTime"): # Trunc stores the source column and the lookup type differently to Date # which is why we have the getattr craziness here lookup_column = ( annotation.lhs.output_field.column if name == "Trunc" else getattr(annotation, "lookup", column) ) lookup_type = getattr(annotation, "lookup_type", getattr(annotation, "kind", None)) assert lookup_type self.extra_selects.append((column, (lambda x: process_date(x, lookup_type), [lookup_column]))) # Override the projection so that we only get this column self.columns = set([lookup_column]) def add_projected_column(self, column): self.init_list.append(column) if not self.projection_possible: # If we previously tried to add a column that couldn't be # projected, we don't try and add any more return field = get_field_from_column(self.model, column) if field is None: raise NotSupportedError( "{} is not a valid column for the queried model. Did you try to join?".format(column) ) if field.db_type(self.connection) in ("bytes", "text", "list", "set"): logger.warn("Disabling projection query as %s is an unprojectable type", column) self.columns = None self.projection_possible = False return if not self.columns: self.columns = set([column]) else: self.columns.add(column) def add_row(self, data): assert self.columns assert len(data) == len(self.columns) self.row_data.append(data) def prepare(self): if not self.init_list: self.init_list = [x.column for x in self.model._meta.fields] self._remove_impossible_branches() self._remove_erroneous_isnull() self._remove_negated_empty_in() self._add_inheritence_filter() self._populate_excluded_pks() self._disable_projection_if_fields_used_in_equality_filter() self._check_only_single_inequality_filter() @property def where(self): return self._where @where.setter def where(self, where): assert where is None or isinstance(where, WhereNode) self._where = where def _populate_excluded_pks(self): if not self._where: return self.excluded_pks = set() def walk(node, negated): if node.connector == "OR": # We can only process AND nodes, if we hit an OR we can't # use the excluded PK optimization return if node.negated: negated = not negated for child in node.children[:]: # As more than one inequality filter is not allowed on the datastore # this leaf + count check is probably pointless, but at least if you # do try to exclude two things it will blow up in the right place and not # return incorrect results if child.is_leaf and len(node.children) == 1: if negated and child.operator == "=" and child.column == "__key__": self.excluded_pks.add(child.value) node.children.remove(child) elif negated and child.operator == "IN" and child.column == "__key__": [self.excluded_pks.add(x) for x in child.value] node.children.remove(child) else: walk(child, negated) node.children = [x for x in node.children if x.children or x.column] walk(self._where, False) if not self._where.children: self._where = None def _remove_negated_empty_in(self): """ An empty exclude(id__in=[]) is pointless, but can cause trouble during denormalization. We remove such nodes here. """ if not self._where: return def walk(node, negated): if node.negated: negated = node.negated for child in node.children[:]: if negated and child.operator == "IN" and not child.value: node.children.remove(child) walk(child, negated) node.children = [x for x in node.children if x.children or x.column] had_where = bool(self._where.children) walk(self._where, False) # Reset the where if that was the only filter if had_where and not bool(self._where.children): self._where = None def _remove_erroneous_isnull(self): # This is a little crazy, but bear with me... # If you run a query like this: filter(thing=1).exclude(field1="test") where field1 is # null-able you'll end up with a negated branch in the where tree which is: # AND (negated) # / \ # field1="test" field1__isnull=False # This is because on SQL, field1 != "test" won't give back rows where field1 is null, so # django has to include the negated isnull=False as well in order to get back the null rows # as well. On App Engine though None is just a value, not the lack of a value, so it's # enough to just have the first branch in the negated node and in fact, if you try to use # the above tree, it will result in looking for: # field1 < "test" and field1 > "test" and field1__isnull=True # which returns the wrong result (it'll return when field1 == None only) def walk(node, negated): if node.negated: negated = not negated if not node.is_leaf: equality_fields = set() negated_isnull_fields = set() isnull_lookup = {} for child in node.children[:]: if negated: if child.lookup_name != "isnull": equality_fields.add(child.column) if child.column in negated_isnull_fields: node.children.remove(isnull_lookup[child.column]) else: negated_isnull_fields.add(child.column) if child.column in equality_fields: node.children.remove(child) else: isnull_lookup[child.column] = child walk(child, negated) if self.where: walk(self._where, False) def _remove_impossible_branches(self): """ If we mark a child node as never returning results we either need to remove those nodes, or remove the branches of the tree they are on depending on the connector of the parent node. """ if not self._where: return def walk(node, negated): if node.negated: negated = not negated for child in node.children[:]: walk(child, negated) if child.will_never_return_results: if node.connector == "AND": if child.negated: node.children.remove(child) else: node.will_never_return_results = True else: # OR if not child.negated: node.children.remove(child) if not node.children: node.will_never_return_results = True else: node.children[:] = [] walk(self._where, False) if self._where.will_never_return_results: # We removed all the children of the root where node, so no results raise EmptyResultSet() def _check_only_single_inequality_filter(self): inequality_fields = set() def walk(node, negated): if node.negated: negated = not negated for child in node.children[:]: if (negated and child.operator == "=") or child.operator in (">", "<", ">=", "<="): inequality_fields.add(child.column) walk(child, negated) if len(inequality_fields) > 1: raise NotSupportedError( "You can only have one inequality filter per query on the rpc. " "Filters were: %s" % " ".join(inequality_fields) ) if self.where: walk(self._where, False) def _disable_projection_if_fields_used_in_equality_filter(self): if not self._where or not self.columns: return equality_columns = set() def walk(node): if not node.is_leaf: for child in node.children: walk(child) elif node.operator == "=" or node.operator == "IN": equality_columns.add(node.column) walk(self._where) if equality_columns and equality_columns.intersection(self.columns): self.columns = None self.projection_possible = False def _add_inheritence_filter(self): """ We support inheritence with polymodels. Whenever we set the 'where' on this query, we manipulate the tree so that the lookups are ANDed with a filter on 'class = db_table' and on inserts, we add the 'class' column if the model is part of an inheritance tree. We only do any of this if the model has concrete parents and isn't a proxy model """ if has_concrete_parents(self.model) and not self.model._meta.proxy: if self.polymodel_filter_added: return new_filter = WhereNode(self.connection.alias) new_filter.column = POLYMODEL_CLASS_ATTRIBUTE new_filter.operator = "=" new_filter.value = self.model._meta.db_table # We add this bare AND just to stay consistent with what Django does new_and = WhereNode(self.connection.alias) new_and.connector = "AND" new_and.children = [new_filter] new_root = WhereNode(self.connection.alias) new_root.connector = "AND" new_root.children = [new_and] if self._where: # Add the original where if there was one new_root.children.append(self._where) self._where = new_root self.polymodel_filter_added = True def serialize(self): """ The idea behind this function is to provide a way to serialize this query to a string which can be compared to another query. Pickle won't work as some of the values etc. might not be picklable. FIXME: This function is incomplete! Not all necessary members are serialized """ if not self.is_normalized: raise ValueError("You cannot serialize queries unless they are normalized") result = {} result["kind"] = self.kind result["table"] = self.model._meta.db_table result["concrete_table"] = self.concrete_model._meta.db_table result["columns"] = list(self.columns or []) # set() is not JSONifiable result["projection_possible"] = self.projection_possible result["init_list"] = self.init_list result["distinct"] = self.distinct result["order_by"] = self.order_by result["low_mark"] = self.low_mark result["high_mark"] = self.high_mark result["excluded_pks"] = list(map(str, self.excluded_pks)) where = [] if self.where: assert self.where.connector == "OR" for node in self.where.children: assert node.connector == "AND" query = {} if node.children: for lookup in node.children: query["".join([lookup.column, lookup.operator])] = _serialize_sql_value(lookup.value) else: query["".join([node.column, node.operator])] = _serialize_sql_value(node.value) where.append(query) result["where"] = where return json.dumps(result) INVALID_ORDERING_FIELD_MESSAGE = ( "Ordering on TextField or BinaryField is not supported on the rpc. " "You might consider using a ComputedCharField which stores the first " "_MAX_STRING_LENGTH (from google.appengine.api.datastore_types) bytes of the " "field and instead order on that." ) def _serialize_sql_value(value): if isinstance(value, int): return value else: return str("NULL" if value is None else value) def _get_parser(query, connection=None): from gcloudc.db.backends.datastore.parsers import base return base.BaseParser(query, connection) def transform_query(connection, query): return _get_parser(query, connection).get_transformed_query() def extract_ordering(query): return _get_parser(query).get_extracted_ordering()
35.857778
116
0.571641
import datetime import json import logging import re from itertools import chain from django.db import ( NotSupportedError, connections, ) from django.db.models import AutoField from django.core.exceptions import EmptyResultSet from . import POLYMODEL_CLASS_ATTRIBUTE from .indexing import ( add_special_index, get_indexer, ) from .utils import ( ensure_datetime, get_field_from_column, get_top_concrete_parent, has_concrete_parents, ) logger = logging.getLogger(__name__) VALID_QUERY_KINDS = ("SELECT", "UPDATE", "INSERT", "DELETE", "COUNT", "AVERAGE") VALID_ANNOTATIONS = {"MIN": min, "MAX": max, "SUM": sum, "COUNT": len, "AVG": lambda x: (sum(x) / len(x))} VALID_CONNECTORS = ("AND", "OR") VALID_OPERATORS = ("=", "<", ">", "<=", ">=", "IN") def convert_operator(operator): if operator == "exact": return "=" elif operator == "gt": return ">" elif operator == "lt": return "<" elif operator == "gte": return ">=" elif operator == "lte": return "<=" return operator.upper() class WhereNode(object): def __init__(self, using): self.using = using self.column = None self.operator = None self.value = None self.output_field = None self.will_never_return_results = False self.lookup_name = None self.children = [] self.connector = "AND" self.negated = False @property def is_leaf(self): return bool(self.column and self.operator) def set_connector(self, connector): self.connector = connector def append_child(self, node): self.children.append(node) def set_leaf(self, column, operator, value, is_pk_field, negated, lookup_name, namespace, target_field=None): wrapper = connections[self.using] wrapper.ensure_connection() gclient = wrapper.connection.gclient assert column assert operator assert isinstance(is_pk_field, bool) assert isinstance(negated, bool) if operator == "iexact" and isinstance(target_field, AutoField): operator = "exact" value = int(value) if is_pk_field: model = get_top_concrete_parent(target_field.model) table = model._meta.db_table if isinstance(value, (list, tuple)): value = [gclient.key(table, x, namespace=namespace) for x in value if x] else: # Django 1.11 has operators as symbols, earlier versions use "exact" etc. if (operator == "isnull" and value is True) or ( operator in ("exact", "lt", "lte", "<", "<=", "=") and not value ): # id=None will never return anything and # Empty strings and 0 are forbidden as keys self.will_never_return_results = True elif operator in ("gt", "gte", ">", ">=") and not value: # If the value is 0 or "", then we need to manipulate the value and operator here to # get the right result (given that both are invalid keys) so for both we return # >= 1 or >= "\0" for strings if isinstance(value, int): value = 1 else: value = "\0" value = gclient.key(table, value, namespace=namespace) operator = "gte" else: value = gclient.key(table, value, namespace=namespace) column = "__key__" # Do any special index conversions necessary to perform this lookup special_indexer = get_indexer(target_field, operator) if special_indexer: if is_pk_field: column = model._meta.pk.column value = str(value.id_or_name) add_special_index(connections[self.using], target_field.model, column, special_indexer, operator, value) index_type = special_indexer.prepare_index_type(operator, value) value = special_indexer.prep_value_for_query( value, model=target_field.model, column=column, connection=connections[self.using] ) column = special_indexer.indexed_column_name(column, value, index_type) operator = special_indexer.prep_query_operator(operator) self.column = column self.operator = convert_operator(operator) self.value = value self.lookup_name = lookup_name def __iter__(self): for child in chain(*map(iter, self.children)): yield child yield self def __repr__(self): if self.is_leaf: return "[%s%s%s]" % (self.column, self.operator, self.value) else: return "(%s:%s%s)" % ( self.connector, "!" if self.negated else "", ",".join([repr(x) for x in self.children]), ) def __eq__(self, rhs): if self.is_leaf != rhs.is_leaf: return False if self.is_leaf: return self.column == rhs.column and self.value == rhs.value and self.operator == rhs.operator else: return self.connector == rhs.connector and self.children == rhs.children def __hash__(self): if self.is_leaf: return hash((self.column, self.value, self.operator)) else: return hash((self.connector,) + tuple([hash(x) for x in self.children])) class Query(object): def __init__(self, model, kind): assert kind in VALID_QUERY_KINDS self.model = model self.concrete_model = get_top_concrete_parent(model) self.kind = kind self.projection_possible = True self.tables = [] self.columns = None # None means all fields self.init_list = [] self.distinct = False self.order_by = [] self.row_data = [] # For insert/updates self._where = None self.low_mark = self.high_mark = None self.annotations = [] self.per_entity_annotations = [] self.extra_selects = [] self.polymodel_filter_added = False # A list of PKs that should be excluded from the resultset self.excluded_pks = set() @property def is_normalized(self): if not self.where: return True # Only a leaf node, return True if not self.where.is_leaf: return True # If we have children, and they are all leaf nodes then this is a normalized # query return self.where.connector == "OR" and self.where.children and all(x.is_leaf for x in self.where.children) def add_extra_select(self, column, lookup): if lookup.lower().startswith("select "): raise ValueError("SQL statements aren't supported with extra(select=)") bool_expr = r"(?P<lhs>[a-zA-Z0-9_]+)\s?(?P<op>[=|>|<]{1,2})\s?(?P<rhs>[\w+|']+)" # Operator expression test op_expr = r"(?P<lhs>[a-zA-Z0-9_]+)\s?(?P<op>[+|-|/|*])\s?(?P<rhs>[\w+|']+)" OP_LOOKUP = { "=": lambda x, y: x == y, "is": lambda x, y: x == y, "<": lambda x, y: x < y, ">": lambda x, y: x > y, ">=": lambda x, y: x >= y, "<=": lambda x, y: x <= y, "+": lambda x, y: x + y, "-": lambda x, y: x - y, "/": lambda x, y: x / y, "*": lambda x, y: x * y, } for regex in (bool_expr, op_expr): match = re.match(regex, lookup) if match: lhs = match.group("lhs") rhs = match.group("rhs") op = match.group("op").lower() if op in OP_LOOKUP: self.extra_selects.append((column, (OP_LOOKUP[op], (lhs, rhs)))) else: raise ValueError("Unsupported operator") return self.extra_selects.append((column, (lambda x: x, [lookup]))) def add_source_table(self, table): if table in self.tables: return self.tables.append(table) def set_distinct(self, distinct_fields): self.distinct = True if distinct_fields: for field in distinct_fields: self.add_projected_column(field) elif not self.columns: for field in self.model._meta.fields: self.add_projected_column(field.column) def add_order_by(self, column): self.order_by.append(column) def add_annotation(self, column, annotation): # strings, rather than importing the class to compare it name = annotation.__class__.__name__ if name == "Count": return # Handled elsewhere if name not in ("Trunc", "Col", "Date", "DateTime"): raise NotSupportedError("Unsupported annotation %s" % name) def process_date(value, lookup_type): value = ensure_datetime(value) ret = datetime.datetime.utcfromtimestamp(0) POSSIBLE_LOOKUPS = ("year", "month", "day", "hour", "minute", "second") ret = ret.replace( value.year, value.month if lookup_type in POSSIBLE_LOOKUPS[1:] else ret.month, value.day if lookup_type in POSSIBLE_LOOKUPS[2:] else ret.day, value.hour if lookup_type in POSSIBLE_LOOKUPS[3:] else ret.hour, value.minute if lookup_type in POSSIBLE_LOOKUPS[4:] else ret.minute, value.second if lookup_type in POSSIBLE_LOOKUPS[5:] else ret.second, ) return ret # Abuse the extra_select functionality if name == "Col": self.extra_selects.append((column, (lambda x: x, [column]))) elif name in ("Trunc", "Date", "DateTime"): # Trunc stores the source column and the lookup type differently to Date # which is why we have the getattr craziness here lookup_column = ( annotation.lhs.output_field.column if name == "Trunc" else getattr(annotation, "lookup", column) ) lookup_type = getattr(annotation, "lookup_type", getattr(annotation, "kind", None)) assert lookup_type self.extra_selects.append((column, (lambda x: process_date(x, lookup_type), [lookup_column]))) # Override the projection so that we only get this column self.columns = set([lookup_column]) def add_projected_column(self, column): self.init_list.append(column) if not self.projection_possible: # If we previously tried to add a column that couldn't be return field = get_field_from_column(self.model, column) if field is None: raise NotSupportedError( "{} is not a valid column for the queried model. Did you try to join?".format(column) ) if field.db_type(self.connection) in ("bytes", "text", "list", "set"): logger.warn("Disabling projection query as %s is an unprojectable type", column) self.columns = None self.projection_possible = False return if not self.columns: self.columns = set([column]) else: self.columns.add(column) def add_row(self, data): assert self.columns assert len(data) == len(self.columns) self.row_data.append(data) def prepare(self): if not self.init_list: self.init_list = [x.column for x in self.model._meta.fields] self._remove_impossible_branches() self._remove_erroneous_isnull() self._remove_negated_empty_in() self._add_inheritence_filter() self._populate_excluded_pks() self._disable_projection_if_fields_used_in_equality_filter() self._check_only_single_inequality_filter() @property def where(self): return self._where @where.setter def where(self, where): assert where is None or isinstance(where, WhereNode) self._where = where def _populate_excluded_pks(self): if not self._where: return self.excluded_pks = set() def walk(node, negated): if node.connector == "OR": # We can only process AND nodes, if we hit an OR we can't return if node.negated: negated = not negated for child in node.children[:]: if child.is_leaf and len(node.children) == 1: if negated and child.operator == "=" and child.column == "__key__": self.excluded_pks.add(child.value) node.children.remove(child) elif negated and child.operator == "IN" and child.column == "__key__": [self.excluded_pks.add(x) for x in child.value] node.children.remove(child) else: walk(child, negated) node.children = [x for x in node.children if x.children or x.column] walk(self._where, False) if not self._where.children: self._where = None def _remove_negated_empty_in(self): if not self._where: return def walk(node, negated): if node.negated: negated = node.negated for child in node.children[:]: if negated and child.operator == "IN" and not child.value: node.children.remove(child) walk(child, negated) node.children = [x for x in node.children if x.children or x.column] had_where = bool(self._where.children) walk(self._where, False) if had_where and not bool(self._where.children): self._where = None def _remove_erroneous_isnull(self): # AND (negated) # / \ # field1="test" field1__isnull=False # This is because on SQL, field1 != "test" won't give back rows where field1 is null, so # enough to just have the first branch in the negated node and in fact, if you try to use # the above tree, it will result in looking for: # field1 < "test" and field1 > "test" and field1__isnull=True # which returns the wrong result (it'll return when field1 == None only) def walk(node, negated): if node.negated: negated = not negated if not node.is_leaf: equality_fields = set() negated_isnull_fields = set() isnull_lookup = {} for child in node.children[:]: if negated: if child.lookup_name != "isnull": equality_fields.add(child.column) if child.column in negated_isnull_fields: node.children.remove(isnull_lookup[child.column]) else: negated_isnull_fields.add(child.column) if child.column in equality_fields: node.children.remove(child) else: isnull_lookup[child.column] = child walk(child, negated) if self.where: walk(self._where, False) def _remove_impossible_branches(self): if not self._where: return def walk(node, negated): if node.negated: negated = not negated for child in node.children[:]: walk(child, negated) if child.will_never_return_results: if node.connector == "AND": if child.negated: node.children.remove(child) else: node.will_never_return_results = True else: if not child.negated: node.children.remove(child) if not node.children: node.will_never_return_results = True else: node.children[:] = [] walk(self._where, False) if self._where.will_never_return_results: raise EmptyResultSet() def _check_only_single_inequality_filter(self): inequality_fields = set() def walk(node, negated): if node.negated: negated = not negated for child in node.children[:]: if (negated and child.operator == "=") or child.operator in (">", "<", ">=", "<="): inequality_fields.add(child.column) walk(child, negated) if len(inequality_fields) > 1: raise NotSupportedError( "You can only have one inequality filter per query on the rpc. " "Filters were: %s" % " ".join(inequality_fields) ) if self.where: walk(self._where, False) def _disable_projection_if_fields_used_in_equality_filter(self): if not self._where or not self.columns: return equality_columns = set() def walk(node): if not node.is_leaf: for child in node.children: walk(child) elif node.operator == "=" or node.operator == "IN": equality_columns.add(node.column) walk(self._where) if equality_columns and equality_columns.intersection(self.columns): self.columns = None self.projection_possible = False def _add_inheritence_filter(self): if has_concrete_parents(self.model) and not self.model._meta.proxy: if self.polymodel_filter_added: return new_filter = WhereNode(self.connection.alias) new_filter.column = POLYMODEL_CLASS_ATTRIBUTE new_filter.operator = "=" new_filter.value = self.model._meta.db_table new_and = WhereNode(self.connection.alias) new_and.connector = "AND" new_and.children = [new_filter] new_root = WhereNode(self.connection.alias) new_root.connector = "AND" new_root.children = [new_and] if self._where: new_root.children.append(self._where) self._where = new_root self.polymodel_filter_added = True def serialize(self): if not self.is_normalized: raise ValueError("You cannot serialize queries unless they are normalized") result = {} result["kind"] = self.kind result["table"] = self.model._meta.db_table result["concrete_table"] = self.concrete_model._meta.db_table result["columns"] = list(self.columns or []) result["projection_possible"] = self.projection_possible result["init_list"] = self.init_list result["distinct"] = self.distinct result["order_by"] = self.order_by result["low_mark"] = self.low_mark result["high_mark"] = self.high_mark result["excluded_pks"] = list(map(str, self.excluded_pks)) where = [] if self.where: assert self.where.connector == "OR" for node in self.where.children: assert node.connector == "AND" query = {} if node.children: for lookup in node.children: query["".join([lookup.column, lookup.operator])] = _serialize_sql_value(lookup.value) else: query["".join([node.column, node.operator])] = _serialize_sql_value(node.value) where.append(query) result["where"] = where return json.dumps(result) INVALID_ORDERING_FIELD_MESSAGE = ( "Ordering on TextField or BinaryField is not supported on the rpc. " "You might consider using a ComputedCharField which stores the first " "_MAX_STRING_LENGTH (from google.appengine.api.datastore_types) bytes of the " "field and instead order on that." ) def _serialize_sql_value(value): if isinstance(value, int): return value else: return str("NULL" if value is None else value) def _get_parser(query, connection=None): from gcloudc.db.backends.datastore.parsers import base return base.BaseParser(query, connection) def transform_query(connection, query): return _get_parser(query, connection).get_transformed_query() def extract_ordering(query): return _get_parser(query).get_extracted_ordering()
true
true
1c2cf6ea1a8354b758be34d8cc95a22caeeb92af
324
py
Python
gif/datasets/setup.py
jm-begon/globally-induced-forest
bf41640a5f0d9db637877dfa077b1d529539dbc6
[ "BSD-3-Clause" ]
6
2018-01-05T11:56:27.000Z
2018-10-13T13:14:05.000Z
gif/datasets/setup.py
jm-begon/globally-induced-forest
bf41640a5f0d9db637877dfa077b1d529539dbc6
[ "BSD-3-Clause" ]
1
2018-01-05T12:04:37.000Z
2018-01-05T13:56:20.000Z
gif/datasets/setup.py
jm-begon/globally-induced-forest
bf41640a5f0d9db637877dfa077b1d529539dbc6
[ "BSD-3-Clause" ]
null
null
null
import os import numpy from numpy.distutils.misc_util import Configuration def configuration(parent_package="", top_path=None): config = Configuration("datasets", parent_package, top_path) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(**configuration().todict())
21.6
64
0.75
import os import numpy from numpy.distutils.misc_util import Configuration def configuration(parent_package="", top_path=None): config = Configuration("datasets", parent_package, top_path) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(**configuration().todict())
true
true
1c2cf78dec9112e6316d9dc8c45b5348f98f1275
3,185
py
Python
Plugins/BoneBox.py
CopyPasteBugs/CryBlendHelpers
0965a3beff900b69cb392df65fe01caded825da2
[ "MIT" ]
null
null
null
Plugins/BoneBox.py
CopyPasteBugs/CryBlendHelpers
0965a3beff900b69cb392df65fe01caded825da2
[ "MIT" ]
null
null
null
Plugins/BoneBox.py
CopyPasteBugs/CryBlendHelpers
0965a3beff900b69cb392df65fe01caded825da2
[ "MIT" ]
null
null
null
bl_info = { "name": "Create Box proxies for Skeletons for CryEngine 5", "author": "ArticLion", "category": "Object", "blender": (2, 77, 0) } import bpy import os import struct import sys import mathutils from math import radians from bpy.props import (BoolProperty) from bpy.props import (EnumProperty) from bpy.props import (FloatProperty) class BoneBox(bpy.types.Operator): bl_idname = "object.bonebox" # unique identifier for buttons and menu items to reference. bl_label = "CryHelpers : Create basic _boneGeometry" # display name in the interface. bl_options = {'REGISTER', 'UNDO'} # enable undo for the operator. def CreateBoxColliders(self, context): scene = context.scene; selected = context.selected_objects i = len(selected) print ("selected count:", i) print (selected[0].type) if (selected[0].type == 'ARMATURE'): #print ("This is ARMA with 300 bones!") for bone in selected[0].data.bones: armature = selected[0] self.CreateColliderForBone(context, armature, bone) def CreateColliderForBone(self, context, arm, bone): #print ("bone name" + bone.name) self.CreateNewBox(context, bone.name, bone.head_local, bone, arm) pass def CreateNewBox(self, context, name, origin,bone, arm): distance = (bone.head - bone.tail).length #print ("distance {0}".format(distance)) bpy.ops.mesh.primitive_cube_add( radius=0.15 * distance, calc_uvs=True, view_align=False, enter_editmode=False, location= bone.head_local, rotation=(0.0, 0.0, 0.0)) #location=(bone.head - bone.tail) * bone.matrix, #location= bone.head_local, ob = bpy.context.object ob.name = name + "_boneGeometry" ob.show_name = True me = ob.data me.name = name #parenting produce wrong mesh orient on export #ob.parent = arm #ob.parent_bone = bone.name #ob.parent_type = 'BONE' #Apply rot & scale for box bpy.ops.object.select_all(action='DESELECT') ob.select = True bpy.ops.object.transform_apply(location=False, rotation=True, scale=True) bpy.ops.object.select_all(action='DESELECT') #so we unparent now #ob.parent = None #ob.parent_bone = '' #ob.parent_type = 'OBJECT' def execute(self, context): self.CreateBoxColliders(context) return {'FINISHED'} def menu_func(self, context): self.layout.operator(BoneBox.bl_idname) def register(): bpy.utils.register_class(BoneBox) bpy.types.VIEW3D_MT_object.append(menu_func) def unregister(): bpy.utils.unregister_class(BoneBox)
34.247312
96
0.555102
bl_info = { "name": "Create Box proxies for Skeletons for CryEngine 5", "author": "ArticLion", "category": "Object", "blender": (2, 77, 0) } import bpy import os import struct import sys import mathutils from math import radians from bpy.props import (BoolProperty) from bpy.props import (EnumProperty) from bpy.props import (FloatProperty) class BoneBox(bpy.types.Operator): bl_idname = "object.bonebox" bl_label = "CryHelpers : Create basic _boneGeometry" bl_options = {'REGISTER', 'UNDO'} def CreateBoxColliders(self, context): scene = context.scene; selected = context.selected_objects i = len(selected) print ("selected count:", i) print (selected[0].type) if (selected[0].type == 'ARMATURE'): for bone in selected[0].data.bones: armature = selected[0] self.CreateColliderForBone(context, armature, bone) def CreateColliderForBone(self, context, arm, bone): self.CreateNewBox(context, bone.name, bone.head_local, bone, arm) pass def CreateNewBox(self, context, name, origin,bone, arm): distance = (bone.head - bone.tail).length bpy.ops.mesh.primitive_cube_add( radius=0.15 * distance, calc_uvs=True, view_align=False, enter_editmode=False, location= bone.head_local, rotation=(0.0, 0.0, 0.0)) ob = bpy.context.object ob.name = name + "_boneGeometry" ob.show_name = True me = ob.data me.name = name bpy.ops.object.select_all(action='DESELECT') ob.select = True bpy.ops.object.transform_apply(location=False, rotation=True, scale=True) bpy.ops.object.select_all(action='DESELECT') def execute(self, context): self.CreateBoxColliders(context) return {'FINISHED'} def menu_func(self, context): self.layout.operator(BoneBox.bl_idname) def register(): bpy.utils.register_class(BoneBox) bpy.types.VIEW3D_MT_object.append(menu_func) def unregister(): bpy.utils.unregister_class(BoneBox)
true
true
1c2cf799737827ae82cb008c68687ac40ab5260f
2,613
py
Python
scripts/tests/generate_host_files.py
NDevTK/cel
e97226416b6e12245564bfc1c3631d610d62f052
[ "BSD-3-Clause" ]
null
null
null
scripts/tests/generate_host_files.py
NDevTK/cel
e97226416b6e12245564bfc1c3631d610d62f052
[ "BSD-3-Clause" ]
null
null
null
scripts/tests/generate_host_files.py
NDevTK/cel
e97226416b6e12245564bfc1c3631d610d62f052
[ "BSD-3-Clause" ]
null
null
null
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import logging import os import sys def ParseArgs(): parser = argparse.ArgumentParser( description='Host file generator for CELab E2E tests') all_tokens = ['project_id', 'storage_bucket', 'storage_prefix'] template_help = 'The full path to the *.host.textpb template file to use. ' template_help += 'Must contain the following tokens: %s' % all_tokens parser.add_argument( '--template', metavar='<host_file>', required=True, help=template_help) parser.add_argument( '--projects', metavar='<projectA;projectB;...>', dest="projects", required=True, help='The values to replace "<project_id>" with.') parser.add_argument( '--storage_bucket', metavar='<token>', dest="storage_bucket", required=True, help='The value to replace "<storage_bucket>" with.') parser.add_argument( '--storage_prefix', metavar='<token>', dest="storage_prefix", required=True, help='The value to replace "<storage_prefix>" with.') parser.add_argument( '--destination_dir', metavar='<path>', dest='destination', required=True, action='store', help='Where to collect extra logs on test failures') return parser.parse_args() def ConfigureLogging(args): logfmt = '%(asctime)s %(filename)s:%(lineno)s: [%(levelname)s] %(message)s' datefmt = '%Y/%m/%d %H:%M:%S' logging.basicConfig(level=logging.INFO, format=logfmt, datefmt=datefmt) if __name__ == '__main__': args = ParseArgs() ConfigureLogging(args) logging.info("Arguments: %s" % args) if not os.path.exists(args.template): raise ValueError('Template host file not found: %s' % args.template) if not os.path.exists(args.destination): raise ValueError('Destination directory not found: %s' % args.destination) # Generate all the host files based off the arguments passed. with open(args.template, 'r') as f: template = f.read() for project_id in args.projects.split(';'): filename = "%s.host.textpb" % project_id destination = os.path.join(args.destination, filename) with open(destination, 'w') as f: logging.info("Generating %s" % destination) content = template.replace("<project_id>", project_id) content = content.replace("<storage_bucket>", args.storage_bucket) content = content.replace("<storage_prefix>", args.storage_prefix) f.write(content) sys.exit(0)
31.107143
78
0.677
import argparse import logging import os import sys def ParseArgs(): parser = argparse.ArgumentParser( description='Host file generator for CELab E2E tests') all_tokens = ['project_id', 'storage_bucket', 'storage_prefix'] template_help = 'The full path to the *.host.textpb template file to use. ' template_help += 'Must contain the following tokens: %s' % all_tokens parser.add_argument( '--template', metavar='<host_file>', required=True, help=template_help) parser.add_argument( '--projects', metavar='<projectA;projectB;...>', dest="projects", required=True, help='The values to replace "<project_id>" with.') parser.add_argument( '--storage_bucket', metavar='<token>', dest="storage_bucket", required=True, help='The value to replace "<storage_bucket>" with.') parser.add_argument( '--storage_prefix', metavar='<token>', dest="storage_prefix", required=True, help='The value to replace "<storage_prefix>" with.') parser.add_argument( '--destination_dir', metavar='<path>', dest='destination', required=True, action='store', help='Where to collect extra logs on test failures') return parser.parse_args() def ConfigureLogging(args): logfmt = '%(asctime)s %(filename)s:%(lineno)s: [%(levelname)s] %(message)s' datefmt = '%Y/%m/%d %H:%M:%S' logging.basicConfig(level=logging.INFO, format=logfmt, datefmt=datefmt) if __name__ == '__main__': args = ParseArgs() ConfigureLogging(args) logging.info("Arguments: %s" % args) if not os.path.exists(args.template): raise ValueError('Template host file not found: %s' % args.template) if not os.path.exists(args.destination): raise ValueError('Destination directory not found: %s' % args.destination) with open(args.template, 'r') as f: template = f.read() for project_id in args.projects.split(';'): filename = "%s.host.textpb" % project_id destination = os.path.join(args.destination, filename) with open(destination, 'w') as f: logging.info("Generating %s" % destination) content = template.replace("<project_id>", project_id) content = content.replace("<storage_bucket>", args.storage_bucket) content = content.replace("<storage_prefix>", args.storage_prefix) f.write(content) sys.exit(0)
true
true
1c2cf82cd0a659ee5f05ba5bb1d2a9465cbdc517
5,960
py
Python
py3status/constants.py
obestwalter/py3status
a79d50ae252626bacb14bfcc8f369e59ae500fd1
[ "BSD-3-Clause" ]
null
null
null
py3status/constants.py
obestwalter/py3status
a79d50ae252626bacb14bfcc8f369e59ae500fd1
[ "BSD-3-Clause" ]
null
null
null
py3status/constants.py
obestwalter/py3status
a79d50ae252626bacb14bfcc8f369e59ae500fd1
[ "BSD-3-Clause" ]
null
null
null
# This file contains various useful constants for py3status GENERAL_DEFAULTS = { "color_bad": "#FF0000", "color_degraded": "#FFFF00", "color_good": "#00FF00", "color_separator": "#333333", "colors": False, "interval": 5, "output_format": "i3bar", } MAX_NESTING_LEVELS = 4 TIME_FORMAT = "%Y-%m-%d %H:%M:%S" TZTIME_FORMAT = "%Y-%m-%d %H:%M:%S %Z" TIME_MODULES = ["time", "tztime"] I3S_INSTANCE_MODULES = [ "battery", "cpu_temperature", "disk", "ethernet", "path_exists", "run_watch", "tztime", "volume", "wireless", ] I3S_SINGLE_NAMES = ["cpu_usage", "ddate", "ipv6", "load", "time"] I3S_ALLOWED_COLORS = ["color_bad", "color_good", "color_degraded"] # i3status modules that allow colors to be passed. # general section also allows colors so is included. I3S_COLOR_MODULES = ["general", "battery", "cpu_temperature", "disk", "load"] I3S_MODULE_NAMES = I3S_SINGLE_NAMES + I3S_INSTANCE_MODULES CONFIG_FILE_SPECIAL_SECTIONS = ["general", "py3status"] ERROR_CONFIG = """ general {colors = true interval = 60} order += "static_string py3status" order += "tztime local" order += "group error" static_string py3status {format = "py3status"} tztime local {format = "%c"} group error{ button_next = 1 button_prev = 0 fixed_width = False format = "{output}" static_string error_min {format = "CONFIG ERROR" color = "#FF0000"} static_string error {format = "$error" color = "#FF0000"} } """ COLOR_NAMES_EXCLUDED = ["good", "bad", "degraded", "separator", "threshold", "None"] COLOR_NAMES = { "aliceblue": "#F0F8FF", "antiquewhite": "#FAEBD7", "aqua": "#00FFFF", "aquamarine": "#7FFFD4", "azure": "#F0FFFF", "beige": "#F5F5DC", "bisque": "#FFE4C4", "black": "#000000", "blanchedalmond": "#FFEBCD", "blue": "#0000FF", "blueviolet": "#8A2BE2", "brown": "#A52A2A", "burlywood": "#DEB887", "cadetblue": "#5F9EA0", "chartreuse": "#7FFF00", "chocolate": "#D2691E", "coral": "#FF7F50", "cornflowerblue": "#6495ED", "cornsilk": "#FFF8DC", "crimson": "#DC143C", "cyan": "#00FFFF", "darkblue": "#00008B", "darkcyan": "#008B8B", "darkgoldenrod": "#B8860B", "darkgray": "#A9A9A9", "darkgrey": "#A9A9A9", "darkgreen": "#006400", "darkkhaki": "#BDB76B", "darkmagenta": "#8B008B", "darkolivegreen": "#556B2F", "darkorange": "#FF8C00", "darkorchid": "#9932CC", "darkred": "#8B0000", "darksalmon": "#E9967A", "darkseagreen": "#8FBC8F", "darkslateblue": "#483D8B", "darkslategray": "#2F4F4F", "darkslategrey": "#2F4F4F", "darkturquoise": "#00CED1", "darkviolet": "#9400D3", "deeppink": "#FF1493", "deepskyblue": "#00BFFF", "dimgray": "#696969", "dimgrey": "#696969", "dodgerblue": "#1E90FF", "firebrick": "#B22222", "floralwhite": "#FFFAF0", "forestgreen": "#228B22", "fuchsia": "#FF00FF", "gainsboro": "#DCDCDC", "ghostwhite": "#F8F8FF", "gold": "#FFD700", "goldenrod": "#DAA520", "gray": "#808080", "grey": "#808080", "green": "#008000", "greenyellow": "#ADFF2F", "honeydew": "#F0FFF0", "hotpink": "#FF69B4", "indianred": "#CD5C5C", "indigo": "#4B0082", "ivory": "#FFFFF0", "khaki": "#F0E68C", "lavender": "#E6E6FA", "lavenderblush": "#FFF0F5", "lawngreen": "#7CFC00", "lemonchiffon": "#FFFACD", "lightblue": "#ADD8E6", "lightcoral": "#F08080", "lightcyan": "#E0FFFF", "lightgoldenrodyellow": "#FAFAD2", "lightgray": "#D3D3D3", "lightgrey": "#D3D3D3", "lightgreen": "#90EE90", "lightpink": "#FFB6C1", "lightsalmon": "#FFA07A", "lightseagreen": "#20B2AA", "lightskyblue": "#87CEFA", "lightslategray": "#778899", "lightslategrey": "#778899", "lightsteelblue": "#B0C4DE", "lightyellow": "#FFFFE0", "lime": "#00FF00", "limegreen": "#32CD32", "linen": "#FAF0E6", "magenta": "#FF00FF", "maroon": "#800000", "mediumaquamarine": "#66CDAA", "mediumblue": "#0000CD", "mediumorchid": "#BA55D3", "mediumpurple": "#9370DB", "mediumseagreen": "#3CB371", "mediumslateblue": "#7B68EE", "mediumspringgreen": "#00FA9A", "mediumturquoise": "#48D1CC", "mediumvioletred": "#C71585", "midnightblue": "#191970", "mintcream": "#F5FFFA", "mistyrose": "#FFE4E1", "moccasin": "#FFE4B5", "navajowhite": "#FFDEAD", "navy": "#000080", "oldlace": "#FDF5E6", "olive": "#808000", "olivedrab": "#6B8E23", "orange": "#FFA500", "orangered": "#FF4500", "orchid": "#DA70D6", "palegoldenrod": "#EEE8AA", "palegreen": "#98FB98", "paleturquoise": "#AFEEEE", "palevioletred": "#DB7093", "papayawhip": "#FFEFD5", "peachpuff": "#FFDAB9", "peru": "#CD853F", "pink": "#FFC0CB", "plum": "#DDA0DD", "powderblue": "#B0E0E6", "purple": "#800080", "rebeccapurple": "#663399", "red": "#FF0000", "rosybrown": "#BC8F8F", "royalblue": "#4169E1", "saddlebrown": "#8B4513", "salmon": "#FA8072", "sandybrown": "#F4A460", "seagreen": "#2E8B57", "seashell": "#FFF5EE", "sienna": "#A0522D", "silver": "#C0C0C0", "skyblue": "#87CEEB", "slateblue": "#6A5ACD", "slategray": "#708090", "slategrey": "#708090", "snow": "#FFFAFA", "springgreen": "#00FF7F", "steelblue": "#4682B4", "tan": "#D2B48C", "teal": "#008080", "thistle": "#D8BFD8", "tomato": "#FF6347", "turquoise": "#40E0D0", "violet": "#EE82EE", "wheat": "#F5DEB3", "white": "#FFFFFF", "whitesmoke": "#F5F5F5", "yellow": "#FFFF00", "yellowgreen": "#9ACD32", } ON_TRIGGER_ACTIONS = ["refresh", "refresh_and_freeze"] POSITIONS = ["left", "center", "right"] RETIRED_MODULES = {"weather_yahoo": ["weather_owm"]} MARKUP_LANGUAGES = ["pango", "none"]
26.607143
84
0.568121
GENERAL_DEFAULTS = { "color_bad": "#FF0000", "color_degraded": "#FFFF00", "color_good": "#00FF00", "color_separator": "#333333", "colors": False, "interval": 5, "output_format": "i3bar", } MAX_NESTING_LEVELS = 4 TIME_FORMAT = "%Y-%m-%d %H:%M:%S" TZTIME_FORMAT = "%Y-%m-%d %H:%M:%S %Z" TIME_MODULES = ["time", "tztime"] I3S_INSTANCE_MODULES = [ "battery", "cpu_temperature", "disk", "ethernet", "path_exists", "run_watch", "tztime", "volume", "wireless", ] I3S_SINGLE_NAMES = ["cpu_usage", "ddate", "ipv6", "load", "time"] I3S_ALLOWED_COLORS = ["color_bad", "color_good", "color_degraded"] I3S_COLOR_MODULES = ["general", "battery", "cpu_temperature", "disk", "load"] I3S_MODULE_NAMES = I3S_SINGLE_NAMES + I3S_INSTANCE_MODULES CONFIG_FILE_SPECIAL_SECTIONS = ["general", "py3status"] ERROR_CONFIG = """ general {colors = true interval = 60} order += "static_string py3status" order += "tztime local" order += "group error" static_string py3status {format = "py3status"} tztime local {format = "%c"} group error{ button_next = 1 button_prev = 0 fixed_width = False format = "{output}" static_string error_min {format = "CONFIG ERROR" color = "#FF0000"} static_string error {format = "$error" color = "#FF0000"} } """ COLOR_NAMES_EXCLUDED = ["good", "bad", "degraded", "separator", "threshold", "None"] COLOR_NAMES = { "aliceblue": "#F0F8FF", "antiquewhite": "#FAEBD7", "aqua": "#00FFFF", "aquamarine": "#7FFFD4", "azure": "#F0FFFF", "beige": "#F5F5DC", "bisque": "#FFE4C4", "black": "#000000", "blanchedalmond": "#FFEBCD", "blue": "#0000FF", "blueviolet": "#8A2BE2", "brown": "#A52A2A", "burlywood": "#DEB887", "cadetblue": "#5F9EA0", "chartreuse": "#7FFF00", "chocolate": "#D2691E", "coral": "#FF7F50", "cornflowerblue": "#6495ED", "cornsilk": "#FFF8DC", "crimson": "#DC143C", "cyan": "#00FFFF", "darkblue": "#00008B", "darkcyan": "#008B8B", "darkgoldenrod": "#B8860B", "darkgray": "#A9A9A9", "darkgrey": "#A9A9A9", "darkgreen": "#006400", "darkkhaki": "#BDB76B", "darkmagenta": "#8B008B", "darkolivegreen": "#556B2F", "darkorange": "#FF8C00", "darkorchid": "#9932CC", "darkred": "#8B0000", "darksalmon": "#E9967A", "darkseagreen": "#8FBC8F", "darkslateblue": "#483D8B", "darkslategray": "#2F4F4F", "darkslategrey": "#2F4F4F", "darkturquoise": "#00CED1", "darkviolet": "#9400D3", "deeppink": "#FF1493", "deepskyblue": "#00BFFF", "dimgray": "#696969", "dimgrey": "#696969", "dodgerblue": "#1E90FF", "firebrick": "#B22222", "floralwhite": "#FFFAF0", "forestgreen": "#228B22", "fuchsia": "#FF00FF", "gainsboro": "#DCDCDC", "ghostwhite": "#F8F8FF", "gold": "#FFD700", "goldenrod": "#DAA520", "gray": "#808080", "grey": "#808080", "green": "#008000", "greenyellow": "#ADFF2F", "honeydew": "#F0FFF0", "hotpink": "#FF69B4", "indianred": "#CD5C5C", "indigo": "#4B0082", "ivory": "#FFFFF0", "khaki": "#F0E68C", "lavender": "#E6E6FA", "lavenderblush": "#FFF0F5", "lawngreen": "#7CFC00", "lemonchiffon": "#FFFACD", "lightblue": "#ADD8E6", "lightcoral": "#F08080", "lightcyan": "#E0FFFF", "lightgoldenrodyellow": "#FAFAD2", "lightgray": "#D3D3D3", "lightgrey": "#D3D3D3", "lightgreen": "#90EE90", "lightpink": "#FFB6C1", "lightsalmon": "#FFA07A", "lightseagreen": "#20B2AA", "lightskyblue": "#87CEFA", "lightslategray": "#778899", "lightslategrey": "#778899", "lightsteelblue": "#B0C4DE", "lightyellow": "#FFFFE0", "lime": "#00FF00", "limegreen": "#32CD32", "linen": "#FAF0E6", "magenta": "#FF00FF", "maroon": "#800000", "mediumaquamarine": "#66CDAA", "mediumblue": "#0000CD", "mediumorchid": "#BA55D3", "mediumpurple": "#9370DB", "mediumseagreen": "#3CB371", "mediumslateblue": "#7B68EE", "mediumspringgreen": "#00FA9A", "mediumturquoise": "#48D1CC", "mediumvioletred": "#C71585", "midnightblue": "#191970", "mintcream": "#F5FFFA", "mistyrose": "#FFE4E1", "moccasin": "#FFE4B5", "navajowhite": "#FFDEAD", "navy": "#000080", "oldlace": "#FDF5E6", "olive": "#808000", "olivedrab": "#6B8E23", "orange": "#FFA500", "orangered": "#FF4500", "orchid": "#DA70D6", "palegoldenrod": "#EEE8AA", "palegreen": "#98FB98", "paleturquoise": "#AFEEEE", "palevioletred": "#DB7093", "papayawhip": "#FFEFD5", "peachpuff": "#FFDAB9", "peru": "#CD853F", "pink": "#FFC0CB", "plum": "#DDA0DD", "powderblue": "#B0E0E6", "purple": "#800080", "rebeccapurple": "#663399", "red": "#FF0000", "rosybrown": "#BC8F8F", "royalblue": "#4169E1", "saddlebrown": "#8B4513", "salmon": "#FA8072", "sandybrown": "#F4A460", "seagreen": "#2E8B57", "seashell": "#FFF5EE", "sienna": "#A0522D", "silver": "#C0C0C0", "skyblue": "#87CEEB", "slateblue": "#6A5ACD", "slategray": "#708090", "slategrey": "#708090", "snow": "#FFFAFA", "springgreen": "#00FF7F", "steelblue": "#4682B4", "tan": "#D2B48C", "teal": "#008080", "thistle": "#D8BFD8", "tomato": "#FF6347", "turquoise": "#40E0D0", "violet": "#EE82EE", "wheat": "#F5DEB3", "white": "#FFFFFF", "whitesmoke": "#F5F5F5", "yellow": "#FFFF00", "yellowgreen": "#9ACD32", } ON_TRIGGER_ACTIONS = ["refresh", "refresh_and_freeze"] POSITIONS = ["left", "center", "right"] RETIRED_MODULES = {"weather_yahoo": ["weather_owm"]} MARKUP_LANGUAGES = ["pango", "none"]
true
true
1c2cf8860a5d04aba92fd23ccf7aa4598225d065
6,749
py
Python
SDE_CG_C/utils/evaluation.py
Zhanghaotian1/SDE_conf
90773e807ab8ccdc1963e113a2c72df16b8899c1
[ "MIT" ]
null
null
null
SDE_CG_C/utils/evaluation.py
Zhanghaotian1/SDE_conf
90773e807ab8ccdc1963e113a2c72df16b8899c1
[ "MIT" ]
null
null
null
SDE_CG_C/utils/evaluation.py
Zhanghaotian1/SDE_conf
90773e807ab8ccdc1963e113a2c72df16b8899c1
[ "MIT" ]
1
2022-01-28T07:56:28.000Z
2022-01-28T07:56:28.000Z
import numpy as np from tqdm.auto import tqdm import torch from torch_geometric.data import Data from rdkit import Chem from rdkit.Chem.rdForceFieldHelpers import MMFFOptimizeMolecule from SDE_CG import utils def get_rmsd_confusion_matrix(data: Data, useFF=False): data.pos_ref = data.pos_ref.view(-1, data.num_nodes, 3) data.pos_gen = data.pos_gen.view(-1, data.num_nodes, 3) num_gen = data.pos_gen.size(0) num_ref = data.pos_ref.size(0) assert num_gen == data.num_pos_gen.item() assert num_ref == data.num_pos_ref.item() rmsd_confusion_mat = -1 * np.ones([num_ref, num_gen],dtype=np.float) for i in range(num_gen): gen_mol = utils.set_rdmol_positions(data.rdmol, data.pos_gen[i]) if useFF: #print('Applying FF on generated molecules...') MMFFOptimizeMolecule(gen_mol) for j in range(num_ref): ref_mol = utils.set_rdmol_positions(data.rdmol, data.pos_ref[j]) rmsd_confusion_mat[j,i] = utils.GetBestRMSD(gen_mol, ref_mol) return rmsd_confusion_mat def evaluate_conf(data: Data, useFF=False, threshold=0.5): rmsd_confusion_mat = get_rmsd_confusion_matrix(data, useFF=useFF) rmsd_ref_min = rmsd_confusion_mat.min(-1) return (rmsd_ref_min<=threshold).mean(), rmsd_ref_min.mean() def evaluate_distance(data: Data, ignore_H=True): data.pos_ref = data.pos_ref.view(-1, data.num_nodes, 3) # (N, num_node, 3) data.pos_gen = data.pos_gen.view(-1, data.num_nodes, 3) # (M, num_node, 3) num_ref = data.pos_ref.size(0) # N num_gen = data.pos_gen.size(0) # M assert num_gen == data.num_pos_gen.item() assert num_ref == data.num_pos_ref.item() smiles = data.smiles edge_index = data.edge_index atom_type = data.atom_type # compute generated length and ref length ref_lengths = (data.pos_ref[:, edge_index[0]] - data.pos_ref[:, edge_index[1]]).norm(dim=-1) # (N, num_edge) gen_lengths = (data.pos_gen[:, edge_index[0]] - data.pos_gen[:, edge_index[1]]).norm(dim=-1) # (M, num_edge) # print(ref_lengths.size(), gen_lengths.size()) #print(ref_lengths.size()) #print(gen_lengths.size()) stats_single = [] first = 1 for i, (row, col) in enumerate(tqdm(edge_index.t())): if row >= col: continue if ignore_H and 1 in (atom_type[row].item(), atom_type[col].item()): continue gen_l = gen_lengths[:, i] ref_l = ref_lengths[:, i] if first: print(gen_l.size(), ref_l.size()) first = 0 mmd = compute_mmd(gen_l.view(-1, 1).cuda(), ref_l.view(-1, 1).cuda()).item() stats_single.append({ 'edge_id': i, 'elems': '%s - %s' % (utils.get_atom_symbol(atom_type[row].item()), utils.get_atom_symbol(atom_type[col].item())), 'nodes': (row.item(), col.item()), 'gen_lengths': gen_l.cpu(), 'ref_lengths': ref_l.cpu(), 'mmd': mmd }) first = 1 stats_pair = [] for i, (row_i, col_i) in enumerate(tqdm(edge_index.t())): if row_i >= col_i: continue if ignore_H and 1 in (atom_type[row_i].item(), atom_type[col_i].item()): continue for j, (row_j, col_j) in enumerate(edge_index.t()): if (row_i >= row_j) or (row_j >= col_j): continue if ignore_H and 1 in (atom_type[row_j].item(), atom_type[col_j].item()): continue gen_L = gen_lengths[:, (i,j)] # (N, 2) ref_L = ref_lengths[:, (i,j)] # (M, 2) if first: # print(gen_L.size(), ref_L.size()) first = 0 mmd = compute_mmd(gen_L.cuda(), ref_L.cuda()).item() stats_pair.append({ 'edge_id': (i, j), 'elems': ( '%s - %s' % (utils.get_atom_symbol(atom_type[row_i].item()), utils.get_atom_symbol(atom_type[col_i].item())), '%s - %s' % (utils.get_atom_symbol(atom_type[row_j].item()), utils.get_atom_symbol(atom_type[col_j].item())), ), 'nodes': ( (row_i.item(), col_i.item()), (row_j.item(), col_j.item()), ), 'gen_lengths': gen_L.cpu(), 'ref_lengths': ref_L.cpu(), 'mmd': mmd }) edge_filter = edge_index[0] < edge_index[1] if ignore_H: for i, (row, col) in enumerate(edge_index.t()): if 1 in (atom_type[row].item(), atom_type[col].item()): edge_filter[i] = False gen_L = gen_lengths[:, edge_filter] # (N, Ef) ref_L = ref_lengths[:, edge_filter] # (M, Ef) # print(gen_L.size(), ref_L.size()) mmd = compute_mmd(gen_L.cuda(), ref_L.cuda()).item() stats_all = { 'gen_lengths': gen_L.cpu(), 'ref_lengths': ref_L.cpu(), 'mmd': mmd } return stats_single, stats_pair, stats_all def guassian_kernel(source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None): ''' Params: source: n * len(x) target: m * len(y) Return: sum(kernel_val): Sum of various kernel matrices ''' n_samples = int(source.size()[0])+int(target.size()[0]) total = torch.cat([source, target], dim=0) total0 = total.unsqueeze(0).expand(int(total.size(0)), int(total.size(0)), int(total.size(1))) total1 = total.unsqueeze(1).expand(int(total.size(0)), int(total.size(0)), int(total.size(1))) L2_distance = ((total0-total1)**2).sum(2) if fix_sigma: bandwidth = fix_sigma else: bandwidth = torch.sum(L2_distance.data) / (n_samples**2-n_samples) bandwidth /= kernel_mul ** (kernel_num // 2) bandwidth_list = [bandwidth * (kernel_mul**i) for i in range(kernel_num)] kernel_val = [torch.exp(-L2_distance / bandwidth_temp) for bandwidth_temp in bandwidth_list] return sum(kernel_val)#/len(kernel_val) def compute_mmd(source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None): ''' Params: source: (N, D) target: (M, D) Return: loss: MMD loss ''' batch_size = int(source.size()[0]) kernels = guassian_kernel(source, target, kernel_mul=kernel_mul, kernel_num=kernel_num, fix_sigma=fix_sigma) XX = kernels[:batch_size, :batch_size] YY = kernels[batch_size:, batch_size:] XY = kernels[:batch_size, batch_size:] YX = kernels[batch_size:, :batch_size] loss = torch.mean(XX) + torch.mean(YY) - torch.mean(XY) - torch.mean(YX) return loss """ Another implementation: https://github.com/martinepalazzo/kernel_methods/blob/master/kernel_methods.py """
36.090909
154
0.59594
import numpy as np from tqdm.auto import tqdm import torch from torch_geometric.data import Data from rdkit import Chem from rdkit.Chem.rdForceFieldHelpers import MMFFOptimizeMolecule from SDE_CG import utils def get_rmsd_confusion_matrix(data: Data, useFF=False): data.pos_ref = data.pos_ref.view(-1, data.num_nodes, 3) data.pos_gen = data.pos_gen.view(-1, data.num_nodes, 3) num_gen = data.pos_gen.size(0) num_ref = data.pos_ref.size(0) assert num_gen == data.num_pos_gen.item() assert num_ref == data.num_pos_ref.item() rmsd_confusion_mat = -1 * np.ones([num_ref, num_gen],dtype=np.float) for i in range(num_gen): gen_mol = utils.set_rdmol_positions(data.rdmol, data.pos_gen[i]) if useFF: MMFFOptimizeMolecule(gen_mol) for j in range(num_ref): ref_mol = utils.set_rdmol_positions(data.rdmol, data.pos_ref[j]) rmsd_confusion_mat[j,i] = utils.GetBestRMSD(gen_mol, ref_mol) return rmsd_confusion_mat def evaluate_conf(data: Data, useFF=False, threshold=0.5): rmsd_confusion_mat = get_rmsd_confusion_matrix(data, useFF=useFF) rmsd_ref_min = rmsd_confusion_mat.min(-1) return (rmsd_ref_min<=threshold).mean(), rmsd_ref_min.mean() def evaluate_distance(data: Data, ignore_H=True): data.pos_ref = data.pos_ref.view(-1, data.num_nodes, 3) data.pos_gen = data.pos_gen.view(-1, data.num_nodes, 3) num_ref = data.pos_ref.size(0) num_gen = data.pos_gen.size(0) assert num_gen == data.num_pos_gen.item() assert num_ref == data.num_pos_ref.item() smiles = data.smiles edge_index = data.edge_index atom_type = data.atom_type ref_lengths = (data.pos_ref[:, edge_index[0]] - data.pos_ref[:, edge_index[1]]).norm(dim=-1) gen_lengths = (data.pos_gen[:, edge_index[0]] - data.pos_gen[:, edge_index[1]]).norm(dim=-1) stats_single = [] first = 1 for i, (row, col) in enumerate(tqdm(edge_index.t())): if row >= col: continue if ignore_H and 1 in (atom_type[row].item(), atom_type[col].item()): continue gen_l = gen_lengths[:, i] ref_l = ref_lengths[:, i] if first: print(gen_l.size(), ref_l.size()) first = 0 mmd = compute_mmd(gen_l.view(-1, 1).cuda(), ref_l.view(-1, 1).cuda()).item() stats_single.append({ 'edge_id': i, 'elems': '%s - %s' % (utils.get_atom_symbol(atom_type[row].item()), utils.get_atom_symbol(atom_type[col].item())), 'nodes': (row.item(), col.item()), 'gen_lengths': gen_l.cpu(), 'ref_lengths': ref_l.cpu(), 'mmd': mmd }) first = 1 stats_pair = [] for i, (row_i, col_i) in enumerate(tqdm(edge_index.t())): if row_i >= col_i: continue if ignore_H and 1 in (atom_type[row_i].item(), atom_type[col_i].item()): continue for j, (row_j, col_j) in enumerate(edge_index.t()): if (row_i >= row_j) or (row_j >= col_j): continue if ignore_H and 1 in (atom_type[row_j].item(), atom_type[col_j].item()): continue gen_L = gen_lengths[:, (i,j)] ref_L = ref_lengths[:, (i,j)] if first: first = 0 mmd = compute_mmd(gen_L.cuda(), ref_L.cuda()).item() stats_pair.append({ 'edge_id': (i, j), 'elems': ( '%s - %s' % (utils.get_atom_symbol(atom_type[row_i].item()), utils.get_atom_symbol(atom_type[col_i].item())), '%s - %s' % (utils.get_atom_symbol(atom_type[row_j].item()), utils.get_atom_symbol(atom_type[col_j].item())), ), 'nodes': ( (row_i.item(), col_i.item()), (row_j.item(), col_j.item()), ), 'gen_lengths': gen_L.cpu(), 'ref_lengths': ref_L.cpu(), 'mmd': mmd }) edge_filter = edge_index[0] < edge_index[1] if ignore_H: for i, (row, col) in enumerate(edge_index.t()): if 1 in (atom_type[row].item(), atom_type[col].item()): edge_filter[i] = False gen_L = gen_lengths[:, edge_filter] ref_L = ref_lengths[:, edge_filter] mmd = compute_mmd(gen_L.cuda(), ref_L.cuda()).item() stats_all = { 'gen_lengths': gen_L.cpu(), 'ref_lengths': ref_L.cpu(), 'mmd': mmd } return stats_single, stats_pair, stats_all def guassian_kernel(source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None): n_samples = int(source.size()[0])+int(target.size()[0]) total = torch.cat([source, target], dim=0) total0 = total.unsqueeze(0).expand(int(total.size(0)), int(total.size(0)), int(total.size(1))) total1 = total.unsqueeze(1).expand(int(total.size(0)), int(total.size(0)), int(total.size(1))) L2_distance = ((total0-total1)**2).sum(2) if fix_sigma: bandwidth = fix_sigma else: bandwidth = torch.sum(L2_distance.data) / (n_samples**2-n_samples) bandwidth /= kernel_mul ** (kernel_num // 2) bandwidth_list = [bandwidth * (kernel_mul**i) for i in range(kernel_num)] kernel_val = [torch.exp(-L2_distance / bandwidth_temp) for bandwidth_temp in bandwidth_list] return sum(kernel_val) def compute_mmd(source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None): batch_size = int(source.size()[0]) kernels = guassian_kernel(source, target, kernel_mul=kernel_mul, kernel_num=kernel_num, fix_sigma=fix_sigma) XX = kernels[:batch_size, :batch_size] YY = kernels[batch_size:, batch_size:] XY = kernels[:batch_size, batch_size:] YX = kernels[batch_size:, :batch_size] loss = torch.mean(XX) + torch.mean(YY) - torch.mean(XY) - torch.mean(YX) return loss
true
true
1c2cfa067573151f4c0869d0c10acd318d538534
6,182
py
Python
src/clustering.py
DianaLaboratory/DeepTSS
9f6d7cb94268aedbd9d38944ee6707ef9d6df882
[ "MIT" ]
null
null
null
src/clustering.py
DianaLaboratory/DeepTSS
9f6d7cb94268aedbd9d38944ee6707ef9d6df882
[ "MIT" ]
null
null
null
src/clustering.py
DianaLaboratory/DeepTSS
9f6d7cb94268aedbd9d38944ee6707ef9d6df882
[ "MIT" ]
null
null
null
import pandas as pd import multiprocessing as mp import time import os from src.FindClusters import * from src.Func import * def _args_(input_file): filename = os.path.basename(input_file) name = os.path.splitext(filename)[0] return(filename, name) def findAllRepresentatives(line): line = line.split('\t') if line[5].rstrip() == '+': out = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}'.format(line[0], line[1], int(line[1].rstrip()) + 1, line[3], line[4], line[5]) elif line[5].rstrip() == '-': out = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}'.format(line[0], int(line[2].rstrip()) - 1, line[2], line[3], line[4], line[5]) return(out) def genome_cov(row, current, hg38_fa_fai): strand = row[0] out = row[1] os.system(f"bedtools genomecov -i {current} -bg -strand {strand} -g {hg38_fa_fai} > {out}") def main_clustering(dict): start_time = time.time() input_file = dict['input_file'] hg38_fa_fai = dict['fai'] quality = dict['quality'] map_distance = dict['map_distance'] threads = dict['threads'] tpm_threshold = dict['tpm'] min_clust_size = dict['min_clust_size'] max_clust_size = dict['max_clust_size'] work_dir = dict['out_dir'] result_directory_id = dict['dir_name'] # input_file = '/mnt/raid0/dgrigor/projects/TSS_CNN/Clustering/test_H9/H9.bam' # hg38_fa_fai = '/mnt/raid0/dgrigor/.GitHub/TSS_CNN/DeepTSS_gitLab/files/genomes/hg38.chrom.sizes' # quality = 10 # map_distance = 50 # threads = 16 # tpm_threshold = 0.5 # min_clust_size = 1 # max_clust_size = 1000 # work_dir = '/mnt/raid0/dgrigor/projects/TSS_CNN/Clustering/test_H9' # result_directory_id = 'test_tpm' # Set path for work/out dir to new folder work_dir = f'{work_dir}/{result_directory_id}' # Create work/results dir create_dir(work_dir) # Save filename with and without extension [filename, name] = _args_(input_file) # If ".bed" file was provided if os.path.splitext(input_file)[1] == ".bed": return(work_dir, input_file) # Get all chr1-22 & chrX, chrY chr = chromosomes() # Create tmp dir for leftovers tmp_dir = f'{work_dir}/{name}_tmpdir' create_dir(tmp_dir) # Bam to bed & Quality filter print(" (1/6) - Applying quality threashold...") # out = f'{tmp_dir}/{name}_quality.bed' # os.system(f"bedtools bamtobed -i {input_file} | awk -F '\t' -v OFS='\t' '{{ if ($5 > {quality}) print $1,$2,$3,$4,$5,$6 }}' > {out}") # Forward strand out_f = f'{tmp_dir}/{name}_quality_f.bed' os.system(f"samtools view -F 16 -@ {threads} -q {quality} {input_file} | awk -F '\t' -v OFS='\t' '{{print $3, $4, $4+length($10)-1, $1, $5, \"+\"}}' > {out_f}") # Reverse strand out_r = f'{tmp_dir}/{name}_quality_r.bed' os.system(f"samtools view -f 16 -@ {threads} -q {quality} {input_file} | awk -F '\t' -v OFS='\t' '{{print $3, $4, $4+length($10)-1, $1, $5, \"-\"}}' > {out_r}") current = f'{tmp_dir}/{name}_quality.bed' os.system(f'cat {out_f} {out_r} > {current}') # Calculate ctss print(" (2/6) - CTSS...") tmp = [] with open(current, 'r') as infile: with mp.Pool(threads) as p: tmp.extend( p.map(findAllRepresentatives, [line for line in infile]) ) # Write ctss to file out = f'{tmp_dir}/{name}_quality_ctss.bed' with open(out, 'w') as f: for item in tmp: if item.split("\t")[0] in chr: # Filter chr 0-22 & X & Y f.write("%s" % item) del tmp current = out # Sort bed file print(" (3/6) - Sorting bed...") out = f'{tmp_dir}/{name}_quality_ctss_sorted.bed' os.system(f'sort --parallel={threads} -k1,1 -k2,2n -V -s {current} > {out}') current = out ################################### Coverage ############################################## # Coverage for all candidate tss representatives print(" (4/6) - Computing coverage...") out_5 = f'{tmp_dir}/{name}_quality_ctss_sorted_coverage_5_tmp.bed' out_3 = f'{tmp_dir}/{name}_quality_ctss_sorted_coverage_3_tmp.bed' cov_input = [['+', out_5], ['-',out_3]] pool = mp.Pool(2) pool.starmap(genome_cov, [(row, current, hg38_fa_fai) for row in cov_input]) pool.close() # Merge 5' and 3' coverage out = f'{tmp_dir}/{name}_quality_ctss_sorted_coverage_5.bed' os.system(f'awk -F \"\t\" -v OFS=\"\t\" \'{{print $1, $2, $3, $4, "+"}}\' {out_5} > {out}') os.system(f'rm {out_5}') # Sort out_5 = f'{tmp_dir}/{name}_quality_ctss_sorted_coverage_all_sorted_5.bed' os.system(f"sort --parallel={threads} -k1,1 -k2,2n -V -s {out} > {out_5}") out = f'{tmp_dir}/{name}_quality_ctss_sorted_coverage_3.bed' os.system(f'awk -F \"\t\" -v OFS=\"\t\" \'{{print $1, $2, $3, $4, "-"}}\' {out_3} > {out}') os.system(f'rm {out_3}') # Sort out_3 = f'{tmp_dir}/{name}_quality_ctss_sorted_coverage_all_sorted_3.bed' os.system(f"sort --parallel={threads} -k1,1 -k2,2n -V -s {out} > {out_3}") # Clustering print(" (5/6) - Clustering...") clusters_5, representatives_5 = clustering(out_5, map_distance, max_clust_size, min_clust_size) clusters_3, representatives_3 = clustering(out_3, map_distance, max_clust_size, min_clust_size) # Combine two strands for clusters and representatives clust = clusters_5 + clusters_3 represent = representatives_5 + representatives_3 if not clust: sys.exit(f'No clusters found. Try to reduce minimum cluster size') print(" (6/6) - Calculating tpm...") total_reads = sum(1 for line in open(f'{tmp_dir}/{name}_quality.bed')) clusters, representatives = fix_clusters_represent(clust, represent, tpm_threshold, total_reads) # Save out_clusters = f'{work_dir}/{name}_clusters.tpm.bed' clusters.to_csv(out_clusters, header=None, index=False, sep="\t") out_representatives = f'{work_dir}/{name}_representative.tpm.bed' representatives.to_csv(out_representatives, header=None, index=False, sep="\t") # os.system(f'rm -R {tmp_dir}') print(f'Clustering time: {round(((time.time() - start_time) / 60), 2)} mins ---') return(work_dir, out_representatives)
38.160494
165
0.620511
import pandas as pd import multiprocessing as mp import time import os from src.FindClusters import * from src.Func import * def _args_(input_file): filename = os.path.basename(input_file) name = os.path.splitext(filename)[0] return(filename, name) def findAllRepresentatives(line): line = line.split('\t') if line[5].rstrip() == '+': out = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}'.format(line[0], line[1], int(line[1].rstrip()) + 1, line[3], line[4], line[5]) elif line[5].rstrip() == '-': out = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}'.format(line[0], int(line[2].rstrip()) - 1, line[2], line[3], line[4], line[5]) return(out) def genome_cov(row, current, hg38_fa_fai): strand = row[0] out = row[1] os.system(f"bedtools genomecov -i {current} -bg -strand {strand} -g {hg38_fa_fai} > {out}") def main_clustering(dict): start_time = time.time() input_file = dict['input_file'] hg38_fa_fai = dict['fai'] quality = dict['quality'] map_distance = dict['map_distance'] threads = dict['threads'] tpm_threshold = dict['tpm'] min_clust_size = dict['min_clust_size'] max_clust_size = dict['max_clust_size'] work_dir = dict['out_dir'] result_directory_id = dict['dir_name'] work_dir = f'{work_dir}/{result_directory_id}' create_dir(work_dir) [filename, name] = _args_(input_file) if os.path.splitext(input_file)[1] == ".bed": return(work_dir, input_file) chr = chromosomes() tmp_dir = f'{work_dir}/{name}_tmpdir' create_dir(tmp_dir) print(" (1/6) - Applying quality threashold...") out_f = f'{tmp_dir}/{name}_quality_f.bed' os.system(f"samtools view -F 16 -@ {threads} -q {quality} {input_file} | awk -F '\t' -v OFS='\t' '{{print $3, $4, $4+length($10)-1, $1, $5, \"+\"}}' > {out_f}") out_r = f'{tmp_dir}/{name}_quality_r.bed' os.system(f"samtools view -f 16 -@ {threads} -q {quality} {input_file} | awk -F '\t' -v OFS='\t' '{{print $3, $4, $4+length($10)-1, $1, $5, \"-\"}}' > {out_r}") current = f'{tmp_dir}/{name}_quality.bed' os.system(f'cat {out_f} {out_r} > {current}') print(" (2/6) - CTSS...") tmp = [] with open(current, 'r') as infile: with mp.Pool(threads) as p: tmp.extend( p.map(findAllRepresentatives, [line for line in infile]) ) out = f'{tmp_dir}/{name}_quality_ctss.bed' with open(out, 'w') as f: for item in tmp: if item.split("\t")[0] in chr: f.write("%s" % item) del tmp current = out print(" (3/6) - Sorting bed...") out = f'{tmp_dir}/{name}_quality_ctss_sorted.bed' os.system(f'sort --parallel={threads} -k1,1 -k2,2n -V -s {current} > {out}') current = out
true
true
1c2cfa1530e0657a58165e5b7d251745010afaf6
113,256
py
Python
pysnmp-with-texts/DATALINK-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
8
2019-05-09T17:04:00.000Z
2021-06-09T06:50:51.000Z
pysnmp-with-texts/DATALINK-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
4
2019-05-31T16:42:59.000Z
2020-01-31T21:57:17.000Z
pysnmp-with-texts/DATALINK-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module DATALINK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DATALINK-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:37:02 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) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") private, ModuleIdentity, ObjectIdentity, internet, mgmt, TimeTicks, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, enterprises, NotificationType, ObjectName, Bits, Integer32, IpAddress, Gauge32, iso, NotificationType, Counter32, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "private", "ModuleIdentity", "ObjectIdentity", "internet", "mgmt", "TimeTicks", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "enterprises", "NotificationType", "ObjectName", "Bits", "Integer32", "IpAddress", "Gauge32", "iso", "NotificationType", "Counter32", "Counter64") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") asentria = MibIdentifier((1, 3, 6, 1, 4, 1, 3052)) datalink = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1)) productIds = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 1)) productConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 2)) unitIds = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 3)) serialPorts = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 4)) time = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 5)) snmpsetup = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 6)) passwords = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 7)) ftpsetup = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 8)) databases = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 9)) alarms = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 10)) actions = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 11)) controls = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12)) alarmhistory = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 13)) realtimesocket = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 14)) iprestrictions = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 15)) ipsetup = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 16)) pppsetup = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 17)) ccode = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 18)) techsupport = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 99)) hardware = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 2, 4)) factorysetup = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5)) commandPassword = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 7, 5)) entireDatabase = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1)) databaseStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 1)) databaseFiles = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2)) filesetup = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 1)) nodataAlarms = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3)) nodataAlarmHolidays = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3)) actionsBuzzer = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 11, 1)) actionsTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 11, 5)) opSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1)) auxportMode = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6)) inlineHskMode = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 4)) modemSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2)) dataRelease = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12, 3)) otherControls = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4)) ftpPush = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3)) actionQueue = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1)) actionHistory = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2)) ipCurrent = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 16, 1)) ipNew = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 16, 2)) pppIdentification = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 17, 1)) datalinkThisProduct = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: datalinkThisProduct.setStatus('mandatory') if mibBuilder.loadTexts: datalinkThisProduct.setDescription('This is a factory-configured string for the product name') productname = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: productname.setStatus('mandatory') if mibBuilder.loadTexts: productname.setDescription('A second string which may also contain name/version info') systemversion = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: systemversion.setStatus('mandatory') if mibBuilder.loadTexts: systemversion.setDescription('system rom version number') appversion = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: appversion.setStatus('mandatory') if mibBuilder.loadTexts: appversion.setDescription('application version') numberports = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 4, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: numberports.setStatus('mandatory') if mibBuilder.loadTexts: numberports.setDescription('number of RS232 ports found') netcard = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 4, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: netcard.setStatus('mandatory') if mibBuilder.loadTexts: netcard.setDescription('0 if no net card, 1 if net card found') modems = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 4, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: modems.setStatus('mandatory') if mibBuilder.loadTexts: modems.setDescription('0 if no modem, 1 if modem was found') networkenabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 4, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: networkenabled.setStatus('mandatory') if mibBuilder.loadTexts: networkenabled.setDescription('0 if not enabled, 1 if enabled') memorysize = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 4, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: memorysize.setStatus('mandatory') if mibBuilder.loadTexts: memorysize.setDescription('memory size in K') modemreport = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 1), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemreport.setStatus('mandatory') if mibBuilder.loadTexts: modemreport.setDescription('5-char string, speed to report for modem speed') modemportspeed = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemportspeed.setStatus('mandatory') if mibBuilder.loadTexts: modemportspeed.setDescription('modem port baud rate 38400, 19200, etc. ') modemsetupstring = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemsetupstring.setStatus('mandatory') if mibBuilder.loadTexts: modemsetupstring.setDescription('modem setup string, e.g., ATe0v0s0=1') modemcddelay = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemcddelay.setStatus('mandatory') if mibBuilder.loadTexts: modemcddelay.setDescription('seconds after CD before sending answer string') modemtype = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemtype.setStatus('mandatory') if mibBuilder.loadTexts: modemtype.setDescription('number factory-assigned to this particular modem, manufacturer, etc.') serialnumber = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 6), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: serialnumber.setStatus('mandatory') if mibBuilder.loadTexts: serialnumber.setDescription('up to 10 chars for factory-assigned serial number') dateofmanufacture = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 7), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: dateofmanufacture.setStatus('mandatory') if mibBuilder.loadTexts: dateofmanufacture.setDescription('up to 8 chars for factory-assigned date of manufacture') databasemode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databasemode.setStatus('mandatory') if mibBuilder.loadTexts: databasemode.setDescription('database compatibility mode, 1 -normal, 2 commandset2, etc.') datalinkSiteId = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 3, 1), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: datalinkSiteId.setStatus('mandatory') if mibBuilder.loadTexts: datalinkSiteId.setDescription('Site ID string') idByPortTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 3, 2), ) if mibBuilder.loadTexts: idByPortTable.setStatus('mandatory') if mibBuilder.loadTexts: idByPortTable.setDescription('an id for type of data by port') sitebyport = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 3, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "siteindex")) if mibBuilder.loadTexts: sitebyport.setStatus('mandatory') if mibBuilder.loadTexts: sitebyport.setDescription('entry for table') siteindex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 3, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: siteindex.setStatus('mandatory') if mibBuilder.loadTexts: siteindex.setDescription('index for which port') siteID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 3, 2, 1, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: siteID.setStatus('mandatory') if mibBuilder.loadTexts: siteID.setDescription('site id or type of data by port') numberPorts = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 4, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: numberPorts.setStatus('mandatory') if mibBuilder.loadTexts: numberPorts.setDescription('number of RS232 ports found. ') portSetupTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2), ) if mibBuilder.loadTexts: portSetupTable.setStatus('mandatory') if mibBuilder.loadTexts: portSetupTable.setDescription('port setup table, serial params, collect data, etc.') portSetupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "portIndex")) if mibBuilder.loadTexts: portSetupEntry.setStatus('mandatory') if mibBuilder.loadTexts: portSetupEntry.setDescription('port setup table, serial params, collect data, etc.') portIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: portIndex.setStatus('mandatory') if mibBuilder.loadTexts: portIndex.setDescription('index for table') portBaud = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portBaud.setStatus('mandatory') if mibBuilder.loadTexts: portBaud.setDescription('baud rate, 19200, 9600, etc.') portWord = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portWord.setStatus('mandatory') if mibBuilder.loadTexts: portWord.setDescription('word length, must be 7 or 8') portParity = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portParity.setStatus('mandatory') if mibBuilder.loadTexts: portParity.setDescription('a single-char string with values of N E or O') portStopbits = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portStopbits.setStatus('mandatory') if mibBuilder.loadTexts: portStopbits.setDescription('number of stop bits, must be 1') portDataStore = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portDataStore.setStatus('mandatory') if mibBuilder.loadTexts: portDataStore.setDescription('0 data is not stored, 1 data is stored from this port') portBinaryMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portBinaryMode.setStatus('mandatory') if mibBuilder.loadTexts: portBinaryMode.setDescription('0 data is ASCII, 1 data is binary') portWrapMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portWrapMode.setStatus('mandatory') if mibBuilder.loadTexts: portWrapMode.setDescription('0 oldest data not overwritten, 1 older data is overwritten') portHskMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portHskMode.setStatus('mandatory') if mibBuilder.loadTexts: portHskMode.setDescription('HSK mode to use when buffer close to full, 0 none, 1 xon, 2 DTR, 3 DTR and Xon') portDateTimeStampMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portDateTimeStampMode.setStatus('mandatory') if mibBuilder.loadTexts: portDateTimeStampMode.setDescription('Date/time stamp mode to use,bit mapped bit 0 - do date stamp bit 1 - include year bit 2 - include year 19xx or 20xx bit 3 - include day of week bit 4 - space after date bit 5 - include time bit 6 - include seconds bit 7 - space after time') portPTMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 11), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portPTMode.setStatus('mandatory') if mibBuilder.loadTexts: portPTMode.setDescription('pass-through access mode. 0=none, 1=by modem, 2=by network any write kills the passthrough connection. any write requires private community name') portPTTime = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: portPTTime.setStatus('mandatory') if mibBuilder.loadTexts: portPTTime.setDescription('pass-through access mode time of this connection, in seconds') portStoreFile = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 13), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portStoreFile.setStatus('mandatory') if mibBuilder.loadTexts: portStoreFile.setDescription('selects which data file data from this port is stored into') portPtStripOutputLfs = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 14), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portPtStripOutputLfs.setStatus('mandatory') if mibBuilder.loadTexts: portPtStripOutputLfs.setDescription('0/1 no/yes in pass-through, strip LFs going to device on this port') portPtStripInputLfs = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 15), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portPtStripInputLfs.setStatus('mandatory') if mibBuilder.loadTexts: portPtStripInputLfs.setDescription('0/1 no/yes in pass-through, strip LFs coming from device on this port') portlowDTR = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 16), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portlowDTR.setStatus('mandatory') if mibBuilder.loadTexts: portlowDTR.setDescription('0/1 no/yes set DTR low and only raise it on SysAdmin & bypass connections') currenttime = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 5, 1), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: currenttime.setStatus('mandatory') if mibBuilder.loadTexts: currenttime.setDescription('Text string for date and time: SUN 01/02/98 12:34:27') autoDstAdjust = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 5, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: autoDstAdjust.setStatus('mandatory') if mibBuilder.loadTexts: autoDstAdjust.setDescription('0 no adjust, 1 adjust') snmpTrapsEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 6, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpTrapsEnabled.setStatus('mandatory') if mibBuilder.loadTexts: snmpTrapsEnabled.setDescription('0 do not send any traps, 1 do send traps') snmpManagerTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 6, 2), ) if mibBuilder.loadTexts: snmpManagerTable.setStatus('mandatory') if mibBuilder.loadTexts: snmpManagerTable.setDescription('management station names and addresses') snmpTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 6, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "snmpMgrIndex")) if mibBuilder.loadTexts: snmpTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: snmpTableEntry.setDescription('entry for snmp table') snmpMgrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 6, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpMgrIndex.setStatus('mandatory') if mibBuilder.loadTexts: snmpMgrIndex.setDescription('index for table') snmpManagerIp = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 6, 2, 1, 2), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpManagerIp.setStatus('mandatory') if mibBuilder.loadTexts: snmpManagerIp.setDescription('the ip address of a manager') snmpManagerName = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 6, 2, 1, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpManagerName.setStatus('mandatory') if mibBuilder.loadTexts: snmpManagerName.setDescription('the name of a manager, up to 80 chars') snmpTrapsAutoRepeatTime = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 6, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpTrapsAutoRepeatTime.setStatus('mandatory') if mibBuilder.loadTexts: snmpTrapsAutoRepeatTime.setDescription('0 do not repeat, else number of minutes to repeat') snmpSendTestTrap = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 6, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpSendTestTrap.setStatus('mandatory') if mibBuilder.loadTexts: snmpSendTestTrap.setDescription('0 on read, any Set sends test trap to all managers in table') modemPasswords = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemPasswords.setStatus('mandatory') if mibBuilder.loadTexts: modemPasswords.setDescription('0 no modem passwords required, 1 modem passwords are required write requires private community name') tcpPasswords = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: tcpPasswords.setStatus('mandatory') if mibBuilder.loadTexts: tcpPasswords.setDescription('0 no telnet/tcp passwords required, 1 passwords are required write requires private community name') ftpPasswords = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPasswords.setStatus('mandatory') if mibBuilder.loadTexts: ftpPasswords.setDescription('0 no ftp passwords required, 1 passwords are required write requires private community name') promptPasswords = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: promptPasswords.setStatus('mandatory') if mibBuilder.loadTexts: promptPasswords.setDescription('0 no Password: prompt, 1 -> show Password: prompt') commandNeedsPassword = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 5, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: commandNeedsPassword.setStatus('mandatory') if mibBuilder.loadTexts: commandNeedsPassword.setDescription('0 not needed, 1 is needed write requires private community name') commandPasswordTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 5, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: commandPasswordTimeout.setStatus('mandatory') if mibBuilder.loadTexts: commandPasswordTimeout.setDescription('1-99, number of minutes of no activity which auto logs user out') passwordTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 7, 6), ) if mibBuilder.loadTexts: passwordTable.setStatus('mandatory') if mibBuilder.loadTexts: passwordTable.setDescription('Table of password entries, r-w only with private comm. name') passwordTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 7, 6, 1), ).setIndexNames((0, "DATALINK-MIB", "passwordIndex")) if mibBuilder.loadTexts: passwordTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: passwordTableEntry.setDescription('entry to password table') passwordIndex = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 6, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: passwordIndex.setStatus('mandatory') if mibBuilder.loadTexts: passwordIndex.setDescription('index to password table') passwordCommand = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 6, 1, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: passwordCommand.setStatus('mandatory') if mibBuilder.loadTexts: passwordCommand.setDescription('password for command access') passwordAccess = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 6, 1, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: passwordAccess.setStatus('mandatory') if mibBuilder.loadTexts: passwordAccess.setDescription('password for pass-through access') ftpAutoDelete = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpAutoDelete.setStatus('mandatory') if mibBuilder.loadTexts: ftpAutoDelete.setDescription('0 files not autodeleted, 1 deleted on reading') ftpDataMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpDataMode.setStatus('mandatory') if mibBuilder.loadTexts: ftpDataMode.setDescription('0 normal, 1 compression mode 1, etc.') ftpPushEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushEnabled.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushEnabled.setDescription('0-no, 1-yes, enables ftp data push') ftpPushTiming = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushTiming.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushTiming.setDescription('how often data is pushed, 2-255 minutes') ftpPushTimer = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushTimer.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushTimer.setDescription('timer which counts to ftpPushTiming') ftpPushIPAddress = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushIPAddress.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushIPAddress.setDescription('ip address of ftp server to which we push the data') ftpPushUser = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 5), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushUser.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushUser.setDescription('text string to send for the user id') ftpPushPass = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 6), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushPass.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushPass.setDescription('text string to send for the ftp server password') ftpPushAcct = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 7), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushAcct.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushAcct.setDescription('text string to send for the account, if used') ftpPushDir = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 8), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushDir.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushDir.setDescription('text string to send for the directory we CWD to') ftppushTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 9), ) if mibBuilder.loadTexts: ftppushTable.setStatus('mandatory') if mibBuilder.loadTexts: ftppushTable.setDescription('Table of ftp push enables') ftppushTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 9, 1), ).setIndexNames((0, "DATALINK-MIB", "ftppushIndex")) if mibBuilder.loadTexts: ftppushTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: ftppushTableEntry.setDescription('entry to ftp push table') ftppushIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 9, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ftppushIndex.setStatus('mandatory') if mibBuilder.loadTexts: ftppushIndex.setDescription('index to ftp push table') ftppushEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 9, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftppushEnable.setStatus('mandatory') if mibBuilder.loadTexts: ftppushEnable.setDescription('enable for ftp push, indexed by file') ftpPushAlarms = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushAlarms.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushAlarms.setDescription('0-no, 1-yes, do we push the ALARMS file') ftpPushCount = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 11), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ftpPushCount.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushCount.setDescription('number of ftp data pushes tried since reboot') ftpPushStatusMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 12), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushStatusMode.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushStatusMode.setDescription('0-none, 1-append, 2-replace, status file modes') ftpPushServerName = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 13), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushServerName.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushServerName.setDescription('Name of the FTP Push Targer Server') databasePfull = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: databasePfull.setStatus('mandatory') if mibBuilder.loadTexts: databasePfull.setDescription('percentage full of all database') databaseSize = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: databaseSize.setStatus('mandatory') if mibBuilder.loadTexts: databaseSize.setDescription('Size of Data Storage Area, in bytes') databaseRecordsAvailable = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: databaseRecordsAvailable.setStatus('mandatory') if mibBuilder.loadTexts: databaseRecordsAvailable.setDescription('Records which are available to read, total in all files') databaseRecordsDeleted = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: databaseRecordsDeleted.setStatus('mandatory') if mibBuilder.loadTexts: databaseRecordsDeleted.setDescription('Records which are deleted, total in all files') databaseAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2), ) if mibBuilder.loadTexts: databaseAlarmTable.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmTable.setDescription('table for levels 1 2 3 of all database alarms and actions') databaseAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "databaseAlarmIndex")) if mibBuilder.loadTexts: databaseAlarmEntry.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmEntry.setDescription('entry for database alarm config and actions table') databaseAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: databaseAlarmIndex.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmIndex.setDescription('Index for table, 1 2 or 3') databaseAlarmActive = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmActive.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmActive.setDescription('0/1, 1 = active') databaseAlarmThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmThreshold.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmThreshold.setDescription('1-99, percentage full threshold level') databaseAlarmBeeperActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmBeeperActions.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmBeeperActions.setDescription('0 1 2, -> none, 1/10 or 10/10') databaseAlarmSerialActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmSerialActions.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmSerialActions.setDescription('bits 0-7 show which messages 1-8 are sent') databaseAlarmPagerActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmPagerActions.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmPagerActions.setDescription('bits 0-7 show which pagers 1-8 are used') databaseAlarmCalloutActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmCalloutActions.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmCalloutActions.setDescription('bits 0-7 show which modem callouts 1-8 are used') databaseAlarmTrapActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmTrapActions.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmTrapActions.setDescription('0/1 for traps are sent or not') databaseAlarmFileStore = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmFileStore.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmFileStore.setDescription('0-no, 1-yes, store alarms in the ALARMS file') databaseAlarmFileMaxSize = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmFileMaxSize.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmFileMaxSize.setDescription('in K, max size for alarms file 4-32k') charmaskEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 1, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: charmaskEnabled.setStatus('mandatory') if mibBuilder.loadTexts: charmaskEnabled.setDescription('0/1 char masking enabled') charmask = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 1, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: charmask.setStatus('mandatory') if mibBuilder.loadTexts: charmask.setDescription('32-byte hex ascii for character masking') maxRecordChars = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: maxRecordChars.setStatus('mandatory') if mibBuilder.loadTexts: maxRecordChars.setDescription('max characters in an ASCII record') binRecordBlocking = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: binRecordBlocking.setStatus('mandatory') if mibBuilder.loadTexts: binRecordBlocking.setDescription('# chars max to block binary records into') recordCollectionTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: recordCollectionTimeout.setStatus('mandatory') if mibBuilder.loadTexts: recordCollectionTimeout.setDescription('# seconds to allow before terminating a record automatically') fileTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2), ) if mibBuilder.loadTexts: fileTable.setStatus('mandatory') if mibBuilder.loadTexts: fileTable.setDescription('table of directory entries') fileTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "fileTableIndex")) if mibBuilder.loadTexts: fileTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: fileTableEntry.setDescription('entry for table') fileTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: fileTableIndex.setDescription('index for the table') fileName = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileName.setStatus('mandatory') if mibBuilder.loadTexts: fileName.setDescription('name of the file') fileType = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileType.setStatus('mandatory') if mibBuilder.loadTexts: fileType.setDescription('type of data, up to 24 chars') fileSize = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileSize.setStatus('mandatory') if mibBuilder.loadTexts: fileSize.setDescription('file size in bytes') fileRecords = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileRecords.setStatus('mandatory') if mibBuilder.loadTexts: fileRecords.setDescription('file size in records') fileRecordsAvailable = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileRecordsAvailable.setStatus('mandatory') if mibBuilder.loadTexts: fileRecordsAvailable.setDescription('# recs available') fileRecordsDeleted = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileRecordsDeleted.setStatus('mandatory') if mibBuilder.loadTexts: fileRecordsDeleted.setDescription('# recs deleted') filePercentNow = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filePercentNow.setStatus('mandatory') if mibBuilder.loadTexts: filePercentNow.setDescription('% of all of memory this file is, right now') fileAlarms = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3), ) if mibBuilder.loadTexts: fileAlarms.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarms.setDescription('file alarms, indexed by file and threshold') fileAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1), ).setIndexNames((0, "DATALINK-MIB", "fileAlarmFileIndex"), (0, "DATALINK-MIB", "fileAlarmThreshold")) if mibBuilder.loadTexts: fileAlarmEntry.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmEntry.setDescription('entry to the table') fileAlarmFileIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileAlarmFileIndex.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmFileIndex.setDescription('index for filenumber') fileAlarmThresholdIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileAlarmThresholdIndex.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmThresholdIndex.setDescription('index for filenumber threshold') fileAlarmActive = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmActive.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmActive.setDescription('0/1 this file alarm active') fileAlarmThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmThreshold.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmThreshold.setDescription('1-99, threshold level') fileAlarmBeeperActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmBeeperActions.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmBeeperActions.setDescription('0 1 2, none, 1/10 or 10/10') fileAlarmSerialActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmSerialActions.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmSerialActions.setDescription('bits 0-7 show which messages 1-8 are sent') fileAlarmPagerActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmPagerActions.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmPagerActions.setDescription('bits 0-7 show which pagers 1-8 are used') fileAlarmCalloutActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmCalloutActions.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmCalloutActions.setDescription('bits 0-7 show which modem callouts 1-8 are used') fileAlarmTrapActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmTrapActions.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmTrapActions.setDescription('0/1 for traps are sent or not') dataAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1), ) if mibBuilder.loadTexts: dataAlarmTable.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmTable.setDescription('table of read-only items for data alarm setup') dataAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1), ).setIndexNames((0, "DATALINK-MIB", "dataAlarmIndex")) if mibBuilder.loadTexts: dataAlarmEntry.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmEntry.setDescription('Data alarm table entry') dataAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmIndex.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmIndex.setDescription('index for data alarms') dataAlarmActive = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmActive.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmActive.setDescription('0/1 active') dataAlarmName = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmName.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmName.setDescription('name of alarm') dataAlarmCounter = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmCounter.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmCounter.setDescription('counter for this alarm') dataAlarmThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmThreshold.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmThreshold.setDescription('threshold for this alarm') dataAlarmClearMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmClearMode.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmClearMode.setDescription('code for clearing mode') dataAlarmClearTime = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 7), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmClearTime.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmClearTime.setDescription('time of day, e.g., 01:20') dataAlarmAcked = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: dataAlarmAcked.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmAcked.setDescription('0 on read, any set to ack this alarm') dataAlarmBeeperActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmBeeperActions.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmBeeperActions.setDescription('0 1 2, none, 1/10 or 10/10') dataAlarmSerialActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 10), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmSerialActions.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmSerialActions.setDescription('bits 0-7 show which messages 1-8 are sent') dataAlarmPagerActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 11), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmPagerActions.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmPagerActions.setDescription('bits 0-7 show which pagers 1-8 are used') dataAlarmCalloutActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmCalloutActions.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmCalloutActions.setDescription('bits 0-7 show which modem callouts 1-8 are used') dataAlarmTrapActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmTrapActions.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmTrapActions.setDescription('0/1 for traps are sent or not') dataAlarmString = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 14), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmString.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmString.setDescription('last data alarm string for this alarm') dataAlarmPort = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 15), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmPort.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmPort.setDescription('port number for last data alarm string for this alarm') dataAlarmAutoClear = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 16), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmAutoClear.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmAutoClear.setDescription('0/1 disabled/enabled to auto clear counter when it reached threshold') sensorAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2), ) if mibBuilder.loadTexts: sensorAlarmTable.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmTable.setDescription('table of read-only items for sensor alarm setup') sensorAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "sensorAlarmIndex")) if mibBuilder.loadTexts: sensorAlarmEntry.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmEntry.setDescription('sensor alarm table entry') sensorAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sensorAlarmIndex.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmIndex.setDescription('index for sensor alarms') sensorAlarmActive = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmActive.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmActive.setDescription('0/1 active') sensorAlarmName = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmName.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmName.setDescription('name of alarm') sensorAlarmMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmMode.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmMode.setDescription('0 - open active, 1 - closed active') sensorAlarmCounter = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmCounter.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmCounter.setDescription('counter for this alarm') sensorAlarmThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmThreshold.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmThreshold.setDescription('threshold for this alarm') sensorAlarmAcked = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmAcked.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmAcked.setDescription('0 on read, any set to ack this alarm') sensorAlarmBeeperActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmBeeperActions.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmBeeperActions.setDescription('0 1 2, none, 1/10 or 10/10') sensorAlarmSerialActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmSerialActions.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmSerialActions.setDescription('bits 0-7 show which messages 1-8 are sent') sensorAlarmPagerActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmPagerActions.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmPagerActions.setDescription('bits 0-7 show which pagers 1-8 are used') sensorAlarmCalloutActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 11), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmCalloutActions.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmCalloutActions.setDescription('bits 0-7 show which modem callouts 1-8 are used') sensorAlarmTrapActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 12), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmTrapActions.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmTrapActions.setDescription('0/1 for traps are sent or not') sensorAlarmState = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sensorAlarmState.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmState.setDescription('0-> open 1-> closed for current state') nodataAlarmStatus = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 1), ) if mibBuilder.loadTexts: nodataAlarmStatus.setStatus('mandatory') if mibBuilder.loadTexts: nodataAlarmStatus.setDescription('no data status table') nodataAlarmStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 1, 1), ).setIndexNames((0, "DATALINK-MIB", "nodataAlarmStatusIndex")) if mibBuilder.loadTexts: nodataAlarmStatusEntry.setStatus('mandatory') if mibBuilder.loadTexts: nodataAlarmStatusEntry.setDescription('status table entry') nodataAlarmStatusIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nodataAlarmStatusIndex.setStatus('mandatory') if mibBuilder.loadTexts: nodataAlarmStatusIndex.setDescription('index for table') nodataAlarmStatusCounter = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 1, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataAlarmStatusCounter.setStatus('mandatory') if mibBuilder.loadTexts: nodataAlarmStatusCounter.setDescription('the nodata counter') nodataAlarmStatusAcked = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 1, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataAlarmStatusAcked.setStatus('mandatory') if mibBuilder.loadTexts: nodataAlarmStatusAcked.setDescription('reads as 0, any write acks this alarm') nodataTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2), ) if mibBuilder.loadTexts: nodataTable.setStatus('mandatory') if mibBuilder.loadTexts: nodataTable.setDescription('nodata table') nodataTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "nodataTablePortIndex"), (0, "DATALINK-MIB", "nodataTableScheduleIndex"), (0, "DATALINK-MIB", "nodataTableLevelIndex")) if mibBuilder.loadTexts: nodataTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableEntry.setDescription('nodata defn. table entry') nodataTablePortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 1), Integer32()) if mibBuilder.loadTexts: nodataTablePortIndex.setStatus('mandatory') if mibBuilder.loadTexts: nodataTablePortIndex.setDescription('index by port') nodataTableScheduleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 2), Integer32()) if mibBuilder.loadTexts: nodataTableScheduleIndex.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableScheduleIndex.setDescription('index by schedule') nodataTableLevelIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 3), Integer32()) if mibBuilder.loadTexts: nodataTableLevelIndex.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableLevelIndex.setDescription('index by level') nodataTableActive = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableActive.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableActive.setDescription('0/1 , enabled or not') nodataTableSchedule = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 5), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableSchedule.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableSchedule.setDescription('schedule, format is hh:mm-hh:mm') nodataTableThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableThreshold.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableThreshold.setDescription('#minutes for no data for alarm') nodataTableBeeperActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableBeeperActions.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableBeeperActions.setDescription('0 1 2, none, 1/10 or 10/10') nodataTableSerialActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableSerialActions.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableSerialActions.setDescription('bits 0-7 show which messages 1-8 are sent') nodataTablePagerActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTablePagerActions.setStatus('mandatory') if mibBuilder.loadTexts: nodataTablePagerActions.setDescription('bits 0-7 show which pagers 1-8 are used') nodataTableCalloutActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableCalloutActions.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableCalloutActions.setDescription('bits 0-7 show which modem callouts 1-8 are used') nodataTableTrapActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 11), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableTrapActions.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableTrapActions.setDescription('0/1 for traps are sent or not') nodataNumberHolidays = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nodataNumberHolidays.setStatus('mandatory') if mibBuilder.loadTexts: nodataNumberHolidays.setDescription('number of nodata holidays defined') nodataHolidayTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 2), ) if mibBuilder.loadTexts: nodataHolidayTable.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayTable.setDescription('holiday table') nodataHolidayTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "nodataHolidayIndex")) if mibBuilder.loadTexts: nodataHolidayTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayTableEntry.setDescription('holiday table entry') nodataHolidayIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nodataHolidayIndex.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayIndex.setDescription('index for holiday list') nodataHolidayItem = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 2, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: nodataHolidayItem.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayItem.setDescription('holiday list item, format is mm/dd') nodataHolidayAdd = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataHolidayAdd.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayAdd.setDescription('null on read, set with holiday to add MM/DD') nodataHolidayDelete = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataHolidayDelete.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayDelete.setDescription('null on read, set with holiday to delete MM/DD') nodataHolidayClear = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataHolidayClear.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayClear.setDescription('read returns 0, write requires private community name. used to clear the holiday list') scheduleAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4), ) if mibBuilder.loadTexts: scheduleAlarmTable.setStatus('mandatory') if mibBuilder.loadTexts: scheduleAlarmTable.setDescription('scheduled alarm table') scheduleAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1), ).setIndexNames((0, "DATALINK-MIB", "scheduleIndex")) if mibBuilder.loadTexts: scheduleAlarmEntry.setStatus('mandatory') if mibBuilder.loadTexts: scheduleAlarmEntry.setDescription('schedule table entry') scheduleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: scheduleIndex.setStatus('mandatory') if mibBuilder.loadTexts: scheduleIndex.setDescription('day index') scheduleActive = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleActive.setStatus('mandatory') if mibBuilder.loadTexts: scheduleActive.setDescription('if active or not') scheduleTime = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleTime.setStatus('mandatory') if mibBuilder.loadTexts: scheduleTime.setDescription('time of day format is: hh:mm') scheduleAcked = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleAcked.setStatus('mandatory') if mibBuilder.loadTexts: scheduleAcked.setDescription('reads 0, any set acks alarm') scheduleBeeperActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleBeeperActions.setStatus('mandatory') if mibBuilder.loadTexts: scheduleBeeperActions.setDescription('0 1 2, none, 1/10 or 10/10') scheduleSerialActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleSerialActions.setStatus('mandatory') if mibBuilder.loadTexts: scheduleSerialActions.setDescription('bits 0-7 show which messages 1-8 are sent') schedulePagerActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: schedulePagerActions.setStatus('mandatory') if mibBuilder.loadTexts: schedulePagerActions.setDescription('bits 0-7 show which pagers 1-8 are used') scheduleCalloutActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleCalloutActions.setStatus('mandatory') if mibBuilder.loadTexts: scheduleCalloutActions.setDescription('bits 0-7 show which modem callouts 1-8 are used') scheduleTrapActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleTrapActions.setStatus('mandatory') if mibBuilder.loadTexts: scheduleTrapActions.setDescription('0/1 for traps are sent or not') actionsBuzzerState = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 11, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionsBuzzerState.setStatus('mandatory') if mibBuilder.loadTexts: actionsBuzzerState.setDescription('current buzzer state 0.1.2') actionsSerialTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 11, 2), ) if mibBuilder.loadTexts: actionsSerialTable.setStatus('mandatory') if mibBuilder.loadTexts: actionsSerialTable.setDescription('serial message table') actionsSerialTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 11, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "serialTableIndex")) if mibBuilder.loadTexts: actionsSerialTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: actionsSerialTableEntry.setDescription('serial table entry') serialTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: serialTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: serialTableIndex.setDescription('serial table index') serialTableMessage = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 2, 1, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: serialTableMessage.setStatus('mandatory') if mibBuilder.loadTexts: serialTableMessage.setDescription('serial table string') actionsPagerTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3), ) if mibBuilder.loadTexts: actionsPagerTable.setStatus('mandatory') if mibBuilder.loadTexts: actionsPagerTable.setDescription('pager table') actionsPagerTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1), ).setIndexNames((0, "DATALINK-MIB", "pagerTableIndex")) if mibBuilder.loadTexts: actionsPagerTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: actionsPagerTableEntry.setDescription('pager table entry') pagerTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pagerTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: pagerTableIndex.setDescription('table index') pagerType = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerType.setStatus('mandatory') if mibBuilder.loadTexts: pagerType.setDescription('0-numeric, 1-alpha') pagerPhonenumber = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerPhonenumber.setStatus('mandatory') if mibBuilder.loadTexts: pagerPhonenumber.setDescription('phone number to call for pager') pagerID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerID.setStatus('mandatory') if mibBuilder.loadTexts: pagerID.setDescription('ID or 2nd number to dial') pagerDialDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerDialDelay.setStatus('mandatory') if mibBuilder.loadTexts: pagerDialDelay.setDescription('# seconds on numeric to delay between dial and send pagerID or message') pagerHangupDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerHangupDelay.setStatus('mandatory') if mibBuilder.loadTexts: pagerHangupDelay.setDescription('# seconds on numeric to delay between messages and before hangup') pagerMessage = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 7), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerMessage.setStatus('mandatory') if mibBuilder.loadTexts: pagerMessage.setDescription('message, either alpha or numeric') pagerSendId = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerSendId.setStatus('mandatory') if mibBuilder.loadTexts: pagerSendId.setDescription('0/1 send unit ID or not to pager') pagerSendReason = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerSendReason.setStatus('mandatory') if mibBuilder.loadTexts: pagerSendReason.setDescription('0/1 send reason for page or not to pager') pagerMaxAttempts = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerMaxAttempts.setStatus('mandatory') if mibBuilder.loadTexts: pagerMaxAttempts.setDescription('max tries to be successful') pagerAttempts = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 11), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerAttempts.setStatus('mandatory') if mibBuilder.loadTexts: pagerAttempts.setDescription('current number of tries') pagerAttemptDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 12), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerAttemptDelay.setStatus('mandatory') if mibBuilder.loadTexts: pagerAttemptDelay.setDescription('# minutes between attempts') pagerRepeat = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 13), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerRepeat.setStatus('mandatory') if mibBuilder.loadTexts: pagerRepeat.setDescription('0/1 do we repeat successful') pagerRepeatDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 14), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerRepeatDelay.setStatus('mandatory') if mibBuilder.loadTexts: pagerRepeatDelay.setDescription('# minutes between repeats, if used') actionsCalloutTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4), ) if mibBuilder.loadTexts: actionsCalloutTable.setStatus('mandatory') if mibBuilder.loadTexts: actionsCalloutTable.setDescription('callout table') actionsCalloutTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1), ).setIndexNames((0, "DATALINK-MIB", "calloutTableIndex")) if mibBuilder.loadTexts: actionsCalloutTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: actionsCalloutTableEntry.setDescription('callout table entry') calloutTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: calloutTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: calloutTableIndex.setDescription('table index') calloutPhonenumber = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutPhonenumber.setStatus('mandatory') if mibBuilder.loadTexts: calloutPhonenumber.setDescription('phone number to call for callout') calloutMaxConnecttime = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutMaxConnecttime.setStatus('mandatory') if mibBuilder.loadTexts: calloutMaxConnecttime.setDescription('# seconds to wait for carrier') calloutMessage = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutMessage.setStatus('mandatory') if mibBuilder.loadTexts: calloutMessage.setDescription('message to send') calloutSendId = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutSendId.setStatus('mandatory') if mibBuilder.loadTexts: calloutSendId.setDescription('0/1 send unit ID or not to callout') calloutSendReason = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutSendReason.setStatus('mandatory') if mibBuilder.loadTexts: calloutSendReason.setDescription('0/1 send reason for page or not to callout') calloutCommandWait = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutCommandWait.setStatus('mandatory') if mibBuilder.loadTexts: calloutCommandWait.setDescription('#seconds to wait for a command on a callout before hangup') calloutMaxAttempts = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutMaxAttempts.setStatus('mandatory') if mibBuilder.loadTexts: calloutMaxAttempts.setDescription('max tries to be successful') calloutAttempts = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutAttempts.setStatus('mandatory') if mibBuilder.loadTexts: calloutAttempts.setDescription('current number of tries') calloutAttemptDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutAttemptDelay.setStatus('mandatory') if mibBuilder.loadTexts: calloutAttemptDelay.setDescription('# minutes between attempts') calloutRepeat = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 11), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutRepeat.setStatus('mandatory') if mibBuilder.loadTexts: calloutRepeat.setDescription('0/1 do we repeat successful') calloutRepeatDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 12), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutRepeatDelay.setStatus('mandatory') if mibBuilder.loadTexts: calloutRepeatDelay.setDescription('# minutes between repeats, if used') actionsTrapsEntSpecific = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 11, 5, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: actionsTrapsEntSpecific.setStatus('mandatory') if mibBuilder.loadTexts: actionsTrapsEntSpecific.setDescription('0/1 enterprise specific traps enabled') actionsTrapsEntSpecCount = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 11, 5, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionsTrapsEntSpecCount.setStatus('mandatory') if mibBuilder.loadTexts: actionsTrapsEntSpecCount.setDescription('number of enterprise specific traps sent since last re-boot') linefeeds = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: linefeeds.setStatus('mandatory') if mibBuilder.loadTexts: linefeeds.setDescription('0/1 are linefeeds added to CRs on command responses?') duplex = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: duplex.setStatus('mandatory') if mibBuilder.loadTexts: duplex.setDescription('0-half 1-full') response = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: response.setStatus('mandatory') if mibBuilder.loadTexts: response.setDescription('0-codes 1-words') datafilterEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: datafilterEnabled.setStatus('mandatory') if mibBuilder.loadTexts: datafilterEnabled.setDescription('0/1 off/on') alarmfilterEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: alarmfilterEnabled.setStatus('mandatory') if mibBuilder.loadTexts: alarmfilterEnabled.setDescription('0/1 off/on') operatingMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: operatingMode.setStatus('mandatory') if mibBuilder.loadTexts: operatingMode.setDescription('1 command 2 input/access 3 unused 4 inline 5 extmodem') inlineMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: inlineMode.setStatus('mandatory') if mibBuilder.loadTexts: inlineMode.setDescription('1,2,3 if inline, mode 1 (N->2) mode 2 (1->2, 3->4) mode 3 (1->2, 3->4, 5->6)') inlineSource = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: inlineSource.setStatus('mandatory') if mibBuilder.loadTexts: inlineSource.setDescription('if inline and inlineMode==1, source of I/O2 inline') inlineHsk2 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 4, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: inlineHsk2.setStatus('mandatory') if mibBuilder.loadTexts: inlineHsk2.setDescription('handshake mode 0-3 for inline port I/O 2') inlineHsk4 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 4, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: inlineHsk4.setStatus('mandatory') if mibBuilder.loadTexts: inlineHsk4.setDescription('handshake mode 0-3 for inline port I/O 4') inlineHsk6 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 4, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: inlineHsk6.setStatus('mandatory') if mibBuilder.loadTexts: inlineHsk6.setDescription('handshake mode 0-3 for inline port I/O 6') sureEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sureEnabled.setStatus('mandatory') if mibBuilder.loadTexts: sureEnabled.setDescription('0/1 off/on') commandTcpipTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: commandTcpipTimeout.setStatus('mandatory') if mibBuilder.loadTexts: commandTcpipTimeout.setDescription('0-none, else number of no-activity minutes -> tcpip command to drop') sysadminTcpipTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysadminTcpipTimeout.setStatus('mandatory') if mibBuilder.loadTexts: sysadminTcpipTimeout.setDescription('0-none, else number of no-activity minutes -> tcpip sysadmin to drop') bypassEndchar = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: bypassEndchar.setStatus('mandatory') if mibBuilder.loadTexts: bypassEndchar.setDescription('ascii value for character to exit bypass mode. default ->27') routerAutoPing = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 11), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: routerAutoPing.setStatus('mandatory') if mibBuilder.loadTexts: routerAutoPing.setDescription('0/1 = no/yes, default is 0, do we ping the default router every 10 minutes?') modemParity = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemParity.setStatus('mandatory') if mibBuilder.loadTexts: modemParity.setDescription('1 7E 2 7O 3 8N') modemUserSetup = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemUserSetup.setStatus('mandatory') if mibBuilder.loadTexts: modemUserSetup.setDescription('sent to modem on init before the factory setup string') modemTapSetup = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemTapSetup.setStatus('mandatory') if mibBuilder.loadTexts: modemTapSetup.setDescription('sent to modem on just before doing TAP (alpha pager) protocol') modemAnswerString = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemAnswerString.setStatus('mandatory') if mibBuilder.loadTexts: modemAnswerString.setDescription('sent when modem makes connection') modemExtSetup = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 5), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemExtSetup.setStatus('mandatory') if mibBuilder.loadTexts: modemExtSetup.setDescription('sent to ext. modem for setup string') modemExtSetupTime = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemExtSetupTime.setStatus('mandatory') if mibBuilder.loadTexts: modemExtSetupTime.setDescription('# minutes of idle time between sending ext. modem setup string') modemInactivityTimer = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemInactivityTimer.setStatus('mandatory') if mibBuilder.loadTexts: modemInactivityTimer.setDescription('# minutes of no transmit which aborts a connection') modemAutoexecString = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 8), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemAutoexecString.setStatus('mandatory') if mibBuilder.loadTexts: modemAutoexecString.setDescription('command string which auto-executes after modem connection if no other command within 10 seconds') modemAutoexecEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemAutoexecEnabled.setStatus('mandatory') if mibBuilder.loadTexts: modemAutoexecEnabled.setDescription('0/1 autoexec enabled') modemTimeBetweenOutbound = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemTimeBetweenOutbound.setStatus('mandatory') if mibBuilder.loadTexts: modemTimeBetweenOutbound.setDescription('# seconds (minimum) between outbound call attempts') releaseMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 3, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: releaseMode.setStatus('mandatory') if mibBuilder.loadTexts: releaseMode.setDescription('1-Line 3-CBB 4-Xmodem') autodeleteEnable = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 3, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: autodeleteEnable.setStatus('mandatory') if mibBuilder.loadTexts: autodeleteEnable.setDescription('1/2 off/on autodelete for CBB and Xmodem') releaseCompressed = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 3, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: releaseCompressed.setStatus('mandatory') if mibBuilder.loadTexts: releaseCompressed.setDescription('1-compressed 2-decompressed') waitMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: waitMode.setStatus('mandatory') if mibBuilder.loadTexts: waitMode.setDescription('1/2 off/on wait for 02 after 01 on rlmodes') tagMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: tagMode.setStatus('mandatory') if mibBuilder.loadTexts: tagMode.setDescription('1/2 off/on Line/Block tag enabled') crcMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: crcMode.setStatus('mandatory') if mibBuilder.loadTexts: crcMode.setDescription('1/2 off/on add CRC to ascii releases') dleMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: dleMode.setStatus('mandatory') if mibBuilder.loadTexts: dleMode.setDescription('1/2 off/on use DLE stuffing on CBB') cbbRetransmits = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cbbRetransmits.setStatus('mandatory') if mibBuilder.loadTexts: cbbRetransmits.setDescription('# times a block retransmitted in CBB mode') cbbTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cbbTimeout.setStatus('mandatory') if mibBuilder.loadTexts: cbbTimeout.setDescription('# seconds to wait for an ack before retransmit in CBB mode') activeDatabase = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: activeDatabase.setStatus('mandatory') if mibBuilder.loadTexts: activeDatabase.setDescription('selects a file. ports 2001-2006 auto select this variable') actionCount = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionCount.setStatus('mandatory') if mibBuilder.loadTexts: actionCount.setDescription('number of active items in action table, 0-nn') actionTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2), ) if mibBuilder.loadTexts: actionTable.setStatus('mandatory') if mibBuilder.loadTexts: actionTable.setDescription('action queue table') actionTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "actionTableIndex")) if mibBuilder.loadTexts: actionTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: actionTableEntry.setDescription('action queue entry') actionTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: actionTableIndex.setDescription('action table entry') actionAcked = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: actionAcked.setStatus('mandatory') if mibBuilder.loadTexts: actionAcked.setDescription('reads 0, any set removes (acks) this action') actionReason = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionReason.setStatus('mandatory') if mibBuilder.loadTexts: actionReason.setDescription('code reason for action') actionReasonID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionReasonID.setStatus('mandatory') if mibBuilder.loadTexts: actionReasonID.setDescription('which of the (reasons) e.g, alarm 3 vs. alarm 4') actionReasonLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionReasonLevel.setStatus('mandatory') if mibBuilder.loadTexts: actionReasonLevel.setDescription('which of the levels for alarms which have 1-3 levels') actionType = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionType.setStatus('mandatory') if mibBuilder.loadTexts: actionType.setDescription('type of action being taken (page, callout, etc.)') actionTypeID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionTypeID.setStatus('mandatory') if mibBuilder.loadTexts: actionTypeID.setDescription('which of the actions e.g, pager 3 vs. pager 4') actionRepeatTime = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionRepeatTime.setStatus('mandatory') if mibBuilder.loadTexts: actionRepeatTime.setDescription('#minutes between repeats of attempts of this action') actionAttempts = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionAttempts.setStatus('mandatory') if mibBuilder.loadTexts: actionAttempts.setDescription('# of attempts to try this action so far') actionNextAttempt = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 10), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionNextAttempt.setStatus('mandatory') if mibBuilder.loadTexts: actionNextAttempt.setDescription('# minutes until the next attempt of this action') actionTimeStamp = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 11), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionTimeStamp.setStatus('mandatory') if mibBuilder.loadTexts: actionTimeStamp.setDescription('date and time string: 02/34 12:34, or text message if no items') historyCount = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyCount.setStatus('mandatory') if mibBuilder.loadTexts: historyCount.setDescription('number of history items in history table, 0-nn') historyTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2), ) if mibBuilder.loadTexts: historyTable.setStatus('mandatory') if mibBuilder.loadTexts: historyTable.setDescription('action history table') historyTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "historyTableIndex")) if mibBuilder.loadTexts: historyTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: historyTableEntry.setDescription('history queue entry') historyTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: historyTableIndex.setDescription('history table entry') historyEntryType = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: historyEntryType.setStatus('mandatory') if mibBuilder.loadTexts: historyEntryType.setDescription('type of entry (e.g., modem fail, pager pass, etc.)') historyReason = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyReason.setStatus('mandatory') if mibBuilder.loadTexts: historyReason.setDescription('code reason for history') historyReasonID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyReasonID.setStatus('mandatory') if mibBuilder.loadTexts: historyReasonID.setDescription('which of the (reasons) e.g, alarm 3 vs. alarm 4') historyReasonLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyReasonLevel.setStatus('mandatory') if mibBuilder.loadTexts: historyReasonLevel.setDescription('which of the levels for alarms which have 1-3 levels') historyType = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyType.setStatus('mandatory') if mibBuilder.loadTexts: historyType.setDescription('type of history being taken (page, callout, etc.)') historyTypeID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyTypeID.setStatus('mandatory') if mibBuilder.loadTexts: historyTypeID.setDescription('which of the historys e.g, pager 3 vs. pager 4') historyTimeStamp = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 8), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyTimeStamp.setStatus('mandatory') if mibBuilder.loadTexts: historyTimeStamp.setDescription('date and time string: 02/34 12:34, or text message if no items') historyClearLog = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: historyClearLog.setStatus('mandatory') if mibBuilder.loadTexts: historyClearLog.setDescription('reads 0, any set clears all history log items') lastCalloutPageReason = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 13, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: lastCalloutPageReason.setStatus('mandatory') if mibBuilder.loadTexts: lastCalloutPageReason.setDescription('the reason string for the last callout or page, or NONE if never used') rtsShowAnswer = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 14, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsShowAnswer.setStatus('deprecated') if mibBuilder.loadTexts: rtsShowAnswer.setDescription('0-no 1-yes, show answer string on connection (deprecated)') rtsNeedPassword = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 14, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rtsNeedPassword.setStatus('deprecated') if mibBuilder.loadTexts: rtsNeedPassword.setDescription('0-no 1-yes, need password on RTS connection (deprecated)') rtsWaitXon = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 14, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsWaitXon.setStatus('deprecated') if mibBuilder.loadTexts: rtsWaitXon.setDescription('0-no 1-yes, wait for Xon after connection before sending data (deprecated)') rtsIdleTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 14, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsIdleTimeout.setStatus('deprecated') if mibBuilder.loadTexts: rtsIdleTimeout.setDescription('0-255, 0-none, 1-255 #idle minutes no data = shutdown socket (deprecated)') rtsEmptyClose = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 14, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsEmptyClose.setStatus('deprecated') if mibBuilder.loadTexts: rtsEmptyClose.setDescription('0->no, 1-> yes, when file empty close socket (polling, not rt data) (deprecated)') rtsTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6), ) if mibBuilder.loadTexts: rtsTable.setStatus('mandatory') if mibBuilder.loadTexts: rtsTable.setDescription('real time socket table') rtsTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1), ).setIndexNames((0, "DATALINK-MIB", "rtsTableIndex")) if mibBuilder.loadTexts: rtsTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: rtsTableEntry.setDescription('rts table entry') rtsTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rtsTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: rtsTableIndex.setDescription('rts table entry index') rtsNoStore = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsNoStore.setStatus('mandatory') if mibBuilder.loadTexts: rtsNoStore.setDescription("0-allow storage, 1-don't store data when RTS socket not connected") rtsDenied = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsDenied.setStatus('mandatory') if mibBuilder.loadTexts: rtsDenied.setDescription("0-don't allow, 1=yes allow this rts socket to connect") rtsSocketState = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rtsSocketState.setStatus('mandatory') if mibBuilder.loadTexts: rtsSocketState.setDescription('0-closed, 1-wait for pass, 2-wait for xon, 3=open for data') rtsPortShowAnswer = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsPortShowAnswer.setStatus('mandatory') if mibBuilder.loadTexts: rtsPortShowAnswer.setDescription('0-no 1-yes, show answer string on connection') rtsPortNeedPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rtsPortNeedPassword.setStatus('mandatory') if mibBuilder.loadTexts: rtsPortNeedPassword.setDescription('0-no 1-yes, need password on RTS connection') rtsPortWaitXon = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsPortWaitXon.setStatus('mandatory') if mibBuilder.loadTexts: rtsPortWaitXon.setDescription('0-no 1-yes, wait for Xon after connection before sending data') rtsPortIdleTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsPortIdleTimeout.setStatus('mandatory') if mibBuilder.loadTexts: rtsPortIdleTimeout.setDescription('0-255, 0-none, 1-255 #idle minutes no data = shutdown socket') rtsPortEmptyClose = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsPortEmptyClose.setStatus('mandatory') if mibBuilder.loadTexts: rtsPortEmptyClose.setDescription('0->no, 1-> yes, when file empty close socket (polling, not rt data)') iprestrictTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 15, 1), ) if mibBuilder.loadTexts: iprestrictTable.setStatus('mandatory') if mibBuilder.loadTexts: iprestrictTable.setDescription('ip restrictions table') iprestrictTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 15, 1, 1), ).setIndexNames((0, "DATALINK-MIB", "iprestrictTableIndex")) if mibBuilder.loadTexts: iprestrictTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: iprestrictTableEntry.setDescription('ip restriction table entry') iprestrictTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 15, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: iprestrictTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: iprestrictTableIndex.setDescription('ip restrict table entry index') iprestrictIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 15, 1, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: iprestrictIpAddress.setStatus('mandatory') if mibBuilder.loadTexts: iprestrictIpAddress.setDescription('an ip address which forces a restriction or allowance for an ip range') suspendIPRestrictions = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 15, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: suspendIPRestrictions.setStatus('mandatory') if mibBuilder.loadTexts: suspendIPRestrictions.setDescription('read returns 0, writing requires the private community name. default is 0 set to 1 to suspend IP restrictions while loading the list set back to 0 to allow the restrictions to be used.') killIPRestrictions = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 15, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: killIPRestrictions.setStatus('mandatory') if mibBuilder.loadTexts: killIPRestrictions.setDescription('read returns 0, writing requires the private community name. any set removes all entries from the IP restrcition list.') addIPRestrictions = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 15, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: addIPRestrictions.setStatus('mandatory') if mibBuilder.loadTexts: addIPRestrictions.setDescription('read returns 0, writing requires the private community name. any set adds an entry to the IP restriction list note that list is no re-sorted, so must add in order') ipCurrentStatic = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipCurrentStatic.setStatus('mandatory') if mibBuilder.loadTexts: ipCurrentStatic.setDescription('1=static, 0=dynamic') ipCurrentAddress = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipCurrentAddress.setStatus('mandatory') if mibBuilder.loadTexts: ipCurrentAddress.setDescription('current IP address') ipCurrentSubnetMask = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 1, 3), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipCurrentSubnetMask.setStatus('mandatory') if mibBuilder.loadTexts: ipCurrentSubnetMask.setDescription('current subnet mask') ipCurrentDefaultRouter = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipCurrentDefaultRouter.setStatus('mandatory') if mibBuilder.loadTexts: ipCurrentDefaultRouter.setDescription('current default router') ipNewStatic = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 2, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNewStatic.setStatus('mandatory') if mibBuilder.loadTexts: ipNewStatic.setDescription('1=static, 0=dynamic. write requires private community name.') ipNewAddress = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 2, 2), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNewAddress.setStatus('mandatory') if mibBuilder.loadTexts: ipNewAddress.setDescription('read=current new address, write requires private community name.') ipNewSubnetMask = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 2, 3), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNewSubnetMask.setStatus('mandatory') if mibBuilder.loadTexts: ipNewSubnetMask.setDescription('read=current new subnet mask, write requires private community name.') ipNewDefaultRouter = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 2, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNewDefaultRouter.setStatus('mandatory') if mibBuilder.loadTexts: ipNewDefaultRouter.setDescription('read=current new default router, write requires private community name.') ipNewSetup = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 2, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNewSetup.setStatus('mandatory') if mibBuilder.loadTexts: ipNewSetup.setDescription('read=0. write requires private community name. any write causes the current object values for ipNewStatic, ipNewAddress, ipNewSubnetMask and ipNewDefaultRouter to be used. Causes the unit to re-initialize its network stacks with these new values. Changes to ipNewStatic, ipNewAddress, ipNewSubnetMask and ipNewDefaultRouter do not affect the network stack until ipNewSetup is written with some value:') pppIDString = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 17, 1, 1), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pppIDString.setStatus('mandatory') if mibBuilder.loadTexts: pppIDString.setDescription('sent in ppp up trap to provide host identification string') pppIPAddress = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 17, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: pppIPAddress.setStatus('mandatory') if mibBuilder.loadTexts: pppIPAddress.setDescription('sent in ppp up trap to provide host identification by IP address') ccodeLoaded = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 18, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ccodeLoaded.setStatus('mandatory') if mibBuilder.loadTexts: ccodeLoaded.setDescription('0/1, no/yes, is ccode loaded') ccodeRunning = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 18, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ccodeRunning.setStatus('mandatory') if mibBuilder.loadTexts: ccodeRunning.setDescription('0/1, no/yes, is ccode running') ccodeStackMainWas = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 18, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ccodeStackMainWas.setStatus('mandatory') if mibBuilder.loadTexts: ccodeStackMainWas.setDescription('# of bytes of stack used by main app, last time run') ccodeStackMainNow = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 18, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ccodeStackMainNow.setStatus('mandatory') if mibBuilder.loadTexts: ccodeStackMainNow.setDescription('# of bytes of stack used by main app, this time run') ccodeStackT2Was = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 18, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ccodeStackT2Was.setStatus('mandatory') if mibBuilder.loadTexts: ccodeStackT2Was.setDescription('# of bytes of stack used by 2nd task of app, last time run') ccodeStackT2Was2 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 18, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ccodeStackT2Was2.setStatus('mandatory') if mibBuilder.loadTexts: ccodeStackT2Was2.setDescription('# of bytes of stack used by 2nd task of app, this time run') techsupportInt1 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 99, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: techsupportInt1.setStatus('mandatory') if mibBuilder.loadTexts: techsupportInt1.setDescription('a debugging integer for technical support use only. Do not use') techsupportInt2 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 99, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: techsupportInt2.setStatus('mandatory') if mibBuilder.loadTexts: techsupportInt2.setDescription('a debugging integer for technical support use only. Do not use') techsupportInt3 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 99, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: techsupportInt3.setStatus('mandatory') if mibBuilder.loadTexts: techsupportInt3.setDescription('a debugging integer for technical support use only. Do not use') techsupportInt4 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 99, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: techsupportInt4.setStatus('mandatory') if mibBuilder.loadTexts: techsupportInt4.setDescription('a debugging integer for technical support use only. Do not use') techsupportInt5 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 99, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: techsupportInt5.setStatus('mandatory') if mibBuilder.loadTexts: techsupportInt5.setDescription('a debugging integer for technical support use only. Do not use') datalinkDbasePfullTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,501)).setObjects(("DATALINK-MIB", "databaseAlarmIndex"), ("DATALINK-MIB", "databasePfull")) if mibBuilder.loadTexts: datalinkDbasePfullTrap.setDescription('The datalinkDbasePfullTrap is issued when the database reaches a pre-determined threshold level, which causes a trap.') datalinkFilePfullTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,502)).setObjects(("DATALINK-MIB", "fileAlarmFileIndex"), ("DATALINK-MIB", "fileAlarmThresholdIndex"), ("DATALINK-MIB", "filePercentNow")) if mibBuilder.loadTexts: datalinkFilePfullTrap.setDescription('The datalinkFilePfullTrap is issued when one of the data files reaches a pre-determined threshold level, which causes a trap.') datalinkDataAlarmTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,503)).setObjects(("DATALINK-MIB", "dataAlarmIndex"), ("DATALINK-MIB", "dataAlarmName"), ("DATALINK-MIB", "dataAlarmString"), ("DATALINK-MIB", "dataAlarmPort")) if mibBuilder.loadTexts: datalinkDataAlarmTrap.setDescription('The datalinkDataAlarmTrap is issued when one of the data alarms reaches a pre-determined threshold level, which causes a trap.') datalinkSensorAlarmTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,504)).setObjects(("DATALINK-MIB", "sensorAlarmIndex"), ("DATALINK-MIB", "sensorAlarmName"), ("DATALINK-MIB", "sensorAlarmState")) if mibBuilder.loadTexts: datalinkSensorAlarmTrap.setDescription('The datalinkSensorAlarmTrap is issued when one of the External Sensors is triggered for a pre-determined threshold amount of time, which causes a trap.') datalinkNoDataAlarmTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,505)).setObjects(("DATALINK-MIB", "nodataTablePortIndex"), ("DATALINK-MIB", "nodataTableScheduleIndex"), ("DATALINK-MIB", "nodataTableLevelIndex"), ("DATALINK-MIB", "nodataAlarmStatusCounter"), ("DATALINK-MIB", "nodataTableThreshold")) if mibBuilder.loadTexts: datalinkNoDataAlarmTrap.setDescription('The datalinkNoDataAlarmTrap is issued when one of the ports receives no input data for a pre-determined threshold amount of time, which causes a trap.') datalinkSchedTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,506)).setObjects(("DATALINK-MIB", "scheduleIndex")) if mibBuilder.loadTexts: datalinkSchedTrap.setDescription('The datalinkSchedTrap is issued when a scheduled event causes a trap.') datalinkImmediateTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,507)) if mibBuilder.loadTexts: datalinkImmediateTrap.setDescription('The datalinkImmediateTrap is issued when the dotrap command is used to issue a test trap to all snmp managers') datalinkPPPupTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,509)).setObjects(("DATALINK-MIB", "pppIDString"), ("DATALINK-MIB", "pppIPAddress")) if mibBuilder.loadTexts: datalinkPPPupTrap.setDescription('The datalinkPPPupTrap is issued when the PPP interface is brought up and the ppp connection has been established') mibBuilder.exportSymbols("DATALINK-MIB", cbbRetransmits=cbbRetransmits, rtsWaitXon=rtsWaitXon, sensorAlarmTable=sensorAlarmTable, actionHistory=actionHistory, scheduleActive=scheduleActive, alarmfilterEnabled=alarmfilterEnabled, rtsNoStore=rtsNoStore, pagerTableIndex=pagerTableIndex, modemTapSetup=modemTapSetup, actionTable=actionTable, ccodeStackMainWas=ccodeStackMainWas, modemExtSetup=modemExtSetup, ftpsetup=ftpsetup, rtsTable=rtsTable, dleMode=dleMode, netcard=netcard, releaseCompressed=releaseCompressed, nodataAlarmStatus=nodataAlarmStatus, modemTimeBetweenOutbound=modemTimeBetweenOutbound, calloutRepeatDelay=calloutRepeatDelay, productname=productname, calloutSendReason=calloutSendReason, rtsSocketState=rtsSocketState, ftpPushEnabled=ftpPushEnabled, pagerHangupDelay=pagerHangupDelay, systemversion=systemversion, ftpPushCount=ftpPushCount, portParity=portParity, calloutMessage=calloutMessage, dataAlarmString=dataAlarmString, fileRecordsAvailable=fileRecordsAvailable, dataAlarmName=dataAlarmName, databaseAlarmCalloutActions=databaseAlarmCalloutActions, calloutTableIndex=calloutTableIndex, techsupport=techsupport, fileTableIndex=fileTableIndex, databaseSize=databaseSize, actionCount=actionCount, rtsNeedPassword=rtsNeedPassword, scheduleAlarmTable=scheduleAlarmTable, actionTableIndex=actionTableIndex, calloutSendId=calloutSendId, modems=modems, dataAlarmAcked=dataAlarmAcked, modemAutoexecString=modemAutoexecString, datalinkPPPupTrap=datalinkPPPupTrap, ftpAutoDelete=ftpAutoDelete, nodataNumberHolidays=nodataNumberHolidays, historyTypeID=historyTypeID, filesetup=filesetup, sitebyport=sitebyport, pagerMaxAttempts=pagerMaxAttempts, historyReasonLevel=historyReasonLevel, techsupportInt3=techsupportInt3, autodeleteEnable=autodeleteEnable, binRecordBlocking=binRecordBlocking, charmask=charmask, autoDstAdjust=autoDstAdjust, databaseAlarmThreshold=databaseAlarmThreshold, factorysetup=factorysetup, bypassEndchar=bypassEndchar, modemUserSetup=modemUserSetup, datalinkFilePfullTrap=datalinkFilePfullTrap, ftpPasswords=ftpPasswords, commandPassword=commandPassword, pagerPhonenumber=pagerPhonenumber, nodataTableLevelIndex=nodataTableLevelIndex, ftpPush=ftpPush, nodataAlarmStatusCounter=nodataAlarmStatusCounter, sensorAlarmEntry=sensorAlarmEntry, datalinkSiteId=datalinkSiteId, memorysize=memorysize, scheduleAcked=scheduleAcked, snmpManagerTable=snmpManagerTable, nodataTableSerialActions=nodataTableSerialActions, portSetupEntry=portSetupEntry, ftpPushUser=ftpPushUser, inlineHskMode=inlineHskMode, ipNewDefaultRouter=ipNewDefaultRouter, fileAlarmBeeperActions=fileAlarmBeeperActions, nodataHolidayClear=nodataHolidayClear, modemExtSetupTime=modemExtSetupTime, fileName=fileName, nodataTablePortIndex=nodataTablePortIndex, snmpSendTestTrap=snmpSendTestTrap, pagerID=pagerID, dataAlarmPort=dataAlarmPort, nodataTableThreshold=nodataTableThreshold, duplex=duplex, nodataAlarmHolidays=nodataAlarmHolidays, pagerAttemptDelay=pagerAttemptDelay, sensorAlarmActive=sensorAlarmActive, databasemode=databasemode, portWord=portWord, tcpPasswords=tcpPasswords, nodataTableEntry=nodataTableEntry, modemsetupstring=modemsetupstring, rtsIdleTimeout=rtsIdleTimeout, filePercentNow=filePercentNow, rtsTableEntry=rtsTableEntry, sensorAlarmMode=sensorAlarmMode, scheduleCalloutActions=scheduleCalloutActions, datafilterEnabled=datafilterEnabled, maxRecordChars=maxRecordChars, dataAlarmTable=dataAlarmTable, ftpPushIPAddress=ftpPushIPAddress, actionAcked=actionAcked, nodataAlarms=nodataAlarms, modemcddelay=modemcddelay, ftpPushAlarms=ftpPushAlarms, sensorAlarmState=sensorAlarmState, fileAlarmFileIndex=fileAlarmFileIndex, inlineHsk4=inlineHsk4, historyClearLog=historyClearLog, scheduleIndex=scheduleIndex, unitIds=unitIds, snmpMgrIndex=snmpMgrIndex, historyType=historyType, dataAlarmBeeperActions=dataAlarmBeeperActions, operatingMode=operatingMode, realtimesocket=realtimesocket, actionsPagerTable=actionsPagerTable, calloutRepeat=calloutRepeat, snmpTrapsAutoRepeatTime=snmpTrapsAutoRepeatTime, fileAlarmSerialActions=fileAlarmSerialActions, actionsBuzzer=actionsBuzzer, datalinkThisProduct=datalinkThisProduct, fileRecords=fileRecords, nodataTableCalloutActions=nodataTableCalloutActions, fileType=fileType, pagerType=pagerType, pagerMessage=pagerMessage, killIPRestrictions=killIPRestrictions, dataAlarmClearTime=dataAlarmClearTime, sensorAlarmSerialActions=sensorAlarmSerialActions, ipCurrentAddress=ipCurrentAddress, rtsShowAnswer=rtsShowAnswer, schedulePagerActions=schedulePagerActions, snmpManagerName=snmpManagerName, entireDatabase=entireDatabase, modemSettings=modemSettings, fileAlarmThreshold=fileAlarmThreshold, sensorAlarmCalloutActions=sensorAlarmCalloutActions, scheduleAlarmEntry=scheduleAlarmEntry, ipNew=ipNew, fileTableEntry=fileTableEntry, passwordTableEntry=passwordTableEntry, modemreport=modemreport, portDateTimeStampMode=portDateTimeStampMode, sensorAlarmTrapActions=sensorAlarmTrapActions, alarmhistory=alarmhistory, passwordCommand=passwordCommand, historyReason=historyReason, dataAlarmIndex=dataAlarmIndex, serialTableIndex=serialTableIndex, ftpPushAcct=ftpPushAcct, actionType=actionType, fileAlarmEntry=fileAlarmEntry, ftpPushStatusMode=ftpPushStatusMode, commandPasswordTimeout=commandPasswordTimeout, dataRelease=dataRelease, databaseAlarmFileMaxSize=databaseAlarmFileMaxSize, ftpPushTiming=ftpPushTiming, modemtype=modemtype, portSetupTable=portSetupTable, time=time, ipCurrent=ipCurrent, pppIDString=pppIDString, techsupportInt2=techsupportInt2, fileAlarmPagerActions=fileAlarmPagerActions, currenttime=currenttime, siteindex=siteindex, inlineSource=inlineSource, rtsTableIndex=rtsTableIndex, modemAutoexecEnabled=modemAutoexecEnabled, dataAlarmEntry=dataAlarmEntry, historyTimeStamp=historyTimeStamp, iprestrictTableEntry=iprestrictTableEntry, actionQueue=actionQueue, serialnumber=serialnumber, rtsPortNeedPassword=rtsPortNeedPassword, actionsTrapsEntSpecCount=actionsTrapsEntSpecCount, scheduleTrapActions=scheduleTrapActions, ftpPushDir=ftpPushDir, ccodeRunning=ccodeRunning, fileAlarms=fileAlarms, snmpTableEntry=snmpTableEntry, dataAlarmActive=dataAlarmActive, portWrapMode=portWrapMode, productIds=productIds, snmpTrapsEnabled=snmpTrapsEnabled, asentria=asentria, actionAttempts=actionAttempts, sysadminTcpipTimeout=sysadminTcpipTimeout, dataAlarmSerialActions=dataAlarmSerialActions, passwordIndex=passwordIndex, fileAlarmThresholdIndex=fileAlarmThresholdIndex, sensorAlarmBeeperActions=sensorAlarmBeeperActions, otherControls=otherControls, nodataAlarmStatusIndex=nodataAlarmStatusIndex, datalink=datalink, historyTableIndex=historyTableIndex, portPtStripOutputLfs=portPtStripOutputLfs, dataAlarmCalloutActions=dataAlarmCalloutActions, dataAlarmClearMode=dataAlarmClearMode, serialTableMessage=serialTableMessage, portlowDTR=portlowDTR, calloutCommandWait=calloutCommandWait, appversion=appversion, actionRepeatTime=actionRepeatTime, databaseAlarmTable=databaseAlarmTable, response=response, rtsDenied=rtsDenied, commandNeedsPassword=commandNeedsPassword, modemInactivityTimer=modemInactivityTimer, nodataTableTrapActions=nodataTableTrapActions, ftppushEnable=ftppushEnable, iprestrictTableIndex=iprestrictTableIndex, actionsTraps=actionsTraps, actionsSerialTableEntry=actionsSerialTableEntry, datalinkNoDataAlarmTrap=datalinkNoDataAlarmTrap, modemParity=modemParity, opSettings=opSettings, actionsCalloutTable=actionsCalloutTable, databaseAlarmEntry=databaseAlarmEntry, portIndex=portIndex, nodataTableBeeperActions=nodataTableBeeperActions, actionReasonID=actionReasonID, portStoreFile=portStoreFile, passwords=passwords, databaseAlarmBeeperActions=databaseAlarmBeeperActions, ftpPushTimer=ftpPushTimer, calloutMaxConnecttime=calloutMaxConnecttime, calloutAttemptDelay=calloutAttemptDelay, fileRecordsDeleted=fileRecordsDeleted, databaseAlarmActive=databaseAlarmActive, waitMode=waitMode, actions=actions, snmpManagerIp=snmpManagerIp, snmpsetup=snmpsetup, actionTypeID=actionTypeID, passwordAccess=passwordAccess, datalinkImmediateTrap=datalinkImmediateTrap, addIPRestrictions=addIPRestrictions, sensorAlarmThreshold=sensorAlarmThreshold, databaseStatus=databaseStatus, nodataHolidayItem=nodataHolidayItem, dataAlarmPagerActions=dataAlarmPagerActions, actionNextAttempt=actionNextAttempt, inlineHsk2=inlineHsk2, nodataAlarmStatusAcked=nodataAlarmStatusAcked, ccode=ccode, ipNewStatic=ipNewStatic, datalinkDataAlarmTrap=datalinkDataAlarmTrap) mibBuilder.exportSymbols("DATALINK-MIB", ipNewSetup=ipNewSetup, databaseAlarmFileStore=databaseAlarmFileStore, pppsetup=pppsetup, fileTable=fileTable, tagMode=tagMode, databaseRecordsAvailable=databaseRecordsAvailable, ipCurrentStatic=ipCurrentStatic, portPTTime=portPTTime, recordCollectionTimeout=recordCollectionTimeout, sensorAlarmPagerActions=sensorAlarmPagerActions, datalinkSensorAlarmTrap=datalinkSensorAlarmTrap, nodataTableSchedule=nodataTableSchedule, activeDatabase=activeDatabase, pagerSendReason=pagerSendReason, databases=databases, rtsPortEmptyClose=rtsPortEmptyClose, ipsetup=ipsetup, nodataAlarmStatusEntry=nodataAlarmStatusEntry, sensorAlarmAcked=sensorAlarmAcked, rtsPortShowAnswer=rtsPortShowAnswer, nodataTableScheduleIndex=nodataTableScheduleIndex, datalinkDbasePfullTrap=datalinkDbasePfullTrap, scheduleSerialActions=scheduleSerialActions, iprestrictIpAddress=iprestrictIpAddress, numberPorts=numberPorts, ftpDataMode=ftpDataMode, ipNewSubnetMask=ipNewSubnetMask, sureEnabled=sureEnabled, fileAlarmCalloutActions=fileAlarmCalloutActions, rtsPortWaitXon=rtsPortWaitXon, calloutAttempts=calloutAttempts, fileAlarmActive=fileAlarmActive, ftppushIndex=ftppushIndex, actionTimeStamp=actionTimeStamp, modemAnswerString=modemAnswerString, scheduleTime=scheduleTime, siteID=siteID, inlineMode=inlineMode, numberports=numberports, historyReasonID=historyReasonID, databaseFiles=databaseFiles, pagerRepeatDelay=pagerRepeatDelay, ccodeLoaded=ccodeLoaded, actionReason=actionReason, actionsBuzzerState=actionsBuzzerState, passwordTable=passwordTable, alarms=alarms, releaseMode=releaseMode, techsupportInt4=techsupportInt4, pagerSendId=pagerSendId, rtsEmptyClose=rtsEmptyClose, nodataTable=nodataTable, charmaskEnabled=charmaskEnabled, nodataHolidayTableEntry=nodataHolidayTableEntry, suspendIPRestrictions=suspendIPRestrictions, lastCalloutPageReason=lastCalloutPageReason, actionsSerialTable=actionsSerialTable, databaseAlarmTrapActions=databaseAlarmTrapActions, portPTMode=portPTMode, ccodeStackMainNow=ccodeStackMainNow, portStopbits=portStopbits, controls=controls, databasePfull=databasePfull, nodataTableActive=nodataTableActive, databaseRecordsDeleted=databaseRecordsDeleted, ipNewAddress=ipNewAddress, historyCount=historyCount, historyTableEntry=historyTableEntry, serialPorts=serialPorts, fileAlarmTrapActions=fileAlarmTrapActions, nodataHolidayIndex=nodataHolidayIndex, datalinkSchedTrap=datalinkSchedTrap, nodataTablePagerActions=nodataTablePagerActions, techsupportInt1=techsupportInt1, nodataHolidayTable=nodataHolidayTable, rtsPortIdleTimeout=rtsPortIdleTimeout, cbbTimeout=cbbTimeout, actionsTrapsEntSpecific=actionsTrapsEntSpecific, nodataHolidayDelete=nodataHolidayDelete, pagerRepeat=pagerRepeat, ccodeStackT2Was2=ccodeStackT2Was2, ftppushTableEntry=ftppushTableEntry, ipCurrentSubnetMask=ipCurrentSubnetMask, crcMode=crcMode, pagerAttempts=pagerAttempts, routerAutoPing=routerAutoPing, historyEntryType=historyEntryType, fileSize=fileSize, actionsCalloutTableEntry=actionsCalloutTableEntry, inlineHsk6=inlineHsk6, portPtStripInputLfs=portPtStripInputLfs, ftpPushPass=ftpPushPass, dataAlarmThreshold=dataAlarmThreshold, databaseAlarmSerialActions=databaseAlarmSerialActions, databaseAlarmIndex=databaseAlarmIndex, modemportspeed=modemportspeed, hardware=hardware, iprestrictions=iprestrictions, actionTableEntry=actionTableEntry, auxportMode=auxportMode, dataAlarmTrapActions=dataAlarmTrapActions, calloutPhonenumber=calloutPhonenumber, actionReasonLevel=actionReasonLevel, idByPortTable=idByPortTable, dataAlarmCounter=dataAlarmCounter, portDataStore=portDataStore, portHskMode=portHskMode, databaseAlarmPagerActions=databaseAlarmPagerActions, modemPasswords=modemPasswords, techsupportInt5=techsupportInt5, actionsPagerTableEntry=actionsPagerTableEntry, linefeeds=linefeeds, portBaud=portBaud, ftpPushServerName=ftpPushServerName, ipCurrentDefaultRouter=ipCurrentDefaultRouter, iprestrictTable=iprestrictTable, dateofmanufacture=dateofmanufacture, calloutMaxAttempts=calloutMaxAttempts, commandTcpipTimeout=commandTcpipTimeout, pppIdentification=pppIdentification, portBinaryMode=portBinaryMode, promptPasswords=promptPasswords, ftppushTable=ftppushTable, historyTable=historyTable, sensorAlarmIndex=sensorAlarmIndex, pagerDialDelay=pagerDialDelay, sensorAlarmName=sensorAlarmName, sensorAlarmCounter=sensorAlarmCounter, pppIPAddress=pppIPAddress, networkenabled=networkenabled, ccodeStackT2Was=ccodeStackT2Was, productConfig=productConfig, nodataHolidayAdd=nodataHolidayAdd, dataAlarmAutoClear=dataAlarmAutoClear, scheduleBeeperActions=scheduleBeeperActions)
104.191352
8,402
0.772807
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") private, ModuleIdentity, ObjectIdentity, internet, mgmt, TimeTicks, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, enterprises, NotificationType, ObjectName, Bits, Integer32, IpAddress, Gauge32, iso, NotificationType, Counter32, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "private", "ModuleIdentity", "ObjectIdentity", "internet", "mgmt", "TimeTicks", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "enterprises", "NotificationType", "ObjectName", "Bits", "Integer32", "IpAddress", "Gauge32", "iso", "NotificationType", "Counter32", "Counter64") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") asentria = MibIdentifier((1, 3, 6, 1, 4, 1, 3052)) datalink = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1)) productIds = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 1)) productConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 2)) unitIds = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 3)) serialPorts = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 4)) time = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 5)) snmpsetup = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 6)) passwords = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 7)) ftpsetup = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 8)) databases = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 9)) alarms = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 10)) actions = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 11)) controls = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12)) alarmhistory = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 13)) realtimesocket = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 14)) iprestrictions = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 15)) ipsetup = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 16)) pppsetup = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 17)) ccode = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 18)) techsupport = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 99)) hardware = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 2, 4)) factorysetup = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5)) commandPassword = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 7, 5)) entireDatabase = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1)) databaseStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 1)) databaseFiles = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2)) filesetup = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 1)) nodataAlarms = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3)) nodataAlarmHolidays = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3)) actionsBuzzer = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 11, 1)) actionsTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 11, 5)) opSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1)) auxportMode = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6)) inlineHskMode = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 4)) modemSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2)) dataRelease = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12, 3)) otherControls = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4)) ftpPush = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3)) actionQueue = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1)) actionHistory = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2)) ipCurrent = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 16, 1)) ipNew = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 16, 2)) pppIdentification = MibIdentifier((1, 3, 6, 1, 4, 1, 3052, 1, 17, 1)) datalinkThisProduct = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: datalinkThisProduct.setStatus('mandatory') if mibBuilder.loadTexts: datalinkThisProduct.setDescription('This is a factory-configured string for the product name') productname = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: productname.setStatus('mandatory') if mibBuilder.loadTexts: productname.setDescription('A second string which may also contain name/version info') systemversion = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: systemversion.setStatus('mandatory') if mibBuilder.loadTexts: systemversion.setDescription('system rom version number') appversion = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: appversion.setStatus('mandatory') if mibBuilder.loadTexts: appversion.setDescription('application version') numberports = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 4, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: numberports.setStatus('mandatory') if mibBuilder.loadTexts: numberports.setDescription('number of RS232 ports found') netcard = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 4, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: netcard.setStatus('mandatory') if mibBuilder.loadTexts: netcard.setDescription('0 if no net card, 1 if net card found') modems = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 4, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: modems.setStatus('mandatory') if mibBuilder.loadTexts: modems.setDescription('0 if no modem, 1 if modem was found') networkenabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 4, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: networkenabled.setStatus('mandatory') if mibBuilder.loadTexts: networkenabled.setDescription('0 if not enabled, 1 if enabled') memorysize = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 4, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: memorysize.setStatus('mandatory') if mibBuilder.loadTexts: memorysize.setDescription('memory size in K') modemreport = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 1), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemreport.setStatus('mandatory') if mibBuilder.loadTexts: modemreport.setDescription('5-char string, speed to report for modem speed') modemportspeed = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemportspeed.setStatus('mandatory') if mibBuilder.loadTexts: modemportspeed.setDescription('modem port baud rate 38400, 19200, etc. ') modemsetupstring = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemsetupstring.setStatus('mandatory') if mibBuilder.loadTexts: modemsetupstring.setDescription('modem setup string, e.g., ATe0v0s0=1') modemcddelay = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemcddelay.setStatus('mandatory') if mibBuilder.loadTexts: modemcddelay.setDescription('seconds after CD before sending answer string') modemtype = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemtype.setStatus('mandatory') if mibBuilder.loadTexts: modemtype.setDescription('number factory-assigned to this particular modem, manufacturer, etc.') serialnumber = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 6), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: serialnumber.setStatus('mandatory') if mibBuilder.loadTexts: serialnumber.setDescription('up to 10 chars for factory-assigned serial number') dateofmanufacture = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 5, 7), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: dateofmanufacture.setStatus('mandatory') if mibBuilder.loadTexts: dateofmanufacture.setDescription('up to 8 chars for factory-assigned date of manufacture') databasemode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 2, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databasemode.setStatus('mandatory') if mibBuilder.loadTexts: databasemode.setDescription('database compatibility mode, 1 -normal, 2 commandset2, etc.') datalinkSiteId = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 3, 1), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: datalinkSiteId.setStatus('mandatory') if mibBuilder.loadTexts: datalinkSiteId.setDescription('Site ID string') idByPortTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 3, 2), ) if mibBuilder.loadTexts: idByPortTable.setStatus('mandatory') if mibBuilder.loadTexts: idByPortTable.setDescription('an id for type of data by port') sitebyport = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 3, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "siteindex")) if mibBuilder.loadTexts: sitebyport.setStatus('mandatory') if mibBuilder.loadTexts: sitebyport.setDescription('entry for table') siteindex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 3, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: siteindex.setStatus('mandatory') if mibBuilder.loadTexts: siteindex.setDescription('index for which port') siteID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 3, 2, 1, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: siteID.setStatus('mandatory') if mibBuilder.loadTexts: siteID.setDescription('site id or type of data by port') numberPorts = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 4, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: numberPorts.setStatus('mandatory') if mibBuilder.loadTexts: numberPorts.setDescription('number of RS232 ports found. ') portSetupTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2), ) if mibBuilder.loadTexts: portSetupTable.setStatus('mandatory') if mibBuilder.loadTexts: portSetupTable.setDescription('port setup table, serial params, collect data, etc.') portSetupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "portIndex")) if mibBuilder.loadTexts: portSetupEntry.setStatus('mandatory') if mibBuilder.loadTexts: portSetupEntry.setDescription('port setup table, serial params, collect data, etc.') portIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: portIndex.setStatus('mandatory') if mibBuilder.loadTexts: portIndex.setDescription('index for table') portBaud = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portBaud.setStatus('mandatory') if mibBuilder.loadTexts: portBaud.setDescription('baud rate, 19200, 9600, etc.') portWord = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portWord.setStatus('mandatory') if mibBuilder.loadTexts: portWord.setDescription('word length, must be 7 or 8') portParity = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portParity.setStatus('mandatory') if mibBuilder.loadTexts: portParity.setDescription('a single-char string with values of N E or O') portStopbits = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portStopbits.setStatus('mandatory') if mibBuilder.loadTexts: portStopbits.setDescription('number of stop bits, must be 1') portDataStore = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portDataStore.setStatus('mandatory') if mibBuilder.loadTexts: portDataStore.setDescription('0 data is not stored, 1 data is stored from this port') portBinaryMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portBinaryMode.setStatus('mandatory') if mibBuilder.loadTexts: portBinaryMode.setDescription('0 data is ASCII, 1 data is binary') portWrapMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portWrapMode.setStatus('mandatory') if mibBuilder.loadTexts: portWrapMode.setDescription('0 oldest data not overwritten, 1 older data is overwritten') portHskMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portHskMode.setStatus('mandatory') if mibBuilder.loadTexts: portHskMode.setDescription('HSK mode to use when buffer close to full, 0 none, 1 xon, 2 DTR, 3 DTR and Xon') portDateTimeStampMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portDateTimeStampMode.setStatus('mandatory') if mibBuilder.loadTexts: portDateTimeStampMode.setDescription('Date/time stamp mode to use,bit mapped bit 0 - do date stamp bit 1 - include year bit 2 - include year 19xx or 20xx bit 3 - include day of week bit 4 - space after date bit 5 - include time bit 6 - include seconds bit 7 - space after time') portPTMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 11), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portPTMode.setStatus('mandatory') if mibBuilder.loadTexts: portPTMode.setDescription('pass-through access mode. 0=none, 1=by modem, 2=by network any write kills the passthrough connection. any write requires private community name') portPTTime = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: portPTTime.setStatus('mandatory') if mibBuilder.loadTexts: portPTTime.setDescription('pass-through access mode time of this connection, in seconds') portStoreFile = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 13), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portStoreFile.setStatus('mandatory') if mibBuilder.loadTexts: portStoreFile.setDescription('selects which data file data from this port is stored into') portPtStripOutputLfs = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 14), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portPtStripOutputLfs.setStatus('mandatory') if mibBuilder.loadTexts: portPtStripOutputLfs.setDescription('0/1 no/yes in pass-through, strip LFs going to device on this port') portPtStripInputLfs = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 15), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portPtStripInputLfs.setStatus('mandatory') if mibBuilder.loadTexts: portPtStripInputLfs.setDescription('0/1 no/yes in pass-through, strip LFs coming from device on this port') portlowDTR = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 4, 2, 1, 16), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: portlowDTR.setStatus('mandatory') if mibBuilder.loadTexts: portlowDTR.setDescription('0/1 no/yes set DTR low and only raise it on SysAdmin & bypass connections') currenttime = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 5, 1), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: currenttime.setStatus('mandatory') if mibBuilder.loadTexts: currenttime.setDescription('Text string for date and time: SUN 01/02/98 12:34:27') autoDstAdjust = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 5, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: autoDstAdjust.setStatus('mandatory') if mibBuilder.loadTexts: autoDstAdjust.setDescription('0 no adjust, 1 adjust') snmpTrapsEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 6, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpTrapsEnabled.setStatus('mandatory') if mibBuilder.loadTexts: snmpTrapsEnabled.setDescription('0 do not send any traps, 1 do send traps') snmpManagerTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 6, 2), ) if mibBuilder.loadTexts: snmpManagerTable.setStatus('mandatory') if mibBuilder.loadTexts: snmpManagerTable.setDescription('management station names and addresses') snmpTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 6, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "snmpMgrIndex")) if mibBuilder.loadTexts: snmpTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: snmpTableEntry.setDescription('entry for snmp table') snmpMgrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 6, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpMgrIndex.setStatus('mandatory') if mibBuilder.loadTexts: snmpMgrIndex.setDescription('index for table') snmpManagerIp = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 6, 2, 1, 2), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpManagerIp.setStatus('mandatory') if mibBuilder.loadTexts: snmpManagerIp.setDescription('the ip address of a manager') snmpManagerName = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 6, 2, 1, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpManagerName.setStatus('mandatory') if mibBuilder.loadTexts: snmpManagerName.setDescription('the name of a manager, up to 80 chars') snmpTrapsAutoRepeatTime = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 6, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpTrapsAutoRepeatTime.setStatus('mandatory') if mibBuilder.loadTexts: snmpTrapsAutoRepeatTime.setDescription('0 do not repeat, else number of minutes to repeat') snmpSendTestTrap = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 6, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpSendTestTrap.setStatus('mandatory') if mibBuilder.loadTexts: snmpSendTestTrap.setDescription('0 on read, any Set sends test trap to all managers in table') modemPasswords = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemPasswords.setStatus('mandatory') if mibBuilder.loadTexts: modemPasswords.setDescription('0 no modem passwords required, 1 modem passwords are required write requires private community name') tcpPasswords = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: tcpPasswords.setStatus('mandatory') if mibBuilder.loadTexts: tcpPasswords.setDescription('0 no telnet/tcp passwords required, 1 passwords are required write requires private community name') ftpPasswords = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPasswords.setStatus('mandatory') if mibBuilder.loadTexts: ftpPasswords.setDescription('0 no ftp passwords required, 1 passwords are required write requires private community name') promptPasswords = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: promptPasswords.setStatus('mandatory') if mibBuilder.loadTexts: promptPasswords.setDescription('0 no Password: prompt, 1 -> show Password: prompt') commandNeedsPassword = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 5, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: commandNeedsPassword.setStatus('mandatory') if mibBuilder.loadTexts: commandNeedsPassword.setDescription('0 not needed, 1 is needed write requires private community name') commandPasswordTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 5, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: commandPasswordTimeout.setStatus('mandatory') if mibBuilder.loadTexts: commandPasswordTimeout.setDescription('1-99, number of minutes of no activity which auto logs user out') passwordTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 7, 6), ) if mibBuilder.loadTexts: passwordTable.setStatus('mandatory') if mibBuilder.loadTexts: passwordTable.setDescription('Table of password entries, r-w only with private comm. name') passwordTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 7, 6, 1), ).setIndexNames((0, "DATALINK-MIB", "passwordIndex")) if mibBuilder.loadTexts: passwordTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: passwordTableEntry.setDescription('entry to password table') passwordIndex = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 6, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: passwordIndex.setStatus('mandatory') if mibBuilder.loadTexts: passwordIndex.setDescription('index to password table') passwordCommand = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 6, 1, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: passwordCommand.setStatus('mandatory') if mibBuilder.loadTexts: passwordCommand.setDescription('password for command access') passwordAccess = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 7, 6, 1, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: passwordAccess.setStatus('mandatory') if mibBuilder.loadTexts: passwordAccess.setDescription('password for pass-through access') ftpAutoDelete = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpAutoDelete.setStatus('mandatory') if mibBuilder.loadTexts: ftpAutoDelete.setDescription('0 files not autodeleted, 1 deleted on reading') ftpDataMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpDataMode.setStatus('mandatory') if mibBuilder.loadTexts: ftpDataMode.setDescription('0 normal, 1 compression mode 1, etc.') ftpPushEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushEnabled.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushEnabled.setDescription('0-no, 1-yes, enables ftp data push') ftpPushTiming = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushTiming.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushTiming.setDescription('how often data is pushed, 2-255 minutes') ftpPushTimer = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushTimer.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushTimer.setDescription('timer which counts to ftpPushTiming') ftpPushIPAddress = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushIPAddress.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushIPAddress.setDescription('ip address of ftp server to which we push the data') ftpPushUser = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 5), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushUser.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushUser.setDescription('text string to send for the user id') ftpPushPass = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 6), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushPass.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushPass.setDescription('text string to send for the ftp server password') ftpPushAcct = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 7), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushAcct.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushAcct.setDescription('text string to send for the account, if used') ftpPushDir = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 8), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushDir.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushDir.setDescription('text string to send for the directory we CWD to') ftppushTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 9), ) if mibBuilder.loadTexts: ftppushTable.setStatus('mandatory') if mibBuilder.loadTexts: ftppushTable.setDescription('Table of ftp push enables') ftppushTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 9, 1), ).setIndexNames((0, "DATALINK-MIB", "ftppushIndex")) if mibBuilder.loadTexts: ftppushTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: ftppushTableEntry.setDescription('entry to ftp push table') ftppushIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 9, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ftppushIndex.setStatus('mandatory') if mibBuilder.loadTexts: ftppushIndex.setDescription('index to ftp push table') ftppushEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 9, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftppushEnable.setStatus('mandatory') if mibBuilder.loadTexts: ftppushEnable.setDescription('enable for ftp push, indexed by file') ftpPushAlarms = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushAlarms.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushAlarms.setDescription('0-no, 1-yes, do we push the ALARMS file') ftpPushCount = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 11), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ftpPushCount.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushCount.setDescription('number of ftp data pushes tried since reboot') ftpPushStatusMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 12), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushStatusMode.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushStatusMode.setDescription('0-none, 1-append, 2-replace, status file modes') ftpPushServerName = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 8, 3, 13), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ftpPushServerName.setStatus('mandatory') if mibBuilder.loadTexts: ftpPushServerName.setDescription('Name of the FTP Push Targer Server') databasePfull = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: databasePfull.setStatus('mandatory') if mibBuilder.loadTexts: databasePfull.setDescription('percentage full of all database') databaseSize = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: databaseSize.setStatus('mandatory') if mibBuilder.loadTexts: databaseSize.setDescription('Size of Data Storage Area, in bytes') databaseRecordsAvailable = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: databaseRecordsAvailable.setStatus('mandatory') if mibBuilder.loadTexts: databaseRecordsAvailable.setDescription('Records which are available to read, total in all files') databaseRecordsDeleted = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: databaseRecordsDeleted.setStatus('mandatory') if mibBuilder.loadTexts: databaseRecordsDeleted.setDescription('Records which are deleted, total in all files') databaseAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2), ) if mibBuilder.loadTexts: databaseAlarmTable.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmTable.setDescription('table for levels 1 2 3 of all database alarms and actions') databaseAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "databaseAlarmIndex")) if mibBuilder.loadTexts: databaseAlarmEntry.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmEntry.setDescription('entry for database alarm config and actions table') databaseAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: databaseAlarmIndex.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmIndex.setDescription('Index for table, 1 2 or 3') databaseAlarmActive = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmActive.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmActive.setDescription('0/1, 1 = active') databaseAlarmThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmThreshold.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmThreshold.setDescription('1-99, percentage full threshold level') databaseAlarmBeeperActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmBeeperActions.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmBeeperActions.setDescription('0 1 2, -> none, 1/10 or 10/10') databaseAlarmSerialActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmSerialActions.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmSerialActions.setDescription('bits 0-7 show which messages 1-8 are sent') databaseAlarmPagerActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmPagerActions.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmPagerActions.setDescription('bits 0-7 show which pagers 1-8 are used') databaseAlarmCalloutActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmCalloutActions.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmCalloutActions.setDescription('bits 0-7 show which modem callouts 1-8 are used') databaseAlarmTrapActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 2, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmTrapActions.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmTrapActions.setDescription('0/1 for traps are sent or not') databaseAlarmFileStore = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmFileStore.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmFileStore.setDescription('0-no, 1-yes, store alarms in the ALARMS file') databaseAlarmFileMaxSize = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: databaseAlarmFileMaxSize.setStatus('mandatory') if mibBuilder.loadTexts: databaseAlarmFileMaxSize.setDescription('in K, max size for alarms file 4-32k') charmaskEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 1, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: charmaskEnabled.setStatus('mandatory') if mibBuilder.loadTexts: charmaskEnabled.setDescription('0/1 char masking enabled') charmask = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 1, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: charmask.setStatus('mandatory') if mibBuilder.loadTexts: charmask.setDescription('32-byte hex ascii for character masking') maxRecordChars = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: maxRecordChars.setStatus('mandatory') if mibBuilder.loadTexts: maxRecordChars.setDescription('max characters in an ASCII record') binRecordBlocking = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: binRecordBlocking.setStatus('mandatory') if mibBuilder.loadTexts: binRecordBlocking.setDescription('# chars max to block binary records into') recordCollectionTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: recordCollectionTimeout.setStatus('mandatory') if mibBuilder.loadTexts: recordCollectionTimeout.setDescription('# seconds to allow before terminating a record automatically') fileTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2), ) if mibBuilder.loadTexts: fileTable.setStatus('mandatory') if mibBuilder.loadTexts: fileTable.setDescription('table of directory entries') fileTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "fileTableIndex")) if mibBuilder.loadTexts: fileTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: fileTableEntry.setDescription('entry for table') fileTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: fileTableIndex.setDescription('index for the table') fileName = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileName.setStatus('mandatory') if mibBuilder.loadTexts: fileName.setDescription('name of the file') fileType = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileType.setStatus('mandatory') if mibBuilder.loadTexts: fileType.setDescription('type of data, up to 24 chars') fileSize = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileSize.setStatus('mandatory') if mibBuilder.loadTexts: fileSize.setDescription('file size in bytes') fileRecords = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileRecords.setStatus('mandatory') if mibBuilder.loadTexts: fileRecords.setDescription('file size in records') fileRecordsAvailable = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileRecordsAvailable.setStatus('mandatory') if mibBuilder.loadTexts: fileRecordsAvailable.setDescription('# recs available') fileRecordsDeleted = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileRecordsDeleted.setStatus('mandatory') if mibBuilder.loadTexts: fileRecordsDeleted.setDescription('# recs deleted') filePercentNow = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 2, 1, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filePercentNow.setStatus('mandatory') if mibBuilder.loadTexts: filePercentNow.setDescription('% of all of memory this file is, right now') fileAlarms = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3), ) if mibBuilder.loadTexts: fileAlarms.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarms.setDescription('file alarms, indexed by file and threshold') fileAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1), ).setIndexNames((0, "DATALINK-MIB", "fileAlarmFileIndex"), (0, "DATALINK-MIB", "fileAlarmThreshold")) if mibBuilder.loadTexts: fileAlarmEntry.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmEntry.setDescription('entry to the table') fileAlarmFileIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileAlarmFileIndex.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmFileIndex.setDescription('index for filenumber') fileAlarmThresholdIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fileAlarmThresholdIndex.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmThresholdIndex.setDescription('index for filenumber threshold') fileAlarmActive = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmActive.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmActive.setDescription('0/1 this file alarm active') fileAlarmThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmThreshold.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmThreshold.setDescription('1-99, threshold level') fileAlarmBeeperActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmBeeperActions.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmBeeperActions.setDescription('0 1 2, none, 1/10 or 10/10') fileAlarmSerialActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmSerialActions.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmSerialActions.setDescription('bits 0-7 show which messages 1-8 are sent') fileAlarmPagerActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmPagerActions.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmPagerActions.setDescription('bits 0-7 show which pagers 1-8 are used') fileAlarmCalloutActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmCalloutActions.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmCalloutActions.setDescription('bits 0-7 show which modem callouts 1-8 are used') fileAlarmTrapActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 9, 2, 3, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: fileAlarmTrapActions.setStatus('mandatory') if mibBuilder.loadTexts: fileAlarmTrapActions.setDescription('0/1 for traps are sent or not') dataAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1), ) if mibBuilder.loadTexts: dataAlarmTable.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmTable.setDescription('table of read-only items for data alarm setup') dataAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1), ).setIndexNames((0, "DATALINK-MIB", "dataAlarmIndex")) if mibBuilder.loadTexts: dataAlarmEntry.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmEntry.setDescription('Data alarm table entry') dataAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmIndex.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmIndex.setDescription('index for data alarms') dataAlarmActive = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmActive.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmActive.setDescription('0/1 active') dataAlarmName = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmName.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmName.setDescription('name of alarm') dataAlarmCounter = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmCounter.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmCounter.setDescription('counter for this alarm') dataAlarmThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmThreshold.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmThreshold.setDescription('threshold for this alarm') dataAlarmClearMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmClearMode.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmClearMode.setDescription('code for clearing mode') dataAlarmClearTime = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 7), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmClearTime.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmClearTime.setDescription('time of day, e.g., 01:20') dataAlarmAcked = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: dataAlarmAcked.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmAcked.setDescription('0 on read, any set to ack this alarm') dataAlarmBeeperActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmBeeperActions.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmBeeperActions.setDescription('0 1 2, none, 1/10 or 10/10') dataAlarmSerialActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 10), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmSerialActions.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmSerialActions.setDescription('bits 0-7 show which messages 1-8 are sent') dataAlarmPagerActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 11), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmPagerActions.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmPagerActions.setDescription('bits 0-7 show which pagers 1-8 are used') dataAlarmCalloutActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmCalloutActions.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmCalloutActions.setDescription('bits 0-7 show which modem callouts 1-8 are used') dataAlarmTrapActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmTrapActions.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmTrapActions.setDescription('0/1 for traps are sent or not') dataAlarmString = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 14), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmString.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmString.setDescription('last data alarm string for this alarm') dataAlarmPort = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 15), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmPort.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmPort.setDescription('port number for last data alarm string for this alarm') dataAlarmAutoClear = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 1, 1, 16), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dataAlarmAutoClear.setStatus('mandatory') if mibBuilder.loadTexts: dataAlarmAutoClear.setDescription('0/1 disabled/enabled to auto clear counter when it reached threshold') sensorAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2), ) if mibBuilder.loadTexts: sensorAlarmTable.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmTable.setDescription('table of read-only items for sensor alarm setup') sensorAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "sensorAlarmIndex")) if mibBuilder.loadTexts: sensorAlarmEntry.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmEntry.setDescription('sensor alarm table entry') sensorAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sensorAlarmIndex.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmIndex.setDescription('index for sensor alarms') sensorAlarmActive = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmActive.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmActive.setDescription('0/1 active') sensorAlarmName = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmName.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmName.setDescription('name of alarm') sensorAlarmMode = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmMode.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmMode.setDescription('0 - open active, 1 - closed active') sensorAlarmCounter = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmCounter.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmCounter.setDescription('counter for this alarm') sensorAlarmThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmThreshold.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmThreshold.setDescription('threshold for this alarm') sensorAlarmAcked = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmAcked.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmAcked.setDescription('0 on read, any set to ack this alarm') sensorAlarmBeeperActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmBeeperActions.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmBeeperActions.setDescription('0 1 2, none, 1/10 or 10/10') sensorAlarmSerialActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmSerialActions.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmSerialActions.setDescription('bits 0-7 show which messages 1-8 are sent') sensorAlarmPagerActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmPagerActions.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmPagerActions.setDescription('bits 0-7 show which pagers 1-8 are used') sensorAlarmCalloutActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 11), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmCalloutActions.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmCalloutActions.setDescription('bits 0-7 show which modem callouts 1-8 are used') sensorAlarmTrapActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 12), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sensorAlarmTrapActions.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmTrapActions.setDescription('0/1 for traps are sent or not') sensorAlarmState = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 2, 1, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sensorAlarmState.setStatus('mandatory') if mibBuilder.loadTexts: sensorAlarmState.setDescription('0-> open 1-> closed for current state') nodataAlarmStatus = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 1), ) if mibBuilder.loadTexts: nodataAlarmStatus.setStatus('mandatory') if mibBuilder.loadTexts: nodataAlarmStatus.setDescription('no data status table') nodataAlarmStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 1, 1), ).setIndexNames((0, "DATALINK-MIB", "nodataAlarmStatusIndex")) if mibBuilder.loadTexts: nodataAlarmStatusEntry.setStatus('mandatory') if mibBuilder.loadTexts: nodataAlarmStatusEntry.setDescription('status table entry') nodataAlarmStatusIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nodataAlarmStatusIndex.setStatus('mandatory') if mibBuilder.loadTexts: nodataAlarmStatusIndex.setDescription('index for table') nodataAlarmStatusCounter = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 1, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataAlarmStatusCounter.setStatus('mandatory') if mibBuilder.loadTexts: nodataAlarmStatusCounter.setDescription('the nodata counter') nodataAlarmStatusAcked = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 1, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataAlarmStatusAcked.setStatus('mandatory') if mibBuilder.loadTexts: nodataAlarmStatusAcked.setDescription('reads as 0, any write acks this alarm') nodataTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2), ) if mibBuilder.loadTexts: nodataTable.setStatus('mandatory') if mibBuilder.loadTexts: nodataTable.setDescription('nodata table') nodataTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "nodataTablePortIndex"), (0, "DATALINK-MIB", "nodataTableScheduleIndex"), (0, "DATALINK-MIB", "nodataTableLevelIndex")) if mibBuilder.loadTexts: nodataTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableEntry.setDescription('nodata defn. table entry') nodataTablePortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 1), Integer32()) if mibBuilder.loadTexts: nodataTablePortIndex.setStatus('mandatory') if mibBuilder.loadTexts: nodataTablePortIndex.setDescription('index by port') nodataTableScheduleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 2), Integer32()) if mibBuilder.loadTexts: nodataTableScheduleIndex.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableScheduleIndex.setDescription('index by schedule') nodataTableLevelIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 3), Integer32()) if mibBuilder.loadTexts: nodataTableLevelIndex.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableLevelIndex.setDescription('index by level') nodataTableActive = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableActive.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableActive.setDescription('0/1 , enabled or not') nodataTableSchedule = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 5), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableSchedule.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableSchedule.setDescription('schedule, format is hh:mm-hh:mm') nodataTableThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableThreshold.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableThreshold.setDescription('#minutes for no data for alarm') nodataTableBeeperActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableBeeperActions.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableBeeperActions.setDescription('0 1 2, none, 1/10 or 10/10') nodataTableSerialActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableSerialActions.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableSerialActions.setDescription('bits 0-7 show which messages 1-8 are sent') nodataTablePagerActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTablePagerActions.setStatus('mandatory') if mibBuilder.loadTexts: nodataTablePagerActions.setDescription('bits 0-7 show which pagers 1-8 are used') nodataTableCalloutActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableCalloutActions.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableCalloutActions.setDescription('bits 0-7 show which modem callouts 1-8 are used') nodataTableTrapActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 2, 1, 11), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataTableTrapActions.setStatus('mandatory') if mibBuilder.loadTexts: nodataTableTrapActions.setDescription('0/1 for traps are sent or not') nodataNumberHolidays = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nodataNumberHolidays.setStatus('mandatory') if mibBuilder.loadTexts: nodataNumberHolidays.setDescription('number of nodata holidays defined') nodataHolidayTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 2), ) if mibBuilder.loadTexts: nodataHolidayTable.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayTable.setDescription('holiday table') nodataHolidayTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "nodataHolidayIndex")) if mibBuilder.loadTexts: nodataHolidayTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayTableEntry.setDescription('holiday table entry') nodataHolidayIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nodataHolidayIndex.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayIndex.setDescription('index for holiday list') nodataHolidayItem = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 2, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: nodataHolidayItem.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayItem.setDescription('holiday list item, format is mm/dd') nodataHolidayAdd = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataHolidayAdd.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayAdd.setDescription('null on read, set with holiday to add MM/DD') nodataHolidayDelete = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataHolidayDelete.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayDelete.setDescription('null on read, set with holiday to delete MM/DD') nodataHolidayClear = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 10, 3, 3, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nodataHolidayClear.setStatus('mandatory') if mibBuilder.loadTexts: nodataHolidayClear.setDescription('read returns 0, write requires private community name. used to clear the holiday list') scheduleAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4), ) if mibBuilder.loadTexts: scheduleAlarmTable.setStatus('mandatory') if mibBuilder.loadTexts: scheduleAlarmTable.setDescription('scheduled alarm table') scheduleAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1), ).setIndexNames((0, "DATALINK-MIB", "scheduleIndex")) if mibBuilder.loadTexts: scheduleAlarmEntry.setStatus('mandatory') if mibBuilder.loadTexts: scheduleAlarmEntry.setDescription('schedule table entry') scheduleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: scheduleIndex.setStatus('mandatory') if mibBuilder.loadTexts: scheduleIndex.setDescription('day index') scheduleActive = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleActive.setStatus('mandatory') if mibBuilder.loadTexts: scheduleActive.setDescription('if active or not') scheduleTime = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleTime.setStatus('mandatory') if mibBuilder.loadTexts: scheduleTime.setDescription('time of day format is: hh:mm') scheduleAcked = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleAcked.setStatus('mandatory') if mibBuilder.loadTexts: scheduleAcked.setDescription('reads 0, any set acks alarm') scheduleBeeperActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleBeeperActions.setStatus('mandatory') if mibBuilder.loadTexts: scheduleBeeperActions.setDescription('0 1 2, none, 1/10 or 10/10') scheduleSerialActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleSerialActions.setStatus('mandatory') if mibBuilder.loadTexts: scheduleSerialActions.setDescription('bits 0-7 show which messages 1-8 are sent') schedulePagerActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: schedulePagerActions.setStatus('mandatory') if mibBuilder.loadTexts: schedulePagerActions.setDescription('bits 0-7 show which pagers 1-8 are used') scheduleCalloutActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleCalloutActions.setStatus('mandatory') if mibBuilder.loadTexts: scheduleCalloutActions.setDescription('bits 0-7 show which modem callouts 1-8 are used') scheduleTrapActions = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 10, 4, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: scheduleTrapActions.setStatus('mandatory') if mibBuilder.loadTexts: scheduleTrapActions.setDescription('0/1 for traps are sent or not') actionsBuzzerState = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 11, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionsBuzzerState.setStatus('mandatory') if mibBuilder.loadTexts: actionsBuzzerState.setDescription('current buzzer state 0.1.2') actionsSerialTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 11, 2), ) if mibBuilder.loadTexts: actionsSerialTable.setStatus('mandatory') if mibBuilder.loadTexts: actionsSerialTable.setDescription('serial message table') actionsSerialTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 11, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "serialTableIndex")) if mibBuilder.loadTexts: actionsSerialTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: actionsSerialTableEntry.setDescription('serial table entry') serialTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: serialTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: serialTableIndex.setDescription('serial table index') serialTableMessage = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 2, 1, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: serialTableMessage.setStatus('mandatory') if mibBuilder.loadTexts: serialTableMessage.setDescription('serial table string') actionsPagerTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3), ) if mibBuilder.loadTexts: actionsPagerTable.setStatus('mandatory') if mibBuilder.loadTexts: actionsPagerTable.setDescription('pager table') actionsPagerTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1), ).setIndexNames((0, "DATALINK-MIB", "pagerTableIndex")) if mibBuilder.loadTexts: actionsPagerTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: actionsPagerTableEntry.setDescription('pager table entry') pagerTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pagerTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: pagerTableIndex.setDescription('table index') pagerType = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerType.setStatus('mandatory') if mibBuilder.loadTexts: pagerType.setDescription('0-numeric, 1-alpha') pagerPhonenumber = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerPhonenumber.setStatus('mandatory') if mibBuilder.loadTexts: pagerPhonenumber.setDescription('phone number to call for pager') pagerID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerID.setStatus('mandatory') if mibBuilder.loadTexts: pagerID.setDescription('ID or 2nd number to dial') pagerDialDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerDialDelay.setStatus('mandatory') if mibBuilder.loadTexts: pagerDialDelay.setDescription('# seconds on numeric to delay between dial and send pagerID or message') pagerHangupDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerHangupDelay.setStatus('mandatory') if mibBuilder.loadTexts: pagerHangupDelay.setDescription('# seconds on numeric to delay between messages and before hangup') pagerMessage = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 7), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerMessage.setStatus('mandatory') if mibBuilder.loadTexts: pagerMessage.setDescription('message, either alpha or numeric') pagerSendId = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerSendId.setStatus('mandatory') if mibBuilder.loadTexts: pagerSendId.setDescription('0/1 send unit ID or not to pager') pagerSendReason = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerSendReason.setStatus('mandatory') if mibBuilder.loadTexts: pagerSendReason.setDescription('0/1 send reason for page or not to pager') pagerMaxAttempts = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerMaxAttempts.setStatus('mandatory') if mibBuilder.loadTexts: pagerMaxAttempts.setDescription('max tries to be successful') pagerAttempts = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 11), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerAttempts.setStatus('mandatory') if mibBuilder.loadTexts: pagerAttempts.setDescription('current number of tries') pagerAttemptDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 12), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerAttemptDelay.setStatus('mandatory') if mibBuilder.loadTexts: pagerAttemptDelay.setDescription('# minutes between attempts') pagerRepeat = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 13), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerRepeat.setStatus('mandatory') if mibBuilder.loadTexts: pagerRepeat.setDescription('0/1 do we repeat successful') pagerRepeatDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 3, 1, 14), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pagerRepeatDelay.setStatus('mandatory') if mibBuilder.loadTexts: pagerRepeatDelay.setDescription('# minutes between repeats, if used') actionsCalloutTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4), ) if mibBuilder.loadTexts: actionsCalloutTable.setStatus('mandatory') if mibBuilder.loadTexts: actionsCalloutTable.setDescription('callout table') actionsCalloutTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1), ).setIndexNames((0, "DATALINK-MIB", "calloutTableIndex")) if mibBuilder.loadTexts: actionsCalloutTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: actionsCalloutTableEntry.setDescription('callout table entry') calloutTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: calloutTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: calloutTableIndex.setDescription('table index') calloutPhonenumber = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutPhonenumber.setStatus('mandatory') if mibBuilder.loadTexts: calloutPhonenumber.setDescription('phone number to call for callout') calloutMaxConnecttime = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutMaxConnecttime.setStatus('mandatory') if mibBuilder.loadTexts: calloutMaxConnecttime.setDescription('# seconds to wait for carrier') calloutMessage = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutMessage.setStatus('mandatory') if mibBuilder.loadTexts: calloutMessage.setDescription('message to send') calloutSendId = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutSendId.setStatus('mandatory') if mibBuilder.loadTexts: calloutSendId.setDescription('0/1 send unit ID or not to callout') calloutSendReason = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutSendReason.setStatus('mandatory') if mibBuilder.loadTexts: calloutSendReason.setDescription('0/1 send reason for page or not to callout') calloutCommandWait = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutCommandWait.setStatus('mandatory') if mibBuilder.loadTexts: calloutCommandWait.setDescription('#seconds to wait for a command on a callout before hangup') calloutMaxAttempts = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutMaxAttempts.setStatus('mandatory') if mibBuilder.loadTexts: calloutMaxAttempts.setDescription('max tries to be successful') calloutAttempts = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutAttempts.setStatus('mandatory') if mibBuilder.loadTexts: calloutAttempts.setDescription('current number of tries') calloutAttemptDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutAttemptDelay.setStatus('mandatory') if mibBuilder.loadTexts: calloutAttemptDelay.setDescription('# minutes between attempts') calloutRepeat = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 11), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutRepeat.setStatus('mandatory') if mibBuilder.loadTexts: calloutRepeat.setDescription('0/1 do we repeat successful') calloutRepeatDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 11, 4, 1, 12), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: calloutRepeatDelay.setStatus('mandatory') if mibBuilder.loadTexts: calloutRepeatDelay.setDescription('# minutes between repeats, if used') actionsTrapsEntSpecific = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 11, 5, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: actionsTrapsEntSpecific.setStatus('mandatory') if mibBuilder.loadTexts: actionsTrapsEntSpecific.setDescription('0/1 enterprise specific traps enabled') actionsTrapsEntSpecCount = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 11, 5, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionsTrapsEntSpecCount.setStatus('mandatory') if mibBuilder.loadTexts: actionsTrapsEntSpecCount.setDescription('number of enterprise specific traps sent since last re-boot') linefeeds = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: linefeeds.setStatus('mandatory') if mibBuilder.loadTexts: linefeeds.setDescription('0/1 are linefeeds added to CRs on command responses?') duplex = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: duplex.setStatus('mandatory') if mibBuilder.loadTexts: duplex.setDescription('0-half 1-full') response = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: response.setStatus('mandatory') if mibBuilder.loadTexts: response.setDescription('0-codes 1-words') datafilterEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: datafilterEnabled.setStatus('mandatory') if mibBuilder.loadTexts: datafilterEnabled.setDescription('0/1 off/on') alarmfilterEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: alarmfilterEnabled.setStatus('mandatory') if mibBuilder.loadTexts: alarmfilterEnabled.setDescription('0/1 off/on') operatingMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: operatingMode.setStatus('mandatory') if mibBuilder.loadTexts: operatingMode.setDescription('1 command 2 input/access 3 unused 4 inline 5 extmodem') inlineMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: inlineMode.setStatus('mandatory') if mibBuilder.loadTexts: inlineMode.setDescription('1,2,3 if inline, mode 1 (N->2) mode 2 (1->2, 3->4) mode 3 (1->2, 3->4, 5->6)') inlineSource = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: inlineSource.setStatus('mandatory') if mibBuilder.loadTexts: inlineSource.setDescription('if inline and inlineMode==1, source of I/O2 inline') inlineHsk2 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 4, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: inlineHsk2.setStatus('mandatory') if mibBuilder.loadTexts: inlineHsk2.setDescription('handshake mode 0-3 for inline port I/O 2') inlineHsk4 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 4, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: inlineHsk4.setStatus('mandatory') if mibBuilder.loadTexts: inlineHsk4.setDescription('handshake mode 0-3 for inline port I/O 4') inlineHsk6 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 6, 4, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: inlineHsk6.setStatus('mandatory') if mibBuilder.loadTexts: inlineHsk6.setDescription('handshake mode 0-3 for inline port I/O 6') sureEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sureEnabled.setStatus('mandatory') if mibBuilder.loadTexts: sureEnabled.setDescription('0/1 off/on') commandTcpipTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: commandTcpipTimeout.setStatus('mandatory') if mibBuilder.loadTexts: commandTcpipTimeout.setDescription('0-none, else number of no-activity minutes -> tcpip command to drop') sysadminTcpipTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysadminTcpipTimeout.setStatus('mandatory') if mibBuilder.loadTexts: sysadminTcpipTimeout.setDescription('0-none, else number of no-activity minutes -> tcpip sysadmin to drop') bypassEndchar = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: bypassEndchar.setStatus('mandatory') if mibBuilder.loadTexts: bypassEndchar.setDescription('ascii value for character to exit bypass mode. default ->27') routerAutoPing = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 1, 11), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: routerAutoPing.setStatus('mandatory') if mibBuilder.loadTexts: routerAutoPing.setDescription('0/1 = no/yes, default is 0, do we ping the default router every 10 minutes?') modemParity = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemParity.setStatus('mandatory') if mibBuilder.loadTexts: modemParity.setDescription('1 7E 2 7O 3 8N') modemUserSetup = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemUserSetup.setStatus('mandatory') if mibBuilder.loadTexts: modemUserSetup.setDescription('sent to modem on init before the factory setup string') modemTapSetup = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemTapSetup.setStatus('mandatory') if mibBuilder.loadTexts: modemTapSetup.setDescription('sent to modem on just before doing TAP (alpha pager) protocol') modemAnswerString = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemAnswerString.setStatus('mandatory') if mibBuilder.loadTexts: modemAnswerString.setDescription('sent when modem makes connection') modemExtSetup = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 5), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemExtSetup.setStatus('mandatory') if mibBuilder.loadTexts: modemExtSetup.setDescription('sent to ext. modem for setup string') modemExtSetupTime = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemExtSetupTime.setStatus('mandatory') if mibBuilder.loadTexts: modemExtSetupTime.setDescription('# minutes of idle time between sending ext. modem setup string') modemInactivityTimer = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemInactivityTimer.setStatus('mandatory') if mibBuilder.loadTexts: modemInactivityTimer.setDescription('# minutes of no transmit which aborts a connection') modemAutoexecString = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 8), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemAutoexecString.setStatus('mandatory') if mibBuilder.loadTexts: modemAutoexecString.setDescription('command string which auto-executes after modem connection if no other command within 10 seconds') modemAutoexecEnabled = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemAutoexecEnabled.setStatus('mandatory') if mibBuilder.loadTexts: modemAutoexecEnabled.setDescription('0/1 autoexec enabled') modemTimeBetweenOutbound = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 2, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: modemTimeBetweenOutbound.setStatus('mandatory') if mibBuilder.loadTexts: modemTimeBetweenOutbound.setDescription('# seconds (minimum) between outbound call attempts') releaseMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 3, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: releaseMode.setStatus('mandatory') if mibBuilder.loadTexts: releaseMode.setDescription('1-Line 3-CBB 4-Xmodem') autodeleteEnable = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 3, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: autodeleteEnable.setStatus('mandatory') if mibBuilder.loadTexts: autodeleteEnable.setDescription('1/2 off/on autodelete for CBB and Xmodem') releaseCompressed = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 3, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: releaseCompressed.setStatus('mandatory') if mibBuilder.loadTexts: releaseCompressed.setDescription('1-compressed 2-decompressed') waitMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: waitMode.setStatus('mandatory') if mibBuilder.loadTexts: waitMode.setDescription('1/2 off/on wait for 02 after 01 on rlmodes') tagMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: tagMode.setStatus('mandatory') if mibBuilder.loadTexts: tagMode.setDescription('1/2 off/on Line/Block tag enabled') crcMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: crcMode.setStatus('mandatory') if mibBuilder.loadTexts: crcMode.setDescription('1/2 off/on add CRC to ascii releases') dleMode = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: dleMode.setStatus('mandatory') if mibBuilder.loadTexts: dleMode.setDescription('1/2 off/on use DLE stuffing on CBB') cbbRetransmits = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cbbRetransmits.setStatus('mandatory') if mibBuilder.loadTexts: cbbRetransmits.setDescription('# times a block retransmitted in CBB mode') cbbTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 4, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cbbTimeout.setStatus('mandatory') if mibBuilder.loadTexts: cbbTimeout.setDescription('# seconds to wait for an ack before retransmit in CBB mode') activeDatabase = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 12, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: activeDatabase.setStatus('mandatory') if mibBuilder.loadTexts: activeDatabase.setDescription('selects a file. ports 2001-2006 auto select this variable') actionCount = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionCount.setStatus('mandatory') if mibBuilder.loadTexts: actionCount.setDescription('number of active items in action table, 0-nn') actionTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2), ) if mibBuilder.loadTexts: actionTable.setStatus('mandatory') if mibBuilder.loadTexts: actionTable.setDescription('action queue table') actionTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "actionTableIndex")) if mibBuilder.loadTexts: actionTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: actionTableEntry.setDescription('action queue entry') actionTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: actionTableIndex.setDescription('action table entry') actionAcked = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: actionAcked.setStatus('mandatory') if mibBuilder.loadTexts: actionAcked.setDescription('reads 0, any set removes (acks) this action') actionReason = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionReason.setStatus('mandatory') if mibBuilder.loadTexts: actionReason.setDescription('code reason for action') actionReasonID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionReasonID.setStatus('mandatory') if mibBuilder.loadTexts: actionReasonID.setDescription('which of the (reasons) e.g, alarm 3 vs. alarm 4') actionReasonLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionReasonLevel.setStatus('mandatory') if mibBuilder.loadTexts: actionReasonLevel.setDescription('which of the levels for alarms which have 1-3 levels') actionType = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionType.setStatus('mandatory') if mibBuilder.loadTexts: actionType.setDescription('type of action being taken (page, callout, etc.)') actionTypeID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionTypeID.setStatus('mandatory') if mibBuilder.loadTexts: actionTypeID.setDescription('which of the actions e.g, pager 3 vs. pager 4') actionRepeatTime = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionRepeatTime.setStatus('mandatory') if mibBuilder.loadTexts: actionRepeatTime.setDescription('#minutes between repeats of attempts of this action') actionAttempts = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionAttempts.setStatus('mandatory') if mibBuilder.loadTexts: actionAttempts.setDescription('# of attempts to try this action so far') actionNextAttempt = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 10), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionNextAttempt.setStatus('mandatory') if mibBuilder.loadTexts: actionNextAttempt.setDescription('# minutes until the next attempt of this action') actionTimeStamp = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 1, 2, 1, 11), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: actionTimeStamp.setStatus('mandatory') if mibBuilder.loadTexts: actionTimeStamp.setDescription('date and time string: 02/34 12:34, or text message if no items') historyCount = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyCount.setStatus('mandatory') if mibBuilder.loadTexts: historyCount.setDescription('number of history items in history table, 0-nn') historyTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2), ) if mibBuilder.loadTexts: historyTable.setStatus('mandatory') if mibBuilder.loadTexts: historyTable.setDescription('action history table') historyTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1), ).setIndexNames((0, "DATALINK-MIB", "historyTableIndex")) if mibBuilder.loadTexts: historyTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: historyTableEntry.setDescription('history queue entry') historyTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: historyTableIndex.setDescription('history table entry') historyEntryType = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: historyEntryType.setStatus('mandatory') if mibBuilder.loadTexts: historyEntryType.setDescription('type of entry (e.g., modem fail, pager pass, etc.)') historyReason = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyReason.setStatus('mandatory') if mibBuilder.loadTexts: historyReason.setDescription('code reason for history') historyReasonID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyReasonID.setStatus('mandatory') if mibBuilder.loadTexts: historyReasonID.setDescription('which of the (reasons) e.g, alarm 3 vs. alarm 4') historyReasonLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyReasonLevel.setStatus('mandatory') if mibBuilder.loadTexts: historyReasonLevel.setDescription('which of the levels for alarms which have 1-3 levels') historyType = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyType.setStatus('mandatory') if mibBuilder.loadTexts: historyType.setDescription('type of history being taken (page, callout, etc.)') historyTypeID = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyTypeID.setStatus('mandatory') if mibBuilder.loadTexts: historyTypeID.setDescription('which of the historys e.g, pager 3 vs. pager 4') historyTimeStamp = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 8), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: historyTimeStamp.setStatus('mandatory') if mibBuilder.loadTexts: historyTimeStamp.setDescription('date and time string: 02/34 12:34, or text message if no items') historyClearLog = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 13, 2, 2, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: historyClearLog.setStatus('mandatory') if mibBuilder.loadTexts: historyClearLog.setDescription('reads 0, any set clears all history log items') lastCalloutPageReason = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 13, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: lastCalloutPageReason.setStatus('mandatory') if mibBuilder.loadTexts: lastCalloutPageReason.setDescription('the reason string for the last callout or page, or NONE if never used') rtsShowAnswer = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 14, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsShowAnswer.setStatus('deprecated') if mibBuilder.loadTexts: rtsShowAnswer.setDescription('0-no 1-yes, show answer string on connection (deprecated)') rtsNeedPassword = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 14, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rtsNeedPassword.setStatus('deprecated') if mibBuilder.loadTexts: rtsNeedPassword.setDescription('0-no 1-yes, need password on RTS connection (deprecated)') rtsWaitXon = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 14, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsWaitXon.setStatus('deprecated') if mibBuilder.loadTexts: rtsWaitXon.setDescription('0-no 1-yes, wait for Xon after connection before sending data (deprecated)') rtsIdleTimeout = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 14, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsIdleTimeout.setStatus('deprecated') if mibBuilder.loadTexts: rtsIdleTimeout.setDescription('0-255, 0-none, 1-255 #idle minutes no data = shutdown socket (deprecated)') rtsEmptyClose = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 14, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsEmptyClose.setStatus('deprecated') if mibBuilder.loadTexts: rtsEmptyClose.setDescription('0->no, 1-> yes, when file empty close socket (polling, not rt data) (deprecated)') rtsTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6), ) if mibBuilder.loadTexts: rtsTable.setStatus('mandatory') if mibBuilder.loadTexts: rtsTable.setDescription('real time socket table') rtsTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1), ).setIndexNames((0, "DATALINK-MIB", "rtsTableIndex")) if mibBuilder.loadTexts: rtsTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: rtsTableEntry.setDescription('rts table entry') rtsTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rtsTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: rtsTableIndex.setDescription('rts table entry index') rtsNoStore = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsNoStore.setStatus('mandatory') if mibBuilder.loadTexts: rtsNoStore.setDescription("0-allow storage, 1-don't store data when RTS socket not connected") rtsDenied = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsDenied.setStatus('mandatory') if mibBuilder.loadTexts: rtsDenied.setDescription("0-don't allow, 1=yes allow this rts socket to connect") rtsSocketState = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rtsSocketState.setStatus('mandatory') if mibBuilder.loadTexts: rtsSocketState.setDescription('0-closed, 1-wait for pass, 2-wait for xon, 3=open for data') rtsPortShowAnswer = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsPortShowAnswer.setStatus('mandatory') if mibBuilder.loadTexts: rtsPortShowAnswer.setDescription('0-no 1-yes, show answer string on connection') rtsPortNeedPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rtsPortNeedPassword.setStatus('mandatory') if mibBuilder.loadTexts: rtsPortNeedPassword.setDescription('0-no 1-yes, need password on RTS connection') rtsPortWaitXon = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsPortWaitXon.setStatus('mandatory') if mibBuilder.loadTexts: rtsPortWaitXon.setDescription('0-no 1-yes, wait for Xon after connection before sending data') rtsPortIdleTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsPortIdleTimeout.setStatus('mandatory') if mibBuilder.loadTexts: rtsPortIdleTimeout.setDescription('0-255, 0-none, 1-255 #idle minutes no data = shutdown socket') rtsPortEmptyClose = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 14, 6, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtsPortEmptyClose.setStatus('mandatory') if mibBuilder.loadTexts: rtsPortEmptyClose.setDescription('0->no, 1-> yes, when file empty close socket (polling, not rt data)') iprestrictTable = MibTable((1, 3, 6, 1, 4, 1, 3052, 1, 15, 1), ) if mibBuilder.loadTexts: iprestrictTable.setStatus('mandatory') if mibBuilder.loadTexts: iprestrictTable.setDescription('ip restrictions table') iprestrictTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3052, 1, 15, 1, 1), ).setIndexNames((0, "DATALINK-MIB", "iprestrictTableIndex")) if mibBuilder.loadTexts: iprestrictTableEntry.setStatus('mandatory') if mibBuilder.loadTexts: iprestrictTableEntry.setDescription('ip restriction table entry') iprestrictTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 15, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: iprestrictTableIndex.setStatus('mandatory') if mibBuilder.loadTexts: iprestrictTableIndex.setDescription('ip restrict table entry index') iprestrictIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 3052, 1, 15, 1, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: iprestrictIpAddress.setStatus('mandatory') if mibBuilder.loadTexts: iprestrictIpAddress.setDescription('an ip address which forces a restriction or allowance for an ip range') suspendIPRestrictions = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 15, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: suspendIPRestrictions.setStatus('mandatory') if mibBuilder.loadTexts: suspendIPRestrictions.setDescription('read returns 0, writing requires the private community name. default is 0 set to 1 to suspend IP restrictions while loading the list set back to 0 to allow the restrictions to be used.') killIPRestrictions = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 15, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: killIPRestrictions.setStatus('mandatory') if mibBuilder.loadTexts: killIPRestrictions.setDescription('read returns 0, writing requires the private community name. any set removes all entries from the IP restrcition list.') addIPRestrictions = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 15, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: addIPRestrictions.setStatus('mandatory') if mibBuilder.loadTexts: addIPRestrictions.setDescription('read returns 0, writing requires the private community name. any set adds an entry to the IP restriction list note that list is no re-sorted, so must add in order') ipCurrentStatic = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipCurrentStatic.setStatus('mandatory') if mibBuilder.loadTexts: ipCurrentStatic.setDescription('1=static, 0=dynamic') ipCurrentAddress = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipCurrentAddress.setStatus('mandatory') if mibBuilder.loadTexts: ipCurrentAddress.setDescription('current IP address') ipCurrentSubnetMask = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 1, 3), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipCurrentSubnetMask.setStatus('mandatory') if mibBuilder.loadTexts: ipCurrentSubnetMask.setDescription('current subnet mask') ipCurrentDefaultRouter = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipCurrentDefaultRouter.setStatus('mandatory') if mibBuilder.loadTexts: ipCurrentDefaultRouter.setDescription('current default router') ipNewStatic = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 2, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNewStatic.setStatus('mandatory') if mibBuilder.loadTexts: ipNewStatic.setDescription('1=static, 0=dynamic. write requires private community name.') ipNewAddress = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 2, 2), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNewAddress.setStatus('mandatory') if mibBuilder.loadTexts: ipNewAddress.setDescription('read=current new address, write requires private community name.') ipNewSubnetMask = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 2, 3), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNewSubnetMask.setStatus('mandatory') if mibBuilder.loadTexts: ipNewSubnetMask.setDescription('read=current new subnet mask, write requires private community name.') ipNewDefaultRouter = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 2, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNewDefaultRouter.setStatus('mandatory') if mibBuilder.loadTexts: ipNewDefaultRouter.setDescription('read=current new default router, write requires private community name.') ipNewSetup = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 16, 2, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNewSetup.setStatus('mandatory') if mibBuilder.loadTexts: ipNewSetup.setDescription('read=0. write requires private community name. any write causes the current object values for ipNewStatic, ipNewAddress, ipNewSubnetMask and ipNewDefaultRouter to be used. Causes the unit to re-initialize its network stacks with these new values. Changes to ipNewStatic, ipNewAddress, ipNewSubnetMask and ipNewDefaultRouter do not affect the network stack until ipNewSetup is written with some value:') pppIDString = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 17, 1, 1), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pppIDString.setStatus('mandatory') if mibBuilder.loadTexts: pppIDString.setDescription('sent in ppp up trap to provide host identification string') pppIPAddress = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 17, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: pppIPAddress.setStatus('mandatory') if mibBuilder.loadTexts: pppIPAddress.setDescription('sent in ppp up trap to provide host identification by IP address') ccodeLoaded = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 18, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ccodeLoaded.setStatus('mandatory') if mibBuilder.loadTexts: ccodeLoaded.setDescription('0/1, no/yes, is ccode loaded') ccodeRunning = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 18, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ccodeRunning.setStatus('mandatory') if mibBuilder.loadTexts: ccodeRunning.setDescription('0/1, no/yes, is ccode running') ccodeStackMainWas = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 18, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ccodeStackMainWas.setStatus('mandatory') if mibBuilder.loadTexts: ccodeStackMainWas.setDescription('# of bytes of stack used by main app, last time run') ccodeStackMainNow = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 18, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ccodeStackMainNow.setStatus('mandatory') if mibBuilder.loadTexts: ccodeStackMainNow.setDescription('# of bytes of stack used by main app, this time run') ccodeStackT2Was = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 18, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ccodeStackT2Was.setStatus('mandatory') if mibBuilder.loadTexts: ccodeStackT2Was.setDescription('# of bytes of stack used by 2nd task of app, last time run') ccodeStackT2Was2 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 18, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ccodeStackT2Was2.setStatus('mandatory') if mibBuilder.loadTexts: ccodeStackT2Was2.setDescription('# of bytes of stack used by 2nd task of app, this time run') techsupportInt1 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 99, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: techsupportInt1.setStatus('mandatory') if mibBuilder.loadTexts: techsupportInt1.setDescription('a debugging integer for technical support use only. Do not use') techsupportInt2 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 99, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: techsupportInt2.setStatus('mandatory') if mibBuilder.loadTexts: techsupportInt2.setDescription('a debugging integer for technical support use only. Do not use') techsupportInt3 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 99, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: techsupportInt3.setStatus('mandatory') if mibBuilder.loadTexts: techsupportInt3.setDescription('a debugging integer for technical support use only. Do not use') techsupportInt4 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 99, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: techsupportInt4.setStatus('mandatory') if mibBuilder.loadTexts: techsupportInt4.setDescription('a debugging integer for technical support use only. Do not use') techsupportInt5 = MibScalar((1, 3, 6, 1, 4, 1, 3052, 1, 99, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: techsupportInt5.setStatus('mandatory') if mibBuilder.loadTexts: techsupportInt5.setDescription('a debugging integer for technical support use only. Do not use') datalinkDbasePfullTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,501)).setObjects(("DATALINK-MIB", "databaseAlarmIndex"), ("DATALINK-MIB", "databasePfull")) if mibBuilder.loadTexts: datalinkDbasePfullTrap.setDescription('The datalinkDbasePfullTrap is issued when the database reaches a pre-determined threshold level, which causes a trap.') datalinkFilePfullTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,502)).setObjects(("DATALINK-MIB", "fileAlarmFileIndex"), ("DATALINK-MIB", "fileAlarmThresholdIndex"), ("DATALINK-MIB", "filePercentNow")) if mibBuilder.loadTexts: datalinkFilePfullTrap.setDescription('The datalinkFilePfullTrap is issued when one of the data files reaches a pre-determined threshold level, which causes a trap.') datalinkDataAlarmTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,503)).setObjects(("DATALINK-MIB", "dataAlarmIndex"), ("DATALINK-MIB", "dataAlarmName"), ("DATALINK-MIB", "dataAlarmString"), ("DATALINK-MIB", "dataAlarmPort")) if mibBuilder.loadTexts: datalinkDataAlarmTrap.setDescription('The datalinkDataAlarmTrap is issued when one of the data alarms reaches a pre-determined threshold level, which causes a trap.') datalinkSensorAlarmTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,504)).setObjects(("DATALINK-MIB", "sensorAlarmIndex"), ("DATALINK-MIB", "sensorAlarmName"), ("DATALINK-MIB", "sensorAlarmState")) if mibBuilder.loadTexts: datalinkSensorAlarmTrap.setDescription('The datalinkSensorAlarmTrap is issued when one of the External Sensors is triggered for a pre-determined threshold amount of time, which causes a trap.') datalinkNoDataAlarmTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,505)).setObjects(("DATALINK-MIB", "nodataTablePortIndex"), ("DATALINK-MIB", "nodataTableScheduleIndex"), ("DATALINK-MIB", "nodataTableLevelIndex"), ("DATALINK-MIB", "nodataAlarmStatusCounter"), ("DATALINK-MIB", "nodataTableThreshold")) if mibBuilder.loadTexts: datalinkNoDataAlarmTrap.setDescription('The datalinkNoDataAlarmTrap is issued when one of the ports receives no input data for a pre-determined threshold amount of time, which causes a trap.') datalinkSchedTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,506)).setObjects(("DATALINK-MIB", "scheduleIndex")) if mibBuilder.loadTexts: datalinkSchedTrap.setDescription('The datalinkSchedTrap is issued when a scheduled event causes a trap.') datalinkImmediateTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,507)) if mibBuilder.loadTexts: datalinkImmediateTrap.setDescription('The datalinkImmediateTrap is issued when the dotrap command is used to issue a test trap to all snmp managers') datalinkPPPupTrap = NotificationType((1, 3, 6, 1, 4, 1, 3052) + (0,509)).setObjects(("DATALINK-MIB", "pppIDString"), ("DATALINK-MIB", "pppIPAddress")) if mibBuilder.loadTexts: datalinkPPPupTrap.setDescription('The datalinkPPPupTrap is issued when the PPP interface is brought up and the ppp connection has been established') mibBuilder.exportSymbols("DATALINK-MIB", cbbRetransmits=cbbRetransmits, rtsWaitXon=rtsWaitXon, sensorAlarmTable=sensorAlarmTable, actionHistory=actionHistory, scheduleActive=scheduleActive, alarmfilterEnabled=alarmfilterEnabled, rtsNoStore=rtsNoStore, pagerTableIndex=pagerTableIndex, modemTapSetup=modemTapSetup, actionTable=actionTable, ccodeStackMainWas=ccodeStackMainWas, modemExtSetup=modemExtSetup, ftpsetup=ftpsetup, rtsTable=rtsTable, dleMode=dleMode, netcard=netcard, releaseCompressed=releaseCompressed, nodataAlarmStatus=nodataAlarmStatus, modemTimeBetweenOutbound=modemTimeBetweenOutbound, calloutRepeatDelay=calloutRepeatDelay, productname=productname, calloutSendReason=calloutSendReason, rtsSocketState=rtsSocketState, ftpPushEnabled=ftpPushEnabled, pagerHangupDelay=pagerHangupDelay, systemversion=systemversion, ftpPushCount=ftpPushCount, portParity=portParity, calloutMessage=calloutMessage, dataAlarmString=dataAlarmString, fileRecordsAvailable=fileRecordsAvailable, dataAlarmName=dataAlarmName, databaseAlarmCalloutActions=databaseAlarmCalloutActions, calloutTableIndex=calloutTableIndex, techsupport=techsupport, fileTableIndex=fileTableIndex, databaseSize=databaseSize, actionCount=actionCount, rtsNeedPassword=rtsNeedPassword, scheduleAlarmTable=scheduleAlarmTable, actionTableIndex=actionTableIndex, calloutSendId=calloutSendId, modems=modems, dataAlarmAcked=dataAlarmAcked, modemAutoexecString=modemAutoexecString, datalinkPPPupTrap=datalinkPPPupTrap, ftpAutoDelete=ftpAutoDelete, nodataNumberHolidays=nodataNumberHolidays, historyTypeID=historyTypeID, filesetup=filesetup, sitebyport=sitebyport, pagerMaxAttempts=pagerMaxAttempts, historyReasonLevel=historyReasonLevel, techsupportInt3=techsupportInt3, autodeleteEnable=autodeleteEnable, binRecordBlocking=binRecordBlocking, charmask=charmask, autoDstAdjust=autoDstAdjust, databaseAlarmThreshold=databaseAlarmThreshold, factorysetup=factorysetup, bypassEndchar=bypassEndchar, modemUserSetup=modemUserSetup, datalinkFilePfullTrap=datalinkFilePfullTrap, ftpPasswords=ftpPasswords, commandPassword=commandPassword, pagerPhonenumber=pagerPhonenumber, nodataTableLevelIndex=nodataTableLevelIndex, ftpPush=ftpPush, nodataAlarmStatusCounter=nodataAlarmStatusCounter, sensorAlarmEntry=sensorAlarmEntry, datalinkSiteId=datalinkSiteId, memorysize=memorysize, scheduleAcked=scheduleAcked, snmpManagerTable=snmpManagerTable, nodataTableSerialActions=nodataTableSerialActions, portSetupEntry=portSetupEntry, ftpPushUser=ftpPushUser, inlineHskMode=inlineHskMode, ipNewDefaultRouter=ipNewDefaultRouter, fileAlarmBeeperActions=fileAlarmBeeperActions, nodataHolidayClear=nodataHolidayClear, modemExtSetupTime=modemExtSetupTime, fileName=fileName, nodataTablePortIndex=nodataTablePortIndex, snmpSendTestTrap=snmpSendTestTrap, pagerID=pagerID, dataAlarmPort=dataAlarmPort, nodataTableThreshold=nodataTableThreshold, duplex=duplex, nodataAlarmHolidays=nodataAlarmHolidays, pagerAttemptDelay=pagerAttemptDelay, sensorAlarmActive=sensorAlarmActive, databasemode=databasemode, portWord=portWord, tcpPasswords=tcpPasswords, nodataTableEntry=nodataTableEntry, modemsetupstring=modemsetupstring, rtsIdleTimeout=rtsIdleTimeout, filePercentNow=filePercentNow, rtsTableEntry=rtsTableEntry, sensorAlarmMode=sensorAlarmMode, scheduleCalloutActions=scheduleCalloutActions, datafilterEnabled=datafilterEnabled, maxRecordChars=maxRecordChars, dataAlarmTable=dataAlarmTable, ftpPushIPAddress=ftpPushIPAddress, actionAcked=actionAcked, nodataAlarms=nodataAlarms, modemcddelay=modemcddelay, ftpPushAlarms=ftpPushAlarms, sensorAlarmState=sensorAlarmState, fileAlarmFileIndex=fileAlarmFileIndex, inlineHsk4=inlineHsk4, historyClearLog=historyClearLog, scheduleIndex=scheduleIndex, unitIds=unitIds, snmpMgrIndex=snmpMgrIndex, historyType=historyType, dataAlarmBeeperActions=dataAlarmBeeperActions, operatingMode=operatingMode, realtimesocket=realtimesocket, actionsPagerTable=actionsPagerTable, calloutRepeat=calloutRepeat, snmpTrapsAutoRepeatTime=snmpTrapsAutoRepeatTime, fileAlarmSerialActions=fileAlarmSerialActions, actionsBuzzer=actionsBuzzer, datalinkThisProduct=datalinkThisProduct, fileRecords=fileRecords, nodataTableCalloutActions=nodataTableCalloutActions, fileType=fileType, pagerType=pagerType, pagerMessage=pagerMessage, killIPRestrictions=killIPRestrictions, dataAlarmClearTime=dataAlarmClearTime, sensorAlarmSerialActions=sensorAlarmSerialActions, ipCurrentAddress=ipCurrentAddress, rtsShowAnswer=rtsShowAnswer, schedulePagerActions=schedulePagerActions, snmpManagerName=snmpManagerName, entireDatabase=entireDatabase, modemSettings=modemSettings, fileAlarmThreshold=fileAlarmThreshold, sensorAlarmCalloutActions=sensorAlarmCalloutActions, scheduleAlarmEntry=scheduleAlarmEntry, ipNew=ipNew, fileTableEntry=fileTableEntry, passwordTableEntry=passwordTableEntry, modemreport=modemreport, portDateTimeStampMode=portDateTimeStampMode, sensorAlarmTrapActions=sensorAlarmTrapActions, alarmhistory=alarmhistory, passwordCommand=passwordCommand, historyReason=historyReason, dataAlarmIndex=dataAlarmIndex, serialTableIndex=serialTableIndex, ftpPushAcct=ftpPushAcct, actionType=actionType, fileAlarmEntry=fileAlarmEntry, ftpPushStatusMode=ftpPushStatusMode, commandPasswordTimeout=commandPasswordTimeout, dataRelease=dataRelease, databaseAlarmFileMaxSize=databaseAlarmFileMaxSize, ftpPushTiming=ftpPushTiming, modemtype=modemtype, portSetupTable=portSetupTable, time=time, ipCurrent=ipCurrent, pppIDString=pppIDString, techsupportInt2=techsupportInt2, fileAlarmPagerActions=fileAlarmPagerActions, currenttime=currenttime, siteindex=siteindex, inlineSource=inlineSource, rtsTableIndex=rtsTableIndex, modemAutoexecEnabled=modemAutoexecEnabled, dataAlarmEntry=dataAlarmEntry, historyTimeStamp=historyTimeStamp, iprestrictTableEntry=iprestrictTableEntry, actionQueue=actionQueue, serialnumber=serialnumber, rtsPortNeedPassword=rtsPortNeedPassword, actionsTrapsEntSpecCount=actionsTrapsEntSpecCount, scheduleTrapActions=scheduleTrapActions, ftpPushDir=ftpPushDir, ccodeRunning=ccodeRunning, fileAlarms=fileAlarms, snmpTableEntry=snmpTableEntry, dataAlarmActive=dataAlarmActive, portWrapMode=portWrapMode, productIds=productIds, snmpTrapsEnabled=snmpTrapsEnabled, asentria=asentria, actionAttempts=actionAttempts, sysadminTcpipTimeout=sysadminTcpipTimeout, dataAlarmSerialActions=dataAlarmSerialActions, passwordIndex=passwordIndex, fileAlarmThresholdIndex=fileAlarmThresholdIndex, sensorAlarmBeeperActions=sensorAlarmBeeperActions, otherControls=otherControls, nodataAlarmStatusIndex=nodataAlarmStatusIndex, datalink=datalink, historyTableIndex=historyTableIndex, portPtStripOutputLfs=portPtStripOutputLfs, dataAlarmCalloutActions=dataAlarmCalloutActions, dataAlarmClearMode=dataAlarmClearMode, serialTableMessage=serialTableMessage, portlowDTR=portlowDTR, calloutCommandWait=calloutCommandWait, appversion=appversion, actionRepeatTime=actionRepeatTime, databaseAlarmTable=databaseAlarmTable, response=response, rtsDenied=rtsDenied, commandNeedsPassword=commandNeedsPassword, modemInactivityTimer=modemInactivityTimer, nodataTableTrapActions=nodataTableTrapActions, ftppushEnable=ftppushEnable, iprestrictTableIndex=iprestrictTableIndex, actionsTraps=actionsTraps, actionsSerialTableEntry=actionsSerialTableEntry, datalinkNoDataAlarmTrap=datalinkNoDataAlarmTrap, modemParity=modemParity, opSettings=opSettings, actionsCalloutTable=actionsCalloutTable, databaseAlarmEntry=databaseAlarmEntry, portIndex=portIndex, nodataTableBeeperActions=nodataTableBeeperActions, actionReasonID=actionReasonID, portStoreFile=portStoreFile, passwords=passwords, databaseAlarmBeeperActions=databaseAlarmBeeperActions, ftpPushTimer=ftpPushTimer, calloutMaxConnecttime=calloutMaxConnecttime, calloutAttemptDelay=calloutAttemptDelay, fileRecordsDeleted=fileRecordsDeleted, databaseAlarmActive=databaseAlarmActive, waitMode=waitMode, actions=actions, snmpManagerIp=snmpManagerIp, snmpsetup=snmpsetup, actionTypeID=actionTypeID, passwordAccess=passwordAccess, datalinkImmediateTrap=datalinkImmediateTrap, addIPRestrictions=addIPRestrictions, sensorAlarmThreshold=sensorAlarmThreshold, databaseStatus=databaseStatus, nodataHolidayItem=nodataHolidayItem, dataAlarmPagerActions=dataAlarmPagerActions, actionNextAttempt=actionNextAttempt, inlineHsk2=inlineHsk2, nodataAlarmStatusAcked=nodataAlarmStatusAcked, ccode=ccode, ipNewStatic=ipNewStatic, datalinkDataAlarmTrap=datalinkDataAlarmTrap) mibBuilder.exportSymbols("DATALINK-MIB", ipNewSetup=ipNewSetup, databaseAlarmFileStore=databaseAlarmFileStore, pppsetup=pppsetup, fileTable=fileTable, tagMode=tagMode, databaseRecordsAvailable=databaseRecordsAvailable, ipCurrentStatic=ipCurrentStatic, portPTTime=portPTTime, recordCollectionTimeout=recordCollectionTimeout, sensorAlarmPagerActions=sensorAlarmPagerActions, datalinkSensorAlarmTrap=datalinkSensorAlarmTrap, nodataTableSchedule=nodataTableSchedule, activeDatabase=activeDatabase, pagerSendReason=pagerSendReason, databases=databases, rtsPortEmptyClose=rtsPortEmptyClose, ipsetup=ipsetup, nodataAlarmStatusEntry=nodataAlarmStatusEntry, sensorAlarmAcked=sensorAlarmAcked, rtsPortShowAnswer=rtsPortShowAnswer, nodataTableScheduleIndex=nodataTableScheduleIndex, datalinkDbasePfullTrap=datalinkDbasePfullTrap, scheduleSerialActions=scheduleSerialActions, iprestrictIpAddress=iprestrictIpAddress, numberPorts=numberPorts, ftpDataMode=ftpDataMode, ipNewSubnetMask=ipNewSubnetMask, sureEnabled=sureEnabled, fileAlarmCalloutActions=fileAlarmCalloutActions, rtsPortWaitXon=rtsPortWaitXon, calloutAttempts=calloutAttempts, fileAlarmActive=fileAlarmActive, ftppushIndex=ftppushIndex, actionTimeStamp=actionTimeStamp, modemAnswerString=modemAnswerString, scheduleTime=scheduleTime, siteID=siteID, inlineMode=inlineMode, numberports=numberports, historyReasonID=historyReasonID, databaseFiles=databaseFiles, pagerRepeatDelay=pagerRepeatDelay, ccodeLoaded=ccodeLoaded, actionReason=actionReason, actionsBuzzerState=actionsBuzzerState, passwordTable=passwordTable, alarms=alarms, releaseMode=releaseMode, techsupportInt4=techsupportInt4, pagerSendId=pagerSendId, rtsEmptyClose=rtsEmptyClose, nodataTable=nodataTable, charmaskEnabled=charmaskEnabled, nodataHolidayTableEntry=nodataHolidayTableEntry, suspendIPRestrictions=suspendIPRestrictions, lastCalloutPageReason=lastCalloutPageReason, actionsSerialTable=actionsSerialTable, databaseAlarmTrapActions=databaseAlarmTrapActions, portPTMode=portPTMode, ccodeStackMainNow=ccodeStackMainNow, portStopbits=portStopbits, controls=controls, databasePfull=databasePfull, nodataTableActive=nodataTableActive, databaseRecordsDeleted=databaseRecordsDeleted, ipNewAddress=ipNewAddress, historyCount=historyCount, historyTableEntry=historyTableEntry, serialPorts=serialPorts, fileAlarmTrapActions=fileAlarmTrapActions, nodataHolidayIndex=nodataHolidayIndex, datalinkSchedTrap=datalinkSchedTrap, nodataTablePagerActions=nodataTablePagerActions, techsupportInt1=techsupportInt1, nodataHolidayTable=nodataHolidayTable, rtsPortIdleTimeout=rtsPortIdleTimeout, cbbTimeout=cbbTimeout, actionsTrapsEntSpecific=actionsTrapsEntSpecific, nodataHolidayDelete=nodataHolidayDelete, pagerRepeat=pagerRepeat, ccodeStackT2Was2=ccodeStackT2Was2, ftppushTableEntry=ftppushTableEntry, ipCurrentSubnetMask=ipCurrentSubnetMask, crcMode=crcMode, pagerAttempts=pagerAttempts, routerAutoPing=routerAutoPing, historyEntryType=historyEntryType, fileSize=fileSize, actionsCalloutTableEntry=actionsCalloutTableEntry, inlineHsk6=inlineHsk6, portPtStripInputLfs=portPtStripInputLfs, ftpPushPass=ftpPushPass, dataAlarmThreshold=dataAlarmThreshold, databaseAlarmSerialActions=databaseAlarmSerialActions, databaseAlarmIndex=databaseAlarmIndex, modemportspeed=modemportspeed, hardware=hardware, iprestrictions=iprestrictions, actionTableEntry=actionTableEntry, auxportMode=auxportMode, dataAlarmTrapActions=dataAlarmTrapActions, calloutPhonenumber=calloutPhonenumber, actionReasonLevel=actionReasonLevel, idByPortTable=idByPortTable, dataAlarmCounter=dataAlarmCounter, portDataStore=portDataStore, portHskMode=portHskMode, databaseAlarmPagerActions=databaseAlarmPagerActions, modemPasswords=modemPasswords, techsupportInt5=techsupportInt5, actionsPagerTableEntry=actionsPagerTableEntry, linefeeds=linefeeds, portBaud=portBaud, ftpPushServerName=ftpPushServerName, ipCurrentDefaultRouter=ipCurrentDefaultRouter, iprestrictTable=iprestrictTable, dateofmanufacture=dateofmanufacture, calloutMaxAttempts=calloutMaxAttempts, commandTcpipTimeout=commandTcpipTimeout, pppIdentification=pppIdentification, portBinaryMode=portBinaryMode, promptPasswords=promptPasswords, ftppushTable=ftppushTable, historyTable=historyTable, sensorAlarmIndex=sensorAlarmIndex, pagerDialDelay=pagerDialDelay, sensorAlarmName=sensorAlarmName, sensorAlarmCounter=sensorAlarmCounter, pppIPAddress=pppIPAddress, networkenabled=networkenabled, ccodeStackT2Was=ccodeStackT2Was, productConfig=productConfig, nodataHolidayAdd=nodataHolidayAdd, dataAlarmAutoClear=dataAlarmAutoClear, scheduleBeeperActions=scheduleBeeperActions)
true
true
1c2cfa80fe0b2e9e9f4ad971d95c5e54f8d46cb0
7,054
py
Python
google/ads/google_ads/v1/proto/enums/local_placeholder_field_pb2.py
jwygoda/google-ads-python
863892b533240cb45269d9c2cceec47e2c5a8b68
[ "Apache-2.0" ]
null
null
null
google/ads/google_ads/v1/proto/enums/local_placeholder_field_pb2.py
jwygoda/google-ads-python
863892b533240cb45269d9c2cceec47e2c5a8b68
[ "Apache-2.0" ]
null
null
null
google/ads/google_ads/v1/proto/enums/local_placeholder_field_pb2.py
jwygoda/google-ads-python
863892b533240cb45269d9c2cceec47e2c5a8b68
[ "Apache-2.0" ]
null
null
null
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads_v1/proto/enums/local_placeholder_field.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='google/ads/googleads_v1/proto/enums/local_placeholder_field.proto', package='google.ads.googleads.v1.enums', syntax='proto3', serialized_options=_b('\n!com.google.ads.googleads.v1.enumsB\032LocalPlaceholderFieldProtoP\001ZBgoogle.golang.org/genproto/googleapis/ads/googleads/v1/enums;enums\242\002\003GAA\252\002\035Google.Ads.GoogleAds.V1.Enums\312\002\035Google\\Ads\\GoogleAds\\V1\\Enums\352\002!Google::Ads::GoogleAds::V1::Enums'), serialized_pb=_b('\nAgoogle/ads/googleads_v1/proto/enums/local_placeholder_field.proto\x12\x1dgoogle.ads.googleads.v1.enums\x1a\x1cgoogle/api/annotations.proto\"\xa8\x03\n\x19LocalPlaceholderFieldEnum\"\x8a\x03\n\x15LocalPlaceholderField\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0b\n\x07UNKNOWN\x10\x01\x12\x0b\n\x07\x44\x45\x41L_ID\x10\x02\x12\r\n\tDEAL_NAME\x10\x03\x12\x0c\n\x08SUBTITLE\x10\x04\x12\x0f\n\x0b\x44\x45SCRIPTION\x10\x05\x12\t\n\x05PRICE\x10\x06\x12\x13\n\x0f\x46ORMATTED_PRICE\x10\x07\x12\x0e\n\nSALE_PRICE\x10\x08\x12\x18\n\x14\x46ORMATTED_SALE_PRICE\x10\t\x12\r\n\tIMAGE_URL\x10\n\x12\x0b\n\x07\x41\x44\x44RESS\x10\x0b\x12\x0c\n\x08\x43\x41TEGORY\x10\x0c\x12\x17\n\x13\x43ONTEXTUAL_KEYWORDS\x10\r\x12\x0e\n\nFINAL_URLS\x10\x0e\x12\x15\n\x11\x46INAL_MOBILE_URLS\x10\x0f\x12\x10\n\x0cTRACKING_URL\x10\x10\x12\x14\n\x10\x41NDROID_APP_LINK\x10\x11\x12\x14\n\x10SIMILAR_DEAL_IDS\x10\x12\x12\x10\n\x0cIOS_APP_LINK\x10\x13\x12\x14\n\x10IOS_APP_STORE_ID\x10\x14\x42\xef\x01\n!com.google.ads.googleads.v1.enumsB\x1aLocalPlaceholderFieldProtoP\x01ZBgoogle.golang.org/genproto/googleapis/ads/googleads/v1/enums;enums\xa2\x02\x03GAA\xaa\x02\x1dGoogle.Ads.GoogleAds.V1.Enums\xca\x02\x1dGoogle\\Ads\\GoogleAds\\V1\\Enums\xea\x02!Google::Ads::GoogleAds::V1::Enumsb\x06proto3') , dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,]) _LOCALPLACEHOLDERFIELDENUM_LOCALPLACEHOLDERFIELD = _descriptor.EnumDescriptor( name='LocalPlaceholderField', full_name='google.ads.googleads.v1.enums.LocalPlaceholderFieldEnum.LocalPlaceholderField', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='UNSPECIFIED', index=0, number=0, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='UNKNOWN', index=1, number=1, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='DEAL_ID', index=2, number=2, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='DEAL_NAME', index=3, number=3, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='SUBTITLE', index=4, number=4, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='DESCRIPTION', index=5, number=5, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='PRICE', index=6, number=6, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='FORMATTED_PRICE', index=7, number=7, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='SALE_PRICE', index=8, number=8, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='FORMATTED_SALE_PRICE', index=9, number=9, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='IMAGE_URL', index=10, number=10, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='ADDRESS', index=11, number=11, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='CATEGORY', index=12, number=12, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='CONTEXTUAL_KEYWORDS', index=13, number=13, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='FINAL_URLS', index=14, number=14, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='FINAL_MOBILE_URLS', index=15, number=15, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='TRACKING_URL', index=16, number=16, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='ANDROID_APP_LINK', index=17, number=17, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='SIMILAR_DEAL_IDS', index=18, number=18, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='IOS_APP_LINK', index=19, number=19, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='IOS_APP_STORE_ID', index=20, number=20, serialized_options=None, type=None), ], containing_type=None, serialized_options=None, serialized_start=161, serialized_end=555, ) _sym_db.RegisterEnumDescriptor(_LOCALPLACEHOLDERFIELDENUM_LOCALPLACEHOLDERFIELD) _LOCALPLACEHOLDERFIELDENUM = _descriptor.Descriptor( name='LocalPlaceholderFieldEnum', full_name='google.ads.googleads.v1.enums.LocalPlaceholderFieldEnum', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ ], extensions=[ ], nested_types=[], enum_types=[ _LOCALPLACEHOLDERFIELDENUM_LOCALPLACEHOLDERFIELD, ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=131, serialized_end=555, ) _LOCALPLACEHOLDERFIELDENUM_LOCALPLACEHOLDERFIELD.containing_type = _LOCALPLACEHOLDERFIELDENUM DESCRIPTOR.message_types_by_name['LocalPlaceholderFieldEnum'] = _LOCALPLACEHOLDERFIELDENUM _sym_db.RegisterFileDescriptor(DESCRIPTOR) LocalPlaceholderFieldEnum = _reflection.GeneratedProtocolMessageType('LocalPlaceholderFieldEnum', (_message.Message,), dict( DESCRIPTOR = _LOCALPLACEHOLDERFIELDENUM, __module__ = 'google.ads.googleads_v1.proto.enums.local_placeholder_field_pb2' , __doc__ = """Values for Local placeholder fields. For more information about dynamic remarketing feeds, see https://support.google.com/google-ads/answer/6053288. """, # @@protoc_insertion_point(class_scope:google.ads.googleads.v1.enums.LocalPlaceholderFieldEnum) )) _sym_db.RegisterMessage(LocalPlaceholderFieldEnum) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
41.251462
1,279
0.759002
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database _sym_db = _symbol_database.Default() from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='google/ads/googleads_v1/proto/enums/local_placeholder_field.proto', package='google.ads.googleads.v1.enums', syntax='proto3', serialized_options=_b('\n!com.google.ads.googleads.v1.enumsB\032LocalPlaceholderFieldProtoP\001ZBgoogle.golang.org/genproto/googleapis/ads/googleads/v1/enums;enums\242\002\003GAA\252\002\035Google.Ads.GoogleAds.V1.Enums\312\002\035Google\\Ads\\GoogleAds\\V1\\Enums\352\002!Google::Ads::GoogleAds::V1::Enums'), serialized_pb=_b('\nAgoogle/ads/googleads_v1/proto/enums/local_placeholder_field.proto\x12\x1dgoogle.ads.googleads.v1.enums\x1a\x1cgoogle/api/annotations.proto\"\xa8\x03\n\x19LocalPlaceholderFieldEnum\"\x8a\x03\n\x15LocalPlaceholderField\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0b\n\x07UNKNOWN\x10\x01\x12\x0b\n\x07\x44\x45\x41L_ID\x10\x02\x12\r\n\tDEAL_NAME\x10\x03\x12\x0c\n\x08SUBTITLE\x10\x04\x12\x0f\n\x0b\x44\x45SCRIPTION\x10\x05\x12\t\n\x05PRICE\x10\x06\x12\x13\n\x0f\x46ORMATTED_PRICE\x10\x07\x12\x0e\n\nSALE_PRICE\x10\x08\x12\x18\n\x14\x46ORMATTED_SALE_PRICE\x10\t\x12\r\n\tIMAGE_URL\x10\n\x12\x0b\n\x07\x41\x44\x44RESS\x10\x0b\x12\x0c\n\x08\x43\x41TEGORY\x10\x0c\x12\x17\n\x13\x43ONTEXTUAL_KEYWORDS\x10\r\x12\x0e\n\nFINAL_URLS\x10\x0e\x12\x15\n\x11\x46INAL_MOBILE_URLS\x10\x0f\x12\x10\n\x0cTRACKING_URL\x10\x10\x12\x14\n\x10\x41NDROID_APP_LINK\x10\x11\x12\x14\n\x10SIMILAR_DEAL_IDS\x10\x12\x12\x10\n\x0cIOS_APP_LINK\x10\x13\x12\x14\n\x10IOS_APP_STORE_ID\x10\x14\x42\xef\x01\n!com.google.ads.googleads.v1.enumsB\x1aLocalPlaceholderFieldProtoP\x01ZBgoogle.golang.org/genproto/googleapis/ads/googleads/v1/enums;enums\xa2\x02\x03GAA\xaa\x02\x1dGoogle.Ads.GoogleAds.V1.Enums\xca\x02\x1dGoogle\\Ads\\GoogleAds\\V1\\Enums\xea\x02!Google::Ads::GoogleAds::V1::Enumsb\x06proto3') , dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,]) _LOCALPLACEHOLDERFIELDENUM_LOCALPLACEHOLDERFIELD = _descriptor.EnumDescriptor( name='LocalPlaceholderField', full_name='google.ads.googleads.v1.enums.LocalPlaceholderFieldEnum.LocalPlaceholderField', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='UNSPECIFIED', index=0, number=0, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='UNKNOWN', index=1, number=1, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='DEAL_ID', index=2, number=2, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='DEAL_NAME', index=3, number=3, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='SUBTITLE', index=4, number=4, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='DESCRIPTION', index=5, number=5, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='PRICE', index=6, number=6, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='FORMATTED_PRICE', index=7, number=7, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='SALE_PRICE', index=8, number=8, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='FORMATTED_SALE_PRICE', index=9, number=9, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='IMAGE_URL', index=10, number=10, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='ADDRESS', index=11, number=11, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='CATEGORY', index=12, number=12, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='CONTEXTUAL_KEYWORDS', index=13, number=13, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='FINAL_URLS', index=14, number=14, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='FINAL_MOBILE_URLS', index=15, number=15, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='TRACKING_URL', index=16, number=16, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='ANDROID_APP_LINK', index=17, number=17, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='SIMILAR_DEAL_IDS', index=18, number=18, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='IOS_APP_LINK', index=19, number=19, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='IOS_APP_STORE_ID', index=20, number=20, serialized_options=None, type=None), ], containing_type=None, serialized_options=None, serialized_start=161, serialized_end=555, ) _sym_db.RegisterEnumDescriptor(_LOCALPLACEHOLDERFIELDENUM_LOCALPLACEHOLDERFIELD) _LOCALPLACEHOLDERFIELDENUM = _descriptor.Descriptor( name='LocalPlaceholderFieldEnum', full_name='google.ads.googleads.v1.enums.LocalPlaceholderFieldEnum', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ ], extensions=[ ], nested_types=[], enum_types=[ _LOCALPLACEHOLDERFIELDENUM_LOCALPLACEHOLDERFIELD, ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=131, serialized_end=555, ) _LOCALPLACEHOLDERFIELDENUM_LOCALPLACEHOLDERFIELD.containing_type = _LOCALPLACEHOLDERFIELDENUM DESCRIPTOR.message_types_by_name['LocalPlaceholderFieldEnum'] = _LOCALPLACEHOLDERFIELDENUM _sym_db.RegisterFileDescriptor(DESCRIPTOR) LocalPlaceholderFieldEnum = _reflection.GeneratedProtocolMessageType('LocalPlaceholderFieldEnum', (_message.Message,), dict( DESCRIPTOR = _LOCALPLACEHOLDERFIELDENUM, __module__ = 'google.ads.googleads_v1.proto.enums.local_placeholder_field_pb2' , __doc__ = """Values for Local placeholder fields. For more information about dynamic remarketing feeds, see https://support.google.com/google-ads/answer/6053288. """, )) _sym_db.RegisterMessage(LocalPlaceholderFieldEnum) DESCRIPTOR._options = None
true
true
1c2cfac891f520e4a1fb7ea15d7dcced206469ae
3,044
py
Python
tests/test_put_no_body.py
Aryabhata-Rootspring/fastapi
f6237ad05a8468ac19c591181adad38d75372c46
[ "MIT" ]
53,007
2018-12-08T10:05:29.000Z
2022-03-31T23:30:02.000Z
tests/test_put_no_body.py
Aryabhata-Rootspring/fastapi
f6237ad05a8468ac19c591181adad38d75372c46
[ "MIT" ]
4,155
2019-01-05T05:07:49.000Z
2022-03-31T21:25:38.000Z
tests/test_put_no_body.py
Aryabhata-Rootspring/fastapi
f6237ad05a8468ac19c591181adad38d75372c46
[ "MIT" ]
4,092
2018-12-09T16:21:00.000Z
2022-03-31T07:59:45.000Z
from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() @app.put("/items/{item_id}") def save_item_no_body(item_id: str): return {"item_id": item_id} client = TestClient(app) openapi_schema = { "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Save Item No Body", "operationId": "save_item_no_body_items__item_id__put", "parameters": [ { "required": True, "schema": {"title": "Item Id", "type": "string"}, "name": "item_id", "in": "path", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": {"type": "string"}, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, } def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == openapi_schema def test_put_no_body(): response = client.put("/items/foo") assert response.status_code == 200, response.text assert response.json() == {"item_id": "foo"} def test_put_no_body_with_body(): response = client.put("/items/foo", json={"name": "Foo"}) assert response.status_code == 200, response.text assert response.json() == {"item_id": "foo"}
31.061224
86
0.396518
from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() @app.put("/items/{item_id}") def save_item_no_body(item_id: str): return {"item_id": item_id} client = TestClient(app) openapi_schema = { "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Save Item No Body", "operationId": "save_item_no_body_items__item_id__put", "parameters": [ { "required": True, "schema": {"title": "Item Id", "type": "string"}, "name": "item_id", "in": "path", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": {"type": "string"}, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, } def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == openapi_schema def test_put_no_body(): response = client.put("/items/foo") assert response.status_code == 200, response.text assert response.json() == {"item_id": "foo"} def test_put_no_body_with_body(): response = client.put("/items/foo", json={"name": "Foo"}) assert response.status_code == 200, response.text assert response.json() == {"item_id": "foo"}
true
true
1c2cfb5cc57393f63b906668f0e0cb4b599d3a76
16,940
py
Python
tasks/uk/cdrc.py
CartoDB/bigmetadata
a32325382500f23b8a607e4e02cc0ec111360869
[ "BSD-3-Clause" ]
45
2015-12-14T03:05:55.000Z
2021-06-29T22:46:40.000Z
tasks/uk/cdrc.py
CartoDB/bigmetadata
a32325382500f23b8a607e4e02cc0ec111360869
[ "BSD-3-Clause" ]
480
2016-02-19T15:58:44.000Z
2021-09-10T16:38:56.000Z
tasks/uk/cdrc.py
CartoDB/bigmetadata
a32325382500f23b8a607e4e02cc0ec111360869
[ "BSD-3-Clause" ]
13
2016-08-09T21:03:02.000Z
2020-04-29T23:40:20.000Z
# https://data.cdrc.ac.uk/dataset/cdrc-2011-oac-geodata-pack-uk from tasks.base_tasks import (ColumnsTask, TableTask, TagsTask, RepoFileUnzipTask, GeoFile2TempTableTask, MetaWrapper, SimplifiedTempTableTask, RepoFile) from tasks.util import shell, copyfile from tasks.meta import GEOM_REF, OBSColumn, OBSTable, OBSTag, current_session from tasks.tags import SectionTags, SubsectionTags, UnitTags, LicenseTags, BoundaryTags from lib.timespan import get_timespan from collections import OrderedDict import os class OpenDemographicsLicenseTags(TagsTask): def tags(self): return [OBSTag(id='opengeodemographics-license', name='Open Geodemographics license', type='license', description='Free to download and reuse, even for ' 'commercial sector applications. More ' 'information `here <http://www.opengeodemographics.com/index.php#why-section>`_' )] class SourceTags(TagsTask): def version(self): return 1 def tags(self): return[ OBSTag(id='cdrc-source', name='Consumer Data Research Centre', type='source', description='The 2011 Area Classification for Output Areas (2011 OAC) is a UK geodemographic classification produced as a collaboration between the Office for National Statistics and University College London. For further information regarding the 2011 OAC please visit: http://www.ons.gov.uk/ons/guide-method/geography/products/area-classifications/ns-area-classifications/ns-2011-area-classifications/index.html or http://www.opengeodemographics.com. CDRC 2011 OAC Geodata Pack by the ESRC Consumer Data Research Centre; Contains National Statistics data Crown copyright and database right 2015; Contains Ordnance Survey data Crown copyright and database right 2015') ] class DownloadOutputAreas(RepoFileUnzipTask): # https://data.cdrc.ac.uk/dataset/cdrc-2011-oac-geodata-pack-uk URL = 'https://data.cdrc.ac.uk/dataset/68771b14-72aa-4ad7-99f3-0b8d1124cb1b/resource/8fff55da-6235-459c-b66d-017577b060d3/download/output-area-classification.zip' def requires(self): return RepoFile(resource_id=self.task_id, version=self.version(), url=self.URL, downloader='cdrc') class ImportOutputAreas(GeoFile2TempTableTask): def requires(self): return DownloadOutputAreas() def input_files(self): return os.path.join(self.input().path, 'Output Area Classification', 'Shapefiles', '2011_OAC.shp') class SimplifiedImportOutputAreas(SimplifiedTempTableTask): def requires(self): return ImportOutputAreas() class OutputAreaColumns(ColumnsTask): def version(self): return 4 def requires(self): return { 'subsections': SubsectionTags(), 'sections': SectionTags(), 'source': SourceTags(), 'license': LicenseTags(), 'boundary': BoundaryTags(), } def columns(self): input_ = self.input() license = input_['license']['uk_ogl'] source = input_['source']['cdrc-source'] boundary_type = input_['boundary'] geom = OBSColumn( type='Geometry', name='Census Output Areas', description='The smallest unit for which census data are published ' 'in the UK. They contain at least 40 households and ' '100 persons, the target size being 125 households. ' 'They were built up from postcode blocks after the ' 'census data were available, with the intention of ' 'standardising population sizes, geographical shape ' 'and social homogeneity (in terms of dwelling types ' 'and housing tenure). The OAs generated in 2001 were ' 'retained as far as possible for the publication of ' 'outputs from the 2011 Census (less than 3% were ' 'changed). -`Wikipedia <https://en.wikipedia.org/' 'wiki/ONS_coding_system#Geography_of_the_UK_Census>`_', weight=8, tags=[input_['subsections']['boundary'], input_['sections']['uk'], source, license, boundary_type['cartographic_boundary'], boundary_type['interpolation_boundary']] ) geomref = OBSColumn( type='Text', name='Census Output Area ID', weight=0, targets={geom: GEOM_REF} ) return OrderedDict([ ('the_geom', geom), (self.geoname_column(), geomref) ]) @staticmethod def geoname_column(): return 'oa_sa' @staticmethod def geoid_column(): return 'oa_sa' class OutputAreas(TableTask): def requires(self): return { 'geom_columns': OutputAreaColumns(), 'data': SimplifiedImportOutputAreas(), } def version(self): return 9 def table_timespan(self): return get_timespan('2011') # TODO: https://github.com/CartoDB/bigmetadata/issues/435 def targets(self): return { OBSTable(id='.'.join([self.schema(), self.name()])): GEOM_REF, } def columns(self): input_ = self.input() cols = OrderedDict() cols.update(input_['geom_columns']) return cols def populate(self): session = current_session() session.execute('INSERT INTO {output} ' 'SELECT ST_MakeValid(wkb_geometry), {geoname_column} ' 'FROM {input}'.format( output=self.output().table, input=self.input()['data'].table, geoname_column=self.geoname_column() )) @staticmethod def geoid_column(): return OutputAreaColumns.geoid_column() @staticmethod def geoname_column(): return OutputAreaColumns.geoname_column() class OutputAreaClassificationColumns(ColumnsTask): sprgrp_mapping = OrderedDict([ ('Rural Residents', '1'), ('Cosmopolitans', '2'), ('Ethnicity Central', '3'), ('Multicultural Metropolitans', '4'), ('Urbanites', '5'), ('Suburbanites', '6'), ('Constrained City Dwellers', '7'), ('Hard-Pressed Living', '8'), ]) grp_mapping = OrderedDict([ ('Farming Communities', '1a'), ('Rural Tenants', '1b'), ('Ageing Rural Dwellers', '1c'), ('Students Around Campus', '2a'), ('Inner-City Students', '2b'), ('Comfortable Cosmopolitans', '2c'), ('Aspiring and Affluent', '2d'), ('Ethnic Family Life', '3a'), ('Endeavouring Ethnic Mix', '3b'), ('Ethnic Dynamics', '3c'), ('Aspirational Techies', '3d'), ('Rented Family Living', '4a'), ('Challenged Asian Terraces', '4b'), ('Asian Traits', '4c'), ('Urban Professionals and Families', '5a'), ('Ageing Urban Living', '5b'), ('Suburban Achievers', '6a'), ('Semi-Detached Suburbia', '6b'), ('Challenged Diversity', '7a'), ('Constrained Flat Dwellers', '7b'), ('White Communities', '7c'), ('Ageing City Dwellers', '7d'), ('Industrious Communities', '8a'), ('Challenged Terraced Workers', '8b'), ('Hard-Pressed Ageing Workers', '8c'), ('Migration and Churn', '8d'), ]) subgrp_mapping = OrderedDict([ ('Rural Workers and Families', '1a1'), ('Established Farming Communities', '1a2'), ('Agricultural Communities', '1a3'), ('Older Farming Communities', '1a4'), ('Rural Life', '1b1'), ('Rural White-Collar Workers', '1b2'), ('Ageing Rural Flat Tenants', '1b3'), ('Rural Employment and Retirees', '1c1'), ('Renting Rural Retirement', '1c2'), ('Detached Rural Retirement', '1c3'), ('Student Communal Living', '2a1'), ('Student Digs', '2a2'), ('Students and Professionals', '2a3'), ('Students and Commuters', '2b1'), ('Multicultural Student Neighbourhoods', '2b2'), ('Migrant Families', '2c1'), ('Migrant Commuters', '2c2'), ('Professional Service Cosmopolitans', '2c3'), ('Urban Cultural Mix', '2d1'), ('Highly-Qualified Quaternary Workers', '2d2'), ('EU White-Collar Workers', '2d3'), ('Established Renting Families', '3a1'), ('Young Families and Students', '3a2'), ('Striving Service Workers', '3b1'), ('Bangladeshi Mixed Employment', '3b2'), ('Multi-Ethnic Professional Service Workers', '3b3'), ('Constrained Neighbourhoods', '3c1'), ('Constrained Commuters', '3c2'), ('New EU Tech Workers', '3d1'), ('Established Tech Workers', '3d2'), ('Old EU Tech Workers', '3d3'), ('Social Renting Young Families', '4a1'), ('Private Renting New Arrivals', '4a2'), ('Commuters with Young Families', '4a3'), ('Asian Terraces and Flats', '4b1'), ('Pakistani Communities', '4b2'), ('Achieving Minorities', '4c1'), ('Multicultural New Arrivals', '4c2'), ('Inner City Ethnic Mix', '4c3'), ('White Professionals', '5a1'), ('Multi-Ethnic Professionals with Families', '5a2'), ('Families in Terraces and Flats', '5a3'), ('Delayed Retirement', '5b1'), ('Communal Retirement', '5b2'), ('Self-Sufficient Retirement', '5b3'), ('Indian Tech Achievers', '6a1'), ('Comfortable Suburbia', '6a2'), ('Detached Retirement Living', '6a3'), ('Ageing in Suburbia', '6a4'), ('Multi-Ethnic Suburbia', '6b1'), ('White Suburban Communities', '6b2'), ('Semi-Detached Ageing', '6b3'), ('Older Workers and Retirement', '6b4'), ('Transitional Eastern European Neighbourhoods', '7a1'), ('Hampered Aspiration', '7a2'), ('Multi-Ethnic Hardship', '7a3'), ('Eastern European Communities', '7b1'), ('Deprived Neighbourhoods', '7b2'), ('Endeavouring Flat Dwellers', '7b3'), ('Challenged Transitionaries', '7c1'), ('Constrained Young Families', '7c2'), ('Outer City Hardship', '7c3'), ('Ageing Communities and Families', '7d1'), ('Retired Independent City Dwellers', '7d2'), ('Retired Communal City Dwellers', '7d3'), ('Retired City Hardship', '7d4'), ('Industrious Transitions', '8a1'), ('Industrious Hardship', '8a2'), ('Deprived Blue-Collar Terraces', '8b1'), ('Hard-Pressed Rented Terraces', '8b2'), ('Ageing Industrious Workers', '8c1'), ('Ageing Rural Industry Workers', '8c2'), ('Renting Hard-Pressed Workers', '8c3'), ('Young Hard-Pressed Families', '8d1'), ('Hard-Pressed Ethnic Mix', '8d2'), ('Hard-Pressed European Settlers', '8d3'), ]) def requires(self): return { 'sections': SectionTags(), 'subsections': SubsectionTags(), 'units': UnitTags(), 'license': OpenDemographicsLicenseTags(), 'source': SourceTags(), } def version(self): return 4 def columns(self): input_ = self.input() uk = input_['sections']['uk'] segments = input_['subsections']['segments'] gen_cats = lambda d: OrderedDict([ (catname, {'description': '', 'details': {}}) for catname in list(d.keys()) ]) segmentation = input_['units']['segmentation'] license = input_['license']['opengeodemographics-license'] source = input_['source']['cdrc-source'] return OrderedDict([ ('sprgrp', OBSColumn( type='Text', weight=1, name='Supergroup Area Classification', description='The 2011 Area Classification for Output Areas ' '(2011 OAC) is a UK geodemographic classification produced as ' 'a collaboration between the Office for National Statistics and ' 'University College London. Visit `here ' '<http://www.ons.gov.uk/ons/guide-method/geography/products/' 'area-classifications/ns-area-classifications/ns-2011-area-' 'classifications/index.html>`_ or `here ' '<http://www.opengeodemographics.com>`_ for further ' 'information regarding the 2011 OAC. ', extra={'categories': gen_cats(self.sprgrp_mapping)}, tags=[uk, segments, segmentation, license, source], )), ('grp', OBSColumn( type='Text', weight=3, name='Group Area Classification', description='The 2011 Area Classification for Output Areas ' '(2011 OAC) is a UK geodemographic classification produced as ' 'a collaboration between the Office for National Statistics and ' 'University College London. Visit `here ' '<http://www.ons.gov.uk/ons/guide-method/geography/products/' 'area-classifications/ns-area-classifications/ns-2011-area-' 'classifications/index.html>`_ or `here ' '<http://www.opengeodemographics.com>`_ for further ' 'information regarding the 2011 OAC. ', extra={'categories': gen_cats(self.grp_mapping)}, tags=[uk, segments, segmentation, license, source], )), ('subgrp', OBSColumn( type='Text', weight=5, name='Subgroup Area Classification', description='The 2011 Area Classification for Output Areas ' '(2011 OAC) is a UK geodemographic classification produced as ' 'a collaboration between the Office for National Statistics and ' 'University College London. Visit `here ' '<http://www.ons.gov.uk/ons/guide-method/geography/products/' 'area-classifications/ns-area-classifications/ns-2011-area-' 'classifications/index.html>`_ or `here ' '<http://www.opengeodemographics.com>`_ for further ' 'information regarding the 2011 OAC. ', extra={'categories': gen_cats(self.subgrp_mapping)}, tags=[uk, segments, segmentation, license, source], )), ]) class OutputAreaClassifications(TableTask): def version(self): return 2 def table_timespan(self): return get_timespan('2011') def requires(self): return { 'geom_columns': OutputAreaColumns(), 'segment_columns': OutputAreaClassificationColumns(), 'data': SimplifiedImportOutputAreas(), 'geo': OutputAreas(), } def targets(self): return { self.input()['geo'].obs_table: GEOM_REF, } def columns(self): input_ = self.input() cols = OrderedDict() cols['oa_sa'] = input_['geom_columns']['oa_sa'] cols.update(input_['segment_columns']) return cols def populate(self): session = current_session() oacc = OutputAreaClassificationColumns sprgrp_case = ' '.join([ "WHEN '{}' THEN '{}'".format(c[1], c[0]) for c in list(oacc.sprgrp_mapping.items()) ]) grp_case = ' '.join([ "WHEN '{}' THEN '{}'".format(c[1], c[0]) for c in list(oacc.grp_mapping.items()) ]) subgrp_case = ' '.join([ "WHEN '{}' THEN '{}'".format(c[1], c[0]) for c in list(oacc.subgrp_mapping.items()) ]) session.execute('INSERT INTO {output} ' 'SELECT oa_sa, ' 'CASE sprgrp {sprgrp_case} END sprgrp, ' 'CASE grp {grp_case} END grp, ' 'CASE subgrp {subgrp_case} END subgrp ' 'FROM {input}'.format( output=self.output().table, input=self.input()['data'].table, sprgrp_case=sprgrp_case, grp_case=grp_case, subgrp_case=subgrp_case, )) class CDRCMetaWrapper(MetaWrapper): def tables(self): yield OutputAreaClassifications() yield OutputAreas()
40.23753
688
0.56588
from tasks.base_tasks import (ColumnsTask, TableTask, TagsTask, RepoFileUnzipTask, GeoFile2TempTableTask, MetaWrapper, SimplifiedTempTableTask, RepoFile) from tasks.util import shell, copyfile from tasks.meta import GEOM_REF, OBSColumn, OBSTable, OBSTag, current_session from tasks.tags import SectionTags, SubsectionTags, UnitTags, LicenseTags, BoundaryTags from lib.timespan import get_timespan from collections import OrderedDict import os class OpenDemographicsLicenseTags(TagsTask): def tags(self): return [OBSTag(id='opengeodemographics-license', name='Open Geodemographics license', type='license', description='Free to download and reuse, even for ' 'commercial sector applications. More ' 'information `here <http://www.opengeodemographics.com/index.php#why-section>`_' )] class SourceTags(TagsTask): def version(self): return 1 def tags(self): return[ OBSTag(id='cdrc-source', name='Consumer Data Research Centre', type='source', description='The 2011 Area Classification for Output Areas (2011 OAC) is a UK geodemographic classification produced as a collaboration between the Office for National Statistics and University College London. For further information regarding the 2011 OAC please visit: http://www.ons.gov.uk/ons/guide-method/geography/products/area-classifications/ns-area-classifications/ns-2011-area-classifications/index.html or http://www.opengeodemographics.com. CDRC 2011 OAC Geodata Pack by the ESRC Consumer Data Research Centre; Contains National Statistics data Crown copyright and database right 2015; Contains Ordnance Survey data Crown copyright and database right 2015') ] class DownloadOutputAreas(RepoFileUnzipTask): URL = 'https://data.cdrc.ac.uk/dataset/68771b14-72aa-4ad7-99f3-0b8d1124cb1b/resource/8fff55da-6235-459c-b66d-017577b060d3/download/output-area-classification.zip' def requires(self): return RepoFile(resource_id=self.task_id, version=self.version(), url=self.URL, downloader='cdrc') class ImportOutputAreas(GeoFile2TempTableTask): def requires(self): return DownloadOutputAreas() def input_files(self): return os.path.join(self.input().path, 'Output Area Classification', 'Shapefiles', '2011_OAC.shp') class SimplifiedImportOutputAreas(SimplifiedTempTableTask): def requires(self): return ImportOutputAreas() class OutputAreaColumns(ColumnsTask): def version(self): return 4 def requires(self): return { 'subsections': SubsectionTags(), 'sections': SectionTags(), 'source': SourceTags(), 'license': LicenseTags(), 'boundary': BoundaryTags(), } def columns(self): input_ = self.input() license = input_['license']['uk_ogl'] source = input_['source']['cdrc-source'] boundary_type = input_['boundary'] geom = OBSColumn( type='Geometry', name='Census Output Areas', description='The smallest unit for which census data are published ' 'in the UK. They contain at least 40 households and ' '100 persons, the target size being 125 households. ' 'They were built up from postcode blocks after the ' 'census data were available, with the intention of ' 'standardising population sizes, geographical shape ' 'and social homogeneity (in terms of dwelling types ' 'and housing tenure). The OAs generated in 2001 were ' 'retained as far as possible for the publication of ' 'outputs from the 2011 Census (less than 3% were ' 'changed). -`Wikipedia <https://en.wikipedia.org/' 'wiki/ONS_coding_system#Geography_of_the_UK_Census>`_', weight=8, tags=[input_['subsections']['boundary'], input_['sections']['uk'], source, license, boundary_type['cartographic_boundary'], boundary_type['interpolation_boundary']] ) geomref = OBSColumn( type='Text', name='Census Output Area ID', weight=0, targets={geom: GEOM_REF} ) return OrderedDict([ ('the_geom', geom), (self.geoname_column(), geomref) ]) @staticmethod def geoname_column(): return 'oa_sa' @staticmethod def geoid_column(): return 'oa_sa' class OutputAreas(TableTask): def requires(self): return { 'geom_columns': OutputAreaColumns(), 'data': SimplifiedImportOutputAreas(), } def version(self): return 9 def table_timespan(self): return get_timespan('2011') def targets(self): return { OBSTable(id='.'.join([self.schema(), self.name()])): GEOM_REF, } def columns(self): input_ = self.input() cols = OrderedDict() cols.update(input_['geom_columns']) return cols def populate(self): session = current_session() session.execute('INSERT INTO {output} ' 'SELECT ST_MakeValid(wkb_geometry), {geoname_column} ' 'FROM {input}'.format( output=self.output().table, input=self.input()['data'].table, geoname_column=self.geoname_column() )) @staticmethod def geoid_column(): return OutputAreaColumns.geoid_column() @staticmethod def geoname_column(): return OutputAreaColumns.geoname_column() class OutputAreaClassificationColumns(ColumnsTask): sprgrp_mapping = OrderedDict([ ('Rural Residents', '1'), ('Cosmopolitans', '2'), ('Ethnicity Central', '3'), ('Multicultural Metropolitans', '4'), ('Urbanites', '5'), ('Suburbanites', '6'), ('Constrained City Dwellers', '7'), ('Hard-Pressed Living', '8'), ]) grp_mapping = OrderedDict([ ('Farming Communities', '1a'), ('Rural Tenants', '1b'), ('Ageing Rural Dwellers', '1c'), ('Students Around Campus', '2a'), ('Inner-City Students', '2b'), ('Comfortable Cosmopolitans', '2c'), ('Aspiring and Affluent', '2d'), ('Ethnic Family Life', '3a'), ('Endeavouring Ethnic Mix', '3b'), ('Ethnic Dynamics', '3c'), ('Aspirational Techies', '3d'), ('Rented Family Living', '4a'), ('Challenged Asian Terraces', '4b'), ('Asian Traits', '4c'), ('Urban Professionals and Families', '5a'), ('Ageing Urban Living', '5b'), ('Suburban Achievers', '6a'), ('Semi-Detached Suburbia', '6b'), ('Challenged Diversity', '7a'), ('Constrained Flat Dwellers', '7b'), ('White Communities', '7c'), ('Ageing City Dwellers', '7d'), ('Industrious Communities', '8a'), ('Challenged Terraced Workers', '8b'), ('Hard-Pressed Ageing Workers', '8c'), ('Migration and Churn', '8d'), ]) subgrp_mapping = OrderedDict([ ('Rural Workers and Families', '1a1'), ('Established Farming Communities', '1a2'), ('Agricultural Communities', '1a3'), ('Older Farming Communities', '1a4'), ('Rural Life', '1b1'), ('Rural White-Collar Workers', '1b2'), ('Ageing Rural Flat Tenants', '1b3'), ('Rural Employment and Retirees', '1c1'), ('Renting Rural Retirement', '1c2'), ('Detached Rural Retirement', '1c3'), ('Student Communal Living', '2a1'), ('Student Digs', '2a2'), ('Students and Professionals', '2a3'), ('Students and Commuters', '2b1'), ('Multicultural Student Neighbourhoods', '2b2'), ('Migrant Families', '2c1'), ('Migrant Commuters', '2c2'), ('Professional Service Cosmopolitans', '2c3'), ('Urban Cultural Mix', '2d1'), ('Highly-Qualified Quaternary Workers', '2d2'), ('EU White-Collar Workers', '2d3'), ('Established Renting Families', '3a1'), ('Young Families and Students', '3a2'), ('Striving Service Workers', '3b1'), ('Bangladeshi Mixed Employment', '3b2'), ('Multi-Ethnic Professional Service Workers', '3b3'), ('Constrained Neighbourhoods', '3c1'), ('Constrained Commuters', '3c2'), ('New EU Tech Workers', '3d1'), ('Established Tech Workers', '3d2'), ('Old EU Tech Workers', '3d3'), ('Social Renting Young Families', '4a1'), ('Private Renting New Arrivals', '4a2'), ('Commuters with Young Families', '4a3'), ('Asian Terraces and Flats', '4b1'), ('Pakistani Communities', '4b2'), ('Achieving Minorities', '4c1'), ('Multicultural New Arrivals', '4c2'), ('Inner City Ethnic Mix', '4c3'), ('White Professionals', '5a1'), ('Multi-Ethnic Professionals with Families', '5a2'), ('Families in Terraces and Flats', '5a3'), ('Delayed Retirement', '5b1'), ('Communal Retirement', '5b2'), ('Self-Sufficient Retirement', '5b3'), ('Indian Tech Achievers', '6a1'), ('Comfortable Suburbia', '6a2'), ('Detached Retirement Living', '6a3'), ('Ageing in Suburbia', '6a4'), ('Multi-Ethnic Suburbia', '6b1'), ('White Suburban Communities', '6b2'), ('Semi-Detached Ageing', '6b3'), ('Older Workers and Retirement', '6b4'), ('Transitional Eastern European Neighbourhoods', '7a1'), ('Hampered Aspiration', '7a2'), ('Multi-Ethnic Hardship', '7a3'), ('Eastern European Communities', '7b1'), ('Deprived Neighbourhoods', '7b2'), ('Endeavouring Flat Dwellers', '7b3'), ('Challenged Transitionaries', '7c1'), ('Constrained Young Families', '7c2'), ('Outer City Hardship', '7c3'), ('Ageing Communities and Families', '7d1'), ('Retired Independent City Dwellers', '7d2'), ('Retired Communal City Dwellers', '7d3'), ('Retired City Hardship', '7d4'), ('Industrious Transitions', '8a1'), ('Industrious Hardship', '8a2'), ('Deprived Blue-Collar Terraces', '8b1'), ('Hard-Pressed Rented Terraces', '8b2'), ('Ageing Industrious Workers', '8c1'), ('Ageing Rural Industry Workers', '8c2'), ('Renting Hard-Pressed Workers', '8c3'), ('Young Hard-Pressed Families', '8d1'), ('Hard-Pressed Ethnic Mix', '8d2'), ('Hard-Pressed European Settlers', '8d3'), ]) def requires(self): return { 'sections': SectionTags(), 'subsections': SubsectionTags(), 'units': UnitTags(), 'license': OpenDemographicsLicenseTags(), 'source': SourceTags(), } def version(self): return 4 def columns(self): input_ = self.input() uk = input_['sections']['uk'] segments = input_['subsections']['segments'] gen_cats = lambda d: OrderedDict([ (catname, {'description': '', 'details': {}}) for catname in list(d.keys()) ]) segmentation = input_['units']['segmentation'] license = input_['license']['opengeodemographics-license'] source = input_['source']['cdrc-source'] return OrderedDict([ ('sprgrp', OBSColumn( type='Text', weight=1, name='Supergroup Area Classification', description='The 2011 Area Classification for Output Areas ' '(2011 OAC) is a UK geodemographic classification produced as ' 'a collaboration between the Office for National Statistics and ' 'University College London. Visit `here ' '<http://www.ons.gov.uk/ons/guide-method/geography/products/' 'area-classifications/ns-area-classifications/ns-2011-area-' 'classifications/index.html>`_ or `here ' '<http://www.opengeodemographics.com>`_ for further ' 'information regarding the 2011 OAC. ', extra={'categories': gen_cats(self.sprgrp_mapping)}, tags=[uk, segments, segmentation, license, source], )), ('grp', OBSColumn( type='Text', weight=3, name='Group Area Classification', description='The 2011 Area Classification for Output Areas ' '(2011 OAC) is a UK geodemographic classification produced as ' 'a collaboration between the Office for National Statistics and ' 'University College London. Visit `here ' '<http://www.ons.gov.uk/ons/guide-method/geography/products/' 'area-classifications/ns-area-classifications/ns-2011-area-' 'classifications/index.html>`_ or `here ' '<http://www.opengeodemographics.com>`_ for further ' 'information regarding the 2011 OAC. ', extra={'categories': gen_cats(self.grp_mapping)}, tags=[uk, segments, segmentation, license, source], )), ('subgrp', OBSColumn( type='Text', weight=5, name='Subgroup Area Classification', description='The 2011 Area Classification for Output Areas ' '(2011 OAC) is a UK geodemographic classification produced as ' 'a collaboration between the Office for National Statistics and ' 'University College London. Visit `here ' '<http://www.ons.gov.uk/ons/guide-method/geography/products/' 'area-classifications/ns-area-classifications/ns-2011-area-' 'classifications/index.html>`_ or `here ' '<http://www.opengeodemographics.com>`_ for further ' 'information regarding the 2011 OAC. ', extra={'categories': gen_cats(self.subgrp_mapping)}, tags=[uk, segments, segmentation, license, source], )), ]) class OutputAreaClassifications(TableTask): def version(self): return 2 def table_timespan(self): return get_timespan('2011') def requires(self): return { 'geom_columns': OutputAreaColumns(), 'segment_columns': OutputAreaClassificationColumns(), 'data': SimplifiedImportOutputAreas(), 'geo': OutputAreas(), } def targets(self): return { self.input()['geo'].obs_table: GEOM_REF, } def columns(self): input_ = self.input() cols = OrderedDict() cols['oa_sa'] = input_['geom_columns']['oa_sa'] cols.update(input_['segment_columns']) return cols def populate(self): session = current_session() oacc = OutputAreaClassificationColumns sprgrp_case = ' '.join([ "WHEN '{}' THEN '{}'".format(c[1], c[0]) for c in list(oacc.sprgrp_mapping.items()) ]) grp_case = ' '.join([ "WHEN '{}' THEN '{}'".format(c[1], c[0]) for c in list(oacc.grp_mapping.items()) ]) subgrp_case = ' '.join([ "WHEN '{}' THEN '{}'".format(c[1], c[0]) for c in list(oacc.subgrp_mapping.items()) ]) session.execute('INSERT INTO {output} ' 'SELECT oa_sa, ' 'CASE sprgrp {sprgrp_case} END sprgrp, ' 'CASE grp {grp_case} END grp, ' 'CASE subgrp {subgrp_case} END subgrp ' 'FROM {input}'.format( output=self.output().table, input=self.input()['data'].table, sprgrp_case=sprgrp_case, grp_case=grp_case, subgrp_case=subgrp_case, )) class CDRCMetaWrapper(MetaWrapper): def tables(self): yield OutputAreaClassifications() yield OutputAreas()
true
true
1c2cfc9242442269152f6a43cae72f34671bae84
2,493
pyw
Python
pyqt/chap04/connections.pyw
liuyangyang2015/PythonDemo
a72c009a31ff833dd12405bb97e688ae91ceda6c
[ "MIT" ]
null
null
null
pyqt/chap04/connections.pyw
liuyangyang2015/PythonDemo
a72c009a31ff833dd12405bb97e688ae91ceda6c
[ "MIT" ]
null
null
null
pyqt/chap04/connections.pyw
liuyangyang2015/PythonDemo
a72c009a31ff833dd12405bb97e688ae91ceda6c
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 2 of the License, or # version 3 of the License, or (at your option) any later version. It is # provided for educational purposes and is distributed in the hope that # it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See # the GNU General Public License for more details. import functools import sys from PyQt4.QtCore import (Qt, SIGNAL) from PyQt4.QtGui import (QApplication, QDialog, QHBoxLayout, QLabel, QPushButton) class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) button1 = QPushButton("One") button2 = QPushButton("Two") button3 = QPushButton("Three") button4 = QPushButton("Four") button5 = QPushButton("Five") self.label = QLabel("Click a button...") layout = QHBoxLayout() layout.addWidget(button1) layout.addWidget(button2) layout.addWidget(button3) layout.addWidget(button4) layout.addWidget(button5) layout.addStretch() layout.addWidget(self.label) self.setLayout(layout) self.connect(button1, SIGNAL("clicked()"), self.one) self.button2callback = functools.partial(self.anyButton, "Two") self.connect(button2, SIGNAL("clicked()"), self.button2callback) self.button3callback = lambda who="Three": self.anyButton(who) self.connect(button3, SIGNAL("clicked()"), self.button3callback) self.connect(button4, SIGNAL("clicked()"), self.clicked) self.connect(button5, SIGNAL("clicked()"), self.clicked) self.setWindowTitle("Connections") def one(self): self.label.setText("You clicked button 'One'") def anyButton(self, who): self.label.setText("You clicked button '{0}'".format(who)) def clicked(self): button = self.sender() if button is None or not isinstance(button, QPushButton): return self.label.setText("You clicked button '{0}'".format( button.text())) app = QApplication(sys.argv) form = Form() form.show() app.exec_()
33.24
74
0.657441
import functools import sys from PyQt4.QtCore import (Qt, SIGNAL) from PyQt4.QtGui import (QApplication, QDialog, QHBoxLayout, QLabel, QPushButton) class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) button1 = QPushButton("One") button2 = QPushButton("Two") button3 = QPushButton("Three") button4 = QPushButton("Four") button5 = QPushButton("Five") self.label = QLabel("Click a button...") layout = QHBoxLayout() layout.addWidget(button1) layout.addWidget(button2) layout.addWidget(button3) layout.addWidget(button4) layout.addWidget(button5) layout.addStretch() layout.addWidget(self.label) self.setLayout(layout) self.connect(button1, SIGNAL("clicked()"), self.one) self.button2callback = functools.partial(self.anyButton, "Two") self.connect(button2, SIGNAL("clicked()"), self.button2callback) self.button3callback = lambda who="Three": self.anyButton(who) self.connect(button3, SIGNAL("clicked()"), self.button3callback) self.connect(button4, SIGNAL("clicked()"), self.clicked) self.connect(button5, SIGNAL("clicked()"), self.clicked) self.setWindowTitle("Connections") def one(self): self.label.setText("You clicked button 'One'") def anyButton(self, who): self.label.setText("You clicked button '{0}'".format(who)) def clicked(self): button = self.sender() if button is None or not isinstance(button, QPushButton): return self.label.setText("You clicked button '{0}'".format( button.text())) app = QApplication(sys.argv) form = Form() form.show() app.exec_()
true
true
1c2cfcf83bf68feb3e9f4c26b9bb7bfa82a0b0d2
6,849
py
Python
tools/win32spawn.py
rockonedege/rt-thread
4fe6c709d0bfe719bed6c927f0144ba373bbda5a
[ "Apache-2.0" ]
7,482
2015-01-01T09:23:08.000Z
2022-03-31T19:34:05.000Z
tools/win32spawn.py
rockonedege/rt-thread
4fe6c709d0bfe719bed6c927f0144ba373bbda5a
[ "Apache-2.0" ]
2,543
2015-01-09T02:01:34.000Z
2022-03-31T23:10:14.000Z
tools/win32spawn.py
rockonedege/rt-thread
4fe6c709d0bfe719bed6c927f0144ba373bbda5a
[ "Apache-2.0" ]
4,645
2015-01-06T07:05:31.000Z
2022-03-31T18:21:50.000Z
# # File : win32spawn.py # This file is part of RT-Thread RTOS # COPYRIGHT (C) 2006 - 2015, RT-Thread Development Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Change Logs: # Date Author Notes # 2015-01-20 Bernard Add copyright information # import os import threading import sys _PY2 = sys.version_info[0] < 3 if _PY2: import Queue else: import queue as Queue # Windows import import win32file import win32pipe import win32api import win32con import win32security import win32process import win32event class Win32Spawn(object): def __init__(self, cmd, shell=False): self.queue = Queue.Queue() self.is_terminated = False self.wake_up_event = win32event.CreateEvent(None, 0, 0, None) exec_dir = os.getcwd() comspec = os.environ.get("COMSPEC", "cmd.exe") cmd = comspec + ' /c ' + cmd win32event.ResetEvent(self.wake_up_event) currproc = win32api.GetCurrentProcess() sa = win32security.SECURITY_ATTRIBUTES() sa.bInheritHandle = 1 child_stdout_rd, child_stdout_wr = win32pipe.CreatePipe(sa, 0) child_stdout_rd_dup = win32api.DuplicateHandle(currproc, child_stdout_rd, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stdout_rd) child_stderr_rd, child_stderr_wr = win32pipe.CreatePipe(sa, 0) child_stderr_rd_dup = win32api.DuplicateHandle(currproc, child_stderr_rd, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stderr_rd) child_stdin_rd, child_stdin_wr = win32pipe.CreatePipe(sa, 0) child_stdin_wr_dup = win32api.DuplicateHandle(currproc, child_stdin_wr, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stdin_wr) startup_info = win32process.STARTUPINFO() startup_info.hStdInput = child_stdin_rd startup_info.hStdOutput = child_stdout_wr startup_info.hStdError = child_stderr_wr startup_info.dwFlags = win32process.STARTF_USESTDHANDLES cr_flags = 0 cr_flags = win32process.CREATE_NEW_PROCESS_GROUP env = os.environ.copy() self.h_process, h_thread, dw_pid, dw_tid = win32process.CreateProcess(None, cmd, None, None, 1, cr_flags, env, os.path.abspath(exec_dir), startup_info) win32api.CloseHandle(h_thread) win32file.CloseHandle(child_stdin_rd) win32file.CloseHandle(child_stdout_wr) win32file.CloseHandle(child_stderr_wr) self.__child_stdout = child_stdout_rd_dup self.__child_stderr = child_stderr_rd_dup self.__child_stdin = child_stdin_wr_dup self.exit_code = -1 def close(self): win32file.CloseHandle(self.__child_stdout) win32file.CloseHandle(self.__child_stderr) win32file.CloseHandle(self.__child_stdin) win32api.CloseHandle(self.h_process) win32api.CloseHandle(self.wake_up_event) def kill_subprocess(): win32event.SetEvent(self.wake_up_event) def sleep(secs): win32event.ResetEvent(self.wake_up_event) timeout = int(1000 * secs) val = win32event.WaitForSingleObject(self.wake_up_event, timeout) if val == win32event.WAIT_TIMEOUT: return True else: # The wake_up_event must have been signalled return False def get(self, block=True, timeout=None): return self.queue.get(block=block, timeout=timeout) def qsize(self): return self.queue.qsize() def __wait_for_child(self): # kick off threads to read from stdout and stderr of the child process threading.Thread(target=self.__do_read, args=(self.__child_stdout, )).start() threading.Thread(target=self.__do_read, args=(self.__child_stderr, )).start() while True: # block waiting for the process to finish or the interrupt to happen handles = (self.wake_up_event, self.h_process) val = win32event.WaitForMultipleObjects(handles, 0, win32event.INFINITE) if val >= win32event.WAIT_OBJECT_0 and val < win32event.WAIT_OBJECT_0 + len(handles): handle = handles[val - win32event.WAIT_OBJECT_0] if handle == self.wake_up_event: win32api.TerminateProcess(self.h_process, 1) win32event.ResetEvent(self.wake_up_event) return False elif handle == self.h_process: # the process has ended naturally return True else: assert False, "Unknown handle fired" else: assert False, "Unexpected return from WaitForMultipleObjects" # Wait for job to finish. Since this method blocks, it can to be called from another thread. # If the application wants to kill the process, it should call kill_subprocess(). def wait(self): if not self.__wait_for_child(): # it's been killed result = False else: # normal termination self.exit_code = win32process.GetExitCodeProcess(self.h_process) result = self.exit_code == 0 self.close() self.is_terminated = True return result # This method gets called on a worker thread to read from either a stderr # or stdout thread from the child process. def __do_read(self, handle): bytesToRead = 1024 while 1: try: finished = 0 hr, data = win32file.ReadFile(handle, bytesToRead, None) if data: self.queue.put_nowait(data) except win32api.error: finished = 1 if finished: return def start_pipe(self): def worker(pipe): return pipe.wait() thrd = threading.Thread(target=worker, args=(self, )) thrd.start()
36.822581
129
0.644182
import os import threading import sys _PY2 = sys.version_info[0] < 3 if _PY2: import Queue else: import queue as Queue import win32file import win32pipe import win32api import win32con import win32security import win32process import win32event class Win32Spawn(object): def __init__(self, cmd, shell=False): self.queue = Queue.Queue() self.is_terminated = False self.wake_up_event = win32event.CreateEvent(None, 0, 0, None) exec_dir = os.getcwd() comspec = os.environ.get("COMSPEC", "cmd.exe") cmd = comspec + ' /c ' + cmd win32event.ResetEvent(self.wake_up_event) currproc = win32api.GetCurrentProcess() sa = win32security.SECURITY_ATTRIBUTES() sa.bInheritHandle = 1 child_stdout_rd, child_stdout_wr = win32pipe.CreatePipe(sa, 0) child_stdout_rd_dup = win32api.DuplicateHandle(currproc, child_stdout_rd, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stdout_rd) child_stderr_rd, child_stderr_wr = win32pipe.CreatePipe(sa, 0) child_stderr_rd_dup = win32api.DuplicateHandle(currproc, child_stderr_rd, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stderr_rd) child_stdin_rd, child_stdin_wr = win32pipe.CreatePipe(sa, 0) child_stdin_wr_dup = win32api.DuplicateHandle(currproc, child_stdin_wr, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stdin_wr) startup_info = win32process.STARTUPINFO() startup_info.hStdInput = child_stdin_rd startup_info.hStdOutput = child_stdout_wr startup_info.hStdError = child_stderr_wr startup_info.dwFlags = win32process.STARTF_USESTDHANDLES cr_flags = 0 cr_flags = win32process.CREATE_NEW_PROCESS_GROUP env = os.environ.copy() self.h_process, h_thread, dw_pid, dw_tid = win32process.CreateProcess(None, cmd, None, None, 1, cr_flags, env, os.path.abspath(exec_dir), startup_info) win32api.CloseHandle(h_thread) win32file.CloseHandle(child_stdin_rd) win32file.CloseHandle(child_stdout_wr) win32file.CloseHandle(child_stderr_wr) self.__child_stdout = child_stdout_rd_dup self.__child_stderr = child_stderr_rd_dup self.__child_stdin = child_stdin_wr_dup self.exit_code = -1 def close(self): win32file.CloseHandle(self.__child_stdout) win32file.CloseHandle(self.__child_stderr) win32file.CloseHandle(self.__child_stdin) win32api.CloseHandle(self.h_process) win32api.CloseHandle(self.wake_up_event) def kill_subprocess(): win32event.SetEvent(self.wake_up_event) def sleep(secs): win32event.ResetEvent(self.wake_up_event) timeout = int(1000 * secs) val = win32event.WaitForSingleObject(self.wake_up_event, timeout) if val == win32event.WAIT_TIMEOUT: return True else: return False def get(self, block=True, timeout=None): return self.queue.get(block=block, timeout=timeout) def qsize(self): return self.queue.qsize() def __wait_for_child(self): threading.Thread(target=self.__do_read, args=(self.__child_stdout, )).start() threading.Thread(target=self.__do_read, args=(self.__child_stderr, )).start() while True: handles = (self.wake_up_event, self.h_process) val = win32event.WaitForMultipleObjects(handles, 0, win32event.INFINITE) if val >= win32event.WAIT_OBJECT_0 and val < win32event.WAIT_OBJECT_0 + len(handles): handle = handles[val - win32event.WAIT_OBJECT_0] if handle == self.wake_up_event: win32api.TerminateProcess(self.h_process, 1) win32event.ResetEvent(self.wake_up_event) return False elif handle == self.h_process: return True else: assert False, "Unknown handle fired" else: assert False, "Unexpected return from WaitForMultipleObjects" def wait(self): if not self.__wait_for_child(): result = False else: # normal termination self.exit_code = win32process.GetExitCodeProcess(self.h_process) result = self.exit_code == 0 self.close() self.is_terminated = True return result # This method gets called on a worker thread to read from either a stderr # or stdout thread from the child process. def __do_read(self, handle): bytesToRead = 1024 while 1: try: finished = 0 hr, data = win32file.ReadFile(handle, bytesToRead, None) if data: self.queue.put_nowait(data) except win32api.error: finished = 1 if finished: return def start_pipe(self): def worker(pipe): return pipe.wait() thrd = threading.Thread(target=worker, args=(self, )) thrd.start()
true
true
1c2cfd302a926b47ec24637ef7aa8c154993ec38
24,689
py
Python
arim/plot.py
will-jj/arim
fc15efe171a41355090123fcea10406ee75efe31
[ "MIT" ]
14
2019-04-05T13:43:36.000Z
2022-02-01T21:38:19.000Z
arim/plot.py
will-jj/arim
fc15efe171a41355090123fcea10406ee75efe31
[ "MIT" ]
2
2019-04-09T10:38:26.000Z
2019-06-17T16:23:16.000Z
arim/plot.py
will-jj/arim
fc15efe171a41355090123fcea10406ee75efe31
[ "MIT" ]
5
2019-04-04T17:02:20.000Z
2020-09-30T15:36:03.000Z
""" Plotting utilities based on `matplotib <http://matplotlib.org/>`_. Some default values are configurable via the dictionary ``arim.plot.conf``. .. py:data:: conf Dictionary of default values. For some functions, if an argument is not populated, its values will be populated from this dictionary. Example:: # save the figure (independently on conf['savefig]) plot_oyz(data, grid, savefig=True, filename='foo') # do not save the figure independently on conf['savefig]) plot_oyz(data, grid, savefig=False, filename='foo') # save the figure depending only if conf['savefig'] is True plot_oyz(data, grid, filename='foo') .. py:data:: micro_formatter .. py:data:: milli_formatter .. py:data:: mega_formatter Format the labels of an axis in a given unit prefix. Usage:: import matplotlib.pyplot as plt ax = plt.plot(distance_vector, data) ax.xaxis.set_major_formatter(arim.plot.milli_formatter) """ from warnings import warn import logging from matplotlib import ticker from mpl_toolkits import axes_grid1 import matplotlib.pyplot as plt import numpy as np import scipy.signal from . import ut from .exceptions import ArimWarning from . import geometry as g from .config import Config __all__ = [ "micro_formatter", "mega_formatter", "milli_formatter", "plot_bscan", "plot_bscan_pulse_echo", "plot_oxz", "plot_oxz_many", "plot_tfm", "plot_directivity_finite_width_2d", "draw_rays_on_click", "RayPlotter", "conf", "common_dynamic_db_scale", ] logger = logging.getLogger(__name__) micro_formatter = ticker.FuncFormatter(lambda x, pos: "{:.1f}".format(x * 1e6)) micro_formatter.__doc__ = "Format an axis to micro (µ).\nExample: ``ax.xaxis.set_major_formatter(micro_formatter)``" milli_formatter = ticker.FuncFormatter(lambda x, pos: "{:.1f}".format(x * 1e3)) milli_formatter.__doc__ = "Format an axis to milli (m).\nExample: ``ax.xaxis.set_major_formatter(milli_formatter)``" mega_formatter = ticker.FuncFormatter(lambda x, pos: "{:.1f}".format(x * 1e-6)) mega_formatter.__doc__ = "Format an axis to mega (M).\nExample: ``ax.xaxis.set_major_formatter(mega_formatter)``" conf = Config( [ ("savefig", False), # save the figure? ("plot_oxz.figsize", None), ("plot_oxz_many.figsize", None), ] ) def plot_bscan( frame, timetraces_idx, use_dB=True, ax=None, title="B-scan", clim=None, interpolation="none", draw_cbar=True, cmap=None, savefig=None, filename="bscan", ): """Plot Bscan (timetraces vs time) Parameters ---------- frame : Frame timetraces_idx : slice or tuple or ndarray timetraces to use. Any valid numpy array is accepted. use_dB : bool, optional ax : matplotlib axis, optional Where to draw. Default: create a new figure and axis. title : str, optional Title of the image (default: "Bscan") clim : tuple, optional Color limits of the image. interpolation : str, optional Image interpolation type (default: "none") draw_cbar : bool, optional cmap : str, optional savefig : bool, optional Default: use ``conf["savefig"]`` filename : str, optional Default: "bscan" Returns ------- ax : matplotlib axis im : matplotlib image Examples -------- >>> arim.plot.plot_bscan(frame, frame.tx == 0) """ if ax is None: fig, ax = plt.subplots() else: fig = ax.figure if savefig is None: savefig = conf["savefig"] timetraces = frame.timetraces[timetraces_idx] numtimetraces = timetraces.shape[0] if use_dB: timetraces = ut.decibel(timetraces) if clim is None: clim = [-40.0, 0.0] im = ax.imshow( timetraces, extent=[frame.time.start, frame.time.end, 0, numtimetraces - 1], interpolation=interpolation, cmap=cmap, origin="lower", ) ax.set_xlabel("Time (µs)") ax.set_ylabel("TX/RX index") ax.xaxis.set_major_formatter(micro_formatter) ax.xaxis.set_minor_formatter(micro_formatter) # Use element index instead of timetrace index (may be different) tx = frame.tx[timetraces_idx] rx = frame.rx[timetraces_idx] def _y_formatter(i, pos): i = int(i) try: return f"({tx[i]}, {rx[i]})" except IndexError: return "" y_formatter = ticker.FuncFormatter(_y_formatter) ax.yaxis.set_major_formatter(y_formatter) ax.yaxis.set_minor_formatter(y_formatter) if draw_cbar: fig.colorbar(im, ax=ax) if clim is not None: im.set_clim(clim) if title is not None: ax.set_title(title) ax.axis("tight") if savefig: ax.figure.savefig(filename) return ax, im def plot_bscan_pulse_echo( frame, use_dB=True, ax=None, title="B-scan (pulse-echo)", clim=None, interpolation="none", draw_cbar=True, cmap=None, savefig=None, filename="bscan", ): """ Plot a B-scan. Use the pulse-echo timetraces. Parameters ---------- frame use_dB ax title clim interpolation draw_cbar cmap Returns ------- axis, image See Also -------- :func:`plot_bscan` """ pulse_echo = frame.tx == frame.rx elements = frame.tx[pulse_echo] ax, im = plot_bscan( frame, pulse_echo, use_dB=use_dB, ax=ax, title=title, clim=clim, interpolation=interpolation, draw_cbar=draw_cbar, cmap=cmap, savefig=False, # save later filename=filename, ) ax.set_ylabel("Element") # Use element index instead of timetrace index (may be different) def _y_formatter(i, pos): i = int(i) if i >= len(elements): return "" else: return str(elements[i]) y_formatter = ticker.FuncFormatter(_y_formatter) ax.yaxis.set_major_formatter(y_formatter) ax.yaxis.set_minor_formatter(y_formatter) if savefig: ax.figure.savefig(filename) return ax, im def plot_psd( frame, idx="all", to_show="filtered", welch_params=None, ax=None, title="Power spectrum estimation", show_legend=True, savefig=None, filename="psd", ): """ Plot the estimated power spectrum of a timetrace using Welch's method. Parameters ---------- frame : Frame idx : int or slice or list Index or indices of the timetrace to use. If multiple indices are given, the arithmetical mean of all PSDs is plotted. Default: use all to_show welch_params : dict Arguments to pass to ``scipy.signal.welch``. ax : matplotlib.axes.Axes or None title show_legend savefig filename Returns ------- ax : matplotlib.axes.Axes lines : dict """ if ax is None: fig, ax = plt.subplots() else: fig = ax.figure if welch_params is None: welch_params = {} if savefig is None: savefig = conf["savefig"] if isinstance(idx, str) and idx == "all": idx = slice(None) fs = 1 / frame.time.step to_show = to_show.lower() if to_show == "both": show_raw = True show_filtered = True elif to_show == "raw": show_raw = True show_filtered = False elif to_show == "filtered": show_raw = False show_filtered = True else: raise ValueError("Valid values for 'to_show' are: filtered, raw, both") lines = {} if show_raw: x = frame.timetraces_raw[idx].real freq, pxx = scipy.signal.welch(x, fs, **welch_params) if pxx.ndim == 2: pxx = np.mean(pxx, axis=0) line = ax.plot(freq, pxx, label="raw".format(idx=idx)) lines["raw"] = line if show_filtered: x = frame.timetraces[idx].real freq, pxx = scipy.signal.welch(x, fs, **welch_params) if pxx.ndim == 2: pxx = np.mean(pxx, axis=0) line = ax.plot(freq, pxx, label="filtered".format(idx=idx)) lines["filtered"] = line ax.set_xlabel("frequency (MHz)") ax.set_ylabel("power spectrum estimation") ax.xaxis.set_major_formatter(mega_formatter) ax.xaxis.set_minor_formatter(mega_formatter) if title is not None: ax.set_title(title) if show_legend: ax.legend(loc="best") if savefig: fig.savefig(filename) return ax, lines def plot_oxz( data, grid, ax=None, title=None, clim=None, interpolation="none", draw_cbar=True, cmap=None, figsize=None, savefig=None, patches=None, filename=None, scale="linear", ref_db=None, ): """ Plot data in the plane Oxz. Parameters ---------- data : ndarray Shape: 2D matrix ``(grid.numx, grid.numz)`` or 3D matrix ``(grid.numx, 1, grid.numz)`` or 1D matrix ``(grid.numx * grid.numz)`` grid : Grid ax : matplotlib.Axis or None Axis where to plot. title : str or None clim : List[Float] or None interpolation : str or None draw_cbar : boolean cmap figsize : List[Float] or None Default: ``conf['plot_oxz.figsize']`` savefig : boolean or None If True, save the figure. Default: ``conf['savefig']`` patches : List[matplotlib.patches.Patch] or None Patches to draw filename : str or None If True scale : str or None 'linear' or 'db'. Default: 'linear' ref_db : float or None Value for 0 dB. Used only for scale=db. Returns ------- axis image Examples -------- :: grid = arim.geometry.Grid(-5e-3, 5e-3, 0, 0, 0, 15e-3, .1e-3) k = 2 * np.pi / 10e-3 data = (np.cos(grid.x * 2 * k) * np.sin(grid.z * k)) ax, im = aplt.plot_oxz(data, grid) """ if figsize is None: figsize = conf["plot_oxz.figsize"] else: if ax is not None: warn( "figsize is ignored because an axis is provided", ArimWarning, stacklevel=2, ) if savefig is None: savefig = conf["savefig"] if ax is None: fig, ax = plt.subplots(figsize=figsize) else: fig = ax.figure if patches is None: patches = [] valid_shapes = [ (grid.numx, 1, grid.numz), (grid.numx, grid.numz), (grid.numx * grid.numz,), ] if data.shape in valid_shapes: data = data.reshape((grid.numx, grid.numz)) else: msg = "invalid data shape (got {}, expected {} or {} or {})".format( data.shape, *valid_shapes ) raise ValueError(msg) data = np.rot90(data) scale = scale.lower() if scale == "linear": if ref_db is not None: warn("ref_db is ignored for linear plot", ArimWarning, stacklevel=2) elif scale == "db": data = ut.decibel(data, ref_db) else: raise ValueError("invalid scale: {}".format(scale)) image = ax.imshow( data, interpolation=interpolation, origin="lower", extent=(grid.xmin, grid.xmax, grid.zmax, grid.zmin), cmap=cmap, ) if ax.get_xlabel() == "": # avoid overwriting labels ax.set_xlabel("x (mm)") if ax.get_ylabel() == "": ax.set_ylabel("z (mm)") ax.xaxis.set_major_formatter(milli_formatter) ax.xaxis.set_minor_formatter(milli_formatter) ax.yaxis.set_major_formatter(milli_formatter) ax.yaxis.set_minor_formatter(milli_formatter) if draw_cbar: # necessary magic to make the colorbar the same height as the image divider = axes_grid1.make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cax.set_aspect(aspect=20, adjustable="box") fig.colorbar(image, ax=ax, cax=cax) if clim is not None: image.set_clim(clim) if title is not None: ax.set_title(title) for p in patches: ax.add_patch(p) # Like axis('equal') but mitigates https://github.com/matplotlib/matplotlib/issues/11416 # adjustable=box to avoid white space (default in matplotlib 3) ax.axis(aspect=1, adjustable="box") ax.axis([grid.xmin, grid.xmax, grid.zmax, grid.zmin]) if savefig: if filename is None: raise ValueError("filename must be provided when savefig is true") fig.savefig(filename) return ax, image def plot_oxz_many( data_list, grid, nrows, ncols, title_list=None, suptitle=None, draw_colorbar=True, figsize=None, savefig=None, clim=None, filename=None, y_title=1.0, y_suptitle=1.0, axes_pad=0.1, **plot_oxz_kwargs, ): """ Plot many Oxz plots on the same figure. Parameters ---------- data_list : List[ndarray] Data are plotted from top left to bottom right, row per row. grid : Grid nrows : int ncols : int title_list : List[str] or None suptitle : str or None draw_colorbar : boolean Default: True figsize : List[Float] or None Default: ``conf['plot_oxz_many.figsize']`` savefig: boolean Default: ``conf['savefig']`` clim : Color limit. Common for all plots. filename y_title : float Adjust y location of the titles. y_suptitle : float Adjust y location of the titles. axes_pad : float Pad between images in inches plot_oxz_kwargs Returns ------- axes_grid : axes_grid1.ImageGrid im_list """ if savefig is None: savefig = conf["savefig"] if figsize is None: figsize = conf["plot_oxz_many.figsize"] if title_list is None: title_list = [None] * len(data_list) # must use a common clim (otherwise the figure does not make sense) if clim is None: clim = ( min(np.nanmin(x) for x in data_list), max(np.nanmax(x) for x in data_list), ) if draw_colorbar: cbar_mode = "single" else: cbar_mode = None fig = plt.figure(figsize=figsize) axes_grid = axes_grid1.ImageGrid( fig, 111, nrows_ncols=(nrows, ncols), axes_pad=axes_pad, share_all=True, cbar_mode=cbar_mode, ) images = [] for data, title, ax in zip(data_list, title_list, axes_grid): # the current function handles saving fig, drawing the cbar and displaying the title # so we prevent plot_oxz to do it. ax, im = plot_oxz( data, grid, ax=ax, clim=clim, draw_cbar=False, savefig=False, **plot_oxz_kwargs, title=None, ) images.append(im) if title is not None: ax.set_title(title, y=y_title) if suptitle is not None: fig.suptitle(suptitle, y=y_suptitle, size="x-large") if draw_colorbar: cax = axes_grid.cbar_axes[0] fig.colorbar(im, cax=cax) cax.set_aspect(20, adjustable="box") if savefig: if filename is None: raise ValueError("filename must be provided when savefig is true") fig.savefig(filename) return axes_grid, images def plot_tfm(tfm, y=0.0, func_res=None, interpolation="bilinear", **plot_oxz_kwargs): """ Plot a TFM in plane Oxz. Parameters ---------- tfm : BaseTFM y : float interpolation : str Cf matplotlib.pyplot.imshow func_res : function Function to apply on tfm.res before plotting it. Example: ``lambda x: np.abs(x)`` plot_oxz_kwargs : dict Returns ------- ax image See Also -------- :func:`plot_oxz` """ grid = tfm.grid iy = np.argmin(np.abs(grid.y - y)) if tfm.res is None: raise ValueError("No result in this TFM object.") if func_res is None: func_res = lambda x: x data = func_res(tfm.res[:, iy, :]) return plot_oxz(data, grid=grid, interpolation=interpolation, **plot_oxz_kwargs) def plot_directivity_finite_width_2d(element_width, wavelength, ax=None, **kwargs): """ Parameters ---------- element_width wavelength ax : matplotlib.axes._subplots.AxesSubplot kwargs Returns ------- """ if ax is None: fig, ax = plt.subplots() else: fig = ax.figure title = kwargs.get( "title", "Directivity of an element (uniform sources along a straight line)" ) ratio = element_width / wavelength theta = np.linspace(-np.pi / 2, np.pi / 2, 100) directivity = ut.directivity_finite_width_2d(theta, element_width, wavelength) ax.plot( np.rad2deg(theta), directivity, label=r"$a/\lambda = {:.2f}$".format(ratio), **kwargs, ) ax.set_xlabel(r"Polar angle $\theta$ (deg)") ax.set_ylabel("directivity (1)") ax.set_title(title) ax.set_xlim([-90, 90]) ax.set_ylim([0, 1.2]) ax.xaxis.set_major_locator(ticker.MultipleLocator(30.0)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(15.0)) ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.1)) ax.legend() return ax class RayPlotter: def __init__( self, grid, ray, element_index, linestyle="m--", tolerance_distance=1e-3 ): self.grid = grid self.ray = ray self.element_index = element_index self.linestyle = linestyle self._lines = [] self.debug = False self.y = 0 self.tolerance_distance = tolerance_distance def __call__(self, event): logger.debug( "button=%d, x=%d, y=%d, xdata=%f, ydata=%f" % (event.button, event.x, event.y, event.xdata, event.ydata) ) ax = event.canvas.figure.axes[0] if event.button == 1: self.draw_ray(ax, event.xdata, event.ydata) elif event.button == 3: self.clear_rays(ax) if self.debug: print("show_ray_on_clic() finish with no error") def draw_ray(self, ax, x, z): gridpoints = self.grid.to_1d_points() wanted_point = (x, self.y, z) point_index = gridpoints.closest_point(*wanted_point) obtained_point = gridpoints[point_index] distance = g.norm2(*(obtained_point - wanted_point)) if distance > self.tolerance_distance: logger.warning( "The closest grid point is far from what you want (dist: {:.2f} mm)".format( distance * 1000 ) ) legs = self.ray.get_coordinates_one(self.element_index, point_index) line = ax.plot(legs.x, legs.z, self.linestyle) self._lines.extend(line) logger.debug("Draw a ray") ax.figure.canvas.draw_idle() def clear_rays(self, ax): """Clear all rays""" lines_to_clear = [line for line in ax.lines if line in self._lines] for line in lines_to_clear: ax.lines.remove(line) self._lines.remove(line) logger.debug("Clear {} ray(s) on figure".format(len(lines_to_clear))) ax.figure.canvas.draw_idle() def connect(self, ax): """Connect to matplotlib event backend""" ax.figure.canvas.mpl_connect("button_press_event", self) def draw_rays_on_click(grid, ray, element_index, ax=None, linestyle="m--"): """ Dynamic plotting of rays on a plot. Left-click: draw a ray between the probe element and the mouse point. Right-click: clear all rays in the plot. Parameters ---------- grid : Grid ray : Rays element_index : int ax : Axis Matplotlib axis on which to plot. If None: current axis. linestyle : str A valid matplotlib linestyle. Default: 'm--' Returns ------- ray_plotter : RayPlotter """ if ax is None: ax = plt.gca() ray_plotter = RayPlotter( grid=grid, ray=ray, element_index=element_index, linestyle=linestyle ) ray_plotter.connect(ax) return ray_plotter def plot_interfaces( oriented_points_list, ax=None, show_probe=True, show_last=True, show_orientations=False, n_arrows=10, title="Interfaces", savefig=None, filename="interfaces", markers=None, show_legend=True, quiver_kwargs=None, ): """ Plot interfaces on the Oxz plane. Assume the first interface is for the probe and the last is for the grid. Parameters ---------- oriented_points_list : list[OrientedPoints] ax : matplotlib.axis.Axis show_probe : boolean Default True show_last : boolean Default: True. Useful for hiding the grid. show_orientations : boolean Plot arrows for the orientations. Default: False n_arrows : int Number of arrows per interface to plot. title : str or None Title to display. None for no title. savefig : boolean If True, the plot will be saved. Default: ``conf['savefig']``. filename : str Filename of the plot, used if savefig is True. Default: 'interfaces' markers : List[str] Matplotlib markers for each interfaces. Default: '.' for probe, ',k' for the grid, '.' for the rest. show_legend : boolean Default True quiver_kwargs : dict Arguments for displaying the arrows (cf. matplotlib function 'quiver') Returns ------- ax : matplotlib.axis.Axis """ if savefig is None: savefig = conf["savefig"] if ax is None: fig, ax = plt.subplots() else: fig = ax.figure if quiver_kwargs is None: quiver_kwargs = dict(width=0.0003) numinterfaces = len(oriented_points_list) if markers is None: markers = ["."] + ["."] * (numinterfaces - 2) + [",k"] for i, (interface, marker) in enumerate(zip(oriented_points_list, markers)): if i == 0 and not show_probe: continue if i == numinterfaces - 1 and not show_last: continue (line,) = ax.plot( interface.points.x, interface.points.z, marker, label=interface.points.name ) if show_orientations: # arrow every k points k = len(interface.points) // n_arrows if k == 0: k = 1 # import pytest; pytest.set_trace() ax.quiver( interface.points.x[::k], interface.points.z[::k], interface.orientations.x[::k, 2], interface.orientations.z[::k, 2], color=line.get_color(), units="xy", angles="xy", **quiver_kwargs, ) # set labels only if there is none in the axis yet if ax.get_xlabel() == "": ax.set_xlabel("x (mm)") if ax.get_ylabel() == "": ax.set_ylabel("z (mm)") ax.xaxis.set_major_formatter(milli_formatter) ax.yaxis.set_major_formatter(milli_formatter) ax.xaxis.set_minor_formatter(milli_formatter) ax.yaxis.set_minor_formatter(milli_formatter) if title is not None: ax.set_title(title) ylim = ax.get_ylim() if ylim[0] < ylim[1]: ax.invert_yaxis() if show_legend: ax.legend(loc="best") ax.axis("equal") if savefig: fig.savefig(filename) return ax def common_dynamic_db_scale(data_list, area=None, db_range=40.0, ref_db=None): """ Scale such as: - 0 dB corresponds to the maximum value in the area for all data arrays, - the clim for each data array are bound by the maximum value in the area. Parameters ---------- data_list db_range : float Yields ------ ref_db (clim_min, clim_max) Examples -------- >>> area = grid.points_in_rectbox(xmin=10, xmax=20) >>> common_db_scale_iter = common_dynamic_db_scale(data_list, area) >>> for data in data_list: ... ref_db, clim = next(common_db_scale_iter) ... plot_oxz(data, grid, scale='db', ref_db=ref_db, clim=clim) """ data_max_list = [] if area is None: area = slice(None) for data in data_list: data_max_list.append(np.nanmax(np.abs(data[area]))) if ref_db is None: ref_db = max(data_max_list) data_max_db_list = ut.decibel(data_max_list, ref_db) for data_max_db in data_max_db_list: yield ref_db, (data_max_db - db_range, data_max_db)
26.292865
116
0.600348
from warnings import warn import logging from matplotlib import ticker from mpl_toolkits import axes_grid1 import matplotlib.pyplot as plt import numpy as np import scipy.signal from . import ut from .exceptions import ArimWarning from . import geometry as g from .config import Config __all__ = [ "micro_formatter", "mega_formatter", "milli_formatter", "plot_bscan", "plot_bscan_pulse_echo", "plot_oxz", "plot_oxz_many", "plot_tfm", "plot_directivity_finite_width_2d", "draw_rays_on_click", "RayPlotter", "conf", "common_dynamic_db_scale", ] logger = logging.getLogger(__name__) micro_formatter = ticker.FuncFormatter(lambda x, pos: "{:.1f}".format(x * 1e6)) micro_formatter.__doc__ = "Format an axis to micro (µ).\nExample: ``ax.xaxis.set_major_formatter(micro_formatter)``" milli_formatter = ticker.FuncFormatter(lambda x, pos: "{:.1f}".format(x * 1e3)) milli_formatter.__doc__ = "Format an axis to milli (m).\nExample: ``ax.xaxis.set_major_formatter(milli_formatter)``" mega_formatter = ticker.FuncFormatter(lambda x, pos: "{:.1f}".format(x * 1e-6)) mega_formatter.__doc__ = "Format an axis to mega (M).\nExample: ``ax.xaxis.set_major_formatter(mega_formatter)``" conf = Config( [ ("savefig", False), ("plot_oxz.figsize", None), ("plot_oxz_many.figsize", None), ] ) def plot_bscan( frame, timetraces_idx, use_dB=True, ax=None, title="B-scan", clim=None, interpolation="none", draw_cbar=True, cmap=None, savefig=None, filename="bscan", ): if ax is None: fig, ax = plt.subplots() else: fig = ax.figure if savefig is None: savefig = conf["savefig"] timetraces = frame.timetraces[timetraces_idx] numtimetraces = timetraces.shape[0] if use_dB: timetraces = ut.decibel(timetraces) if clim is None: clim = [-40.0, 0.0] im = ax.imshow( timetraces, extent=[frame.time.start, frame.time.end, 0, numtimetraces - 1], interpolation=interpolation, cmap=cmap, origin="lower", ) ax.set_xlabel("Time (µs)") ax.set_ylabel("TX/RX index") ax.xaxis.set_major_formatter(micro_formatter) ax.xaxis.set_minor_formatter(micro_formatter) tx = frame.tx[timetraces_idx] rx = frame.rx[timetraces_idx] def _y_formatter(i, pos): i = int(i) try: return f"({tx[i]}, {rx[i]})" except IndexError: return "" y_formatter = ticker.FuncFormatter(_y_formatter) ax.yaxis.set_major_formatter(y_formatter) ax.yaxis.set_minor_formatter(y_formatter) if draw_cbar: fig.colorbar(im, ax=ax) if clim is not None: im.set_clim(clim) if title is not None: ax.set_title(title) ax.axis("tight") if savefig: ax.figure.savefig(filename) return ax, im def plot_bscan_pulse_echo( frame, use_dB=True, ax=None, title="B-scan (pulse-echo)", clim=None, interpolation="none", draw_cbar=True, cmap=None, savefig=None, filename="bscan", ): pulse_echo = frame.tx == frame.rx elements = frame.tx[pulse_echo] ax, im = plot_bscan( frame, pulse_echo, use_dB=use_dB, ax=ax, title=title, clim=clim, interpolation=interpolation, draw_cbar=draw_cbar, cmap=cmap, savefig=False, filename=filename, ) ax.set_ylabel("Element") def _y_formatter(i, pos): i = int(i) if i >= len(elements): return "" else: return str(elements[i]) y_formatter = ticker.FuncFormatter(_y_formatter) ax.yaxis.set_major_formatter(y_formatter) ax.yaxis.set_minor_formatter(y_formatter) if savefig: ax.figure.savefig(filename) return ax, im def plot_psd( frame, idx="all", to_show="filtered", welch_params=None, ax=None, title="Power spectrum estimation", show_legend=True, savefig=None, filename="psd", ): if ax is None: fig, ax = plt.subplots() else: fig = ax.figure if welch_params is None: welch_params = {} if savefig is None: savefig = conf["savefig"] if isinstance(idx, str) and idx == "all": idx = slice(None) fs = 1 / frame.time.step to_show = to_show.lower() if to_show == "both": show_raw = True show_filtered = True elif to_show == "raw": show_raw = True show_filtered = False elif to_show == "filtered": show_raw = False show_filtered = True else: raise ValueError("Valid values for 'to_show' are: filtered, raw, both") lines = {} if show_raw: x = frame.timetraces_raw[idx].real freq, pxx = scipy.signal.welch(x, fs, **welch_params) if pxx.ndim == 2: pxx = np.mean(pxx, axis=0) line = ax.plot(freq, pxx, label="raw".format(idx=idx)) lines["raw"] = line if show_filtered: x = frame.timetraces[idx].real freq, pxx = scipy.signal.welch(x, fs, **welch_params) if pxx.ndim == 2: pxx = np.mean(pxx, axis=0) line = ax.plot(freq, pxx, label="filtered".format(idx=idx)) lines["filtered"] = line ax.set_xlabel("frequency (MHz)") ax.set_ylabel("power spectrum estimation") ax.xaxis.set_major_formatter(mega_formatter) ax.xaxis.set_minor_formatter(mega_formatter) if title is not None: ax.set_title(title) if show_legend: ax.legend(loc="best") if savefig: fig.savefig(filename) return ax, lines def plot_oxz( data, grid, ax=None, title=None, clim=None, interpolation="none", draw_cbar=True, cmap=None, figsize=None, savefig=None, patches=None, filename=None, scale="linear", ref_db=None, ): if figsize is None: figsize = conf["plot_oxz.figsize"] else: if ax is not None: warn( "figsize is ignored because an axis is provided", ArimWarning, stacklevel=2, ) if savefig is None: savefig = conf["savefig"] if ax is None: fig, ax = plt.subplots(figsize=figsize) else: fig = ax.figure if patches is None: patches = [] valid_shapes = [ (grid.numx, 1, grid.numz), (grid.numx, grid.numz), (grid.numx * grid.numz,), ] if data.shape in valid_shapes: data = data.reshape((grid.numx, grid.numz)) else: msg = "invalid data shape (got {}, expected {} or {} or {})".format( data.shape, *valid_shapes ) raise ValueError(msg) data = np.rot90(data) scale = scale.lower() if scale == "linear": if ref_db is not None: warn("ref_db is ignored for linear plot", ArimWarning, stacklevel=2) elif scale == "db": data = ut.decibel(data, ref_db) else: raise ValueError("invalid scale: {}".format(scale)) image = ax.imshow( data, interpolation=interpolation, origin="lower", extent=(grid.xmin, grid.xmax, grid.zmax, grid.zmin), cmap=cmap, ) if ax.get_xlabel() == "": ax.set_xlabel("x (mm)") if ax.get_ylabel() == "": ax.set_ylabel("z (mm)") ax.xaxis.set_major_formatter(milli_formatter) ax.xaxis.set_minor_formatter(milli_formatter) ax.yaxis.set_major_formatter(milli_formatter) ax.yaxis.set_minor_formatter(milli_formatter) if draw_cbar: divider = axes_grid1.make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cax.set_aspect(aspect=20, adjustable="box") fig.colorbar(image, ax=ax, cax=cax) if clim is not None: image.set_clim(clim) if title is not None: ax.set_title(title) for p in patches: ax.add_patch(p) ax.axis(aspect=1, adjustable="box") ax.axis([grid.xmin, grid.xmax, grid.zmax, grid.zmin]) if savefig: if filename is None: raise ValueError("filename must be provided when savefig is true") fig.savefig(filename) return ax, image def plot_oxz_many( data_list, grid, nrows, ncols, title_list=None, suptitle=None, draw_colorbar=True, figsize=None, savefig=None, clim=None, filename=None, y_title=1.0, y_suptitle=1.0, axes_pad=0.1, **plot_oxz_kwargs, ): if savefig is None: savefig = conf["savefig"] if figsize is None: figsize = conf["plot_oxz_many.figsize"] if title_list is None: title_list = [None] * len(data_list) if clim is None: clim = ( min(np.nanmin(x) for x in data_list), max(np.nanmax(x) for x in data_list), ) if draw_colorbar: cbar_mode = "single" else: cbar_mode = None fig = plt.figure(figsize=figsize) axes_grid = axes_grid1.ImageGrid( fig, 111, nrows_ncols=(nrows, ncols), axes_pad=axes_pad, share_all=True, cbar_mode=cbar_mode, ) images = [] for data, title, ax in zip(data_list, title_list, axes_grid): ax, im = plot_oxz( data, grid, ax=ax, clim=clim, draw_cbar=False, savefig=False, **plot_oxz_kwargs, title=None, ) images.append(im) if title is not None: ax.set_title(title, y=y_title) if suptitle is not None: fig.suptitle(suptitle, y=y_suptitle, size="x-large") if draw_colorbar: cax = axes_grid.cbar_axes[0] fig.colorbar(im, cax=cax) cax.set_aspect(20, adjustable="box") if savefig: if filename is None: raise ValueError("filename must be provided when savefig is true") fig.savefig(filename) return axes_grid, images def plot_tfm(tfm, y=0.0, func_res=None, interpolation="bilinear", **plot_oxz_kwargs): grid = tfm.grid iy = np.argmin(np.abs(grid.y - y)) if tfm.res is None: raise ValueError("No result in this TFM object.") if func_res is None: func_res = lambda x: x data = func_res(tfm.res[:, iy, :]) return plot_oxz(data, grid=grid, interpolation=interpolation, **plot_oxz_kwargs) def plot_directivity_finite_width_2d(element_width, wavelength, ax=None, **kwargs): if ax is None: fig, ax = plt.subplots() else: fig = ax.figure title = kwargs.get( "title", "Directivity of an element (uniform sources along a straight line)" ) ratio = element_width / wavelength theta = np.linspace(-np.pi / 2, np.pi / 2, 100) directivity = ut.directivity_finite_width_2d(theta, element_width, wavelength) ax.plot( np.rad2deg(theta), directivity, label=r"$a/\lambda = {:.2f}$".format(ratio), **kwargs, ) ax.set_xlabel(r"Polar angle $\theta$ (deg)") ax.set_ylabel("directivity (1)") ax.set_title(title) ax.set_xlim([-90, 90]) ax.set_ylim([0, 1.2]) ax.xaxis.set_major_locator(ticker.MultipleLocator(30.0)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(15.0)) ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.1)) ax.legend() return ax class RayPlotter: def __init__( self, grid, ray, element_index, linestyle="m--", tolerance_distance=1e-3 ): self.grid = grid self.ray = ray self.element_index = element_index self.linestyle = linestyle self._lines = [] self.debug = False self.y = 0 self.tolerance_distance = tolerance_distance def __call__(self, event): logger.debug( "button=%d, x=%d, y=%d, xdata=%f, ydata=%f" % (event.button, event.x, event.y, event.xdata, event.ydata) ) ax = event.canvas.figure.axes[0] if event.button == 1: self.draw_ray(ax, event.xdata, event.ydata) elif event.button == 3: self.clear_rays(ax) if self.debug: print("show_ray_on_clic() finish with no error") def draw_ray(self, ax, x, z): gridpoints = self.grid.to_1d_points() wanted_point = (x, self.y, z) point_index = gridpoints.closest_point(*wanted_point) obtained_point = gridpoints[point_index] distance = g.norm2(*(obtained_point - wanted_point)) if distance > self.tolerance_distance: logger.warning( "The closest grid point is far from what you want (dist: {:.2f} mm)".format( distance * 1000 ) ) legs = self.ray.get_coordinates_one(self.element_index, point_index) line = ax.plot(legs.x, legs.z, self.linestyle) self._lines.extend(line) logger.debug("Draw a ray") ax.figure.canvas.draw_idle() def clear_rays(self, ax): lines_to_clear = [line for line in ax.lines if line in self._lines] for line in lines_to_clear: ax.lines.remove(line) self._lines.remove(line) logger.debug("Clear {} ray(s) on figure".format(len(lines_to_clear))) ax.figure.canvas.draw_idle() def connect(self, ax): ax.figure.canvas.mpl_connect("button_press_event", self) def draw_rays_on_click(grid, ray, element_index, ax=None, linestyle="m--"): if ax is None: ax = plt.gca() ray_plotter = RayPlotter( grid=grid, ray=ray, element_index=element_index, linestyle=linestyle ) ray_plotter.connect(ax) return ray_plotter def plot_interfaces( oriented_points_list, ax=None, show_probe=True, show_last=True, show_orientations=False, n_arrows=10, title="Interfaces", savefig=None, filename="interfaces", markers=None, show_legend=True, quiver_kwargs=None, ): if savefig is None: savefig = conf["savefig"] if ax is None: fig, ax = plt.subplots() else: fig = ax.figure if quiver_kwargs is None: quiver_kwargs = dict(width=0.0003) numinterfaces = len(oriented_points_list) if markers is None: markers = ["."] + ["."] * (numinterfaces - 2) + [",k"] for i, (interface, marker) in enumerate(zip(oriented_points_list, markers)): if i == 0 and not show_probe: continue if i == numinterfaces - 1 and not show_last: continue (line,) = ax.plot( interface.points.x, interface.points.z, marker, label=interface.points.name ) if show_orientations: k = len(interface.points) // n_arrows if k == 0: k = 1 ax.quiver( interface.points.x[::k], interface.points.z[::k], interface.orientations.x[::k, 2], interface.orientations.z[::k, 2], color=line.get_color(), units="xy", angles="xy", **quiver_kwargs, ) if ax.get_xlabel() == "": ax.set_xlabel("x (mm)") if ax.get_ylabel() == "": ax.set_ylabel("z (mm)") ax.xaxis.set_major_formatter(milli_formatter) ax.yaxis.set_major_formatter(milli_formatter) ax.xaxis.set_minor_formatter(milli_formatter) ax.yaxis.set_minor_formatter(milli_formatter) if title is not None: ax.set_title(title) ylim = ax.get_ylim() if ylim[0] < ylim[1]: ax.invert_yaxis() if show_legend: ax.legend(loc="best") ax.axis("equal") if savefig: fig.savefig(filename) return ax def common_dynamic_db_scale(data_list, area=None, db_range=40.0, ref_db=None): data_max_list = [] if area is None: area = slice(None) for data in data_list: data_max_list.append(np.nanmax(np.abs(data[area]))) if ref_db is None: ref_db = max(data_max_list) data_max_db_list = ut.decibel(data_max_list, ref_db) for data_max_db in data_max_db_list: yield ref_db, (data_max_db - db_range, data_max_db)
true
true
1c2cfdef260371d2f04c95b5d6fd301a62493e68
1,149
py
Python
commserver/setup.py
ErathosthemesAmmoro/track-communities
7afd60aaa62ed0b81c7f785974ea0a8687ea136e
[ "Apache-2.0" ]
12
2015-02-02T13:13:52.000Z
2022-03-16T12:35:32.000Z
commserver/setup.py
ErathosthemesAmmoro/track-communities
7afd60aaa62ed0b81c7f785974ea0a8687ea136e
[ "Apache-2.0" ]
null
null
null
commserver/setup.py
ErathosthemesAmmoro/track-communities
7afd60aaa62ed0b81c7f785974ea0a8687ea136e
[ "Apache-2.0" ]
3
2015-10-05T00:27:38.000Z
2020-03-02T17:51:39.000Z
# # Copyright 2016 Sotera Defense Solutions Inc. # # Licensed under the Apache License, Version 2.0 (the "License”); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from setuptools import setup, find_packages setup( name='commserver', version='0.1', description='Simple Server linking Louvain Modularity Output with Aggregate Micropathing Output', long_description='Simple Server linking Louvain Modularity Output with Aggregate Micropathing Output', author='Justin Gawrilow', author_email='justin.gawrilow@soteradefense.com', url='', packages=find_packages(), scripts = ['go.py'], keywords='louvain', install_requires=[ 'bottle', 'impyla' ], license='Apache License, Version 2.0' )
32.828571
104
0.750218
# 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 setuptools import setup, find_packages setup( name='commserver', version='0.1', description='Simple Server linking Louvain Modularity Output with Aggregate Micropathing Output', long_description='Simple Server linking Louvain Modularity Output with Aggregate Micropathing Output', author='Justin Gawrilow', author_email='justin.gawrilow@soteradefense.com', url='', packages=find_packages(), scripts = ['go.py'], keywords='louvain', install_requires=[ 'bottle', 'impyla' ], license='Apache License, Version 2.0' )
true
true
1c2cfe6635d76e5fb69b8e012ff32daa23046125
567
py
Python
estoque/migrations/0003_auto_20190619_1852.py
Felipebros/mini_curso_django
965dd5e8837db9dea4485e889c2b8703fb5e902d
[ "MIT" ]
8
2019-06-18T20:20:39.000Z
2019-11-09T20:21:06.000Z
estoque/migrations/0003_auto_20190619_1852.py
Felipebros/mini_curso_django
965dd5e8837db9dea4485e889c2b8703fb5e902d
[ "MIT" ]
8
2019-12-04T23:26:42.000Z
2022-02-10T12:02:19.000Z
estoque/migrations/0003_auto_20190619_1852.py
Felipebros/mini_curso_django
965dd5e8837db9dea4485e889c2b8703fb5e902d
[ "MIT" ]
3
2019-06-21T22:37:32.000Z
2019-10-31T00:38:45.000Z
# Generated by Django 2.2.2 on 2019-06-19 21:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('estoque', '0002_auto_20190619_1735'), ] operations = [ migrations.AlterField( model_name='estoque', name='tipo_movimentacao', field=models.CharField(choices=[('ENTRADA', 'Entrada'), ('SAIDA', 'Saída'), ('VENDA_EFETUADA', 'Venda Efetuada'), ('VENDA_CANCELADA', 'Venda Cancelada')], max_length=10, verbose_name='Tipo de Movimentação'), ), ]
29.842105
219
0.634921
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('estoque', '0002_auto_20190619_1735'), ] operations = [ migrations.AlterField( model_name='estoque', name='tipo_movimentacao', field=models.CharField(choices=[('ENTRADA', 'Entrada'), ('SAIDA', 'Saída'), ('VENDA_EFETUADA', 'Venda Efetuada'), ('VENDA_CANCELADA', 'Venda Cancelada')], max_length=10, verbose_name='Tipo de Movimentação'), ), ]
true
true
1c2cfe6f65b98c8add69de13446ed21f91e4e0cb
23,312
py
Python
families/block_info/sawtooth_block_info/protobuf/state_context_pb2.py
shmup/sawtooth-core
301655857205f677b0f9383812aaefecd27cc048
[ "Apache-2.0" ]
1
2021-06-09T19:25:41.000Z
2021-06-09T19:25:41.000Z
families/block_info/sawtooth_block_info/protobuf/state_context_pb2.py
shmup/sawtooth-core
301655857205f677b0f9383812aaefecd27cc048
[ "Apache-2.0" ]
null
null
null
families/block_info/sawtooth_block_info/protobuf/state_context_pb2.py
shmup/sawtooth-core
301655857205f677b0f9383812aaefecd27cc048
[ "Apache-2.0" ]
null
null
null
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: sawtooth_block_info/protobuf/state_context.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from sawtooth_block_info.protobuf import events_pb2 as sawtooth__block__info_dot_protobuf_dot_events__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='sawtooth_block_info/protobuf/state_context.proto', package='', syntax='proto3', serialized_pb=_b('\n0sawtooth_block_info/protobuf/state_context.proto\x1a)sawtooth_block_info/protobuf/events.proto\"-\n\x0cTpStateEntry\x12\x0f\n\x07\x61\x64\x64ress\x18\x01 \x01(\t\x12\x0c\n\x04\x64\x61ta\x18\x02 \x01(\x0c\":\n\x11TpStateGetRequest\x12\x12\n\ncontext_id\x18\x01 \x01(\t\x12\x11\n\taddresses\x18\x02 \x03(\t\"\x9d\x01\n\x12TpStateGetResponse\x12\x1e\n\x07\x65ntries\x18\x01 \x03(\x0b\x32\r.TpStateEntry\x12*\n\x06status\x18\x02 \x01(\x0e\x32\x1a.TpStateGetResponse.Status\";\n\x06Status\x12\x10\n\x0cSTATUS_UNSET\x10\x00\x12\x06\n\x02OK\x10\x01\x12\x17\n\x13\x41UTHORIZATION_ERROR\x10\x02\"G\n\x11TpStateSetRequest\x12\x12\n\ncontext_id\x18\x01 \x01(\t\x12\x1e\n\x07\x65ntries\x18\x02 \x03(\x0b\x32\r.TpStateEntry\"\x90\x01\n\x12TpStateSetResponse\x12\x11\n\taddresses\x18\x01 \x03(\t\x12*\n\x06status\x18\x02 \x01(\x0e\x32\x1a.TpStateSetResponse.Status\";\n\x06Status\x12\x10\n\x0cSTATUS_UNSET\x10\x00\x12\x06\n\x02OK\x10\x01\x12\x17\n\x13\x41UTHORIZATION_ERROR\x10\x02\"=\n\x14TpStateDeleteRequest\x12\x12\n\ncontext_id\x18\x01 \x01(\t\x12\x11\n\taddresses\x18\x02 \x03(\t\"\x96\x01\n\x15TpStateDeleteResponse\x12\x11\n\taddresses\x18\x01 \x03(\t\x12-\n\x06status\x18\x02 \x01(\x0e\x32\x1d.TpStateDeleteResponse.Status\";\n\x06Status\x12\x10\n\x0cSTATUS_UNSET\x10\x00\x12\x06\n\x02OK\x10\x01\x12\x17\n\x13\x41UTHORIZATION_ERROR\x10\x02\";\n\x17TpReceiptAddDataRequest\x12\x12\n\ncontext_id\x18\x01 \x01(\t\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\"{\n\x18TpReceiptAddDataResponse\x12\x30\n\x06status\x18\x02 \x01(\x0e\x32 .TpReceiptAddDataResponse.Status\"-\n\x06Status\x12\x10\n\x0cSTATUS_UNSET\x10\x00\x12\x06\n\x02OK\x10\x01\x12\t\n\x05\x45RROR\x10\x02\">\n\x11TpEventAddRequest\x12\x12\n\ncontext_id\x18\x01 \x01(\t\x12\x15\n\x05\x65vent\x18\x02 \x01(\x0b\x32\x06.Event\"o\n\x12TpEventAddResponse\x12*\n\x06status\x18\x02 \x01(\x0e\x32\x1a.TpEventAddResponse.Status\"-\n\x06Status\x12\x10\n\x0cSTATUS_UNSET\x10\x00\x12\x06\n\x02OK\x10\x01\x12\t\n\x05\x45RROR\x10\x02\x42,\n\x15sawtooth.sdk.protobufP\x01Z\x11state_context_pb2b\x06proto3') , dependencies=[sawtooth__block__info_dot_protobuf_dot_events__pb2.DESCRIPTOR,]) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _TPSTATEGETRESPONSE_STATUS = _descriptor.EnumDescriptor( name='Status', full_name='TpStateGetResponse.Status', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='STATUS_UNSET', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='OK', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='AUTHORIZATION_ERROR', index=2, number=2, options=None, type=None), ], containing_type=None, options=None, serialized_start=301, serialized_end=360, ) _sym_db.RegisterEnumDescriptor(_TPSTATEGETRESPONSE_STATUS) _TPSTATESETRESPONSE_STATUS = _descriptor.EnumDescriptor( name='Status', full_name='TpStateSetResponse.Status', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='STATUS_UNSET', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='OK', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='AUTHORIZATION_ERROR', index=2, number=2, options=None, type=None), ], containing_type=None, options=None, serialized_start=301, serialized_end=360, ) _sym_db.RegisterEnumDescriptor(_TPSTATESETRESPONSE_STATUS) _TPSTATEDELETERESPONSE_STATUS = _descriptor.EnumDescriptor( name='Status', full_name='TpStateDeleteResponse.Status', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='STATUS_UNSET', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='OK', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='AUTHORIZATION_ERROR', index=2, number=2, options=None, type=None), ], containing_type=None, options=None, serialized_start=301, serialized_end=360, ) _sym_db.RegisterEnumDescriptor(_TPSTATEDELETERESPONSE_STATUS) _TPRECEIPTADDDATARESPONSE_STATUS = _descriptor.EnumDescriptor( name='Status', full_name='TpReceiptAddDataResponse.Status', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='STATUS_UNSET', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='OK', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='ERROR', index=2, number=2, options=None, type=None), ], containing_type=None, options=None, serialized_start=937, serialized_end=982, ) _sym_db.RegisterEnumDescriptor(_TPRECEIPTADDDATARESPONSE_STATUS) _TPEVENTADDRESPONSE_STATUS = _descriptor.EnumDescriptor( name='Status', full_name='TpEventAddResponse.Status', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='STATUS_UNSET', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='OK', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='ERROR', index=2, number=2, options=None, type=None), ], containing_type=None, options=None, serialized_start=937, serialized_end=982, ) _sym_db.RegisterEnumDescriptor(_TPEVENTADDRESPONSE_STATUS) _TPSTATEENTRY = _descriptor.Descriptor( name='TpStateEntry', full_name='TpStateEntry', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='address', full_name='TpStateEntry.address', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='data', full_name='TpStateEntry.data', index=1, number=2, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=95, serialized_end=140, ) _TPSTATEGETREQUEST = _descriptor.Descriptor( name='TpStateGetRequest', full_name='TpStateGetRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='context_id', full_name='TpStateGetRequest.context_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='addresses', full_name='TpStateGetRequest.addresses', index=1, number=2, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=142, serialized_end=200, ) _TPSTATEGETRESPONSE = _descriptor.Descriptor( name='TpStateGetResponse', full_name='TpStateGetResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='entries', full_name='TpStateGetResponse.entries', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='status', full_name='TpStateGetResponse.status', index=1, number=2, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _TPSTATEGETRESPONSE_STATUS, ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=203, serialized_end=360, ) _TPSTATESETREQUEST = _descriptor.Descriptor( name='TpStateSetRequest', full_name='TpStateSetRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='context_id', full_name='TpStateSetRequest.context_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='entries', full_name='TpStateSetRequest.entries', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=362, serialized_end=433, ) _TPSTATESETRESPONSE = _descriptor.Descriptor( name='TpStateSetResponse', full_name='TpStateSetResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='addresses', full_name='TpStateSetResponse.addresses', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='status', full_name='TpStateSetResponse.status', index=1, number=2, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _TPSTATESETRESPONSE_STATUS, ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=436, serialized_end=580, ) _TPSTATEDELETEREQUEST = _descriptor.Descriptor( name='TpStateDeleteRequest', full_name='TpStateDeleteRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='context_id', full_name='TpStateDeleteRequest.context_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='addresses', full_name='TpStateDeleteRequest.addresses', index=1, number=2, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=582, serialized_end=643, ) _TPSTATEDELETERESPONSE = _descriptor.Descriptor( name='TpStateDeleteResponse', full_name='TpStateDeleteResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='addresses', full_name='TpStateDeleteResponse.addresses', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='status', full_name='TpStateDeleteResponse.status', index=1, number=2, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _TPSTATEDELETERESPONSE_STATUS, ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=646, serialized_end=796, ) _TPRECEIPTADDDATAREQUEST = _descriptor.Descriptor( name='TpReceiptAddDataRequest', full_name='TpReceiptAddDataRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='context_id', full_name='TpReceiptAddDataRequest.context_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='data', full_name='TpReceiptAddDataRequest.data', index=1, number=3, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=798, serialized_end=857, ) _TPRECEIPTADDDATARESPONSE = _descriptor.Descriptor( name='TpReceiptAddDataResponse', full_name='TpReceiptAddDataResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='status', full_name='TpReceiptAddDataResponse.status', index=0, number=2, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _TPRECEIPTADDDATARESPONSE_STATUS, ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=859, serialized_end=982, ) _TPEVENTADDREQUEST = _descriptor.Descriptor( name='TpEventAddRequest', full_name='TpEventAddRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='context_id', full_name='TpEventAddRequest.context_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='event', full_name='TpEventAddRequest.event', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=984, serialized_end=1046, ) _TPEVENTADDRESPONSE = _descriptor.Descriptor( name='TpEventAddResponse', full_name='TpEventAddResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='status', full_name='TpEventAddResponse.status', index=0, number=2, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _TPEVENTADDRESPONSE_STATUS, ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1048, serialized_end=1159, ) _TPSTATEGETRESPONSE.fields_by_name['entries'].message_type = _TPSTATEENTRY _TPSTATEGETRESPONSE.fields_by_name['status'].enum_type = _TPSTATEGETRESPONSE_STATUS _TPSTATEGETRESPONSE_STATUS.containing_type = _TPSTATEGETRESPONSE _TPSTATESETREQUEST.fields_by_name['entries'].message_type = _TPSTATEENTRY _TPSTATESETRESPONSE.fields_by_name['status'].enum_type = _TPSTATESETRESPONSE_STATUS _TPSTATESETRESPONSE_STATUS.containing_type = _TPSTATESETRESPONSE _TPSTATEDELETERESPONSE.fields_by_name['status'].enum_type = _TPSTATEDELETERESPONSE_STATUS _TPSTATEDELETERESPONSE_STATUS.containing_type = _TPSTATEDELETERESPONSE _TPRECEIPTADDDATARESPONSE.fields_by_name['status'].enum_type = _TPRECEIPTADDDATARESPONSE_STATUS _TPRECEIPTADDDATARESPONSE_STATUS.containing_type = _TPRECEIPTADDDATARESPONSE _TPEVENTADDREQUEST.fields_by_name['event'].message_type = sawtooth__block__info_dot_protobuf_dot_events__pb2._EVENT _TPEVENTADDRESPONSE.fields_by_name['status'].enum_type = _TPEVENTADDRESPONSE_STATUS _TPEVENTADDRESPONSE_STATUS.containing_type = _TPEVENTADDRESPONSE DESCRIPTOR.message_types_by_name['TpStateEntry'] = _TPSTATEENTRY DESCRIPTOR.message_types_by_name['TpStateGetRequest'] = _TPSTATEGETREQUEST DESCRIPTOR.message_types_by_name['TpStateGetResponse'] = _TPSTATEGETRESPONSE DESCRIPTOR.message_types_by_name['TpStateSetRequest'] = _TPSTATESETREQUEST DESCRIPTOR.message_types_by_name['TpStateSetResponse'] = _TPSTATESETRESPONSE DESCRIPTOR.message_types_by_name['TpStateDeleteRequest'] = _TPSTATEDELETEREQUEST DESCRIPTOR.message_types_by_name['TpStateDeleteResponse'] = _TPSTATEDELETERESPONSE DESCRIPTOR.message_types_by_name['TpReceiptAddDataRequest'] = _TPRECEIPTADDDATAREQUEST DESCRIPTOR.message_types_by_name['TpReceiptAddDataResponse'] = _TPRECEIPTADDDATARESPONSE DESCRIPTOR.message_types_by_name['TpEventAddRequest'] = _TPEVENTADDREQUEST DESCRIPTOR.message_types_by_name['TpEventAddResponse'] = _TPEVENTADDRESPONSE TpStateEntry = _reflection.GeneratedProtocolMessageType('TpStateEntry', (_message.Message,), dict( DESCRIPTOR = _TPSTATEENTRY, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' # @@protoc_insertion_point(class_scope:TpStateEntry) )) _sym_db.RegisterMessage(TpStateEntry) TpStateGetRequest = _reflection.GeneratedProtocolMessageType('TpStateGetRequest', (_message.Message,), dict( DESCRIPTOR = _TPSTATEGETREQUEST, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' # @@protoc_insertion_point(class_scope:TpStateGetRequest) )) _sym_db.RegisterMessage(TpStateGetRequest) TpStateGetResponse = _reflection.GeneratedProtocolMessageType('TpStateGetResponse', (_message.Message,), dict( DESCRIPTOR = _TPSTATEGETRESPONSE, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' # @@protoc_insertion_point(class_scope:TpStateGetResponse) )) _sym_db.RegisterMessage(TpStateGetResponse) TpStateSetRequest = _reflection.GeneratedProtocolMessageType('TpStateSetRequest', (_message.Message,), dict( DESCRIPTOR = _TPSTATESETREQUEST, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' # @@protoc_insertion_point(class_scope:TpStateSetRequest) )) _sym_db.RegisterMessage(TpStateSetRequest) TpStateSetResponse = _reflection.GeneratedProtocolMessageType('TpStateSetResponse', (_message.Message,), dict( DESCRIPTOR = _TPSTATESETRESPONSE, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' # @@protoc_insertion_point(class_scope:TpStateSetResponse) )) _sym_db.RegisterMessage(TpStateSetResponse) TpStateDeleteRequest = _reflection.GeneratedProtocolMessageType('TpStateDeleteRequest', (_message.Message,), dict( DESCRIPTOR = _TPSTATEDELETEREQUEST, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' # @@protoc_insertion_point(class_scope:TpStateDeleteRequest) )) _sym_db.RegisterMessage(TpStateDeleteRequest) TpStateDeleteResponse = _reflection.GeneratedProtocolMessageType('TpStateDeleteResponse', (_message.Message,), dict( DESCRIPTOR = _TPSTATEDELETERESPONSE, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' # @@protoc_insertion_point(class_scope:TpStateDeleteResponse) )) _sym_db.RegisterMessage(TpStateDeleteResponse) TpReceiptAddDataRequest = _reflection.GeneratedProtocolMessageType('TpReceiptAddDataRequest', (_message.Message,), dict( DESCRIPTOR = _TPRECEIPTADDDATAREQUEST, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' # @@protoc_insertion_point(class_scope:TpReceiptAddDataRequest) )) _sym_db.RegisterMessage(TpReceiptAddDataRequest) TpReceiptAddDataResponse = _reflection.GeneratedProtocolMessageType('TpReceiptAddDataResponse', (_message.Message,), dict( DESCRIPTOR = _TPRECEIPTADDDATARESPONSE, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' # @@protoc_insertion_point(class_scope:TpReceiptAddDataResponse) )) _sym_db.RegisterMessage(TpReceiptAddDataResponse) TpEventAddRequest = _reflection.GeneratedProtocolMessageType('TpEventAddRequest', (_message.Message,), dict( DESCRIPTOR = _TPEVENTADDREQUEST, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' # @@protoc_insertion_point(class_scope:TpEventAddRequest) )) _sym_db.RegisterMessage(TpEventAddRequest) TpEventAddResponse = _reflection.GeneratedProtocolMessageType('TpEventAddResponse', (_message.Message,), dict( DESCRIPTOR = _TPEVENTADDRESPONSE, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' # @@protoc_insertion_point(class_scope:TpEventAddResponse) )) _sym_db.RegisterMessage(TpEventAddResponse) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\025sawtooth.sdk.protobufP\001Z\021state_context_pb2')) # @@protoc_insertion_point(module_scope)
34.536296
2,065
0.754247
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 _sym_db = _symbol_database.Default() from sawtooth_block_info.protobuf import events_pb2 as sawtooth__block__info_dot_protobuf_dot_events__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='sawtooth_block_info/protobuf/state_context.proto', package='', syntax='proto3', serialized_pb=_b('\n0sawtooth_block_info/protobuf/state_context.proto\x1a)sawtooth_block_info/protobuf/events.proto\"-\n\x0cTpStateEntry\x12\x0f\n\x07\x61\x64\x64ress\x18\x01 \x01(\t\x12\x0c\n\x04\x64\x61ta\x18\x02 \x01(\x0c\":\n\x11TpStateGetRequest\x12\x12\n\ncontext_id\x18\x01 \x01(\t\x12\x11\n\taddresses\x18\x02 \x03(\t\"\x9d\x01\n\x12TpStateGetResponse\x12\x1e\n\x07\x65ntries\x18\x01 \x03(\x0b\x32\r.TpStateEntry\x12*\n\x06status\x18\x02 \x01(\x0e\x32\x1a.TpStateGetResponse.Status\";\n\x06Status\x12\x10\n\x0cSTATUS_UNSET\x10\x00\x12\x06\n\x02OK\x10\x01\x12\x17\n\x13\x41UTHORIZATION_ERROR\x10\x02\"G\n\x11TpStateSetRequest\x12\x12\n\ncontext_id\x18\x01 \x01(\t\x12\x1e\n\x07\x65ntries\x18\x02 \x03(\x0b\x32\r.TpStateEntry\"\x90\x01\n\x12TpStateSetResponse\x12\x11\n\taddresses\x18\x01 \x03(\t\x12*\n\x06status\x18\x02 \x01(\x0e\x32\x1a.TpStateSetResponse.Status\";\n\x06Status\x12\x10\n\x0cSTATUS_UNSET\x10\x00\x12\x06\n\x02OK\x10\x01\x12\x17\n\x13\x41UTHORIZATION_ERROR\x10\x02\"=\n\x14TpStateDeleteRequest\x12\x12\n\ncontext_id\x18\x01 \x01(\t\x12\x11\n\taddresses\x18\x02 \x03(\t\"\x96\x01\n\x15TpStateDeleteResponse\x12\x11\n\taddresses\x18\x01 \x03(\t\x12-\n\x06status\x18\x02 \x01(\x0e\x32\x1d.TpStateDeleteResponse.Status\";\n\x06Status\x12\x10\n\x0cSTATUS_UNSET\x10\x00\x12\x06\n\x02OK\x10\x01\x12\x17\n\x13\x41UTHORIZATION_ERROR\x10\x02\";\n\x17TpReceiptAddDataRequest\x12\x12\n\ncontext_id\x18\x01 \x01(\t\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\"{\n\x18TpReceiptAddDataResponse\x12\x30\n\x06status\x18\x02 \x01(\x0e\x32 .TpReceiptAddDataResponse.Status\"-\n\x06Status\x12\x10\n\x0cSTATUS_UNSET\x10\x00\x12\x06\n\x02OK\x10\x01\x12\t\n\x05\x45RROR\x10\x02\">\n\x11TpEventAddRequest\x12\x12\n\ncontext_id\x18\x01 \x01(\t\x12\x15\n\x05\x65vent\x18\x02 \x01(\x0b\x32\x06.Event\"o\n\x12TpEventAddResponse\x12*\n\x06status\x18\x02 \x01(\x0e\x32\x1a.TpEventAddResponse.Status\"-\n\x06Status\x12\x10\n\x0cSTATUS_UNSET\x10\x00\x12\x06\n\x02OK\x10\x01\x12\t\n\x05\x45RROR\x10\x02\x42,\n\x15sawtooth.sdk.protobufP\x01Z\x11state_context_pb2b\x06proto3') , dependencies=[sawtooth__block__info_dot_protobuf_dot_events__pb2.DESCRIPTOR,]) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _TPSTATEGETRESPONSE_STATUS = _descriptor.EnumDescriptor( name='Status', full_name='TpStateGetResponse.Status', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='STATUS_UNSET', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='OK', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='AUTHORIZATION_ERROR', index=2, number=2, options=None, type=None), ], containing_type=None, options=None, serialized_start=301, serialized_end=360, ) _sym_db.RegisterEnumDescriptor(_TPSTATEGETRESPONSE_STATUS) _TPSTATESETRESPONSE_STATUS = _descriptor.EnumDescriptor( name='Status', full_name='TpStateSetResponse.Status', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='STATUS_UNSET', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='OK', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='AUTHORIZATION_ERROR', index=2, number=2, options=None, type=None), ], containing_type=None, options=None, serialized_start=301, serialized_end=360, ) _sym_db.RegisterEnumDescriptor(_TPSTATESETRESPONSE_STATUS) _TPSTATEDELETERESPONSE_STATUS = _descriptor.EnumDescriptor( name='Status', full_name='TpStateDeleteResponse.Status', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='STATUS_UNSET', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='OK', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='AUTHORIZATION_ERROR', index=2, number=2, options=None, type=None), ], containing_type=None, options=None, serialized_start=301, serialized_end=360, ) _sym_db.RegisterEnumDescriptor(_TPSTATEDELETERESPONSE_STATUS) _TPRECEIPTADDDATARESPONSE_STATUS = _descriptor.EnumDescriptor( name='Status', full_name='TpReceiptAddDataResponse.Status', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='STATUS_UNSET', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='OK', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='ERROR', index=2, number=2, options=None, type=None), ], containing_type=None, options=None, serialized_start=937, serialized_end=982, ) _sym_db.RegisterEnumDescriptor(_TPRECEIPTADDDATARESPONSE_STATUS) _TPEVENTADDRESPONSE_STATUS = _descriptor.EnumDescriptor( name='Status', full_name='TpEventAddResponse.Status', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='STATUS_UNSET', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='OK', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='ERROR', index=2, number=2, options=None, type=None), ], containing_type=None, options=None, serialized_start=937, serialized_end=982, ) _sym_db.RegisterEnumDescriptor(_TPEVENTADDRESPONSE_STATUS) _TPSTATEENTRY = _descriptor.Descriptor( name='TpStateEntry', full_name='TpStateEntry', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='address', full_name='TpStateEntry.address', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='data', full_name='TpStateEntry.data', index=1, number=2, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=95, serialized_end=140, ) _TPSTATEGETREQUEST = _descriptor.Descriptor( name='TpStateGetRequest', full_name='TpStateGetRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='context_id', full_name='TpStateGetRequest.context_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='addresses', full_name='TpStateGetRequest.addresses', index=1, number=2, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=142, serialized_end=200, ) _TPSTATEGETRESPONSE = _descriptor.Descriptor( name='TpStateGetResponse', full_name='TpStateGetResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='entries', full_name='TpStateGetResponse.entries', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='status', full_name='TpStateGetResponse.status', index=1, number=2, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _TPSTATEGETRESPONSE_STATUS, ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=203, serialized_end=360, ) _TPSTATESETREQUEST = _descriptor.Descriptor( name='TpStateSetRequest', full_name='TpStateSetRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='context_id', full_name='TpStateSetRequest.context_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='entries', full_name='TpStateSetRequest.entries', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=362, serialized_end=433, ) _TPSTATESETRESPONSE = _descriptor.Descriptor( name='TpStateSetResponse', full_name='TpStateSetResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='addresses', full_name='TpStateSetResponse.addresses', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='status', full_name='TpStateSetResponse.status', index=1, number=2, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _TPSTATESETRESPONSE_STATUS, ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=436, serialized_end=580, ) _TPSTATEDELETEREQUEST = _descriptor.Descriptor( name='TpStateDeleteRequest', full_name='TpStateDeleteRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='context_id', full_name='TpStateDeleteRequest.context_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='addresses', full_name='TpStateDeleteRequest.addresses', index=1, number=2, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=582, serialized_end=643, ) _TPSTATEDELETERESPONSE = _descriptor.Descriptor( name='TpStateDeleteResponse', full_name='TpStateDeleteResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='addresses', full_name='TpStateDeleteResponse.addresses', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='status', full_name='TpStateDeleteResponse.status', index=1, number=2, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _TPSTATEDELETERESPONSE_STATUS, ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=646, serialized_end=796, ) _TPRECEIPTADDDATAREQUEST = _descriptor.Descriptor( name='TpReceiptAddDataRequest', full_name='TpReceiptAddDataRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='context_id', full_name='TpReceiptAddDataRequest.context_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='data', full_name='TpReceiptAddDataRequest.data', index=1, number=3, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=798, serialized_end=857, ) _TPRECEIPTADDDATARESPONSE = _descriptor.Descriptor( name='TpReceiptAddDataResponse', full_name='TpReceiptAddDataResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='status', full_name='TpReceiptAddDataResponse.status', index=0, number=2, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _TPRECEIPTADDDATARESPONSE_STATUS, ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=859, serialized_end=982, ) _TPEVENTADDREQUEST = _descriptor.Descriptor( name='TpEventAddRequest', full_name='TpEventAddRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='context_id', full_name='TpEventAddRequest.context_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='event', full_name='TpEventAddRequest.event', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=984, serialized_end=1046, ) _TPEVENTADDRESPONSE = _descriptor.Descriptor( name='TpEventAddResponse', full_name='TpEventAddResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='status', full_name='TpEventAddResponse.status', index=0, number=2, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _TPEVENTADDRESPONSE_STATUS, ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1048, serialized_end=1159, ) _TPSTATEGETRESPONSE.fields_by_name['entries'].message_type = _TPSTATEENTRY _TPSTATEGETRESPONSE.fields_by_name['status'].enum_type = _TPSTATEGETRESPONSE_STATUS _TPSTATEGETRESPONSE_STATUS.containing_type = _TPSTATEGETRESPONSE _TPSTATESETREQUEST.fields_by_name['entries'].message_type = _TPSTATEENTRY _TPSTATESETRESPONSE.fields_by_name['status'].enum_type = _TPSTATESETRESPONSE_STATUS _TPSTATESETRESPONSE_STATUS.containing_type = _TPSTATESETRESPONSE _TPSTATEDELETERESPONSE.fields_by_name['status'].enum_type = _TPSTATEDELETERESPONSE_STATUS _TPSTATEDELETERESPONSE_STATUS.containing_type = _TPSTATEDELETERESPONSE _TPRECEIPTADDDATARESPONSE.fields_by_name['status'].enum_type = _TPRECEIPTADDDATARESPONSE_STATUS _TPRECEIPTADDDATARESPONSE_STATUS.containing_type = _TPRECEIPTADDDATARESPONSE _TPEVENTADDREQUEST.fields_by_name['event'].message_type = sawtooth__block__info_dot_protobuf_dot_events__pb2._EVENT _TPEVENTADDRESPONSE.fields_by_name['status'].enum_type = _TPEVENTADDRESPONSE_STATUS _TPEVENTADDRESPONSE_STATUS.containing_type = _TPEVENTADDRESPONSE DESCRIPTOR.message_types_by_name['TpStateEntry'] = _TPSTATEENTRY DESCRIPTOR.message_types_by_name['TpStateGetRequest'] = _TPSTATEGETREQUEST DESCRIPTOR.message_types_by_name['TpStateGetResponse'] = _TPSTATEGETRESPONSE DESCRIPTOR.message_types_by_name['TpStateSetRequest'] = _TPSTATESETREQUEST DESCRIPTOR.message_types_by_name['TpStateSetResponse'] = _TPSTATESETRESPONSE DESCRIPTOR.message_types_by_name['TpStateDeleteRequest'] = _TPSTATEDELETEREQUEST DESCRIPTOR.message_types_by_name['TpStateDeleteResponse'] = _TPSTATEDELETERESPONSE DESCRIPTOR.message_types_by_name['TpReceiptAddDataRequest'] = _TPRECEIPTADDDATAREQUEST DESCRIPTOR.message_types_by_name['TpReceiptAddDataResponse'] = _TPRECEIPTADDDATARESPONSE DESCRIPTOR.message_types_by_name['TpEventAddRequest'] = _TPEVENTADDREQUEST DESCRIPTOR.message_types_by_name['TpEventAddResponse'] = _TPEVENTADDRESPONSE TpStateEntry = _reflection.GeneratedProtocolMessageType('TpStateEntry', (_message.Message,), dict( DESCRIPTOR = _TPSTATEENTRY, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' )) _sym_db.RegisterMessage(TpStateEntry) TpStateGetRequest = _reflection.GeneratedProtocolMessageType('TpStateGetRequest', (_message.Message,), dict( DESCRIPTOR = _TPSTATEGETREQUEST, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' )) _sym_db.RegisterMessage(TpStateGetRequest) TpStateGetResponse = _reflection.GeneratedProtocolMessageType('TpStateGetResponse', (_message.Message,), dict( DESCRIPTOR = _TPSTATEGETRESPONSE, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' )) _sym_db.RegisterMessage(TpStateGetResponse) TpStateSetRequest = _reflection.GeneratedProtocolMessageType('TpStateSetRequest', (_message.Message,), dict( DESCRIPTOR = _TPSTATESETREQUEST, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' )) _sym_db.RegisterMessage(TpStateSetRequest) TpStateSetResponse = _reflection.GeneratedProtocolMessageType('TpStateSetResponse', (_message.Message,), dict( DESCRIPTOR = _TPSTATESETRESPONSE, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' )) _sym_db.RegisterMessage(TpStateSetResponse) TpStateDeleteRequest = _reflection.GeneratedProtocolMessageType('TpStateDeleteRequest', (_message.Message,), dict( DESCRIPTOR = _TPSTATEDELETEREQUEST, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' )) _sym_db.RegisterMessage(TpStateDeleteRequest) TpStateDeleteResponse = _reflection.GeneratedProtocolMessageType('TpStateDeleteResponse', (_message.Message,), dict( DESCRIPTOR = _TPSTATEDELETERESPONSE, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' )) _sym_db.RegisterMessage(TpStateDeleteResponse) TpReceiptAddDataRequest = _reflection.GeneratedProtocolMessageType('TpReceiptAddDataRequest', (_message.Message,), dict( DESCRIPTOR = _TPRECEIPTADDDATAREQUEST, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' )) _sym_db.RegisterMessage(TpReceiptAddDataRequest) TpReceiptAddDataResponse = _reflection.GeneratedProtocolMessageType('TpReceiptAddDataResponse', (_message.Message,), dict( DESCRIPTOR = _TPRECEIPTADDDATARESPONSE, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' )) _sym_db.RegisterMessage(TpReceiptAddDataResponse) TpEventAddRequest = _reflection.GeneratedProtocolMessageType('TpEventAddRequest', (_message.Message,), dict( DESCRIPTOR = _TPEVENTADDREQUEST, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' )) _sym_db.RegisterMessage(TpEventAddRequest) TpEventAddResponse = _reflection.GeneratedProtocolMessageType('TpEventAddResponse', (_message.Message,), dict( DESCRIPTOR = _TPEVENTADDRESPONSE, __module__ = 'sawtooth_block_info.protobuf.state_context_pb2' )) _sym_db.RegisterMessage(TpEventAddResponse) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\025sawtooth.sdk.protobufP\001Z\021state_context_pb2'))
true
true
1c2cfea1595e21192e774b30ce71c1553103954c
3,344
py
Python
src/minecraft/monitor/simple_latency_strategy.py
Cameron-Alberts/MinecraftProcessManager
6ea8b4035fee59ca11f1d8d69df2c6237239d898
[ "MIT" ]
null
null
null
src/minecraft/monitor/simple_latency_strategy.py
Cameron-Alberts/MinecraftProcessManager
6ea8b4035fee59ca11f1d8d69df2c6237239d898
[ "MIT" ]
null
null
null
src/minecraft/monitor/simple_latency_strategy.py
Cameron-Alberts/MinecraftProcessManager
6ea8b4035fee59ca11f1d8d69df2c6237239d898
[ "MIT" ]
null
null
null
import logging as log from .health_monitor_strategy import AbstractHealthMonitorStrategy class SimpleLatencyHealthMonitorStrategy(AbstractHealthMonitorStrategy): def __init__(self, max_latency_in_seconds=1.0, number_of_pings=5, health_checks_queue_size=5, expected_percent_healthy=.75, *args, **kwargs): AbstractHealthMonitorStrategy.__init__(self, *args, **kwargs) if max_latency_in_seconds <= 0.0: raise ValueError("max_latency_in_seconds must be greater than zero!") if number_of_pings <= 0.0: raise ValueError("number_of_pings must be greater than zero!") if health_checks_queue_size <= 0.0: raise ValueError("health_checks_queue_size must be greater than zero!") if expected_percent_healthy <= 0.0 or expected_percent_healthy > 1.0: raise ValueError("expected_percent_healthy should be between (0.0, 1.0]") self.__max_latency = max_latency_in_seconds self.__number_of_pings = number_of_pings self.__health_checks_queue_size = health_checks_queue_size self.__health_checks = [True] * health_checks_queue_size self.__expected_percent_healthy = expected_percent_healthy def health_check(self): ping_responses = [self._minecraft_server.ping() for _ in range(self.__number_of_pings)] health_check = self.__is_successful(ping_responses) and self.__is_latency_healthy(ping_responses) self.__health_checks = [health_check] + self.__health_checks[0:-1] healthy = sum(self.__health_checks) / len(self.__health_checks) >= 0.5 if healthy: log.info("Moving window health checks healthy! health_checks={}".format(self.__health_checks)) else: log.warning("Moving window health checks unhealthy! health_checks={}".format(self.__health_checks)) # Reset health checks, since returning unhealthy will cause the server to bounce self.__health_checks = [True] * self.__health_checks_queue_size return healthy def __is_latency_healthy(self, ping_responses): pings_with_time = list(filter(lambda x: x.time is not None, ping_responses)) if not pings_with_time: log.warning("No pings with a valid time value! pings = {}" .format(' '.join([str(x) for x in ping_responses]))) return False total_latency = sum(x.time for x in pings_with_time) avg_latency = total_latency / len(pings_with_time) healthy = avg_latency < self.__max_latency if not healthy: log.warning("Avg latency = {} millis, expected it to be less than {} millis" .format(avg_latency * 1000, self.__max_latency * 1000)) else: log.info("Healthy avg latency of {} millis".format(avg_latency * 1000)) return healthy @staticmethod def __is_successful(ping_responses): successful = all(x.success for x in ping_responses) if not successful: log.warning("Not all pings were successful, pings={}" .format(' '.join([str(x) for x in ping_responses]))) else: log.info("All pings successful!") return successful
49.176471
111
0.659988
import logging as log from .health_monitor_strategy import AbstractHealthMonitorStrategy class SimpleLatencyHealthMonitorStrategy(AbstractHealthMonitorStrategy): def __init__(self, max_latency_in_seconds=1.0, number_of_pings=5, health_checks_queue_size=5, expected_percent_healthy=.75, *args, **kwargs): AbstractHealthMonitorStrategy.__init__(self, *args, **kwargs) if max_latency_in_seconds <= 0.0: raise ValueError("max_latency_in_seconds must be greater than zero!") if number_of_pings <= 0.0: raise ValueError("number_of_pings must be greater than zero!") if health_checks_queue_size <= 0.0: raise ValueError("health_checks_queue_size must be greater than zero!") if expected_percent_healthy <= 0.0 or expected_percent_healthy > 1.0: raise ValueError("expected_percent_healthy should be between (0.0, 1.0]") self.__max_latency = max_latency_in_seconds self.__number_of_pings = number_of_pings self.__health_checks_queue_size = health_checks_queue_size self.__health_checks = [True] * health_checks_queue_size self.__expected_percent_healthy = expected_percent_healthy def health_check(self): ping_responses = [self._minecraft_server.ping() for _ in range(self.__number_of_pings)] health_check = self.__is_successful(ping_responses) and self.__is_latency_healthy(ping_responses) self.__health_checks = [health_check] + self.__health_checks[0:-1] healthy = sum(self.__health_checks) / len(self.__health_checks) >= 0.5 if healthy: log.info("Moving window health checks healthy! health_checks={}".format(self.__health_checks)) else: log.warning("Moving window health checks unhealthy! health_checks={}".format(self.__health_checks)) self.__health_checks = [True] * self.__health_checks_queue_size return healthy def __is_latency_healthy(self, ping_responses): pings_with_time = list(filter(lambda x: x.time is not None, ping_responses)) if not pings_with_time: log.warning("No pings with a valid time value! pings = {}" .format(' '.join([str(x) for x in ping_responses]))) return False total_latency = sum(x.time for x in pings_with_time) avg_latency = total_latency / len(pings_with_time) healthy = avg_latency < self.__max_latency if not healthy: log.warning("Avg latency = {} millis, expected it to be less than {} millis" .format(avg_latency * 1000, self.__max_latency * 1000)) else: log.info("Healthy avg latency of {} millis".format(avg_latency * 1000)) return healthy @staticmethod def __is_successful(ping_responses): successful = all(x.success for x in ping_responses) if not successful: log.warning("Not all pings were successful, pings={}" .format(' '.join([str(x) for x in ping_responses]))) else: log.info("All pings successful!") return successful
true
true
1c2cfed1333a7025da594f0f50f1a8d2d2f9bc29
17,151
py
Python
models/convert.py
zongdaoming/TinyTransformer
8e64f8816117048c388b4b20e3a56760ce149fe3
[ "Apache-2.0" ]
2
2021-08-08T11:23:14.000Z
2021-09-16T04:05:23.000Z
models/convert.py
zongdaoming/TinyTransformer
8e64f8816117048c388b4b20e3a56760ce149fe3
[ "Apache-2.0" ]
1
2021-08-08T11:25:47.000Z
2021-08-08T11:26:15.000Z
models/convert.py
zongdaoming/TinyTransformer
8e64f8816117048c388b4b20e3a56760ce149fe3
[ "Apache-2.0" ]
null
null
null
''' Author: your name Date: 2021-08-31 21:36:45 LastEditTime: 2021-08-31 22:09:43 LastEditors: Please set LastEditors Description: In User Settings Edit FilePath: /models/SmallT/convert.py ''' import torch import sys from torch.autograd import Variable from os.path import splitext, getsize from spring.nart.tools.pytorch.onnx_utils import load from spring.nart.tools.pytorch.network_utils import make_network from spring.nart.tools.pytorch.module_utils import convert_mode import threading from spring.nart.tools.io import send from spring.nart.tools.pytorch.match_chain import _scope_module_name from spring.nart.tools.pytorch.trace_graph import trace_graph import logging from spring.nart.utils import deprecated def export(*args, **kwargs): minor = torch.__version__.split('.')[1] if int(minor) < 5 and 'enable_onnx_checker' in kwargs: del kwargs['enable_onnx_checker'] import pdb pdb.set_trace() # IndexError: list index out of range torch.onnx.export(*args, **kwargs) def convert_v2(model, input_shapes, filename="test", log=True, input_names=None, output_names=None, input_dict=None, verbose=False, output_weights=True, cloze=True): ''' Convert a pytorch model into a caffe model @params: model: the pytorch model to be converted input_shapes: list of ints of the shape of model input filename: the file name (without postfix) to be saved for the caffe model log: indicate whether to log this call input_names: list of strs of the name of model input output_names: list of strs of the name of model output input_dict: dict of model configs except those of 'image' key verbose: indicate whether the detailed structure of model is displayed output_weights: indicate whether the weight file of caffe model is generated cloze: indicate whether to add a "1" at the head of each input shape ''' custom_info = {"Method": "convert", "Module": "spring.nart.tools"} try: module_names = export_onnx(model, input_shapes, filename, input_names=input_names, output_names=output_names, log=False, input_dict=input_dict, verbose=verbose, cloze=cloze) convert_onnx_v2(filename + '.onnx', log=False, input_names=input_names, output_names=output_names, verbose=verbose, output_weights=output_weights, module_names=module_names) custom_info["Status"] = "Success" custom_info["Caffe Model Size"] = '{} Bytes'.format(getsize(filename + '.caffemodel')) custom_info["ONNX Model Size"] = '{} Bytes'.format(getsize(filename + '.onnx')) except Exception as e: custom_info["Status"] = str(e) raise e finally: if log: log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() return filename + '.prototxt', filename + '.caffemodel' from spring.nart.utils.alter.caffe import NonParamLayer class Hswish(NonParamLayer): def layer_type(self): return 'HSwish' class Hsigmoid(NonParamLayer): def layer_type(self): return 'Hsigmoid' def convert_onnx_v2(filename, log=True, input_names=None, output_names=None, verbose=False, output_weights=True, module_names=None): if verbose: print("====convert: start of onnx-to-caffe export") custom_info = {"Method": "convert_onnx", "Module": "spring.nart.tools"} try: from spring.nart.tools.pytorch.network_utils import merge_shuffle_channel_nodes, merge_reshape_nodes model = load(filename) merge_reshape_nodes(model) merge_shuffle_channel_nodes(model) if module_names is not None: if len(module_names) != len(model.graph.node): print("[WARNING] len of traced module_names is not equal to nodes") else: for idx, (node, name) in enumerate(zip(model.graph.node, module_names)): node.name = name + '_' + str(idx) from spring.nart.utils.alter import CaffeAlter, CaffeAlterContext from spring.nart.utils.alter.caffe import register_caffe_layer, Layer from spring.nart.core import Graph, Node from spring.nart.utils.onnx_utils import OnnxDecoder from spring.nart.passes import ConstantToInitializer, FoldConstantToAttr, DeadCodeElimination, ExtractEltwise, EliminateNodes from spring.nart.utils.passes import ExtractHswish, ExtractHsigmoid, ExtractGemm, EliminateReshapeNode from spring.nart.proto import nart_caffe_pb2 as caffe_pb2 from spring.nart.ops.op import Dropout, Cast name = splitext(filename)[0] graph = OnnxDecoder().decode(model) graph.update_tensor_shape() graph.update_topology() def should_remove(node, graph): return isinstance(node, (Dropout, Cast)) FoldConstantToAttr().run(graph) ExtractHswish().run(graph) ExtractHsigmoid().run(graph) ExtractGemm().run(graph) ExtractEltwise().run(graph) EliminateReshapeNode().run(graph) EliminateNodes(should_remove).run(graph) ConstantToInitializer().run(graph) DeadCodeElimination().run(graph) graph.update_topology() with CaffeAlterContext() as ctx: register_caffe_layer('Hswish', Hswish) register_caffe_layer('Hsigmoid', Hsigmoid) alter = CaffeAlter(graph) cnet = alter.parse() with open(name + '.caffemodel', 'wb') as f: f.write(cnet.SerializeToString()) for l in cnet.layer: l.ClearField('blobs') with open(name + '.prototxt', 'wt') as f: f.write(str(cnet)) custom_info["Status"] = "Success" custom_info["Caffe Model Size"] = '{} Bytes'.format(getsize(name + '.caffemodel')) except Exception as e: custom_info["Status"] = str(e) raise e finally: if log: log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() if verbose: print("====convert: end of onnx-to-caffe export") @deprecated(new_fn=convert_v2) def convert_v1(model, input_shapes, filename="test", log=True, input_names=None, output_names=None, input_dict=None, verbose=False, output_weights=True, cloze=True): ''' Convert a pytorch model into a caffe model @params: model: the pytorch model to be converted input_shapes: list of ints of the shape of model input filename: the file name (without postfix) to be saved for the caffe model log: indicate whether to log this call input_names: list of strs of the name of model input output_names: list of strs of the name of model output input_dict: dict of model configs except those of 'image' key verbose: indicate whether the detailed structure of model is displayed output_weights: indicate whether the weight file of caffe model is generated cloze: indicate whether to add a "1" at the head of each input shape ''' custom_info = {"Method": "convert", "Module": "spring.nart.tools"} try: module_names = export_onnx(model, input_shapes, filename, log=False, input_dict=input_dict, verbose=verbose, cloze=cloze) convert_onnx_v1(filename + '.onnx', log=False, input_names=input_names, output_names=output_names, verbose=verbose, output_weights=output_weights, module_names=module_names) custom_info["Status"] = "Success" custom_info["Caffe Model Size"] = '{} Bytes'.format(getsize(filename + '.caffemodel')) custom_info["ONNX Model Size"] = '{} Bytes'.format(getsize(filename + '.onnx')) except Exception as e: custom_info["Status"] = str(e) raise e finally: if log: log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() return filename + '.prototxt', filename + '.caffemodel' convert = convert_v1 convert_caffe_by_return = convert def convert_onnx_by_return(model, input_shapes, filename="test", log=True, input_dict=None, verbose=False, cloze=True): ''' Convert a pytorch model into an onnx model @params: model: the pytorch model to be converted input_shapes: list of ints of the shape of model input filename: the file name (without postfix) to be saved for the onnx model log: indicate whether to log this call input_dict: dict of model configs except those of 'image' key verbose: indicate whether the detailed structure of model is displayed cloze: indicate whether to add a "1" at the head of each input shape ''' if verbose: print("====convert: start of pytorch-to-onnx export") custom_info = {"Method": "export_onnx", "Module": "spring.nart.tools"} try: model.cpu() model.eval() if input_dict is not None: print("Input dict is not None. Automatically setting cloze to be False.") cloze = False input_variables = Convert.substitute_shape(input_shapes, cloze) if input_dict is not None: input_dict['image'] = input_variables export(model, (input_dict,), filename + ".onnx", verbose=verbose, enable_onnx_checker=False) else: export(model, input_variables, filename + ".onnx", verbose=verbose, enable_onnx_checker=False) custom_info["Status"] = "Success" custom_info["ONNX Model Size"] = '{} Bytes'.format(getsize(filename + '.onnx')) except Exception as e: custom_info["Status"] = str(e) raise e finally: if log: log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() if verbose: print("====convert: end of pytorch-to-onnx export") return filename + '.onnx' def export_onnx(model, input_shapes, filename, input_names=None, output_names=None, log=True, input_dict=None, verbose=False, cloze=True): ''' Convert a pytorch model into an onnx model @params: model: the pytorch model to be converted input_shapes: list of ints of the shape of model input filename: the file name (without postfix) to be saved for the onnx model log: indicate whether to log this call input_dict: dict of model configs except those of 'image' key verbose: indicate whether the detailed structure of model is displayed cloze: indicate whether to add a "1" at the head of each input shape ''' if verbose: print("====convert: start of pytorch-to-onnx export") custom_info = {"Method": "export_onnx", "Module": "spring.nart.tools"} module_names = None try: model.cpu() model.eval() if input_dict is not None: print("Input dict is not None. Automatically setting cloze to be False.") cloze = False input_variables = Convert.substitute_shape(input_shapes, cloze) if input_dict is not None: input_dict['image'] = input_variables # export(model, (input_dict,), filename + ".onnx", verbose=verbose, enable_onnx_checker=False) export(model, (input_dict,), filename + ".onnx", verbose=verbose, enable_onnx_checker=True) # reset input_variables cause `torch.onnx.export` side-effect input_dict['image'] = input_variables graph = trace_graph(model, (input_dict,), torch.onnx.OperatorExportTypes.ONNX) else: export(model, input_variables, filename + ".onnx", verbose=verbose, enable_onnx_checker=True) graph = trace_graph(model, input_variables, torch.onnx.OperatorExportTypes.ONNX) import onnx onnx_model = load(filename + ".onnx") from spring.nart.tools.pytorch.network_utils.common import update_input_names, update_output_names if input_names is not None: update_input_names(onnx_model, input_names) if output_names is not None: update_output_names(onnx_model, output_names) onnx.save(onnx_model, filename + ".onnx") module_names = list(map( lambda x: _scope_module_name(x.scopeName()), graph.nodes() )) custom_info["Status"] = "Success" custom_info["ONNX Model Size"] = '{} Bytes'.format(getsize(filename + '.onnx')) except Exception as e: custom_info["Status"] = str(e) raise e finally: if log: log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() if verbose: print("====convert: end of pytorch-to-onnx export") return module_names @deprecated(new_fn=convert_onnx_v2) def convert_onnx_v1(filename, log=True, input_names=None, output_names=None, verbose=False, output_weights=True, module_names=None): ''' Convert an onnx model into a caffe model @params: filename: the file name (with postfix) of the onnx model log: indicate whether to log this call input_names: list of strs of the name of model input output_names: list of strs of the name of model output verbose: indicate whether the detailed structure of model is displayed output_weights: indicate whether the weight file of caffe model is generated ''' if verbose: print("====convert: start of onnx-to-caffe export") custom_info = {"Method": "convert_onnx", "Module": "spring.nart.tools"} try: model = load(filename) if module_names is not None: if len(module_names) != len(model.graph.node): print("[WARNING] len of traced module_names is not equal to nodes") else: for idx, (node, name) in enumerate(zip(model.graph.node, module_names)): attr = node.attribute.add() attr.name = "module_name" attr.s = (name + '_' + str(idx)).encode('utf-8') name = splitext(filename)[0] network = make_network(model, name, input_names, output_names) network.save(verbose=verbose, output_weights=output_weights) custom_info["Status"] = "Success" custom_info["Caffe Model Size"] = '{} Bytes'.format(getsize(name + '.caffemodel')) except Exception as e: custom_info["Status"] = str(e) raise e finally: if log: log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() if verbose: print("====convert: end of onnx-to-caffe export") convert_onnx = convert_onnx_v1 @deprecated() def rearrange_channel(filename, indices, log=True): ''' ----毒瘤函数,无关人员速速退散---- Rearrange the channel every 2 channels @params: filename: the name (without postfix) of the caffe model indices: the list of indices of the layers to be rearranged log: indicate whether to log this call ----版本旧约,对齐协议早早解脱---- ''' import numpy as np from spring.nart.tools.proto import caffe_pb2 if log: custom_info = {"Method": "rearrange_channel", "Module": "spring.nart.tools"} log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() net = caffe_pb2.NetParameter() with open(filename + '.caffemodel', 'rb') as fin: net.ParseFromString(fin.read()) for layer in net.layer: layer_index = int(layer.name.split('_')[-1]) if layer_index not in indices: continue weight = np.array(layer.blobs[0].data[:]) span = weight.shape[0] // 2 duliu = [] for i in range(span): duliu.append(weight[2 * i]) for i in range(span): duliu.append(weight[2 * i + 1]) layer.blobs[0].data[:] = np.array(duliu) with open(filename + '.caffemodel', 'wb') as fout: fout.write(net.SerializeToString()) class Convert(sys.modules[__name__].__class__): @staticmethod def __call__(model, input_shapes, filename, log=True, input_names=None, output_names=None, input_dict=None, verbose=False, output_weights=True, cloze=True): convert(model, input_shapes, filename, log=log, input_names=input_names, output_names=output_names, input_dict=input_dict, verbose=verbose, output_weights=output_weights, cloze=cloze) @staticmethod def substitute_shape(input_shapes, cloze): input_variables = [] for input_shape in input_shapes: if all(map(lambda shape: isinstance(shape, int), input_shape)): if cloze: input_shape = [1] + list(input_shape) tensor = torch.randn(input_shape) variable = Variable(tensor, requires_grad=True) input_variables.append(variable) else: input_variables.append(Convert.substitute_shape(input_shape, cloze)) return tuple(input_variables) sys.modules[__name__].__class__ = Convert
42.140049
133
0.656055
import torch import sys from torch.autograd import Variable from os.path import splitext, getsize from spring.nart.tools.pytorch.onnx_utils import load from spring.nart.tools.pytorch.network_utils import make_network from spring.nart.tools.pytorch.module_utils import convert_mode import threading from spring.nart.tools.io import send from spring.nart.tools.pytorch.match_chain import _scope_module_name from spring.nart.tools.pytorch.trace_graph import trace_graph import logging from spring.nart.utils import deprecated def export(*args, **kwargs): minor = torch.__version__.split('.')[1] if int(minor) < 5 and 'enable_onnx_checker' in kwargs: del kwargs['enable_onnx_checker'] import pdb pdb.set_trace() torch.onnx.export(*args, **kwargs) def convert_v2(model, input_shapes, filename="test", log=True, input_names=None, output_names=None, input_dict=None, verbose=False, output_weights=True, cloze=True): custom_info = {"Method": "convert", "Module": "spring.nart.tools"} try: module_names = export_onnx(model, input_shapes, filename, input_names=input_names, output_names=output_names, log=False, input_dict=input_dict, verbose=verbose, cloze=cloze) convert_onnx_v2(filename + '.onnx', log=False, input_names=input_names, output_names=output_names, verbose=verbose, output_weights=output_weights, module_names=module_names) custom_info["Status"] = "Success" custom_info["Caffe Model Size"] = '{} Bytes'.format(getsize(filename + '.caffemodel')) custom_info["ONNX Model Size"] = '{} Bytes'.format(getsize(filename + '.onnx')) except Exception as e: custom_info["Status"] = str(e) raise e finally: if log: log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() return filename + '.prototxt', filename + '.caffemodel' from spring.nart.utils.alter.caffe import NonParamLayer class Hswish(NonParamLayer): def layer_type(self): return 'HSwish' class Hsigmoid(NonParamLayer): def layer_type(self): return 'Hsigmoid' def convert_onnx_v2(filename, log=True, input_names=None, output_names=None, verbose=False, output_weights=True, module_names=None): if verbose: print("====convert: start of onnx-to-caffe export") custom_info = {"Method": "convert_onnx", "Module": "spring.nart.tools"} try: from spring.nart.tools.pytorch.network_utils import merge_shuffle_channel_nodes, merge_reshape_nodes model = load(filename) merge_reshape_nodes(model) merge_shuffle_channel_nodes(model) if module_names is not None: if len(module_names) != len(model.graph.node): print("[WARNING] len of traced module_names is not equal to nodes") else: for idx, (node, name) in enumerate(zip(model.graph.node, module_names)): node.name = name + '_' + str(idx) from spring.nart.utils.alter import CaffeAlter, CaffeAlterContext from spring.nart.utils.alter.caffe import register_caffe_layer, Layer from spring.nart.core import Graph, Node from spring.nart.utils.onnx_utils import OnnxDecoder from spring.nart.passes import ConstantToInitializer, FoldConstantToAttr, DeadCodeElimination, ExtractEltwise, EliminateNodes from spring.nart.utils.passes import ExtractHswish, ExtractHsigmoid, ExtractGemm, EliminateReshapeNode from spring.nart.proto import nart_caffe_pb2 as caffe_pb2 from spring.nart.ops.op import Dropout, Cast name = splitext(filename)[0] graph = OnnxDecoder().decode(model) graph.update_tensor_shape() graph.update_topology() def should_remove(node, graph): return isinstance(node, (Dropout, Cast)) FoldConstantToAttr().run(graph) ExtractHswish().run(graph) ExtractHsigmoid().run(graph) ExtractGemm().run(graph) ExtractEltwise().run(graph) EliminateReshapeNode().run(graph) EliminateNodes(should_remove).run(graph) ConstantToInitializer().run(graph) DeadCodeElimination().run(graph) graph.update_topology() with CaffeAlterContext() as ctx: register_caffe_layer('Hswish', Hswish) register_caffe_layer('Hsigmoid', Hsigmoid) alter = CaffeAlter(graph) cnet = alter.parse() with open(name + '.caffemodel', 'wb') as f: f.write(cnet.SerializeToString()) for l in cnet.layer: l.ClearField('blobs') with open(name + '.prototxt', 'wt') as f: f.write(str(cnet)) custom_info["Status"] = "Success" custom_info["Caffe Model Size"] = '{} Bytes'.format(getsize(name + '.caffemodel')) except Exception as e: custom_info["Status"] = str(e) raise e finally: if log: log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() if verbose: print("====convert: end of onnx-to-caffe export") @deprecated(new_fn=convert_v2) def convert_v1(model, input_shapes, filename="test", log=True, input_names=None, output_names=None, input_dict=None, verbose=False, output_weights=True, cloze=True): custom_info = {"Method": "convert", "Module": "spring.nart.tools"} try: module_names = export_onnx(model, input_shapes, filename, log=False, input_dict=input_dict, verbose=verbose, cloze=cloze) convert_onnx_v1(filename + '.onnx', log=False, input_names=input_names, output_names=output_names, verbose=verbose, output_weights=output_weights, module_names=module_names) custom_info["Status"] = "Success" custom_info["Caffe Model Size"] = '{} Bytes'.format(getsize(filename + '.caffemodel')) custom_info["ONNX Model Size"] = '{} Bytes'.format(getsize(filename + '.onnx')) except Exception as e: custom_info["Status"] = str(e) raise e finally: if log: log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() return filename + '.prototxt', filename + '.caffemodel' convert = convert_v1 convert_caffe_by_return = convert def convert_onnx_by_return(model, input_shapes, filename="test", log=True, input_dict=None, verbose=False, cloze=True): if verbose: print("====convert: start of pytorch-to-onnx export") custom_info = {"Method": "export_onnx", "Module": "spring.nart.tools"} try: model.cpu() model.eval() if input_dict is not None: print("Input dict is not None. Automatically setting cloze to be False.") cloze = False input_variables = Convert.substitute_shape(input_shapes, cloze) if input_dict is not None: input_dict['image'] = input_variables export(model, (input_dict,), filename + ".onnx", verbose=verbose, enable_onnx_checker=False) else: export(model, input_variables, filename + ".onnx", verbose=verbose, enable_onnx_checker=False) custom_info["Status"] = "Success" custom_info["ONNX Model Size"] = '{} Bytes'.format(getsize(filename + '.onnx')) except Exception as e: custom_info["Status"] = str(e) raise e finally: if log: log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() if verbose: print("====convert: end of pytorch-to-onnx export") return filename + '.onnx' def export_onnx(model, input_shapes, filename, input_names=None, output_names=None, log=True, input_dict=None, verbose=False, cloze=True): if verbose: print("====convert: start of pytorch-to-onnx export") custom_info = {"Method": "export_onnx", "Module": "spring.nart.tools"} module_names = None try: model.cpu() model.eval() if input_dict is not None: print("Input dict is not None. Automatically setting cloze to be False.") cloze = False input_variables = Convert.substitute_shape(input_shapes, cloze) if input_dict is not None: input_dict['image'] = input_variables export(model, (input_dict,), filename + ".onnx", verbose=verbose, enable_onnx_checker=True) input_dict['image'] = input_variables graph = trace_graph(model, (input_dict,), torch.onnx.OperatorExportTypes.ONNX) else: export(model, input_variables, filename + ".onnx", verbose=verbose, enable_onnx_checker=True) graph = trace_graph(model, input_variables, torch.onnx.OperatorExportTypes.ONNX) import onnx onnx_model = load(filename + ".onnx") from spring.nart.tools.pytorch.network_utils.common import update_input_names, update_output_names if input_names is not None: update_input_names(onnx_model, input_names) if output_names is not None: update_output_names(onnx_model, output_names) onnx.save(onnx_model, filename + ".onnx") module_names = list(map( lambda x: _scope_module_name(x.scopeName()), graph.nodes() )) custom_info["Status"] = "Success" custom_info["ONNX Model Size"] = '{} Bytes'.format(getsize(filename + '.onnx')) except Exception as e: custom_info["Status"] = str(e) raise e finally: if log: log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() if verbose: print("====convert: end of pytorch-to-onnx export") return module_names @deprecated(new_fn=convert_onnx_v2) def convert_onnx_v1(filename, log=True, input_names=None, output_names=None, verbose=False, output_weights=True, module_names=None): if verbose: print("====convert: start of onnx-to-caffe export") custom_info = {"Method": "convert_onnx", "Module": "spring.nart.tools"} try: model = load(filename) if module_names is not None: if len(module_names) != len(model.graph.node): print("[WARNING] len of traced module_names is not equal to nodes") else: for idx, (node, name) in enumerate(zip(model.graph.node, module_names)): attr = node.attribute.add() attr.name = "module_name" attr.s = (name + '_' + str(idx)).encode('utf-8') name = splitext(filename)[0] network = make_network(model, name, input_names, output_names) network.save(verbose=verbose, output_weights=output_weights) custom_info["Status"] = "Success" custom_info["Caffe Model Size"] = '{} Bytes'.format(getsize(name + '.caffemodel')) except Exception as e: custom_info["Status"] = str(e) raise e finally: if log: log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() if verbose: print("====convert: end of onnx-to-caffe export") convert_onnx = convert_onnx_v1 @deprecated() def rearrange_channel(filename, indices, log=True): import numpy as np from spring.nart.tools.proto import caffe_pb2 if log: custom_info = {"Method": "rearrange_channel", "Module": "spring.nart.tools"} log_thread = threading.Thread(target=send, args=(custom_info,)) log_thread.start() net = caffe_pb2.NetParameter() with open(filename + '.caffemodel', 'rb') as fin: net.ParseFromString(fin.read()) for layer in net.layer: layer_index = int(layer.name.split('_')[-1]) if layer_index not in indices: continue weight = np.array(layer.blobs[0].data[:]) span = weight.shape[0] // 2 duliu = [] for i in range(span): duliu.append(weight[2 * i]) for i in range(span): duliu.append(weight[2 * i + 1]) layer.blobs[0].data[:] = np.array(duliu) with open(filename + '.caffemodel', 'wb') as fout: fout.write(net.SerializeToString()) class Convert(sys.modules[__name__].__class__): @staticmethod def __call__(model, input_shapes, filename, log=True, input_names=None, output_names=None, input_dict=None, verbose=False, output_weights=True, cloze=True): convert(model, input_shapes, filename, log=log, input_names=input_names, output_names=output_names, input_dict=input_dict, verbose=verbose, output_weights=output_weights, cloze=cloze) @staticmethod def substitute_shape(input_shapes, cloze): input_variables = [] for input_shape in input_shapes: if all(map(lambda shape: isinstance(shape, int), input_shape)): if cloze: input_shape = [1] + list(input_shape) tensor = torch.randn(input_shape) variable = Variable(tensor, requires_grad=True) input_variables.append(variable) else: input_variables.append(Convert.substitute_shape(input_shape, cloze)) return tuple(input_variables) sys.modules[__name__].__class__ = Convert
true
true
1c2cff4cf4924b3b8ab3e9ab411e4d167ad36b35
4,470
py
Python
scripts/bump-version.py
dsblank/jupyterlite
b51c265dd7450bd053a0ad2f8d5cd94a70cb0669
[ "BSD-3-Clause" ]
2
2021-09-18T03:05:02.000Z
2021-11-15T11:55:30.000Z
scripts/bump-version.py
dsblank/jupyterlite
b51c265dd7450bd053a0ad2f8d5cd94a70cb0669
[ "BSD-3-Clause" ]
1
2022-03-31T12:32:29.000Z
2022-03-31T12:32:29.000Z
scripts/bump-version.py
dsblank/jupyterlite
b51c265dd7450bd053a0ad2f8d5cd94a70cb0669
[ "BSD-3-Clause" ]
null
null
null
# Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License.import click # Heavily inspired by: # - https://github.com/jupyterlab/jupyterlab/blob/master/buildutils/src/bumpversion.ts # - https://github.com/jupyterlab/retrolab/blob/main/buildutils/src/release-bump.ts # - https://github.com/voila-dashboards/voila/blob/master/scripts/bump-version.py import json from pathlib import Path import click from jupyter_releaser.util import get_version, is_prerelease, run OPTIONS = ["major", "minor", "release", "build"] ENC = dict(encoding="utf-8") ROOT = Path(__file__).parent.parent ROOT_PACKAGE_JSON = ROOT / "package.json" APP_PACKAGE_JSON = ROOT / "app" / "package.json" APP_JUPYTERLITE_JSON = ROOT / "app" / "jupyter-lite.json" def postbump(): # read the new app version app_json = json.loads(APP_PACKAGE_JSON.read_text(**ENC)) new_version = app_json["version"] # save the new version to the app jupyter-lite.json jupyterlite_json = json.loads(APP_JUPYTERLITE_JSON.read_text(**ENC)) jupyterlite_json["jupyter-config-data"]["appVersion"] = new_version APP_JUPYTERLITE_JSON.write_text( json.dumps(jupyterlite_json, indent=2) + "\n", **ENC ) # save the new version to the top-level package.json py_version = ( new_version.replace("-alpha.", "a").replace("-beta.", "b").replace("-rc.", "rc") ) root_json = json.loads(ROOT_PACKAGE_JSON.read_text(**ENC)) root_json["version"] = py_version ROOT_PACKAGE_JSON.write_text(json.dumps(root_json, indent=2), **ENC) run("doit repo:integrity", cwd=ROOT) def patch(force=False): version = get_version() if is_prerelease(version): raise Exception("Can only make a patch release from a final version") run("bumpversion patch", quiet=True) # switches to alpha run("bumpversion release --allow-dirty", quiet=True) # switches to beta run("bumpversion release --allow-dirty", quiet=True) # switches to rc. run("bumpversion release --allow-dirty", quiet=True) # switches to final. # Version the changed cmd = "yarn run lerna version patch --no-push --force-publish --no-git-tag-version" if force: cmd += " --yes" run(cmd) def update(spec, force=False): prev = get_version() # Make sure we have a valid version spec. if spec not in OPTIONS: raise Exception(f"Version spec must be one of: {OPTIONS}") is_final = not is_prerelease(prev) if is_final and spec == "release": raise Exception('Use "major" or "minor" to switch back to alpha release') if is_final and spec == "build": raise Exception("Cannot increment a build on a final release") # If this is a major release during the alpha cycle, bump # just the Python version. if "a" in prev and spec == "major": run(f"bumpversion {spec}") return # Determine the version spec to use for lerna. lerna_version = "preminor" if spec == "build": lerna_version = "prerelease" # a -> b elif spec == "release" and "a" in prev: lerna_version = "prerelease --preid=beta" # b -> rc elif spec == "release" and "b" in prev: lerna_version = "prerelease --preid=rc" # rc -> final elif spec == "release" and "c" in prev: lerna_version = "patch" if lerna_version == "preminor": lerna_version += " --preid=alpha" cmd = f"yarn run lerna version --force-publish --no-push --no-git-tag-version {lerna_version}" if force: cmd += " --yes" # For a preminor release, we bump 10 minor versions so that we do # not conflict with versions during minor releases of the top level package. if lerna_version == "preminor": for i in range(10): run(cmd) else: run(cmd) # Bump the version. run(f"bumpversion {spec} --allow-dirty") @click.command() @click.option("--force", default=False, is_flag=True) @click.argument("spec", nargs=1) def bump(force, spec): status = run("git status --porcelain").strip() if len(status) > 0: raise Exception("Must be in a clean git state with no untracked files") prev = get_version() is_final = not is_prerelease(prev) if spec == "next": spec = "patch" if is_final else "build" if spec == "patch": patch(force) return update(spec, force) postbump() if __name__ == "__main__": bump()
30.616438
98
0.655705
import json from pathlib import Path import click from jupyter_releaser.util import get_version, is_prerelease, run OPTIONS = ["major", "minor", "release", "build"] ENC = dict(encoding="utf-8") ROOT = Path(__file__).parent.parent ROOT_PACKAGE_JSON = ROOT / "package.json" APP_PACKAGE_JSON = ROOT / "app" / "package.json" APP_JUPYTERLITE_JSON = ROOT / "app" / "jupyter-lite.json" def postbump(): app_json = json.loads(APP_PACKAGE_JSON.read_text(**ENC)) new_version = app_json["version"] jupyterlite_json = json.loads(APP_JUPYTERLITE_JSON.read_text(**ENC)) jupyterlite_json["jupyter-config-data"]["appVersion"] = new_version APP_JUPYTERLITE_JSON.write_text( json.dumps(jupyterlite_json, indent=2) + "\n", **ENC ) py_version = ( new_version.replace("-alpha.", "a").replace("-beta.", "b").replace("-rc.", "rc") ) root_json = json.loads(ROOT_PACKAGE_JSON.read_text(**ENC)) root_json["version"] = py_version ROOT_PACKAGE_JSON.write_text(json.dumps(root_json, indent=2), **ENC) run("doit repo:integrity", cwd=ROOT) def patch(force=False): version = get_version() if is_prerelease(version): raise Exception("Can only make a patch release from a final version") run("bumpversion patch", quiet=True) run("bumpversion release --allow-dirty", quiet=True) run("bumpversion release --allow-dirty", quiet=True) run("bumpversion release --allow-dirty", quiet=True) cmd = "yarn run lerna version patch --no-push --force-publish --no-git-tag-version" if force: cmd += " --yes" run(cmd) def update(spec, force=False): prev = get_version() if spec not in OPTIONS: raise Exception(f"Version spec must be one of: {OPTIONS}") is_final = not is_prerelease(prev) if is_final and spec == "release": raise Exception('Use "major" or "minor" to switch back to alpha release') if is_final and spec == "build": raise Exception("Cannot increment a build on a final release") if "a" in prev and spec == "major": run(f"bumpversion {spec}") return lerna_version = "preminor" if spec == "build": lerna_version = "prerelease" elif spec == "release" and "a" in prev: lerna_version = "prerelease --preid=beta" elif spec == "release" and "b" in prev: lerna_version = "prerelease --preid=rc" elif spec == "release" and "c" in prev: lerna_version = "patch" if lerna_version == "preminor": lerna_version += " --preid=alpha" cmd = f"yarn run lerna version --force-publish --no-push --no-git-tag-version {lerna_version}" if force: cmd += " --yes" if lerna_version == "preminor": for i in range(10): run(cmd) else: run(cmd) run(f"bumpversion {spec} --allow-dirty") @click.command() @click.option("--force", default=False, is_flag=True) @click.argument("spec", nargs=1) def bump(force, spec): status = run("git status --porcelain").strip() if len(status) > 0: raise Exception("Must be in a clean git state with no untracked files") prev = get_version() is_final = not is_prerelease(prev) if spec == "next": spec = "patch" if is_final else "build" if spec == "patch": patch(force) return update(spec, force) postbump() if __name__ == "__main__": bump()
true
true
1c2cff78866cc8542cc4ff5da7ec91714d669ea9
8,198
py
Python
websocketsip.py
thr0wforks/pjsip-through-websocket-demo
3b141fde4d39b0b59c788733903963a85e7661f5
[ "MIT" ]
null
null
null
websocketsip.py
thr0wforks/pjsip-through-websocket-demo
3b141fde4d39b0b59c788733903963a85e7661f5
[ "MIT" ]
null
null
null
websocketsip.py
thr0wforks/pjsip-through-websocket-demo
3b141fde4d39b0b59c788733903963a85e7661f5
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import signal import pjsua as pj import logging import logging.config from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket from jsonrpc import JSONRPCResponseManager, dispatcher from jsonrpc.jsonrpc2 import JSONRPC20Request import sys if sys.version_info.major == 3: unicode = str logging.config.fileConfig('logging.conf') logger = logging.getLogger('wssip') server = "186.209.79.26" login = "7009" password = "D39q&#D96t" localport = 7000 sockethost = "*" if sockethost == '*': sockethost = '' socketport = 8066 lib = None acc = None # Logging callback def log_cb(level, str, len): logger.info(str) def signal_handler(signal, frame): global lib logger.info('You pressed Ctrl+C!') # We're done, shutdown the library if lib: lib.destroy() lib = None sys.exit(0) signal.signal(signal.SIGINT, signal_handler) try: lib = pj.Lib() # Init library with default config lib.init(log_cfg=pj.LogConfig(level=6, callback=log_cb)) # Create UDP transport which listens to any available port tcfg = pj.TransportConfig(port=localport) lib.create_transport(pj.TransportType.UDP, tcfg) # Start the library lib.start() # Create local/user-less account try: acc_cfg = pj.AccountConfig(server, login, password) acc = lib.create_account(acc_cfg) except pj.Error as err: logger.info('Error creating account: %s', err) except pj.Error as e: logger.error("Exception: %s", str(e)) lib.destroy() lib = None sys.exit(-1) class MyCallCallback(pj.CallCallback): """ Call state variations. NULL -- call is not initialized. CALLING -- initial INVITE is sent. INCOMING -- initial INVITE is received. EARLY -- provisional response has been sent or received. CONNECTING -- 200/OK response has been sent or received. CONFIRMED -- ACK has been sent or received. DISCONNECTED -- call is disconnected. Call media state variations. NULL -- media is not available. ACTIVE -- media is active. LOCAL_HOLD -- media is put on-hold by local party. REMOTE_HOLD -- media is put on-hold by remote party. ERROR -- media error (e.g. ICE negotiation failure). """ media_state = { pj.MediaState.NULL: 'not_available', pj.MediaState.ACTIVE: 'active', pj.MediaState.LOCAL_HOLD: 'local_hold', pj.MediaState.REMOTE_HOLD: 'remote_hold', pj.MediaState.ERROR: 'error', } def __init__(self, websocket=None, call=None): self.websocket = websocket pj.CallCallback.__init__(self, call) # Notification when call state has changed def on_state(self): s_text = self.call.info().state_text code = self.call.info().last_code reason = self.call.info().last_reason media_state = self.media_state.get( self.call.info().media_state, 'unknown' ) notify20(self.websocket, 'call_status_update', {'status': s_text, 'code': code, 'reason': reason, 'media_state': media_state}) if s_text == 'DISCONNCTD': # nullify call istance to prevent lib from crash self.websocket.call = None # Notification when call's media state has changed. def on_media_state(self): global lib if self.call.info().media_state == pj.MediaState.ACTIVE: # Connect the call to sound device call_slot = self.call.info().conf_slot lib.conf_connect(call_slot, 0) lib.conf_connect(0, call_slot) s_text = self.call.info().state_text code = self.call.info().last_code reason = self.call.info().last_reason media_state = self.media_state.get( self.call.info().media_state, 'unknown' ) notify20(self.websocket, 'call_media_state_update', {'status': s_text, 'code': code, 'reason': reason, 'media_state': media_state}) def notify20(websocket, method, params=None): # Sending notifications to the clients helper function try: notification = unicode( JSONRPC20Request(method, params, is_notification=True).json, 'utf-8') logger.info("Sending notification: %r", notification) websocket.sendMessage(notification) except Exception as e: logger.exception(e) class Dispatcher: call = None def __init__(self, websocket): global lib global acc self.lib = lib self.acc = acc self.websocket = websocket def __getitem__(self, key): try: return getattr(self, key) except AttributeError: raise KeyError def make_call(self, sip_uri): logger.debug('called make_call method') # Make call if self.call: logger.info('only one call supported') return logger.info("calling %s...", sip_uri) if sip_uri.startswith('sip:'): self.call = acc.make_call( sip_uri.encode(), MyCallCallback(self.websocket)) return True else: raise ValueError("Wrong SIP id {}.".format(sip_uri)) def hangup(self): logger.debug('called hangup method') if self.call: self.call.hangup() self.call = None return True else: return False def hold(self): logger.debug('called hold method') if self.call: self.call.hold() return True else: return False def unhold(self): logger.debug('called unhold method') if self.call: self.call.unhold() return True else: return False def mute_mic(self): logger.debug('called mute_mic method') if not self.lib: return _tx_level, rx_level = self.lib.conf_get_signal_level(0) if rx_level > 0.0: self.lib.conf_set_rx_level(0, 0) levels = self.lib.conf_get_signal_level(0) return levels else: self.lib.conf_set_rx_level(0, 1) levels = self.lib.conf_get_signal_level(0) return levels def enum_devices(self): return ["%s <in: %s, out: %s>" % (dev.name, dev.input_channels, dev.output_channels ) for dev in self.lib.enum_snd_dev()] def get_current_devices(self): return self.lib.get_snd_dev() def set_current_devices(self, capture_dev, playback_dev): return self.lib.set_snd_dev(capture_dev, playback_dev) class WebSocketSip(WebSocket): def handleMessage(self): logger.debug("Reseived from %s data: %s", self.address, self.data) # dispatch comand try: response = JSONRPCResponseManager.handle(self.data, self.dispatcher) except Exception as e: logger.exception(e) if response is not None: logger.info("Request: %r, Response: %r", self.data, unicode(response.json, 'utf-8')) self.sendMessage(unicode(response.json, 'utf-8')) else: logger.info("Notification received: %r", self.data) def handleConnected(self): # The Lib supports only one instance in memory self.dispatcher = Dispatcher(self) notify20(self, 'connected', {'account': str(acc)}) logger.info('Connected: %s', self.address) def handleClose(self): logger.info('Connection closed: %s', self.address) server = SimpleWebSocketServer(sockethost, socketport, WebSocketSip) server.serveforever()
30.589552
80
0.58685
import os import sys import signal import pjsua as pj import logging import logging.config from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket from jsonrpc import JSONRPCResponseManager, dispatcher from jsonrpc.jsonrpc2 import JSONRPC20Request import sys if sys.version_info.major == 3: unicode = str logging.config.fileConfig('logging.conf') logger = logging.getLogger('wssip') server = "186.209.79.26" login = "7009" password = "D39q&#D96t" localport = 7000 sockethost = "*" if sockethost == '*': sockethost = '' socketport = 8066 lib = None acc = None def log_cb(level, str, len): logger.info(str) def signal_handler(signal, frame): global lib logger.info('You pressed Ctrl+C!') if lib: lib.destroy() lib = None sys.exit(0) signal.signal(signal.SIGINT, signal_handler) try: lib = pj.Lib() # Init library with default config lib.init(log_cfg=pj.LogConfig(level=6, callback=log_cb)) # Create UDP transport which listens to any available port tcfg = pj.TransportConfig(port=localport) lib.create_transport(pj.TransportType.UDP, tcfg) # Start the library lib.start() # Create local/user-less account try: acc_cfg = pj.AccountConfig(server, login, password) acc = lib.create_account(acc_cfg) except pj.Error as err: logger.info('Error creating account: %s', err) except pj.Error as e: logger.error("Exception: %s", str(e)) lib.destroy() lib = None sys.exit(-1) class MyCallCallback(pj.CallCallback): media_state = { pj.MediaState.NULL: 'not_available', pj.MediaState.ACTIVE: 'active', pj.MediaState.LOCAL_HOLD: 'local_hold', pj.MediaState.REMOTE_HOLD: 'remote_hold', pj.MediaState.ERROR: 'error', } def __init__(self, websocket=None, call=None): self.websocket = websocket pj.CallCallback.__init__(self, call) # Notification when call state has changed def on_state(self): s_text = self.call.info().state_text code = self.call.info().last_code reason = self.call.info().last_reason media_state = self.media_state.get( self.call.info().media_state, 'unknown' ) notify20(self.websocket, 'call_status_update', {'status': s_text, 'code': code, 'reason': reason, 'media_state': media_state}) if s_text == 'DISCONNCTD': # nullify call istance to prevent lib from crash self.websocket.call = None # Notification when call's media state has changed. def on_media_state(self): global lib if self.call.info().media_state == pj.MediaState.ACTIVE: call_slot = self.call.info().conf_slot lib.conf_connect(call_slot, 0) lib.conf_connect(0, call_slot) s_text = self.call.info().state_text code = self.call.info().last_code reason = self.call.info().last_reason media_state = self.media_state.get( self.call.info().media_state, 'unknown' ) notify20(self.websocket, 'call_media_state_update', {'status': s_text, 'code': code, 'reason': reason, 'media_state': media_state}) def notify20(websocket, method, params=None): try: notification = unicode( JSONRPC20Request(method, params, is_notification=True).json, 'utf-8') logger.info("Sending notification: %r", notification) websocket.sendMessage(notification) except Exception as e: logger.exception(e) class Dispatcher: call = None def __init__(self, websocket): global lib global acc self.lib = lib self.acc = acc self.websocket = websocket def __getitem__(self, key): try: return getattr(self, key) except AttributeError: raise KeyError def make_call(self, sip_uri): logger.debug('called make_call method') if self.call: logger.info('only one call supported') return logger.info("calling %s...", sip_uri) if sip_uri.startswith('sip:'): self.call = acc.make_call( sip_uri.encode(), MyCallCallback(self.websocket)) return True else: raise ValueError("Wrong SIP id {}.".format(sip_uri)) def hangup(self): logger.debug('called hangup method') if self.call: self.call.hangup() self.call = None return True else: return False def hold(self): logger.debug('called hold method') if self.call: self.call.hold() return True else: return False def unhold(self): logger.debug('called unhold method') if self.call: self.call.unhold() return True else: return False def mute_mic(self): logger.debug('called mute_mic method') if not self.lib: return _tx_level, rx_level = self.lib.conf_get_signal_level(0) if rx_level > 0.0: self.lib.conf_set_rx_level(0, 0) levels = self.lib.conf_get_signal_level(0) return levels else: self.lib.conf_set_rx_level(0, 1) levels = self.lib.conf_get_signal_level(0) return levels def enum_devices(self): return ["%s <in: %s, out: %s>" % (dev.name, dev.input_channels, dev.output_channels ) for dev in self.lib.enum_snd_dev()] def get_current_devices(self): return self.lib.get_snd_dev() def set_current_devices(self, capture_dev, playback_dev): return self.lib.set_snd_dev(capture_dev, playback_dev) class WebSocketSip(WebSocket): def handleMessage(self): logger.debug("Reseived from %s data: %s", self.address, self.data) try: response = JSONRPCResponseManager.handle(self.data, self.dispatcher) except Exception as e: logger.exception(e) if response is not None: logger.info("Request: %r, Response: %r", self.data, unicode(response.json, 'utf-8')) self.sendMessage(unicode(response.json, 'utf-8')) else: logger.info("Notification received: %r", self.data) def handleConnected(self): self.dispatcher = Dispatcher(self) notify20(self, 'connected', {'account': str(acc)}) logger.info('Connected: %s', self.address) def handleClose(self): logger.info('Connection closed: %s', self.address) server = SimpleWebSocketServer(sockethost, socketport, WebSocketSip) server.serveforever()
true
true
1c2d003aea679272b6063971b88bad61c6b7d23b
77,924
py
Python
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ip_rsvp_cfg.py
bopopescu/ACI
dd717bc74739eeed4747b3ea9e36b239580df5e1
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ip_rsvp_cfg.py
bopopescu/ACI
dd717bc74739eeed4747b3ea9e36b239580df5e1
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ip_rsvp_cfg.py
bopopescu/ACI
dd717bc74739eeed4747b3ea9e36b239580df5e1
[ "ECL-2.0", "Apache-2.0" ]
1
2020-07-22T04:04:44.000Z
2020-07-22T04:04:44.000Z
""" Cisco_IOS_XR_ip_rsvp_cfg This module contains a collection of YANG definitions for Cisco IOS\-XR ip\-rsvp package configuration. This module contains definitions for the following management objects\: rsvp\: Global RSVP configuration commands This YANG module augments the Cisco\-IOS\-XR\-snmp\-agent\-cfg module with configuration data. Copyright (c) 2013\-2017 by Cisco Systems, Inc. All rights reserved. """ from collections import OrderedDict from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64 from ydk.filters import YFilter from ydk.errors import YError, YModelError from ydk.errors.error_handler import handle_type_error as _handle_type_error class RsvpBc0(Enum): """ RsvpBc0 (Enum Class) Rsvp bc0 .. data:: bc0 = 1 Keyword is bc0 .. data:: global_pool = 2 Keyword is global-pool .. data:: not_specified = 3 Keyword is not specified """ bc0 = Enum.YLeaf(1, "bc0") global_pool = Enum.YLeaf(2, "global-pool") not_specified = Enum.YLeaf(3, "not-specified") class RsvpBc1(Enum): """ RsvpBc1 (Enum Class) Rsvp bc1 .. data:: bc1 = 1 Keyword is bc1 .. data:: sub_pool = 2 Keyword is sub-pool """ bc1 = Enum.YLeaf(1, "bc1") sub_pool = Enum.YLeaf(2, "sub-pool") class RsvpBwCfg(Enum): """ RsvpBwCfg (Enum Class) Rsvp bw cfg .. data:: absolute = 0 Configuration is in absolute bandwidth values .. data:: percentage = 1 Configuration is in percentage of physical bandwidth values """ absolute = Enum.YLeaf(0, "absolute") percentage = Enum.YLeaf(1, "percentage") class RsvpRdm(Enum): """ RsvpRdm (Enum Class) Rsvp rdm .. data:: rdm = 1 RDM Keyword Specified .. data:: not_specified = 2 RDM Keyword Not Specified .. data:: use_default_bandwidth = 3 Use Default Bandwidth - 75% Link Bandwidth """ rdm = Enum.YLeaf(1, "rdm") not_specified = Enum.YLeaf(2, "not-specified") use_default_bandwidth = Enum.YLeaf(3, "use-default-bandwidth") class Rsvp(Entity): """ Global RSVP configuration commands .. attribute:: neighbors RSVP Neighbor Table **type**\: :py:class:`Neighbors <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Neighbors>` .. attribute:: controllers Controller table **type**\: :py:class:`Controllers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Controllers>` .. attribute:: global_logging Global Logging **type**\: :py:class:`GlobalLogging <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.GlobalLogging>` .. attribute:: global_bandwidth Configure Global Bandwidth Parameters **type**\: :py:class:`GlobalBandwidth <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.GlobalBandwidth>` .. attribute:: interfaces Interface table **type**\: :py:class:`Interfaces <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Interfaces>` .. attribute:: signalling Configure Global RSVP signalling parameters **type**\: :py:class:`Signalling <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Signalling>` .. attribute:: authentication Configure RSVP authentication **type**\: :py:class:`Authentication <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Authentication>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp, self).__init__() self._top_entity = None self.yang_name = "rsvp" self.yang_parent_name = "Cisco-IOS-XR-ip-rsvp-cfg" self.is_top_level_class = True self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([("neighbors", ("neighbors", Rsvp.Neighbors)), ("controllers", ("controllers", Rsvp.Controllers)), ("global-logging", ("global_logging", Rsvp.GlobalLogging)), ("global-bandwidth", ("global_bandwidth", Rsvp.GlobalBandwidth)), ("interfaces", ("interfaces", Rsvp.Interfaces)), ("signalling", ("signalling", Rsvp.Signalling)), ("authentication", ("authentication", Rsvp.Authentication))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict() self.neighbors = Rsvp.Neighbors() self.neighbors.parent = self self._children_name_map["neighbors"] = "neighbors" self._children_yang_names.add("neighbors") self.controllers = Rsvp.Controllers() self.controllers.parent = self self._children_name_map["controllers"] = "controllers" self._children_yang_names.add("controllers") self.global_logging = Rsvp.GlobalLogging() self.global_logging.parent = self self._children_name_map["global_logging"] = "global-logging" self._children_yang_names.add("global-logging") self.global_bandwidth = Rsvp.GlobalBandwidth() self.global_bandwidth.parent = self self._children_name_map["global_bandwidth"] = "global-bandwidth" self._children_yang_names.add("global-bandwidth") self.interfaces = Rsvp.Interfaces() self.interfaces.parent = self self._children_name_map["interfaces"] = "interfaces" self._children_yang_names.add("interfaces") self.signalling = Rsvp.Signalling() self.signalling.parent = self self._children_name_map["signalling"] = "signalling" self._children_yang_names.add("signalling") self.authentication = Rsvp.Authentication() self.authentication.parent = self self._children_name_map["authentication"] = "authentication" self._children_yang_names.add("authentication") self._segment_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp" class Neighbors(Entity): """ RSVP Neighbor Table .. attribute:: neighbor RSVP neighbor configuration **type**\: list of :py:class:`Neighbor <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Neighbors.Neighbor>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Neighbors, self).__init__() self.yang_name = "neighbors" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([("neighbor", ("neighbor", Rsvp.Neighbors.Neighbor))]) self._leafs = OrderedDict() self.neighbor = YList(self) self._segment_path = lambda: "neighbors" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Neighbors, [], name, value) class Neighbor(Entity): """ RSVP neighbor configuration .. attribute:: neighbor (key) Neighbor IP address **type**\: str **pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)? .. attribute:: authentication Configure RSVP authentication **type**\: :py:class:`Authentication <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Neighbors.Neighbor.Authentication>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Neighbors.Neighbor, self).__init__() self.yang_name = "neighbor" self.yang_parent_name = "neighbors" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = ['neighbor'] self._child_container_classes = OrderedDict([("authentication", ("authentication", Rsvp.Neighbors.Neighbor.Authentication))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('neighbor', YLeaf(YType.str, 'neighbor')), ]) self.neighbor = None self.authentication = Rsvp.Neighbors.Neighbor.Authentication() self.authentication.parent = self self._children_name_map["authentication"] = "authentication" self._children_yang_names.add("authentication") self._segment_path = lambda: "neighbor" + "[neighbor='" + str(self.neighbor) + "']" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/neighbors/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Neighbors.Neighbor, ['neighbor'], name, value) class Authentication(Entity): """ Configure RSVP authentication .. attribute:: life_time Life time (in seconds) for each security association **type**\: int **range:** 30..86400 **units**\: second .. attribute:: enable Enable or disable RSVP authentication **type**\: bool .. attribute:: window_size Window\-size to limit number of out\-of\-order messages **type**\: int **range:** 1..64 .. attribute:: key_chain Key chain to authenticate RSVP signalling messages **type**\: str **length:** 1..32 """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Neighbors.Neighbor.Authentication, self).__init__() self.yang_name = "authentication" self.yang_parent_name = "neighbor" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('life_time', YLeaf(YType.uint32, 'life-time')), ('enable', YLeaf(YType.boolean, 'enable')), ('window_size', YLeaf(YType.uint32, 'window-size')), ('key_chain', YLeaf(YType.str, 'key-chain')), ]) self.life_time = None self.enable = None self.window_size = None self.key_chain = None self._segment_path = lambda: "authentication" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Neighbors.Neighbor.Authentication, ['life_time', 'enable', 'window_size', 'key_chain'], name, value) class Controllers(Entity): """ Controller table .. attribute:: controller Controller configuration **type**\: list of :py:class:`Controller <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Controllers.Controller>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Controllers, self).__init__() self.yang_name = "controllers" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([("controller", ("controller", Rsvp.Controllers.Controller))]) self._leafs = OrderedDict() self.controller = YList(self) self._segment_path = lambda: "controllers" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Controllers, [], name, value) class Controller(Entity): """ Controller configuration .. attribute:: controller_name (key) Name of controller **type**\: str **pattern:** [a\-zA\-Z0\-9./\-]+ .. attribute:: cntl_signalling Configure RSVP signalling parameters **type**\: :py:class:`CntlSignalling <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Controllers.Controller.CntlSignalling>` .. attribute:: enable Enable RSVP on an interface **type**\: :py:class:`Empty<ydk.types.Empty>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Controllers.Controller, self).__init__() self.yang_name = "controller" self.yang_parent_name = "controllers" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = ['controller_name'] self._child_container_classes = OrderedDict([("cntl-signalling", ("cntl_signalling", Rsvp.Controllers.Controller.CntlSignalling))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('controller_name', YLeaf(YType.str, 'controller-name')), ('enable', YLeaf(YType.empty, 'enable')), ]) self.controller_name = None self.enable = None self.cntl_signalling = Rsvp.Controllers.Controller.CntlSignalling() self.cntl_signalling.parent = self self._children_name_map["cntl_signalling"] = "cntl-signalling" self._children_yang_names.add("cntl-signalling") self._segment_path = lambda: "controller" + "[controller-name='" + str(self.controller_name) + "']" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/controllers/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Controllers.Controller, ['controller_name', 'enable'], name, value) class CntlSignalling(Entity): """ Configure RSVP signalling parameters .. attribute:: out_of_band Configure RSVP out\-of\-band signalling parameters **type**\: :py:class:`OutOfBand <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Controllers.Controller.CntlSignalling.OutOfBand>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Controllers.Controller.CntlSignalling, self).__init__() self.yang_name = "cntl-signalling" self.yang_parent_name = "controller" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([("out-of-band", ("out_of_band", Rsvp.Controllers.Controller.CntlSignalling.OutOfBand))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict() self.out_of_band = Rsvp.Controllers.Controller.CntlSignalling.OutOfBand() self.out_of_band.parent = self self._children_name_map["out_of_band"] = "out-of-band" self._children_yang_names.add("out-of-band") self._segment_path = lambda: "cntl-signalling" class OutOfBand(Entity): """ Configure RSVP out\-of\-band signalling parameters .. attribute:: missed_messages Configure max number of consecutive missed messages for state expiry for out\-of\-band tunnels **type**\: int **range:** 1..110000 **default value**\: 38000 .. attribute:: refresh_interval Configure interval between successive refreshes for out\-of\-band tunnels **type**\: int **range:** 180..86400 **units**\: second """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Controllers.Controller.CntlSignalling.OutOfBand, self).__init__() self.yang_name = "out-of-band" self.yang_parent_name = "cntl-signalling" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('missed_messages', YLeaf(YType.uint32, 'missed-messages')), ('refresh_interval', YLeaf(YType.uint32, 'refresh-interval')), ]) self.missed_messages = None self.refresh_interval = None self._segment_path = lambda: "out-of-band" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Controllers.Controller.CntlSignalling.OutOfBand, ['missed_messages', 'refresh_interval'], name, value) class GlobalLogging(Entity): """ Global Logging .. attribute:: log_nsr_status Enable NSR Status Logging **type**\: :py:class:`Empty<ydk.types.Empty>` .. attribute:: log_issu_status Enable ISSU Status Logging **type**\: :py:class:`Empty<ydk.types.Empty>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.GlobalLogging, self).__init__() self.yang_name = "global-logging" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('log_nsr_status', YLeaf(YType.empty, 'log-nsr-status')), ('log_issu_status', YLeaf(YType.empty, 'log-issu-status')), ]) self.log_nsr_status = None self.log_issu_status = None self._segment_path = lambda: "global-logging" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.GlobalLogging, ['log_nsr_status', 'log_issu_status'], name, value) class GlobalBandwidth(Entity): """ Configure Global Bandwidth Parameters .. attribute:: default_interface_percent Configure Global RSVP signalling parameters **type**\: :py:class:`DefaultInterfacePercent <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.GlobalBandwidth.DefaultInterfacePercent>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.GlobalBandwidth, self).__init__() self.yang_name = "global-bandwidth" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([("default-interface-percent", ("default_interface_percent", Rsvp.GlobalBandwidth.DefaultInterfacePercent))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict() self.default_interface_percent = Rsvp.GlobalBandwidth.DefaultInterfacePercent() self.default_interface_percent.parent = self self._children_name_map["default_interface_percent"] = "default-interface-percent" self._children_yang_names.add("default-interface-percent") self._segment_path = lambda: "global-bandwidth" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() class DefaultInterfacePercent(Entity): """ Configure Global RSVP signalling parameters .. attribute:: mam Configure global default MAM I/F percent bandwidth parameters **type**\: :py:class:`Mam <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.GlobalBandwidth.DefaultInterfacePercent.Mam>` .. attribute:: rdm Configure global default RDM I/F percent bandwidth parameters **type**\: :py:class:`Rdm <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.GlobalBandwidth.DefaultInterfacePercent.Rdm>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.GlobalBandwidth.DefaultInterfacePercent, self).__init__() self.yang_name = "default-interface-percent" self.yang_parent_name = "global-bandwidth" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([("mam", ("mam", Rsvp.GlobalBandwidth.DefaultInterfacePercent.Mam)), ("rdm", ("rdm", Rsvp.GlobalBandwidth.DefaultInterfacePercent.Rdm))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict() self.mam = Rsvp.GlobalBandwidth.DefaultInterfacePercent.Mam() self.mam.parent = self self._children_name_map["mam"] = "mam" self._children_yang_names.add("mam") self.rdm = Rsvp.GlobalBandwidth.DefaultInterfacePercent.Rdm() self.rdm.parent = self self._children_name_map["rdm"] = "rdm" self._children_yang_names.add("rdm") self._segment_path = lambda: "default-interface-percent" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/global-bandwidth/%s" % self._segment_path() class Mam(Entity): """ Configure global default MAM I/F percent bandwidth parameters .. attribute:: max_res_percent Default maximum reservable I/F % B/W **type**\: int **range:** 0..10000 .. attribute:: bc0_percent Default BC0 pool I/F % B/W **type**\: int **range:** 0..10000 .. attribute:: bc1_percent Default BC1 pool I/F % B/W **type**\: int **range:** 0..10000 """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.GlobalBandwidth.DefaultInterfacePercent.Mam, self).__init__() self.yang_name = "mam" self.yang_parent_name = "default-interface-percent" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('max_res_percent', YLeaf(YType.uint32, 'max-res-percent')), ('bc0_percent', YLeaf(YType.uint32, 'bc0-percent')), ('bc1_percent', YLeaf(YType.uint32, 'bc1-percent')), ]) self.max_res_percent = None self.bc0_percent = None self.bc1_percent = None self._segment_path = lambda: "mam" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/global-bandwidth/default-interface-percent/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.GlobalBandwidth.DefaultInterfacePercent.Mam, ['max_res_percent', 'bc0_percent', 'bc1_percent'], name, value) class Rdm(Entity): """ Configure global default RDM I/F percent bandwidth parameters .. attribute:: bc0_percent Default BC0 pool I/F % B/W **type**\: int **range:** 0..10000 .. attribute:: bc1_percent Default BC1 pool I/F % B/W **type**\: int **range:** 0..10000 """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.GlobalBandwidth.DefaultInterfacePercent.Rdm, self).__init__() self.yang_name = "rdm" self.yang_parent_name = "default-interface-percent" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('bc0_percent', YLeaf(YType.uint32, 'bc0-percent')), ('bc1_percent', YLeaf(YType.uint32, 'bc1-percent')), ]) self.bc0_percent = None self.bc1_percent = None self._segment_path = lambda: "rdm" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/global-bandwidth/default-interface-percent/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.GlobalBandwidth.DefaultInterfacePercent.Rdm, ['bc0_percent', 'bc1_percent'], name, value) class Interfaces(Entity): """ Interface table .. attribute:: interface Interface configuration **type**\: list of :py:class:`Interface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Interfaces.Interface>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces, self).__init__() self.yang_name = "interfaces" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([("interface", ("interface", Rsvp.Interfaces.Interface))]) self._leafs = OrderedDict() self.interface = YList(self) self._segment_path = lambda: "interfaces" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces, [], name, value) class Interface(Entity): """ Interface configuration .. attribute:: name (key) Name of interface **type**\: str **pattern:** [a\-zA\-Z0\-9./\-]+ .. attribute:: if_signalling Configure RSVP signalling parameters **type**\: :py:class:`IfSignalling <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Interfaces.Interface.IfSignalling>` .. attribute:: bandwidth Configure Bandwidth **type**\: :py:class:`Bandwidth <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Interfaces.Interface.Bandwidth>` .. attribute:: enable Enable RSVP on an interface **type**\: :py:class:`Empty<ydk.types.Empty>` .. attribute:: authentication Configure RSVP authentication **type**\: :py:class:`Authentication <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Interfaces.Interface.Authentication>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface, self).__init__() self.yang_name = "interface" self.yang_parent_name = "interfaces" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = ['name'] self._child_container_classes = OrderedDict([("if-signalling", ("if_signalling", Rsvp.Interfaces.Interface.IfSignalling)), ("bandwidth", ("bandwidth", Rsvp.Interfaces.Interface.Bandwidth)), ("authentication", ("authentication", Rsvp.Interfaces.Interface.Authentication))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('name', YLeaf(YType.str, 'name')), ('enable', YLeaf(YType.empty, 'enable')), ]) self.name = None self.enable = None self.if_signalling = Rsvp.Interfaces.Interface.IfSignalling() self.if_signalling.parent = self self._children_name_map["if_signalling"] = "if-signalling" self._children_yang_names.add("if-signalling") self.bandwidth = Rsvp.Interfaces.Interface.Bandwidth() self.bandwidth.parent = self self._children_name_map["bandwidth"] = "bandwidth" self._children_yang_names.add("bandwidth") self.authentication = Rsvp.Interfaces.Interface.Authentication() self.authentication.parent = self self._children_name_map["authentication"] = "authentication" self._children_yang_names.add("authentication") self._segment_path = lambda: "interface" + "[name='" + str(self.name) + "']" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/interfaces/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface, ['name', 'enable'], name, value) class IfSignalling(Entity): """ Configure RSVP signalling parameters .. attribute:: refresh_reduction Configure RSVP Refresh Reduction parameters **type**\: :py:class:`RefreshReduction <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Interfaces.Interface.IfSignalling.RefreshReduction>` .. attribute:: interval_rate Configure number of messages to be sent per interval **type**\: :py:class:`IntervalRate <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Interfaces.Interface.IfSignalling.IntervalRate>` .. attribute:: dscp Differentiated Services Code Point (DSCP) **type**\: int **range:** 0..63 .. attribute:: missed_messages Configure max number of consecutive missed messages for state expiry **type**\: int **range:** 1..8 **default value**\: 4 .. attribute:: hello_graceful_restart_if_based Enable IF\-based Hello adjacency on a RSVP interface **type**\: :py:class:`Empty<ydk.types.Empty>` .. attribute:: pacing Enable rate\-limiting on the interface **type**\: :py:class:`Empty<ydk.types.Empty>` .. attribute:: refresh_interval Configure interval between successive refreshes **type**\: int **range:** 10..180 **units**\: second **default value**\: 45 .. attribute:: out_of_band Configure RSVP out\-of\-band signalling parameters **type**\: :py:class:`OutOfBand <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Interfaces.Interface.IfSignalling.OutOfBand>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.IfSignalling, self).__init__() self.yang_name = "if-signalling" self.yang_parent_name = "interface" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([("refresh-reduction", ("refresh_reduction", Rsvp.Interfaces.Interface.IfSignalling.RefreshReduction)), ("interval-rate", ("interval_rate", Rsvp.Interfaces.Interface.IfSignalling.IntervalRate)), ("out-of-band", ("out_of_band", Rsvp.Interfaces.Interface.IfSignalling.OutOfBand))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('dscp', YLeaf(YType.uint32, 'dscp')), ('missed_messages', YLeaf(YType.uint32, 'missed-messages')), ('hello_graceful_restart_if_based', YLeaf(YType.empty, 'hello-graceful-restart-if-based')), ('pacing', YLeaf(YType.empty, 'pacing')), ('refresh_interval', YLeaf(YType.uint32, 'refresh-interval')), ]) self.dscp = None self.missed_messages = None self.hello_graceful_restart_if_based = None self.pacing = None self.refresh_interval = None self.refresh_reduction = Rsvp.Interfaces.Interface.IfSignalling.RefreshReduction() self.refresh_reduction.parent = self self._children_name_map["refresh_reduction"] = "refresh-reduction" self._children_yang_names.add("refresh-reduction") self.interval_rate = Rsvp.Interfaces.Interface.IfSignalling.IntervalRate() self.interval_rate.parent = self self._children_name_map["interval_rate"] = "interval-rate" self._children_yang_names.add("interval-rate") self.out_of_band = Rsvp.Interfaces.Interface.IfSignalling.OutOfBand() self.out_of_band.parent = self self._children_name_map["out_of_band"] = "out-of-band" self._children_yang_names.add("out-of-band") self._segment_path = lambda: "if-signalling" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.IfSignalling, ['dscp', 'missed_messages', 'hello_graceful_restart_if_based', 'pacing', 'refresh_interval'], name, value) class RefreshReduction(Entity): """ Configure RSVP Refresh Reduction parameters .. attribute:: disable Disable refresh reduction **type**\: :py:class:`Empty<ydk.types.Empty>` .. attribute:: reliable_ack_max_size Configure max size of a single RSVP ACK message **type**\: int **range:** 20..65000 **units**\: byte **default value**\: 4096 .. attribute:: reliable_ack_hold_time Configure hold time for sending RSVP ACK message(s) **type**\: int **range:** 100..5000 **units**\: millisecond **default value**\: 400 .. attribute:: reliable_retransmit_time Configure min delay to wait for an ACK before a retransmit **type**\: int **range:** 100..10000 **units**\: millisecond **default value**\: 2100 .. attribute:: reliable_s_refresh Configure use of reliable messaging for summary refresh **type**\: :py:class:`Empty<ydk.types.Empty>` .. attribute:: summary_max_size Configure max size of a single RSVP summary refresh message **type**\: int **range:** 20..65000 **units**\: byte **default value**\: 4096 .. attribute:: bundle_message_max_size Configure maximum size of a single RSVP Bundle message **type**\: int **range:** 512..65000 **units**\: byte **default value**\: 4096 """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.IfSignalling.RefreshReduction, self).__init__() self.yang_name = "refresh-reduction" self.yang_parent_name = "if-signalling" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('disable', YLeaf(YType.empty, 'disable')), ('reliable_ack_max_size', YLeaf(YType.uint32, 'reliable-ack-max-size')), ('reliable_ack_hold_time', YLeaf(YType.uint32, 'reliable-ack-hold-time')), ('reliable_retransmit_time', YLeaf(YType.uint32, 'reliable-retransmit-time')), ('reliable_s_refresh', YLeaf(YType.empty, 'reliable-s-refresh')), ('summary_max_size', YLeaf(YType.uint32, 'summary-max-size')), ('bundle_message_max_size', YLeaf(YType.uint32, 'bundle-message-max-size')), ]) self.disable = None self.reliable_ack_max_size = None self.reliable_ack_hold_time = None self.reliable_retransmit_time = None self.reliable_s_refresh = None self.summary_max_size = None self.bundle_message_max_size = None self._segment_path = lambda: "refresh-reduction" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.IfSignalling.RefreshReduction, ['disable', 'reliable_ack_max_size', 'reliable_ack_hold_time', 'reliable_retransmit_time', 'reliable_s_refresh', 'summary_max_size', 'bundle_message_max_size'], name, value) class IntervalRate(Entity): """ Configure number of messages to be sent per interval .. attribute:: messages_per_interval Number of messages to be sent per interval **type**\: int **range:** 1..500 **default value**\: 100 .. attribute:: interval_size Size of an interval (milliseconds) **type**\: int **range:** 250..2000 **units**\: millisecond **default value**\: 1000 """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.IfSignalling.IntervalRate, self).__init__() self.yang_name = "interval-rate" self.yang_parent_name = "if-signalling" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('messages_per_interval', YLeaf(YType.uint32, 'messages-per-interval')), ('interval_size', YLeaf(YType.uint32, 'interval-size')), ]) self.messages_per_interval = None self.interval_size = None self._segment_path = lambda: "interval-rate" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.IfSignalling.IntervalRate, ['messages_per_interval', 'interval_size'], name, value) class OutOfBand(Entity): """ Configure RSVP out\-of\-band signalling parameters .. attribute:: missed_messages Configure max number of consecutive missed messages for state expiry for out\-of\-band tunnels **type**\: int **range:** 1..110000 **default value**\: 38000 .. attribute:: refresh_interval Configure interval between successive refreshes for out\-of\-band tunnels **type**\: int **range:** 180..86400 **units**\: second """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.IfSignalling.OutOfBand, self).__init__() self.yang_name = "out-of-band" self.yang_parent_name = "if-signalling" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('missed_messages', YLeaf(YType.uint32, 'missed-messages')), ('refresh_interval', YLeaf(YType.uint32, 'refresh-interval')), ]) self.missed_messages = None self.refresh_interval = None self._segment_path = lambda: "out-of-band" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.IfSignalling.OutOfBand, ['missed_messages', 'refresh_interval'], name, value) class Bandwidth(Entity): """ Configure Bandwidth .. attribute:: mam Configure MAM bandwidth parameters **type**\: :py:class:`Mam <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Interfaces.Interface.Bandwidth.Mam>` .. attribute:: rdm Configure RDM bandwidth parameters **type**\: :py:class:`Rdm <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Interfaces.Interface.Bandwidth.Rdm>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.Bandwidth, self).__init__() self.yang_name = "bandwidth" self.yang_parent_name = "interface" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([("mam", ("mam", Rsvp.Interfaces.Interface.Bandwidth.Mam)), ("rdm", ("rdm", Rsvp.Interfaces.Interface.Bandwidth.Rdm))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict() self.mam = Rsvp.Interfaces.Interface.Bandwidth.Mam() self.mam.parent = self self._children_name_map["mam"] = "mam" self._children_yang_names.add("mam") self.rdm = Rsvp.Interfaces.Interface.Bandwidth.Rdm() self.rdm.parent = self self._children_name_map["rdm"] = "rdm" self._children_yang_names.add("rdm") self._segment_path = lambda: "bandwidth" class Mam(Entity): """ Configure MAM bandwidth parameters .. attribute:: max_resv_bandwidth Maximum reservable bandwidth (Kbps or percent of physical bandwidth) **type**\: int **range:** 0..4294967295 .. attribute:: max_resv_flow Largest reservable flow (Kbps or percent of physical bandwidth) **type**\: int **range:** 0..4294967295 .. attribute:: bc0_bandwidth Reservable bandwidth in BC0 (Kbps or percent of physical bandwidth) **type**\: int **range:** 0..4294967295 .. attribute:: bc1_bandwidth Reservable bandwidth in BC1 (Kbps or percent of physical bandwidth) **type**\: int **range:** 0..4294967295 .. attribute:: bandwidth_mode Absolute or Percentage bandwidth mode **type**\: :py:class:`RsvpBwCfg <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.RsvpBwCfg>` **units**\: percentage """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.Bandwidth.Mam, self).__init__() self.yang_name = "mam" self.yang_parent_name = "bandwidth" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('max_resv_bandwidth', YLeaf(YType.uint32, 'max-resv-bandwidth')), ('max_resv_flow', YLeaf(YType.uint32, 'max-resv-flow')), ('bc0_bandwidth', YLeaf(YType.uint32, 'bc0-bandwidth')), ('bc1_bandwidth', YLeaf(YType.uint32, 'bc1-bandwidth')), ('bandwidth_mode', YLeaf(YType.enumeration, 'bandwidth-mode')), ]) self.max_resv_bandwidth = None self.max_resv_flow = None self.bc0_bandwidth = None self.bc1_bandwidth = None self.bandwidth_mode = None self._segment_path = lambda: "mam" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.Bandwidth.Mam, ['max_resv_bandwidth', 'max_resv_flow', 'bc0_bandwidth', 'bc1_bandwidth', 'bandwidth_mode'], name, value) class Rdm(Entity): """ Configure RDM bandwidth parameters .. attribute:: max_resv_flow Largest reservable flow (Kbps or percent of physical bandwidth) **type**\: int **range:** 0..4294967295 .. attribute:: bc0_bandwidth Reservable bandwidth in BC0 (Kbps or percent of physical bandwidth) **type**\: int **range:** 0..4294967295 .. attribute:: bc1_bandwidth Reservable bandwidth in BC1 (Kbps or percent of physical bandwidth) **type**\: int **range:** 0..4294967295 .. attribute:: rdm_keyword Set requests should always use RDM **type**\: :py:class:`RsvpRdm <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.RsvpRdm>` .. attribute:: bc0_keyword Set requests should always use BC0 **type**\: :py:class:`RsvpBc0 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.RsvpBc0>` .. attribute:: bc1_keyword Set requests should always use BC1 **type**\: :py:class:`RsvpBc1 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.RsvpBc1>` .. attribute:: bandwidth_mode Absolute or Percentage bandwidth mode **type**\: :py:class:`RsvpBwCfg <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.RsvpBwCfg>` **units**\: percentage """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.Bandwidth.Rdm, self).__init__() self.yang_name = "rdm" self.yang_parent_name = "bandwidth" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('max_resv_flow', YLeaf(YType.uint32, 'max-resv-flow')), ('bc0_bandwidth', YLeaf(YType.uint32, 'bc0-bandwidth')), ('bc1_bandwidth', YLeaf(YType.uint32, 'bc1-bandwidth')), ('rdm_keyword', YLeaf(YType.enumeration, 'rdm-keyword')), ('bc0_keyword', YLeaf(YType.enumeration, 'bc0-keyword')), ('bc1_keyword', YLeaf(YType.enumeration, 'bc1-keyword')), ('bandwidth_mode', YLeaf(YType.enumeration, 'bandwidth-mode')), ]) self.max_resv_flow = None self.bc0_bandwidth = None self.bc1_bandwidth = None self.rdm_keyword = None self.bc0_keyword = None self.bc1_keyword = None self.bandwidth_mode = None self._segment_path = lambda: "rdm" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.Bandwidth.Rdm, ['max_resv_flow', 'bc0_bandwidth', 'bc1_bandwidth', 'rdm_keyword', 'bc0_keyword', 'bc1_keyword', 'bandwidth_mode'], name, value) class Authentication(Entity): """ Configure RSVP authentication .. attribute:: life_time Life time (in seconds) for each security association **type**\: int **range:** 30..86400 **units**\: second .. attribute:: enable Enable or disable RSVP authentication **type**\: bool .. attribute:: window_size Window\-size to limit number of out\-of\-order messages **type**\: int **range:** 1..64 .. attribute:: key_chain Key chain to authenticate RSVP signalling messages **type**\: str **length:** 1..32 """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.Authentication, self).__init__() self.yang_name = "authentication" self.yang_parent_name = "interface" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('life_time', YLeaf(YType.uint32, 'life-time')), ('enable', YLeaf(YType.boolean, 'enable')), ('window_size', YLeaf(YType.uint32, 'window-size')), ('key_chain', YLeaf(YType.str, 'key-chain')), ]) self.life_time = None self.enable = None self.window_size = None self.key_chain = None self._segment_path = lambda: "authentication" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.Authentication, ['life_time', 'enable', 'window_size', 'key_chain'], name, value) class Signalling(Entity): """ Configure Global RSVP signalling parameters .. attribute:: global_out_of_band Configure out\-of\-band signalling parameters **type**\: :py:class:`GlobalOutOfBand <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Signalling.GlobalOutOfBand>` .. attribute:: graceful_restart Configure RSVP Graceful\-Restart parameters **type**\: :py:class:`GracefulRestart <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Signalling.GracefulRestart>` .. attribute:: prefix_filtering Configure prefix filtering parameters **type**\: :py:class:`PrefixFiltering <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Signalling.PrefixFiltering>` .. attribute:: pesr Sending Path Error with State\-Removal flag **type**\: :py:class:`Pesr <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Signalling.Pesr>` .. attribute:: checksum RSVP message checksum computation **type**\: :py:class:`Checksum <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Signalling.Checksum>` .. attribute:: hello_graceful_restart_misses Configure max number of consecutive missed Hello messages **type**\: int **range:** 1..10 **default value**\: 3 .. attribute:: hello_graceful_restart_interval Configure interval between successive Hello messages **type**\: int **range:** 3000..30000 **units**\: millisecond **default value**\: 5000 """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling, self).__init__() self.yang_name = "signalling" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([("global-out-of-band", ("global_out_of_band", Rsvp.Signalling.GlobalOutOfBand)), ("graceful-restart", ("graceful_restart", Rsvp.Signalling.GracefulRestart)), ("prefix-filtering", ("prefix_filtering", Rsvp.Signalling.PrefixFiltering)), ("pesr", ("pesr", Rsvp.Signalling.Pesr)), ("checksum", ("checksum", Rsvp.Signalling.Checksum))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('hello_graceful_restart_misses', YLeaf(YType.uint32, 'hello-graceful-restart-misses')), ('hello_graceful_restart_interval', YLeaf(YType.uint32, 'hello-graceful-restart-interval')), ]) self.hello_graceful_restart_misses = None self.hello_graceful_restart_interval = None self.global_out_of_band = Rsvp.Signalling.GlobalOutOfBand() self.global_out_of_band.parent = self self._children_name_map["global_out_of_band"] = "global-out-of-band" self._children_yang_names.add("global-out-of-band") self.graceful_restart = Rsvp.Signalling.GracefulRestart() self.graceful_restart.parent = self self._children_name_map["graceful_restart"] = "graceful-restart" self._children_yang_names.add("graceful-restart") self.prefix_filtering = Rsvp.Signalling.PrefixFiltering() self.prefix_filtering.parent = self self._children_name_map["prefix_filtering"] = "prefix-filtering" self._children_yang_names.add("prefix-filtering") self.pesr = Rsvp.Signalling.Pesr() self.pesr.parent = self self._children_name_map["pesr"] = "pesr" self._children_yang_names.add("pesr") self.checksum = Rsvp.Signalling.Checksum() self.checksum.parent = self self._children_name_map["checksum"] = "checksum" self._children_yang_names.add("checksum") self._segment_path = lambda: "signalling" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling, ['hello_graceful_restart_misses', 'hello_graceful_restart_interval'], name, value) class GlobalOutOfBand(Entity): """ Configure out\-of\-band signalling parameters .. attribute:: vrf VRF used for out\-of\-band control signalling **type**\: str **length:** 1..32 """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.GlobalOutOfBand, self).__init__() self.yang_name = "global-out-of-band" self.yang_parent_name = "signalling" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('vrf', YLeaf(YType.str, 'vrf')), ]) self.vrf = None self._segment_path = lambda: "global-out-of-band" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.GlobalOutOfBand, ['vrf'], name, value) class GracefulRestart(Entity): """ Configure RSVP Graceful\-Restart parameters .. attribute:: lsp_class_type Send LSP's ctype for recovery and suggested label **type**\: :py:class:`LspClassType <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Signalling.GracefulRestart.LspClassType>` .. attribute:: enable Enable RSVP graceful restart **type**\: bool .. attribute:: restart_time Graceful restart time (seconds) **type**\: int **range:** 60..3600 **units**\: second **default value**\: 120 .. attribute:: recovery_time Graceful restart recovery time (seconds) **type**\: int **range:** 0..3600 **units**\: second **default value**\: 120 """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.GracefulRestart, self).__init__() self.yang_name = "graceful-restart" self.yang_parent_name = "signalling" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([("lsp-class-type", ("lsp_class_type", Rsvp.Signalling.GracefulRestart.LspClassType))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('enable', YLeaf(YType.boolean, 'enable')), ('restart_time', YLeaf(YType.uint32, 'restart-time')), ('recovery_time', YLeaf(YType.uint32, 'recovery-time')), ]) self.enable = None self.restart_time = None self.recovery_time = None self.lsp_class_type = Rsvp.Signalling.GracefulRestart.LspClassType() self.lsp_class_type.parent = self self._children_name_map["lsp_class_type"] = "lsp-class-type" self._children_yang_names.add("lsp-class-type") self._segment_path = lambda: "graceful-restart" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.GracefulRestart, ['enable', 'restart_time', 'recovery_time'], name, value) class LspClassType(Entity): """ Send LSP's ctype for recovery and suggested label .. attribute:: enable Send LSP's ctype for recovery and suggested label **type**\: bool """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.GracefulRestart.LspClassType, self).__init__() self.yang_name = "lsp-class-type" self.yang_parent_name = "graceful-restart" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('enable', YLeaf(YType.boolean, 'enable')), ]) self.enable = None self._segment_path = lambda: "lsp-class-type" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/graceful-restart/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.GracefulRestart.LspClassType, ['enable'], name, value) class PrefixFiltering(Entity): """ Configure prefix filtering parameters .. attribute:: default_deny_action Configure RSVP behaviour for scenarios where ACL match yields a default (implicit) deny **type**\: :py:class:`DefaultDenyAction <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_rsvp_cfg.Rsvp.Signalling.PrefixFiltering.DefaultDenyAction>` .. attribute:: acl Configure an ACL to perform prefix filtering of RSVP Router Alert messages **type**\: str **length:** 1..65 """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.PrefixFiltering, self).__init__() self.yang_name = "prefix-filtering" self.yang_parent_name = "signalling" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([("default-deny-action", ("default_deny_action", Rsvp.Signalling.PrefixFiltering.DefaultDenyAction))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('acl', YLeaf(YType.str, 'acl')), ]) self.acl = None self.default_deny_action = Rsvp.Signalling.PrefixFiltering.DefaultDenyAction() self.default_deny_action.parent = self self._children_name_map["default_deny_action"] = "default-deny-action" self._children_yang_names.add("default-deny-action") self._segment_path = lambda: "prefix-filtering" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.PrefixFiltering, ['acl'], name, value) class DefaultDenyAction(Entity): """ Configure RSVP behaviour for scenarios where ACL match yields a default (implicit) deny .. attribute:: drop Configure RSVP to drop packets when ACL match yields a default (implicit) deny **type**\: :py:class:`Empty<ydk.types.Empty>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.PrefixFiltering.DefaultDenyAction, self).__init__() self.yang_name = "default-deny-action" self.yang_parent_name = "prefix-filtering" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('drop', YLeaf(YType.empty, 'drop')), ]) self.drop = None self._segment_path = lambda: "default-deny-action" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/prefix-filtering/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.PrefixFiltering.DefaultDenyAction, ['drop'], name, value) class Pesr(Entity): """ Sending Path Error with State\-Removal flag .. attribute:: disable Disable RSVP PESR **type**\: :py:class:`Empty<ydk.types.Empty>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.Pesr, self).__init__() self.yang_name = "pesr" self.yang_parent_name = "signalling" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('disable', YLeaf(YType.empty, 'disable')), ]) self.disable = None self._segment_path = lambda: "pesr" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.Pesr, ['disable'], name, value) class Checksum(Entity): """ RSVP message checksum computation .. attribute:: disable Disable RSVP message checksum computation **type**\: :py:class:`Empty<ydk.types.Empty>` """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.Checksum, self).__init__() self.yang_name = "checksum" self.yang_parent_name = "signalling" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('disable', YLeaf(YType.empty, 'disable')), ]) self.disable = None self._segment_path = lambda: "checksum" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.Checksum, ['disable'], name, value) class Authentication(Entity): """ Configure RSVP authentication .. attribute:: life_time Life time (in seconds) for each security association **type**\: int **range:** 30..86400 **units**\: second .. attribute:: enable Enable or disable RSVP authentication **type**\: bool .. attribute:: window_size Window\-size to limit number of out\-of\-order messages **type**\: int **range:** 1..64 .. attribute:: key_chain Key chain to authenticate RSVP signalling messages **type**\: str **length:** 1..32 """ _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Authentication, self).__init__() self.yang_name = "authentication" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('life_time', YLeaf(YType.uint32, 'life-time')), ('enable', YLeaf(YType.boolean, 'enable')), ('window_size', YLeaf(YType.uint32, 'window-size')), ('key_chain', YLeaf(YType.str, 'key-chain')), ]) self.life_time = None self.enable = None self.window_size = None self.key_chain = None self._segment_path = lambda: "authentication" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Authentication, ['life_time', 'enable', 'window_size', 'key_chain'], name, value) def clone_ptr(self): self._top_entity = Rsvp() return self._top_entity
39.615658
436
0.512576
from collections import OrderedDict from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64 from ydk.filters import YFilter from ydk.errors import YError, YModelError from ydk.errors.error_handler import handle_type_error as _handle_type_error class RsvpBc0(Enum): bc0 = Enum.YLeaf(1, "bc0") global_pool = Enum.YLeaf(2, "global-pool") not_specified = Enum.YLeaf(3, "not-specified") class RsvpBc1(Enum): bc1 = Enum.YLeaf(1, "bc1") sub_pool = Enum.YLeaf(2, "sub-pool") class RsvpBwCfg(Enum): absolute = Enum.YLeaf(0, "absolute") percentage = Enum.YLeaf(1, "percentage") class RsvpRdm(Enum): rdm = Enum.YLeaf(1, "rdm") not_specified = Enum.YLeaf(2, "not-specified") use_default_bandwidth = Enum.YLeaf(3, "use-default-bandwidth") class Rsvp(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp, self).__init__() self._top_entity = None self.yang_name = "rsvp" self.yang_parent_name = "Cisco-IOS-XR-ip-rsvp-cfg" self.is_top_level_class = True self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([("neighbors", ("neighbors", Rsvp.Neighbors)), ("controllers", ("controllers", Rsvp.Controllers)), ("global-logging", ("global_logging", Rsvp.GlobalLogging)), ("global-bandwidth", ("global_bandwidth", Rsvp.GlobalBandwidth)), ("interfaces", ("interfaces", Rsvp.Interfaces)), ("signalling", ("signalling", Rsvp.Signalling)), ("authentication", ("authentication", Rsvp.Authentication))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict() self.neighbors = Rsvp.Neighbors() self.neighbors.parent = self self._children_name_map["neighbors"] = "neighbors" self._children_yang_names.add("neighbors") self.controllers = Rsvp.Controllers() self.controllers.parent = self self._children_name_map["controllers"] = "controllers" self._children_yang_names.add("controllers") self.global_logging = Rsvp.GlobalLogging() self.global_logging.parent = self self._children_name_map["global_logging"] = "global-logging" self._children_yang_names.add("global-logging") self.global_bandwidth = Rsvp.GlobalBandwidth() self.global_bandwidth.parent = self self._children_name_map["global_bandwidth"] = "global-bandwidth" self._children_yang_names.add("global-bandwidth") self.interfaces = Rsvp.Interfaces() self.interfaces.parent = self self._children_name_map["interfaces"] = "interfaces" self._children_yang_names.add("interfaces") self.signalling = Rsvp.Signalling() self.signalling.parent = self self._children_name_map["signalling"] = "signalling" self._children_yang_names.add("signalling") self.authentication = Rsvp.Authentication() self.authentication.parent = self self._children_name_map["authentication"] = "authentication" self._children_yang_names.add("authentication") self._segment_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp" class Neighbors(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Neighbors, self).__init__() self.yang_name = "neighbors" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([("neighbor", ("neighbor", Rsvp.Neighbors.Neighbor))]) self._leafs = OrderedDict() self.neighbor = YList(self) self._segment_path = lambda: "neighbors" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Neighbors, [], name, value) class Neighbor(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Neighbors.Neighbor, self).__init__() self.yang_name = "neighbor" self.yang_parent_name = "neighbors" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = ['neighbor'] self._child_container_classes = OrderedDict([("authentication", ("authentication", Rsvp.Neighbors.Neighbor.Authentication))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('neighbor', YLeaf(YType.str, 'neighbor')), ]) self.neighbor = None self.authentication = Rsvp.Neighbors.Neighbor.Authentication() self.authentication.parent = self self._children_name_map["authentication"] = "authentication" self._children_yang_names.add("authentication") self._segment_path = lambda: "neighbor" + "[neighbor='" + str(self.neighbor) + "']" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/neighbors/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Neighbors.Neighbor, ['neighbor'], name, value) class Authentication(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Neighbors.Neighbor.Authentication, self).__init__() self.yang_name = "authentication" self.yang_parent_name = "neighbor" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('life_time', YLeaf(YType.uint32, 'life-time')), ('enable', YLeaf(YType.boolean, 'enable')), ('window_size', YLeaf(YType.uint32, 'window-size')), ('key_chain', YLeaf(YType.str, 'key-chain')), ]) self.life_time = None self.enable = None self.window_size = None self.key_chain = None self._segment_path = lambda: "authentication" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Neighbors.Neighbor.Authentication, ['life_time', 'enable', 'window_size', 'key_chain'], name, value) class Controllers(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Controllers, self).__init__() self.yang_name = "controllers" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([("controller", ("controller", Rsvp.Controllers.Controller))]) self._leafs = OrderedDict() self.controller = YList(self) self._segment_path = lambda: "controllers" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Controllers, [], name, value) class Controller(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Controllers.Controller, self).__init__() self.yang_name = "controller" self.yang_parent_name = "controllers" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = ['controller_name'] self._child_container_classes = OrderedDict([("cntl-signalling", ("cntl_signalling", Rsvp.Controllers.Controller.CntlSignalling))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('controller_name', YLeaf(YType.str, 'controller-name')), ('enable', YLeaf(YType.empty, 'enable')), ]) self.controller_name = None self.enable = None self.cntl_signalling = Rsvp.Controllers.Controller.CntlSignalling() self.cntl_signalling.parent = self self._children_name_map["cntl_signalling"] = "cntl-signalling" self._children_yang_names.add("cntl-signalling") self._segment_path = lambda: "controller" + "[controller-name='" + str(self.controller_name) + "']" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/controllers/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Controllers.Controller, ['controller_name', 'enable'], name, value) class CntlSignalling(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Controllers.Controller.CntlSignalling, self).__init__() self.yang_name = "cntl-signalling" self.yang_parent_name = "controller" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([("out-of-band", ("out_of_band", Rsvp.Controllers.Controller.CntlSignalling.OutOfBand))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict() self.out_of_band = Rsvp.Controllers.Controller.CntlSignalling.OutOfBand() self.out_of_band.parent = self self._children_name_map["out_of_band"] = "out-of-band" self._children_yang_names.add("out-of-band") self._segment_path = lambda: "cntl-signalling" class OutOfBand(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Controllers.Controller.CntlSignalling.OutOfBand, self).__init__() self.yang_name = "out-of-band" self.yang_parent_name = "cntl-signalling" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('missed_messages', YLeaf(YType.uint32, 'missed-messages')), ('refresh_interval', YLeaf(YType.uint32, 'refresh-interval')), ]) self.missed_messages = None self.refresh_interval = None self._segment_path = lambda: "out-of-band" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Controllers.Controller.CntlSignalling.OutOfBand, ['missed_messages', 'refresh_interval'], name, value) class GlobalLogging(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.GlobalLogging, self).__init__() self.yang_name = "global-logging" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('log_nsr_status', YLeaf(YType.empty, 'log-nsr-status')), ('log_issu_status', YLeaf(YType.empty, 'log-issu-status')), ]) self.log_nsr_status = None self.log_issu_status = None self._segment_path = lambda: "global-logging" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.GlobalLogging, ['log_nsr_status', 'log_issu_status'], name, value) class GlobalBandwidth(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.GlobalBandwidth, self).__init__() self.yang_name = "global-bandwidth" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([("default-interface-percent", ("default_interface_percent", Rsvp.GlobalBandwidth.DefaultInterfacePercent))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict() self.default_interface_percent = Rsvp.GlobalBandwidth.DefaultInterfacePercent() self.default_interface_percent.parent = self self._children_name_map["default_interface_percent"] = "default-interface-percent" self._children_yang_names.add("default-interface-percent") self._segment_path = lambda: "global-bandwidth" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() class DefaultInterfacePercent(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.GlobalBandwidth.DefaultInterfacePercent, self).__init__() self.yang_name = "default-interface-percent" self.yang_parent_name = "global-bandwidth" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([("mam", ("mam", Rsvp.GlobalBandwidth.DefaultInterfacePercent.Mam)), ("rdm", ("rdm", Rsvp.GlobalBandwidth.DefaultInterfacePercent.Rdm))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict() self.mam = Rsvp.GlobalBandwidth.DefaultInterfacePercent.Mam() self.mam.parent = self self._children_name_map["mam"] = "mam" self._children_yang_names.add("mam") self.rdm = Rsvp.GlobalBandwidth.DefaultInterfacePercent.Rdm() self.rdm.parent = self self._children_name_map["rdm"] = "rdm" self._children_yang_names.add("rdm") self._segment_path = lambda: "default-interface-percent" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/global-bandwidth/%s" % self._segment_path() class Mam(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.GlobalBandwidth.DefaultInterfacePercent.Mam, self).__init__() self.yang_name = "mam" self.yang_parent_name = "default-interface-percent" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('max_res_percent', YLeaf(YType.uint32, 'max-res-percent')), ('bc0_percent', YLeaf(YType.uint32, 'bc0-percent')), ('bc1_percent', YLeaf(YType.uint32, 'bc1-percent')), ]) self.max_res_percent = None self.bc0_percent = None self.bc1_percent = None self._segment_path = lambda: "mam" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/global-bandwidth/default-interface-percent/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.GlobalBandwidth.DefaultInterfacePercent.Mam, ['max_res_percent', 'bc0_percent', 'bc1_percent'], name, value) class Rdm(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.GlobalBandwidth.DefaultInterfacePercent.Rdm, self).__init__() self.yang_name = "rdm" self.yang_parent_name = "default-interface-percent" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('bc0_percent', YLeaf(YType.uint32, 'bc0-percent')), ('bc1_percent', YLeaf(YType.uint32, 'bc1-percent')), ]) self.bc0_percent = None self.bc1_percent = None self._segment_path = lambda: "rdm" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/global-bandwidth/default-interface-percent/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.GlobalBandwidth.DefaultInterfacePercent.Rdm, ['bc0_percent', 'bc1_percent'], name, value) class Interfaces(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces, self).__init__() self.yang_name = "interfaces" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([("interface", ("interface", Rsvp.Interfaces.Interface))]) self._leafs = OrderedDict() self.interface = YList(self) self._segment_path = lambda: "interfaces" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces, [], name, value) class Interface(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface, self).__init__() self.yang_name = "interface" self.yang_parent_name = "interfaces" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = ['name'] self._child_container_classes = OrderedDict([("if-signalling", ("if_signalling", Rsvp.Interfaces.Interface.IfSignalling)), ("bandwidth", ("bandwidth", Rsvp.Interfaces.Interface.Bandwidth)), ("authentication", ("authentication", Rsvp.Interfaces.Interface.Authentication))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('name', YLeaf(YType.str, 'name')), ('enable', YLeaf(YType.empty, 'enable')), ]) self.name = None self.enable = None self.if_signalling = Rsvp.Interfaces.Interface.IfSignalling() self.if_signalling.parent = self self._children_name_map["if_signalling"] = "if-signalling" self._children_yang_names.add("if-signalling") self.bandwidth = Rsvp.Interfaces.Interface.Bandwidth() self.bandwidth.parent = self self._children_name_map["bandwidth"] = "bandwidth" self._children_yang_names.add("bandwidth") self.authentication = Rsvp.Interfaces.Interface.Authentication() self.authentication.parent = self self._children_name_map["authentication"] = "authentication" self._children_yang_names.add("authentication") self._segment_path = lambda: "interface" + "[name='" + str(self.name) + "']" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/interfaces/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface, ['name', 'enable'], name, value) class IfSignalling(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.IfSignalling, self).__init__() self.yang_name = "if-signalling" self.yang_parent_name = "interface" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([("refresh-reduction", ("refresh_reduction", Rsvp.Interfaces.Interface.IfSignalling.RefreshReduction)), ("interval-rate", ("interval_rate", Rsvp.Interfaces.Interface.IfSignalling.IntervalRate)), ("out-of-band", ("out_of_band", Rsvp.Interfaces.Interface.IfSignalling.OutOfBand))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('dscp', YLeaf(YType.uint32, 'dscp')), ('missed_messages', YLeaf(YType.uint32, 'missed-messages')), ('hello_graceful_restart_if_based', YLeaf(YType.empty, 'hello-graceful-restart-if-based')), ('pacing', YLeaf(YType.empty, 'pacing')), ('refresh_interval', YLeaf(YType.uint32, 'refresh-interval')), ]) self.dscp = None self.missed_messages = None self.hello_graceful_restart_if_based = None self.pacing = None self.refresh_interval = None self.refresh_reduction = Rsvp.Interfaces.Interface.IfSignalling.RefreshReduction() self.refresh_reduction.parent = self self._children_name_map["refresh_reduction"] = "refresh-reduction" self._children_yang_names.add("refresh-reduction") self.interval_rate = Rsvp.Interfaces.Interface.IfSignalling.IntervalRate() self.interval_rate.parent = self self._children_name_map["interval_rate"] = "interval-rate" self._children_yang_names.add("interval-rate") self.out_of_band = Rsvp.Interfaces.Interface.IfSignalling.OutOfBand() self.out_of_band.parent = self self._children_name_map["out_of_band"] = "out-of-band" self._children_yang_names.add("out-of-band") self._segment_path = lambda: "if-signalling" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.IfSignalling, ['dscp', 'missed_messages', 'hello_graceful_restart_if_based', 'pacing', 'refresh_interval'], name, value) class RefreshReduction(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.IfSignalling.RefreshReduction, self).__init__() self.yang_name = "refresh-reduction" self.yang_parent_name = "if-signalling" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('disable', YLeaf(YType.empty, 'disable')), ('reliable_ack_max_size', YLeaf(YType.uint32, 'reliable-ack-max-size')), ('reliable_ack_hold_time', YLeaf(YType.uint32, 'reliable-ack-hold-time')), ('reliable_retransmit_time', YLeaf(YType.uint32, 'reliable-retransmit-time')), ('reliable_s_refresh', YLeaf(YType.empty, 'reliable-s-refresh')), ('summary_max_size', YLeaf(YType.uint32, 'summary-max-size')), ('bundle_message_max_size', YLeaf(YType.uint32, 'bundle-message-max-size')), ]) self.disable = None self.reliable_ack_max_size = None self.reliable_ack_hold_time = None self.reliable_retransmit_time = None self.reliable_s_refresh = None self.summary_max_size = None self.bundle_message_max_size = None self._segment_path = lambda: "refresh-reduction" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.IfSignalling.RefreshReduction, ['disable', 'reliable_ack_max_size', 'reliable_ack_hold_time', 'reliable_retransmit_time', 'reliable_s_refresh', 'summary_max_size', 'bundle_message_max_size'], name, value) class IntervalRate(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.IfSignalling.IntervalRate, self).__init__() self.yang_name = "interval-rate" self.yang_parent_name = "if-signalling" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('messages_per_interval', YLeaf(YType.uint32, 'messages-per-interval')), ('interval_size', YLeaf(YType.uint32, 'interval-size')), ]) self.messages_per_interval = None self.interval_size = None self._segment_path = lambda: "interval-rate" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.IfSignalling.IntervalRate, ['messages_per_interval', 'interval_size'], name, value) class OutOfBand(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.IfSignalling.OutOfBand, self).__init__() self.yang_name = "out-of-band" self.yang_parent_name = "if-signalling" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('missed_messages', YLeaf(YType.uint32, 'missed-messages')), ('refresh_interval', YLeaf(YType.uint32, 'refresh-interval')), ]) self.missed_messages = None self.refresh_interval = None self._segment_path = lambda: "out-of-band" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.IfSignalling.OutOfBand, ['missed_messages', 'refresh_interval'], name, value) class Bandwidth(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.Bandwidth, self).__init__() self.yang_name = "bandwidth" self.yang_parent_name = "interface" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([("mam", ("mam", Rsvp.Interfaces.Interface.Bandwidth.Mam)), ("rdm", ("rdm", Rsvp.Interfaces.Interface.Bandwidth.Rdm))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict() self.mam = Rsvp.Interfaces.Interface.Bandwidth.Mam() self.mam.parent = self self._children_name_map["mam"] = "mam" self._children_yang_names.add("mam") self.rdm = Rsvp.Interfaces.Interface.Bandwidth.Rdm() self.rdm.parent = self self._children_name_map["rdm"] = "rdm" self._children_yang_names.add("rdm") self._segment_path = lambda: "bandwidth" class Mam(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.Bandwidth.Mam, self).__init__() self.yang_name = "mam" self.yang_parent_name = "bandwidth" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('max_resv_bandwidth', YLeaf(YType.uint32, 'max-resv-bandwidth')), ('max_resv_flow', YLeaf(YType.uint32, 'max-resv-flow')), ('bc0_bandwidth', YLeaf(YType.uint32, 'bc0-bandwidth')), ('bc1_bandwidth', YLeaf(YType.uint32, 'bc1-bandwidth')), ('bandwidth_mode', YLeaf(YType.enumeration, 'bandwidth-mode')), ]) self.max_resv_bandwidth = None self.max_resv_flow = None self.bc0_bandwidth = None self.bc1_bandwidth = None self.bandwidth_mode = None self._segment_path = lambda: "mam" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.Bandwidth.Mam, ['max_resv_bandwidth', 'max_resv_flow', 'bc0_bandwidth', 'bc1_bandwidth', 'bandwidth_mode'], name, value) class Rdm(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.Bandwidth.Rdm, self).__init__() self.yang_name = "rdm" self.yang_parent_name = "bandwidth" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('max_resv_flow', YLeaf(YType.uint32, 'max-resv-flow')), ('bc0_bandwidth', YLeaf(YType.uint32, 'bc0-bandwidth')), ('bc1_bandwidth', YLeaf(YType.uint32, 'bc1-bandwidth')), ('rdm_keyword', YLeaf(YType.enumeration, 'rdm-keyword')), ('bc0_keyword', YLeaf(YType.enumeration, 'bc0-keyword')), ('bc1_keyword', YLeaf(YType.enumeration, 'bc1-keyword')), ('bandwidth_mode', YLeaf(YType.enumeration, 'bandwidth-mode')), ]) self.max_resv_flow = None self.bc0_bandwidth = None self.bc1_bandwidth = None self.rdm_keyword = None self.bc0_keyword = None self.bc1_keyword = None self.bandwidth_mode = None self._segment_path = lambda: "rdm" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.Bandwidth.Rdm, ['max_resv_flow', 'bc0_bandwidth', 'bc1_bandwidth', 'rdm_keyword', 'bc0_keyword', 'bc1_keyword', 'bandwidth_mode'], name, value) class Authentication(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Interfaces.Interface.Authentication, self).__init__() self.yang_name = "authentication" self.yang_parent_name = "interface" self.is_top_level_class = False self.has_list_ancestor = True self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('life_time', YLeaf(YType.uint32, 'life-time')), ('enable', YLeaf(YType.boolean, 'enable')), ('window_size', YLeaf(YType.uint32, 'window-size')), ('key_chain', YLeaf(YType.str, 'key-chain')), ]) self.life_time = None self.enable = None self.window_size = None self.key_chain = None self._segment_path = lambda: "authentication" def __setattr__(self, name, value): self._perform_setattr(Rsvp.Interfaces.Interface.Authentication, ['life_time', 'enable', 'window_size', 'key_chain'], name, value) class Signalling(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling, self).__init__() self.yang_name = "signalling" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([("global-out-of-band", ("global_out_of_band", Rsvp.Signalling.GlobalOutOfBand)), ("graceful-restart", ("graceful_restart", Rsvp.Signalling.GracefulRestart)), ("prefix-filtering", ("prefix_filtering", Rsvp.Signalling.PrefixFiltering)), ("pesr", ("pesr", Rsvp.Signalling.Pesr)), ("checksum", ("checksum", Rsvp.Signalling.Checksum))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('hello_graceful_restart_misses', YLeaf(YType.uint32, 'hello-graceful-restart-misses')), ('hello_graceful_restart_interval', YLeaf(YType.uint32, 'hello-graceful-restart-interval')), ]) self.hello_graceful_restart_misses = None self.hello_graceful_restart_interval = None self.global_out_of_band = Rsvp.Signalling.GlobalOutOfBand() self.global_out_of_band.parent = self self._children_name_map["global_out_of_band"] = "global-out-of-band" self._children_yang_names.add("global-out-of-band") self.graceful_restart = Rsvp.Signalling.GracefulRestart() self.graceful_restart.parent = self self._children_name_map["graceful_restart"] = "graceful-restart" self._children_yang_names.add("graceful-restart") self.prefix_filtering = Rsvp.Signalling.PrefixFiltering() self.prefix_filtering.parent = self self._children_name_map["prefix_filtering"] = "prefix-filtering" self._children_yang_names.add("prefix-filtering") self.pesr = Rsvp.Signalling.Pesr() self.pesr.parent = self self._children_name_map["pesr"] = "pesr" self._children_yang_names.add("pesr") self.checksum = Rsvp.Signalling.Checksum() self.checksum.parent = self self._children_name_map["checksum"] = "checksum" self._children_yang_names.add("checksum") self._segment_path = lambda: "signalling" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling, ['hello_graceful_restart_misses', 'hello_graceful_restart_interval'], name, value) class GlobalOutOfBand(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.GlobalOutOfBand, self).__init__() self.yang_name = "global-out-of-band" self.yang_parent_name = "signalling" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('vrf', YLeaf(YType.str, 'vrf')), ]) self.vrf = None self._segment_path = lambda: "global-out-of-band" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.GlobalOutOfBand, ['vrf'], name, value) class GracefulRestart(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.GracefulRestart, self).__init__() self.yang_name = "graceful-restart" self.yang_parent_name = "signalling" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([("lsp-class-type", ("lsp_class_type", Rsvp.Signalling.GracefulRestart.LspClassType))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('enable', YLeaf(YType.boolean, 'enable')), ('restart_time', YLeaf(YType.uint32, 'restart-time')), ('recovery_time', YLeaf(YType.uint32, 'recovery-time')), ]) self.enable = None self.restart_time = None self.recovery_time = None self.lsp_class_type = Rsvp.Signalling.GracefulRestart.LspClassType() self.lsp_class_type.parent = self self._children_name_map["lsp_class_type"] = "lsp-class-type" self._children_yang_names.add("lsp-class-type") self._segment_path = lambda: "graceful-restart" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.GracefulRestart, ['enable', 'restart_time', 'recovery_time'], name, value) class LspClassType(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.GracefulRestart.LspClassType, self).__init__() self.yang_name = "lsp-class-type" self.yang_parent_name = "graceful-restart" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('enable', YLeaf(YType.boolean, 'enable')), ]) self.enable = None self._segment_path = lambda: "lsp-class-type" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/graceful-restart/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.GracefulRestart.LspClassType, ['enable'], name, value) class PrefixFiltering(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.PrefixFiltering, self).__init__() self.yang_name = "prefix-filtering" self.yang_parent_name = "signalling" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([("default-deny-action", ("default_deny_action", Rsvp.Signalling.PrefixFiltering.DefaultDenyAction))]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('acl', YLeaf(YType.str, 'acl')), ]) self.acl = None self.default_deny_action = Rsvp.Signalling.PrefixFiltering.DefaultDenyAction() self.default_deny_action.parent = self self._children_name_map["default_deny_action"] = "default-deny-action" self._children_yang_names.add("default-deny-action") self._segment_path = lambda: "prefix-filtering" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.PrefixFiltering, ['acl'], name, value) class DefaultDenyAction(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.PrefixFiltering.DefaultDenyAction, self).__init__() self.yang_name = "default-deny-action" self.yang_parent_name = "prefix-filtering" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('drop', YLeaf(YType.empty, 'drop')), ]) self.drop = None self._segment_path = lambda: "default-deny-action" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/prefix-filtering/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.PrefixFiltering.DefaultDenyAction, ['drop'], name, value) class Pesr(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.Pesr, self).__init__() self.yang_name = "pesr" self.yang_parent_name = "signalling" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('disable', YLeaf(YType.empty, 'disable')), ]) self.disable = None self._segment_path = lambda: "pesr" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.Pesr, ['disable'], name, value) class Checksum(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Signalling.Checksum, self).__init__() self.yang_name = "checksum" self.yang_parent_name = "signalling" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('disable', YLeaf(YType.empty, 'disable')), ]) self.disable = None self._segment_path = lambda: "checksum" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/signalling/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Signalling.Checksum, ['disable'], name, value) class Authentication(Entity): _prefix = 'ip-rsvp-cfg' _revision = '2017-05-01' def __init__(self): super(Rsvp.Authentication, self).__init__() self.yang_name = "authentication" self.yang_parent_name = "rsvp" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_container_classes = OrderedDict([]) self._child_list_classes = OrderedDict([]) self._leafs = OrderedDict([ ('life_time', YLeaf(YType.uint32, 'life-time')), ('enable', YLeaf(YType.boolean, 'enable')), ('window_size', YLeaf(YType.uint32, 'window-size')), ('key_chain', YLeaf(YType.str, 'key-chain')), ]) self.life_time = None self.enable = None self.window_size = None self.key_chain = None self._segment_path = lambda: "authentication" self._absolute_path = lambda: "Cisco-IOS-XR-ip-rsvp-cfg:rsvp/%s" % self._segment_path() def __setattr__(self, name, value): self._perform_setattr(Rsvp.Authentication, ['life_time', 'enable', 'window_size', 'key_chain'], name, value) def clone_ptr(self): self._top_entity = Rsvp() return self._top_entity
true
true
1c2d005be4a9936657d02d76301a9f51bdffde72
10,986
py
Python
dwave/system/composites/virtual_graph.py
mdecandia/dwave-system
263c3cf0f0053ade092c4b72c22d4201148f7ec6
[ "Apache-2.0" ]
null
null
null
dwave/system/composites/virtual_graph.py
mdecandia/dwave-system
263c3cf0f0053ade092c4b72c22d4201148f7ec6
[ "Apache-2.0" ]
null
null
null
dwave/system/composites/virtual_graph.py
mdecandia/dwave-system
263c3cf0f0053ade092c4b72c22d4201148f7ec6
[ "Apache-2.0" ]
null
null
null
# Copyright 2018 D-Wave Systems Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ============================================================================= """ A :std:doc:`dimod composite <oceandocs:docs_dimod/reference/samplers>` that uses the D-Wave virtual graph feature for improved :std:doc:`minor-embedding <oceandocs:docs_system/intro>`. D-Wave *virtual graphs* simplify the process of minor-embedding by enabling you to more easily create, optimize, use, and reuse an embedding for a given working graph. When you submit an embedding and specify a chain strength using these tools, they automatically calibrate the qubits in a chain to compensate for the effects of biases that may be introduced as a result of strong couplings. See `Ocean Glossary <https://docs.ocean.dwavesys.com/en/latest/glossary.html>`_ for explanations of technical terms in descriptions of Ocean tools. """ import dimod from dwave.system.composites.embedding import FixedEmbeddingComposite from dwave.system.flux_bias_offsets import get_flux_biases FLUX_BIAS_KWARG = 'flux_biases' __all__ = ['VirtualGraphComposite'] class VirtualGraphComposite(FixedEmbeddingComposite): """Composite to use the D-Wave virtual graph feature for minor-embedding. Calibrates qubits in chains to compensate for the effects of biases and enables easy creation, optimization, use, and reuse of an embedding for a given working graph. Inherits from :class:`dimod.ComposedSampler` and :class:`dimod.Structured`. Args: sampler (:class:`.DWaveSampler`): A dimod :class:`dimod.Sampler`. Typically a :obj:`.DWaveSampler` or derived composite sampler; other samplers may not work or make sense with this composite layer. embedding (dict[hashable, iterable]): Mapping from a source graph to the specified sampler's graph (the target graph). chain_strength (float, optional, default=None): Desired chain coupling strength. This is the magnitude of couplings between qubits in a chain. If None, uses the maximum available as returned by a SAPI query to the D-Wave solver. flux_biases (list/False/None, optional, default=None): Per-qubit flux bias offsets in the form of a list of lists, where each sublist is of length 2 and specifies a variable and the flux bias offset associated with that variable. Qubits in a chain with strong negative J values experience a J-induced bias; this parameter compensates by recalibrating to remove that bias. If False, no flux bias is applied or calculated. If None, flux biases are pulled from the database or calculated empirically. flux_bias_num_reads (int, optional, default=1000): Number of samples to collect per flux bias value to calculate calibration information. flux_bias_max_age (int, optional, default=3600): Maximum age (in seconds) allowed for a previously calculated flux bias offset to be considered valid. .. attention:: D-Wave's *virtual graphs* feature can require many seconds of D-Wave system time to calibrate qubits to compensate for the effects of biases. If your account has limited D-Wave system access, consider using *FixedEmbeddingComposite()* instead. Examples: This example uses :class:`.VirtualGraphComposite` to instantiate a composed sampler that submits a QUBO problem to a D-Wave solver. The problem represents a logical AND gate using penalty function :math:`P = xy - 2(x+y)z +3z`, where variables x and y are the gate's inputs and z the output. This simple three-variable problem is manually minor-embedded to a single :std:doc:`Chimera <oceandocs:docs_system/intro>` unit cell: variables x and y are represented by qubits 1 and 5, respectively, and z by a two-qubit chain consisting of qubits 0 and 4. The chain strength is set to the maximum allowed found from querying the solver's extended J range. In this example, the ten returned samples all represent valid states of the AND gate. >>> from dwave.system.samplers import DWaveSampler >>> from dwave.system.composites import VirtualGraphComposite >>> embedding = {'x': {1}, 'y': {5}, 'z': {0, 4}} >>> DWaveSampler().properties['extended_j_range'] # doctest: +SKIP [-2.0, 1.0] >>> sampler = VirtualGraphComposite(DWaveSampler(), embedding, chain_strength=2) # doctest: +SKIP >>> Q = {('x', 'y'): 1, ('x', 'z'): -2, ('y', 'z'): -2, ('z', 'z'): 3} >>> response = sampler.sample_qubo(Q, num_reads=10) # doctest: +SKIP >>> for sample in response.samples(): # doctest: +SKIP ... print(sample) ... {'y': 0, 'x': 1, 'z': 0} {'y': 1, 'x': 0, 'z': 0} {'y': 1, 'x': 0, 'z': 0} {'y': 1, 'x': 1, 'z': 1} {'y': 0, 'x': 1, 'z': 0} {'y': 1, 'x': 0, 'z': 0} {'y': 0, 'x': 1, 'z': 0} {'y': 0, 'x': 1, 'z': 0} {'y': 0, 'x': 0, 'z': 0} {'y': 1, 'x': 0, 'z': 0} See `Ocean Glossary <https://docs.ocean.dwavesys.com/en/latest/glossary.html>`_ for explanations of technical terms in descriptions of Ocean tools. """ def __init__(self, sampler, embedding, chain_strength=None, flux_biases=None, flux_bias_num_reads=1000, flux_bias_max_age=3600): super(VirtualGraphComposite, self).__init__(sampler, embedding) self.parameters.update(apply_flux_bias_offsets=[]) # Validate the chain strength, or obtain it from J-range if chain strength is not provided. self.chain_strength = _validate_chain_strength(sampler, chain_strength) if flux_biases is False: # use 'is' because bool(None) is False # in this case we are done self.flux_biases = None return if FLUX_BIAS_KWARG not in sampler.parameters: raise ValueError("Given child sampler does not accept flux_biases.") # come back as a dict flux_biases = get_flux_biases(sampler, embedding, num_reads=flux_bias_num_reads, chain_strength=self.chain_strength, max_age=flux_bias_max_age) self.flux_biases = [flux_biases.get(v, 0.0) for v in range(sampler.properties['num_qubits'])] return @dimod.bqm_structured def sample(self, bqm, apply_flux_bias_offsets=True, **kwargs): """Sample from the given Ising model. Args: h (list/dict): Linear biases of the Ising model. If a list, the list's indices are used as variable labels. J (dict of (int, int):float): Quadratic biases of the Ising model. apply_flux_bias_offsets (bool, optional): If True, use the calculated flux_bias offsets (if available). **kwargs: Optional keyword arguments for the sampling method, specified per solver. Examples: This example uses :class:`.VirtualGraphComposite` to instantiate a composed sampler that submits an Ising problem to a D-Wave solver. The problem represents a logical NOT gate using penalty function :math:`P = xy`, where variable x is the gate's input and y the output. This simple two-variable problem is manually minor-embedded to a single :std:doc:`Chimera <oceandocs:docs_system/intro>` unit cell: each variable is represented by a chain of half the cell's qubits, x as qubits 0, 1, 4, 5, and y as qubits 2, 3, 6, 7. The chain strength is set to half the maximum allowed found from querying the solver's extended J range. In this example, the ten returned samples all represent valid states of the NOT gate. >>> from dwave.system.samplers import DWaveSampler >>> from dwave.system.composites import VirtualGraphComposite >>> embedding = {'x': {0, 4, 1, 5}, 'y': {2, 6, 3, 7}} >>> DWaveSampler().properties['extended_j_range'] # doctest: +SKIP [-2.0, 1.0] >>> sampler = VirtualGraphComposite(DWaveSampler(), embedding, chain_strength=1) # doctest: +SKIP >>> h = {} >>> J = {('x', 'y'): 1} >>> response = sampler.sample_ising(h, J, num_reads=10) # doctest: +SKIP >>> for sample in response.samples(): # doctest: +SKIP ... print(sample) ... {'y': -1, 'x': 1} {'y': 1, 'x': -1} {'y': -1, 'x': 1} {'y': -1, 'x': 1} {'y': -1, 'x': 1} {'y': 1, 'x': -1} {'y': 1, 'x': -1} {'y': 1, 'x': -1} {'y': -1, 'x': 1} {'y': 1, 'x': -1} See `Ocean Glossary <https://docs.ocean.dwavesys.com/en/latest/glossary.html>`_ for explanations of technical terms in descriptions of Ocean tools. """ if apply_flux_bias_offsets: if self.flux_biases is not None: kwargs[FLUX_BIAS_KWARG] = self.flux_biases kwargs.setdefault('chain_strength', self.chain_strength) return super(VirtualGraphComposite, self).sample(bqm, **kwargs) def _validate_chain_strength(sampler, chain_strength): """Validate the provided chain strength, checking J-ranges of the sampler's children. Args: chain_strength (float) The provided chain strength. Use None to use J-range. Returns (float): A valid chain strength, either provided or based on available J-range. Positive finite float. """ properties = sampler.properties if 'extended_j_range' in properties: max_chain_strength = - min(properties['extended_j_range']) elif 'j_range' in properties: max_chain_strength = - min(properties['j_range']) else: raise ValueError("input sampler should have 'j_range' and/or 'extended_j_range' property.") if chain_strength is None: chain_strength = max_chain_strength elif chain_strength > max_chain_strength: raise ValueError("Provided chain strength exceedds the allowed range.") return chain_strength
44.477733
108
0.633261
import dimod from dwave.system.composites.embedding import FixedEmbeddingComposite from dwave.system.flux_bias_offsets import get_flux_biases FLUX_BIAS_KWARG = 'flux_biases' __all__ = ['VirtualGraphComposite'] class VirtualGraphComposite(FixedEmbeddingComposite): def __init__(self, sampler, embedding, chain_strength=None, flux_biases=None, flux_bias_num_reads=1000, flux_bias_max_age=3600): super(VirtualGraphComposite, self).__init__(sampler, embedding) self.parameters.update(apply_flux_bias_offsets=[]) self.chain_strength = _validate_chain_strength(sampler, chain_strength) if flux_biases is False: self.flux_biases = None return if FLUX_BIAS_KWARG not in sampler.parameters: raise ValueError("Given child sampler does not accept flux_biases.") flux_biases = get_flux_biases(sampler, embedding, num_reads=flux_bias_num_reads, chain_strength=self.chain_strength, max_age=flux_bias_max_age) self.flux_biases = [flux_biases.get(v, 0.0) for v in range(sampler.properties['num_qubits'])] return @dimod.bqm_structured def sample(self, bqm, apply_flux_bias_offsets=True, **kwargs): if apply_flux_bias_offsets: if self.flux_biases is not None: kwargs[FLUX_BIAS_KWARG] = self.flux_biases kwargs.setdefault('chain_strength', self.chain_strength) return super(VirtualGraphComposite, self).sample(bqm, **kwargs) def _validate_chain_strength(sampler, chain_strength): properties = sampler.properties if 'extended_j_range' in properties: max_chain_strength = - min(properties['extended_j_range']) elif 'j_range' in properties: max_chain_strength = - min(properties['j_range']) else: raise ValueError("input sampler should have 'j_range' and/or 'extended_j_range' property.") if chain_strength is None: chain_strength = max_chain_strength elif chain_strength > max_chain_strength: raise ValueError("Provided chain strength exceedds the allowed range.") return chain_strength
true
true
1c2d00aed8665fd04416d0f7b83afbb2c85fa80a
25,632
py
Python
tests/python/contrib/test_onnx.py
wjj19950828/tvm
9c63f4fc318652f6fff68342da2d11b26592a3e0
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0" ]
3
2021-05-08T17:04:39.000Z
2021-07-11T17:40:54.000Z
tests/python/contrib/test_onnx.py
wjj19950828/tvm
9c63f4fc318652f6fff68342da2d11b26592a3e0
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0" ]
1
2019-08-16T20:37:41.000Z
2019-08-16T20:38:15.000Z
tests/python/contrib/test_onnx.py
wjj19950828/tvm
9c63f4fc318652f6fff68342da2d11b26592a3e0
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0" ]
1
2019-05-31T20:10:11.000Z
2019-05-31T20:10:11.000Z
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Relay to ONNX serialization test cases""" import pytest pytest.importorskip("onnx") pytest.importorskip("onnxruntime") import numpy as np import onnxruntime as rt import tvm from tvm import relay from tvm.contrib.target.onnx import to_onnx from tvm.relay.testing import run_infer_type def func_to_onnx(func, name): mod = tvm.IRModule() mod["main"] = func onnx_model = to_onnx(mod, {}, name, path=None) return onnx_model.SerializeToString() def run_onnx(onnx_model, input_data): sess = rt.InferenceSession(onnx_model) input_names = {} for input, data in zip(sess.get_inputs(), input_data): input_names[input.name] = data output_names = [out.name for out in sess.get_outputs()] res = sess.run(output_names, input_names) return res def run_relay(func, data_tuple): target = "llvm" dev = tvm.device("llvm", 0) intrp = relay.create_executor("graph", device=dev, target=target) relay_res = intrp.evaluate(func)(*data_tuple) result = [] relay_res = relay_res if isinstance(relay_res, list) else [relay_res] for res in relay_res: result.append(res.numpy()) return result def verify_results(relay_func, indata, test_name, rtol=1e-7, atol=0): relay_results = run_relay(relay_func, indata) onnx_results = run_onnx(func_to_onnx(relay_func, test_name), indata) for relay_res, onnx_res in zip(relay_results, onnx_results): np.testing.assert_allclose(relay_res, onnx_res, rtol=rtol, atol=atol) def test_add(): dtype = "float32" t1 = relay.TensorType((5, 10, 5)) t2 = relay.TensorType((5, 10, 5)) x = relay.var("x", t1, dtype=dtype) y = relay.var("y", t2, dtype=dtype) z = relay.add(x, y) func = relay.Function([x, y], z) x_data = np.random.rand(5, 10, 5).astype(dtype) y_data = np.random.rand(5, 10, 5).astype(dtype) verify_results(func, [x_data, y_data], "test_add") def test_bias_add(): for dtype in ["float16", "float32"]: xshape = (10, 2, 3, 4) bshape = (2,) rtol = 1e-2 if dtype == "float16" else 1e-5 x = relay.var("x", shape=xshape, dtype=dtype) bias = relay.var("bias", shape=bshape, dtype=dtype) z = relay.nn.bias_add(x, bias) func = relay.Function([x, bias], z) x_data = np.random.uniform(size=xshape).astype(dtype) y_data = np.random.uniform(size=bshape).astype(dtype) verify_results(func, [x_data, y_data], "test_bias_add", rtol=rtol) def test_conv2d(): def verify_conv2d( dtype, scale, dshape, kshape, padding=(1, 1), groups=1, dilation=(1, 1), **attrs ): x = relay.var("x", shape=dshape, dtype=dtype) w = relay.var("w", shape=kshape, dtype=dtype) y = relay.nn.conv2d(x, w, padding=padding, dilation=dilation, groups=groups, **attrs) func = relay.Function([x, w], y) data = np.random.uniform(-scale, scale, size=dshape).astype(dtype) kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype) verify_results(func, [data, kernel], "test_conv2d", rtol=1e-5, atol=1e-5) dshape = (1, 32, 18, 18) kshape = (32, 1, 3, 3) verify_conv2d( "float32", 1, dshape, kshape, padding=(1, 1), channels=32, groups=32, kernel_size=(3, 3) ) dshape = (1, 32, 18, 18) kshape = (32, 4, 3, 3) verify_conv2d( "float32", 1, dshape, kshape, padding=(1, 1), channels=32, groups=8, kernel_size=(3, 3) ) # also group conv2d dshape = (1, 32, 18, 18) kshape = (64, 1, 3, 3) verify_conv2d( "float32", 1, dshape, kshape, padding=(1, 1), channels=64, groups=32, kernel_size=(3, 3) ) # normal conv2d dshape = (1, 3, 224, 224) kshape = (10, 3, 3, 3) verify_conv2d("float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(3, 3)) dshape = (1, 3, 224, 224) kshape = (10, 3, 3, 3) verify_conv2d("float32", 1, dshape, kshape, padding=(2, 2), channels=10, kernel_size=(3, 3)) dshape = (1, 3, 18, 18) kshape = (10, 3, 3, 3) verify_conv2d( "float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(3, 3), dilation=(3, 3), ) dshape = (1, 3, 18, 18) kshape = (10, 3, 2, 2) verify_conv2d( "float32", 1, dshape, kshape, padding=(2, 2), channels=10, kernel_size=(2, 2), dilation=(1, 1), ) dshape = (1, 3, 18, 18) kshape = (10, 3, 4, 4) verify_conv2d("float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(4, 4)) dshape = (1, 3, 18, 18) kshape = (10, 3, 4, 4) verify_conv2d("float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(4, 4)) def test_conv2d_transpose(): """Conv2d_Transpose unit tests.""" def verify_conv2d_transpose( dtype, scale, dshape, kshape, padding=(1, 1), groups=1, dilation=(1, 1), **attrs ): x = relay.var("x", shape=dshape, dtype=dtype) w = relay.var("w", shape=kshape, dtype=dtype) y = relay.nn.conv2d_transpose( x, w, padding=padding, dilation=dilation, groups=groups, **attrs ) func = relay.Function([x, w], y) data = np.random.uniform(-scale, scale, size=dshape).astype(dtype) kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype) verify_results(func, [data, kernel], "test_conv2d_transpose", rtol=1e-5, atol=1e-5) dshape = (1, 3, 224, 224) kshape = (3, 10, 3, 3) verify_conv2d_transpose( "float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(3, 3) ) dshape = (1, 3, 224, 224) kshape = (3, 10, 3, 3) verify_conv2d_transpose( "float32", 1, dshape, kshape, padding=(2, 2), channels=10, kernel_size=(3, 3) ) dshape = (1, 3, 18, 18) kshape = (3, 10, 2, 2) verify_conv2d_transpose( "float32", 1, dshape, kshape, padding=(2, 2), channels=10, kernel_size=(2, 2), dilation=(1, 1), ) dshape = (1, 3, 18, 18) kshape = (3, 10, 4, 4) verify_conv2d_transpose( "float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(4, 4) ) dshape = (1, 3, 18, 18) kshape = (3, 10, 4, 4) verify_conv2d_transpose( "float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(4, 4) ) def test_reshape(): def verify_reshape(shape, newshape): x = relay.var("x", relay.TensorType(shape, "float32")) z = relay.reshape(x, newshape=newshape) func = relay.Function([x], z) x_data = np.random.uniform(low=-1, high=1, size=shape).astype("float32") verify_results(func, [x_data], "test_reshape", rtol=1e-5, atol=1e-5) verify_reshape((2, 3, 4), tuple(np.array([4, 2, 3], dtype=np.int64))) verify_reshape((2, 3, 4), tuple(np.array([2, 0, 0], dtype=np.int64))) verify_reshape((2, 3, 4), tuple(np.array([0, -1], dtype=np.int64))) verify_reshape((2, 3, 4), tuple(np.array([-1, 0], dtype=np.int64))) def test_transpose(): def verify_reshape(shape, newshape): x = relay.var("x", relay.TensorType(shape, "float32")) z = relay.transpose(x, newshape) func = relay.Function([x], z) x_data = np.random.uniform(low=-1, high=1, size=shape).astype("float32") verify_results(func, [x_data], "test_transpose", rtol=1e-5, atol=1e-5) verify_reshape((1, 2, 3, 4), (0, 2, 3, 1)) verify_reshape((1, 2, 3, 4), (0, 3, 2, 1)) def test_dense(): def verify_dense(d_shape, w_shape): data = relay.var("data", relay.TensorType(d_shape, "float32")) weight = relay.var("weight", relay.TensorType(w_shape, "float32")) func = relay.Function([data, weight], relay.nn.dense(data, weight)) x_data = np.random.uniform(size=d_shape).astype("float32") w_data = np.random.uniform(size=w_shape).astype("float32") verify_results(func, [x_data, w_data], "test_dense", rtol=1e-5, atol=1e-5) verify_dense((1, 8), (16, 8)) verify_dense((1, 4), (3, 4)) def test_max_pool(): def verify_max_pool(x_shape, pool_size, strides, padding, ceil_mode): x = relay.var("x", relay.TensorType(x_shape, "float32")) y = tvm.relay.nn.max_pool2d( x, pool_size=pool_size, strides=strides, padding=padding, ceil_mode=ceil_mode ) func = relay.Function([x], y) x_data = np.random.uniform(size=x_shape).astype("float32") verify_results(func, [x_data], "test_max_pool", rtol=1e-5, atol=1e-5) verify_max_pool( (1, 4, 16, 16), pool_size=(2, 2), strides=(2, 2), padding=(0, 0), ceil_mode=False ) def test_batch_flatten(): def verify_test_batch_flatten(d_shape): data = relay.var("data", relay.TensorType(d_shape, "float32")) func = relay.Function([data], relay.nn.batch_flatten(data)) x_data = np.random.uniform(size=d_shape).astype("float32") verify_results(func, [x_data], "test_batch_flatten", rtol=1e-5, atol=1e-5) verify_test_batch_flatten((1, 2, 3, 4)) verify_test_batch_flatten((1, 8)) def test_batch_norm(): def verify_batch_norm(axis=1): for dtype in ["float16", "float32"]: data = relay.var("data", relay.TensorType((2, 4, 4, 1), dtype)) gamma_shape = (data.type_annotation.shape[axis].value,) beta = relay.var("beta", relay.TensorType(gamma_shape, dtype)) gamma = relay.var("gamma", relay.TensorType(gamma_shape, dtype)) moving_mean = relay.var("moving_mean", relay.TensorType(gamma_shape, dtype)) moving_var = relay.var("moving_var", relay.TensorType(gamma_shape, dtype)) y = relay.nn.batch_norm(data, gamma, beta, moving_mean, moving_var, axis=axis) func = relay.Function([data, gamma, beta, moving_mean, moving_var], y[0]) x_data = np.random.uniform(size=(2, 4, 4, 1)).astype(dtype) beta = np.random.uniform(size=gamma_shape).astype(dtype) gamma = np.random.uniform(size=gamma_shape).astype(dtype) moving_mean = np.random.uniform(size=gamma_shape).astype(dtype) moving_var = np.random.uniform(size=gamma_shape).astype(dtype) verify_results( func, [x_data, gamma, beta, moving_mean, moving_var], "test_batch_norm", rtol=1e-1, atol=1e-1, ) verify_batch_norm(axis=1) verify_batch_norm(axis=3) def test_pad(): """Pad unit test.""" def verify_pad(): dshape = (4, 10, 7, 7) x = relay.var("x", shape=dshape, dtype="int32") y = relay.nn.pad(x, ((1, 1), (2, 2), (3, 3), (4, 4))) func = relay.Function([x], y) func = run_infer_type(func) x_data = np.random.randint(low=-255, high=255, size=dshape).astype(np.int32) verify_results(func, [x_data], "test_pad", rtol=1e-5, atol=1e-5) verify_pad() def test_sofmax(): def verify_sofmax(): for dtype in ["float32"]: shape = (10, 4) x = relay.var("x", shape=shape, dtype=dtype) y = relay.nn.softmax(x, axis=1) func = relay.Function([x], y) x_data = np.random.uniform(size=shape).astype(dtype) verify_results(func, [x_data], "test_softmax", rtol=1e-5, atol=1e-5) verify_sofmax() def test_squeeze(): def verify_squeeze(shape, dtype, axis): x = relay.var("x", relay.TensorType(shape, dtype)) z = relay.squeeze(x, axis=axis) func = relay.Function([x], z) x_data = np.random.random_sample(shape).astype(dtype) verify_results(func, [x_data], "test_squeeze", rtol=1e-5, atol=1e-5) verify_squeeze((1, 3, 2, 5), "float32", None) verify_squeeze( (1, 3, 1), "float32", [ 2, ], ) verify_squeeze((1, 2, 1, 2, 1), "float32", [0, 2]) def test_mean(): def verify_mean(data_shape, axis, exclude, keepdims): dtype = "float32" x = relay.var("x", shape=data_shape, dtype=dtype) y = relay.mean(x, axis, keepdims, exclude) func = relay.Function([x], y) x_data = np.random.uniform(size=data_shape).astype(dtype) verify_results(func, [x_data], "test_mean", rtol=1e-5, atol=1e-5) verify_mean((1, 2), 0, False, False) verify_mean((1, 2), 0, True, False) verify_mean((1, 2), 0, True, True) verify_mean((1, 2), 1, True, True) verify_mean((3, 2, 1), 1, False, True) def test_split(): def verify_split(dshape, indices_or_sections, axis=None): dtype = "float32" x = relay.var("x", relay.ty.TensorType(dshape, "float32")) y = relay.split(x, indices_or_sections, axis=axis) func = relay.Function([x], y.astuple()) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_split", rtol=1e-5, atol=1e-5) verify_split((5, 5, 2, 2), 5, axis=1) verify_split((5, 5, 2, 2), 5, axis=0) verify_split((5, 5, 2, 2), [1, 3, 4], axis=0) verify_split((5, 5, 2, 2), [1, 3, 4], axis=1) def test_concatenate(): def verify_concatenate(shapes, axis, dtype="float32"): in_vars = [] in_data = [] for i, shape in enumerate(shapes): in_vars.append(relay.var("x" + str(i), relay.ty.TensorType(shape, dtype))) in_data.append(np.random.uniform(size=shape).astype(dtype)) out_tensor = relay.concatenate(in_vars, axis) func = relay.Function(in_vars, out_tensor) verify_results(func, in_data, "test_concatenate", rtol=1e-5, atol=1e-5) verify_concatenate([(2,), (2,), (2,)], -1) verify_concatenate([(2, 3, 4), (2, 2, 4), (2, 5, 4)], 1) verify_concatenate([(1, 2, 4), (1, 2, 3), (1, 2, 7), (1, 2, 8), (1, 2, 1)], -1) verify_concatenate([(5, 6, 7, 3), (16, 6, 7, 3), (12, 6, 7, 3), (8, 6, 7, 3), (2, 6, 7, 3)], 0) verify_concatenate([(1, 14400), (1, 2400), (1, 640), (1, 240)], 1) def test_strided_slice(): def verify_strided_slice(dshape, begin, end, strides, mode): x = relay.var("x", relay.TensorType(dshape, "float32")) if mode == "size": strides = None z = relay.strided_slice(x, begin=begin, end=end, strides=strides, slice_mode=mode) func = relay.Function([x], z) x_data = np.random.uniform(size=dshape).astype("float32") verify_results(func, [x_data], "test_strided_slice", rtol=1e-5, atol=1e-5) for mode in ["end", "size"]: verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 2, 3], None, mode) verify_strided_slice((3, 4, 3), [1, -1, 0], [4, -1, 3], [1, 2], mode) verify_strided_slice( (3, 4, 3), [ 1, ], [4, -3], None, mode, ) verify_strided_slice((3, 4, 3), [0, 0, 0], [4, -5, 4], [1, -1, 2], mode) verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 4, -3], [2, 1, 1], mode) verify_strided_slice((3, 4, 3), [1, -1, 0], [4, -5, 3], [2, -1, 1], mode) verify_strided_slice((3, 4, 3), [1, 0, 0], [2, 2, 3], [1, 1, 2], mode) verify_strided_slice((3, 4, 3), [1, -1, 0], [2, -3, 3], [1, -1, 1], mode) verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 1000, 3], None, mode) verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 4], None, mode) verify_strided_slice((3, 4, 3), [1, 1], [4, 4, 3], None, mode) verify_strided_slice((3, 4, 3), [1, 1], [4, 4, 3], [1, 1, 2], mode) def test_cmp_type(): for op, ref in ((relay.greater, np.greater), (relay.less, np.less), (relay.equal, np.equal)): x_shape = (10, 4) y_shape = (5, 10, 1) t1 = relay.TensorType(x_shape) t2 = relay.TensorType(y_shape) x = relay.var("x", t1) y = relay.var("y", t2) z = op(x, y) x_data = np.random.rand(*x_shape).astype(t1.dtype) y_data = np.random.rand(*y_shape).astype(t2.dtype) func = relay.Function([x, y], z) verify_results(func, [x_data, y_data], "test_cmp_type", rtol=1e-5, atol=1e-5) def test_unary_identity(): for dtype in ["int16", "float32", "float64"]: for op, ref in [(relay.zeros_like, np.zeros_like), (relay.ones_like, np.ones_like)]: shape = (8, 9, 4) x = relay.var("x", relay.TensorType(shape, dtype)) y = op(x) func = relay.Function( [ x, ], y, ) x_data = np.random.rand(*shape).astype(dtype) verify_results(func, [x_data], "test_cmp_type", rtol=1e-5, atol=1e-5) def test_binary_op(): def check_binary_op(opfunc, dtype): t1 = relay.TensorType((5, 10, 5)) t2 = relay.TensorType((5, 10, 5)) x = relay.var("x", t1, dtype=dtype) y = relay.var("y", t2, dtype=dtype) z = opfunc(x, y) x_data = np.random.rand(5, 10, 5).astype(dtype) y_data = np.random.rand(5, 10, 5).astype(dtype) func = relay.Function([x, y], z) verify_results(func, [x_data, y_data], "test_binary_op", rtol=1e-5, atol=1e-5) for opfunc, ref in [ (relay.add, np.add), (relay.subtract, np.subtract), (relay.multiply, np.multiply), (relay.divide, np.divide), ]: for dtype in ["float32"]: check_binary_op(opfunc, dtype) def test_tuple_types(): def verify_tuple_types(dshape, indices_or_sections, axis=None, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.split(x, indices_or_sections, axis=axis) z = relay.concatenate(y, axis=axis) func = relay.Function([x], z) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_tuple_types", rtol=1e-5, atol=1e-5) split_z = relay.split(z, indices_or_sections, axis=axis) func = relay.Function([x], split_z.astuple()) verify_results(func, [x_data], "test_tuple_types", rtol=1e-5, atol=1e-5) out = relay.Tuple([y[0] + y[1], y[0] - y[1]]) func = relay.Function([x], out) verify_results(func, [x_data], "test_tuple_types", rtol=1e-5, atol=1e-5) z = relay.concatenate(out, axis=axis) func = relay.Function([x], z) verify_results(func, [x_data], "test_tuple_types", rtol=1e-5, atol=1e-5) verify_tuple_types((5, 5, 2, 2), 5, axis=1) verify_tuple_types((5, 5, 2, 2), 5, axis=0) verify_tuple_types((5, 5, 2, 2), [1, 3, 4], axis=0) verify_tuple_types((5, 5, 2, 2), [1, 3, 4], axis=1) def test_layout_transform(): def verify_layout_transform(dshape, src_layout, dst_layout, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.layout_transform(x, src_layout, dst_layout) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_layout_transform", rtol=1e-5, atol=1e-5) verify_layout_transform((1, 3, 8, 8), "NCHW", "NHWC") verify_layout_transform((1, 8, 8, 3), "NHWC", "NCHW") def test_clip(): def verify_clip(dshape, a_min, a_max, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.clip(x, a_min, a_max) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_clip", rtol=1e-5, atol=1e-5) verify_clip((5, 5, 2, 5), 0, 0.2) verify_clip((5, 5, 2, 5), 0.2, 0.5) def test_expand_dims(): def verify_expand_dims(dshape, axis, num_newaxis, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.expand_dims(x, axis, num_newaxis) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_expand_dims", rtol=1e-5, atol=1e-5) verify_expand_dims((1, 1001), 0, 2) verify_expand_dims((1, 1, 1001), 2, 2) def test_lrn(): """LRN unit test.""" def verify_lrn(xshape, size, dtype="float32"): x = relay.var("x", relay.ty.TensorType(xshape, dtype)) y = relay.nn.lrn(x, size=size, axis=1, alpha=1.0, beta=1.0, bias=1.0) func = relay.Function([x], y) x_data = np.random.uniform(size=xshape).astype(dtype) verify_results(func, [x_data], "test_lrn", rtol=1e-5, atol=1e-5) isize = [(1, 1, 480, 640), (1, 3, 224, 224)] sizes = [1, 3] for i in isize: for s in sizes: verify_lrn(i, s) def test_sigmoid(): """Sigmoid unit test.""" def verify_sigmoid(dshape, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.sigmoid(x) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_sigmoid", rtol=1e-4, atol=1e-4) isize = [(1, 3, 480, 640), (1, 3, 224, 224)] for i in isize: verify_sigmoid(i) def test_copy(): """Copy unit test.""" def verify_copy(dshape, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.copy(x) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_copy", rtol=1e-4, atol=1e-4) isize = [(1, 3, 480, 640), (1, 3, 224, 224)] for i in isize: verify_copy(i) def test_round(): """Round unit test.""" def verify_round(dshape, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.round(x) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_round", rtol=1e-4, atol=1e-4) isize = [(1, 3, 480, 640), (1, 3, 224, 224)] for i in isize: verify_round(i) def test_cast(): """Cast unit test.""" def verify_cast(dshape, dtype): x = relay.var("x", relay.ty.TensorType(dshape, "float32")) y = relay.cast(x, dtype) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype("float32") verify_results(func, [x_data], "test_cast", rtol=1e-4, atol=1e-4) isize = [(1, 3, 480, 640), (1, 3, 224, 224)] out_dtypes = ["int8", "int16", "uint8", "uint16"] for i in isize: for o_dtype in out_dtypes: verify_cast(i, o_dtype) def test_resize(): """Resize unit test.""" def verify_resize(dshape, outsize, method, coord_trans, rounding_method, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.image.resize2d( x, outsize, layout="NCHW", method=method, coordinate_transformation_mode=coord_trans, rounding_method=rounding_method, ) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_resize", rtol=1e-4, atol=1e-4) method = ["nearest_neighbor", "linear", "cubic"] coord_trans = ["half_pixel", "align_corners", "asymmetric"] rounding_method = ["round", "floor", "ceil"] isize = (1, 3, 480, 640) # Downsample osize = (240, 320) for i in method: for j in coord_trans: for k in rounding_method: if (i == "nearest_neighbor" and j == "align_corners") or ( i == "cubic" and j in ["half_pixel", "align_corners"] ): continue verify_resize(isize, osize, method=i, coord_trans=j, rounding_method=k) # Upsample osize = (960, 1280) for i in method: for j in coord_trans: for k in rounding_method: if (i == "nearest_neighbor" and j == "align_corners") or (i == "cubic"): continue verify_resize(isize, osize, method=i, coord_trans=j, rounding_method=k) if __name__ == "__main__": test_add() test_bias_add() test_conv2d() test_conv2d_transpose() test_reshape() test_transpose() test_dense() test_max_pool() test_batch_flatten() test_batch_norm() test_pad() test_mean() test_split() test_concatenate() test_sofmax() test_squeeze() test_strided_slice() test_cmp_type() test_binary_op() test_tuple_types() test_layout_transform() test_clip() test_expand_dims() test_lrn() test_sigmoid() test_copy() test_round() test_cast() test_resize()
35.016393
99
0.591097
import pytest pytest.importorskip("onnx") pytest.importorskip("onnxruntime") import numpy as np import onnxruntime as rt import tvm from tvm import relay from tvm.contrib.target.onnx import to_onnx from tvm.relay.testing import run_infer_type def func_to_onnx(func, name): mod = tvm.IRModule() mod["main"] = func onnx_model = to_onnx(mod, {}, name, path=None) return onnx_model.SerializeToString() def run_onnx(onnx_model, input_data): sess = rt.InferenceSession(onnx_model) input_names = {} for input, data in zip(sess.get_inputs(), input_data): input_names[input.name] = data output_names = [out.name for out in sess.get_outputs()] res = sess.run(output_names, input_names) return res def run_relay(func, data_tuple): target = "llvm" dev = tvm.device("llvm", 0) intrp = relay.create_executor("graph", device=dev, target=target) relay_res = intrp.evaluate(func)(*data_tuple) result = [] relay_res = relay_res if isinstance(relay_res, list) else [relay_res] for res in relay_res: result.append(res.numpy()) return result def verify_results(relay_func, indata, test_name, rtol=1e-7, atol=0): relay_results = run_relay(relay_func, indata) onnx_results = run_onnx(func_to_onnx(relay_func, test_name), indata) for relay_res, onnx_res in zip(relay_results, onnx_results): np.testing.assert_allclose(relay_res, onnx_res, rtol=rtol, atol=atol) def test_add(): dtype = "float32" t1 = relay.TensorType((5, 10, 5)) t2 = relay.TensorType((5, 10, 5)) x = relay.var("x", t1, dtype=dtype) y = relay.var("y", t2, dtype=dtype) z = relay.add(x, y) func = relay.Function([x, y], z) x_data = np.random.rand(5, 10, 5).astype(dtype) y_data = np.random.rand(5, 10, 5).astype(dtype) verify_results(func, [x_data, y_data], "test_add") def test_bias_add(): for dtype in ["float16", "float32"]: xshape = (10, 2, 3, 4) bshape = (2,) rtol = 1e-2 if dtype == "float16" else 1e-5 x = relay.var("x", shape=xshape, dtype=dtype) bias = relay.var("bias", shape=bshape, dtype=dtype) z = relay.nn.bias_add(x, bias) func = relay.Function([x, bias], z) x_data = np.random.uniform(size=xshape).astype(dtype) y_data = np.random.uniform(size=bshape).astype(dtype) verify_results(func, [x_data, y_data], "test_bias_add", rtol=rtol) def test_conv2d(): def verify_conv2d( dtype, scale, dshape, kshape, padding=(1, 1), groups=1, dilation=(1, 1), **attrs ): x = relay.var("x", shape=dshape, dtype=dtype) w = relay.var("w", shape=kshape, dtype=dtype) y = relay.nn.conv2d(x, w, padding=padding, dilation=dilation, groups=groups, **attrs) func = relay.Function([x, w], y) data = np.random.uniform(-scale, scale, size=dshape).astype(dtype) kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype) verify_results(func, [data, kernel], "test_conv2d", rtol=1e-5, atol=1e-5) dshape = (1, 32, 18, 18) kshape = (32, 1, 3, 3) verify_conv2d( "float32", 1, dshape, kshape, padding=(1, 1), channels=32, groups=32, kernel_size=(3, 3) ) dshape = (1, 32, 18, 18) kshape = (32, 4, 3, 3) verify_conv2d( "float32", 1, dshape, kshape, padding=(1, 1), channels=32, groups=8, kernel_size=(3, 3) ) dshape = (1, 32, 18, 18) kshape = (64, 1, 3, 3) verify_conv2d( "float32", 1, dshape, kshape, padding=(1, 1), channels=64, groups=32, kernel_size=(3, 3) ) dshape = (1, 3, 224, 224) kshape = (10, 3, 3, 3) verify_conv2d("float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(3, 3)) dshape = (1, 3, 224, 224) kshape = (10, 3, 3, 3) verify_conv2d("float32", 1, dshape, kshape, padding=(2, 2), channels=10, kernel_size=(3, 3)) dshape = (1, 3, 18, 18) kshape = (10, 3, 3, 3) verify_conv2d( "float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(3, 3), dilation=(3, 3), ) dshape = (1, 3, 18, 18) kshape = (10, 3, 2, 2) verify_conv2d( "float32", 1, dshape, kshape, padding=(2, 2), channels=10, kernel_size=(2, 2), dilation=(1, 1), ) dshape = (1, 3, 18, 18) kshape = (10, 3, 4, 4) verify_conv2d("float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(4, 4)) dshape = (1, 3, 18, 18) kshape = (10, 3, 4, 4) verify_conv2d("float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(4, 4)) def test_conv2d_transpose(): def verify_conv2d_transpose( dtype, scale, dshape, kshape, padding=(1, 1), groups=1, dilation=(1, 1), **attrs ): x = relay.var("x", shape=dshape, dtype=dtype) w = relay.var("w", shape=kshape, dtype=dtype) y = relay.nn.conv2d_transpose( x, w, padding=padding, dilation=dilation, groups=groups, **attrs ) func = relay.Function([x, w], y) data = np.random.uniform(-scale, scale, size=dshape).astype(dtype) kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype) verify_results(func, [data, kernel], "test_conv2d_transpose", rtol=1e-5, atol=1e-5) dshape = (1, 3, 224, 224) kshape = (3, 10, 3, 3) verify_conv2d_transpose( "float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(3, 3) ) dshape = (1, 3, 224, 224) kshape = (3, 10, 3, 3) verify_conv2d_transpose( "float32", 1, dshape, kshape, padding=(2, 2), channels=10, kernel_size=(3, 3) ) dshape = (1, 3, 18, 18) kshape = (3, 10, 2, 2) verify_conv2d_transpose( "float32", 1, dshape, kshape, padding=(2, 2), channels=10, kernel_size=(2, 2), dilation=(1, 1), ) dshape = (1, 3, 18, 18) kshape = (3, 10, 4, 4) verify_conv2d_transpose( "float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(4, 4) ) dshape = (1, 3, 18, 18) kshape = (3, 10, 4, 4) verify_conv2d_transpose( "float32", 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(4, 4) ) def test_reshape(): def verify_reshape(shape, newshape): x = relay.var("x", relay.TensorType(shape, "float32")) z = relay.reshape(x, newshape=newshape) func = relay.Function([x], z) x_data = np.random.uniform(low=-1, high=1, size=shape).astype("float32") verify_results(func, [x_data], "test_reshape", rtol=1e-5, atol=1e-5) verify_reshape((2, 3, 4), tuple(np.array([4, 2, 3], dtype=np.int64))) verify_reshape((2, 3, 4), tuple(np.array([2, 0, 0], dtype=np.int64))) verify_reshape((2, 3, 4), tuple(np.array([0, -1], dtype=np.int64))) verify_reshape((2, 3, 4), tuple(np.array([-1, 0], dtype=np.int64))) def test_transpose(): def verify_reshape(shape, newshape): x = relay.var("x", relay.TensorType(shape, "float32")) z = relay.transpose(x, newshape) func = relay.Function([x], z) x_data = np.random.uniform(low=-1, high=1, size=shape).astype("float32") verify_results(func, [x_data], "test_transpose", rtol=1e-5, atol=1e-5) verify_reshape((1, 2, 3, 4), (0, 2, 3, 1)) verify_reshape((1, 2, 3, 4), (0, 3, 2, 1)) def test_dense(): def verify_dense(d_shape, w_shape): data = relay.var("data", relay.TensorType(d_shape, "float32")) weight = relay.var("weight", relay.TensorType(w_shape, "float32")) func = relay.Function([data, weight], relay.nn.dense(data, weight)) x_data = np.random.uniform(size=d_shape).astype("float32") w_data = np.random.uniform(size=w_shape).astype("float32") verify_results(func, [x_data, w_data], "test_dense", rtol=1e-5, atol=1e-5) verify_dense((1, 8), (16, 8)) verify_dense((1, 4), (3, 4)) def test_max_pool(): def verify_max_pool(x_shape, pool_size, strides, padding, ceil_mode): x = relay.var("x", relay.TensorType(x_shape, "float32")) y = tvm.relay.nn.max_pool2d( x, pool_size=pool_size, strides=strides, padding=padding, ceil_mode=ceil_mode ) func = relay.Function([x], y) x_data = np.random.uniform(size=x_shape).astype("float32") verify_results(func, [x_data], "test_max_pool", rtol=1e-5, atol=1e-5) verify_max_pool( (1, 4, 16, 16), pool_size=(2, 2), strides=(2, 2), padding=(0, 0), ceil_mode=False ) def test_batch_flatten(): def verify_test_batch_flatten(d_shape): data = relay.var("data", relay.TensorType(d_shape, "float32")) func = relay.Function([data], relay.nn.batch_flatten(data)) x_data = np.random.uniform(size=d_shape).astype("float32") verify_results(func, [x_data], "test_batch_flatten", rtol=1e-5, atol=1e-5) verify_test_batch_flatten((1, 2, 3, 4)) verify_test_batch_flatten((1, 8)) def test_batch_norm(): def verify_batch_norm(axis=1): for dtype in ["float16", "float32"]: data = relay.var("data", relay.TensorType((2, 4, 4, 1), dtype)) gamma_shape = (data.type_annotation.shape[axis].value,) beta = relay.var("beta", relay.TensorType(gamma_shape, dtype)) gamma = relay.var("gamma", relay.TensorType(gamma_shape, dtype)) moving_mean = relay.var("moving_mean", relay.TensorType(gamma_shape, dtype)) moving_var = relay.var("moving_var", relay.TensorType(gamma_shape, dtype)) y = relay.nn.batch_norm(data, gamma, beta, moving_mean, moving_var, axis=axis) func = relay.Function([data, gamma, beta, moving_mean, moving_var], y[0]) x_data = np.random.uniform(size=(2, 4, 4, 1)).astype(dtype) beta = np.random.uniform(size=gamma_shape).astype(dtype) gamma = np.random.uniform(size=gamma_shape).astype(dtype) moving_mean = np.random.uniform(size=gamma_shape).astype(dtype) moving_var = np.random.uniform(size=gamma_shape).astype(dtype) verify_results( func, [x_data, gamma, beta, moving_mean, moving_var], "test_batch_norm", rtol=1e-1, atol=1e-1, ) verify_batch_norm(axis=1) verify_batch_norm(axis=3) def test_pad(): def verify_pad(): dshape = (4, 10, 7, 7) x = relay.var("x", shape=dshape, dtype="int32") y = relay.nn.pad(x, ((1, 1), (2, 2), (3, 3), (4, 4))) func = relay.Function([x], y) func = run_infer_type(func) x_data = np.random.randint(low=-255, high=255, size=dshape).astype(np.int32) verify_results(func, [x_data], "test_pad", rtol=1e-5, atol=1e-5) verify_pad() def test_sofmax(): def verify_sofmax(): for dtype in ["float32"]: shape = (10, 4) x = relay.var("x", shape=shape, dtype=dtype) y = relay.nn.softmax(x, axis=1) func = relay.Function([x], y) x_data = np.random.uniform(size=shape).astype(dtype) verify_results(func, [x_data], "test_softmax", rtol=1e-5, atol=1e-5) verify_sofmax() def test_squeeze(): def verify_squeeze(shape, dtype, axis): x = relay.var("x", relay.TensorType(shape, dtype)) z = relay.squeeze(x, axis=axis) func = relay.Function([x], z) x_data = np.random.random_sample(shape).astype(dtype) verify_results(func, [x_data], "test_squeeze", rtol=1e-5, atol=1e-5) verify_squeeze((1, 3, 2, 5), "float32", None) verify_squeeze( (1, 3, 1), "float32", [ 2, ], ) verify_squeeze((1, 2, 1, 2, 1), "float32", [0, 2]) def test_mean(): def verify_mean(data_shape, axis, exclude, keepdims): dtype = "float32" x = relay.var("x", shape=data_shape, dtype=dtype) y = relay.mean(x, axis, keepdims, exclude) func = relay.Function([x], y) x_data = np.random.uniform(size=data_shape).astype(dtype) verify_results(func, [x_data], "test_mean", rtol=1e-5, atol=1e-5) verify_mean((1, 2), 0, False, False) verify_mean((1, 2), 0, True, False) verify_mean((1, 2), 0, True, True) verify_mean((1, 2), 1, True, True) verify_mean((3, 2, 1), 1, False, True) def test_split(): def verify_split(dshape, indices_or_sections, axis=None): dtype = "float32" x = relay.var("x", relay.ty.TensorType(dshape, "float32")) y = relay.split(x, indices_or_sections, axis=axis) func = relay.Function([x], y.astuple()) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_split", rtol=1e-5, atol=1e-5) verify_split((5, 5, 2, 2), 5, axis=1) verify_split((5, 5, 2, 2), 5, axis=0) verify_split((5, 5, 2, 2), [1, 3, 4], axis=0) verify_split((5, 5, 2, 2), [1, 3, 4], axis=1) def test_concatenate(): def verify_concatenate(shapes, axis, dtype="float32"): in_vars = [] in_data = [] for i, shape in enumerate(shapes): in_vars.append(relay.var("x" + str(i), relay.ty.TensorType(shape, dtype))) in_data.append(np.random.uniform(size=shape).astype(dtype)) out_tensor = relay.concatenate(in_vars, axis) func = relay.Function(in_vars, out_tensor) verify_results(func, in_data, "test_concatenate", rtol=1e-5, atol=1e-5) verify_concatenate([(2,), (2,), (2,)], -1) verify_concatenate([(2, 3, 4), (2, 2, 4), (2, 5, 4)], 1) verify_concatenate([(1, 2, 4), (1, 2, 3), (1, 2, 7), (1, 2, 8), (1, 2, 1)], -1) verify_concatenate([(5, 6, 7, 3), (16, 6, 7, 3), (12, 6, 7, 3), (8, 6, 7, 3), (2, 6, 7, 3)], 0) verify_concatenate([(1, 14400), (1, 2400), (1, 640), (1, 240)], 1) def test_strided_slice(): def verify_strided_slice(dshape, begin, end, strides, mode): x = relay.var("x", relay.TensorType(dshape, "float32")) if mode == "size": strides = None z = relay.strided_slice(x, begin=begin, end=end, strides=strides, slice_mode=mode) func = relay.Function([x], z) x_data = np.random.uniform(size=dshape).astype("float32") verify_results(func, [x_data], "test_strided_slice", rtol=1e-5, atol=1e-5) for mode in ["end", "size"]: verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 2, 3], None, mode) verify_strided_slice((3, 4, 3), [1, -1, 0], [4, -1, 3], [1, 2], mode) verify_strided_slice( (3, 4, 3), [ 1, ], [4, -3], None, mode, ) verify_strided_slice((3, 4, 3), [0, 0, 0], [4, -5, 4], [1, -1, 2], mode) verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 4, -3], [2, 1, 1], mode) verify_strided_slice((3, 4, 3), [1, -1, 0], [4, -5, 3], [2, -1, 1], mode) verify_strided_slice((3, 4, 3), [1, 0, 0], [2, 2, 3], [1, 1, 2], mode) verify_strided_slice((3, 4, 3), [1, -1, 0], [2, -3, 3], [1, -1, 1], mode) verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 1000, 3], None, mode) verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 4], None, mode) verify_strided_slice((3, 4, 3), [1, 1], [4, 4, 3], None, mode) verify_strided_slice((3, 4, 3), [1, 1], [4, 4, 3], [1, 1, 2], mode) def test_cmp_type(): for op, ref in ((relay.greater, np.greater), (relay.less, np.less), (relay.equal, np.equal)): x_shape = (10, 4) y_shape = (5, 10, 1) t1 = relay.TensorType(x_shape) t2 = relay.TensorType(y_shape) x = relay.var("x", t1) y = relay.var("y", t2) z = op(x, y) x_data = np.random.rand(*x_shape).astype(t1.dtype) y_data = np.random.rand(*y_shape).astype(t2.dtype) func = relay.Function([x, y], z) verify_results(func, [x_data, y_data], "test_cmp_type", rtol=1e-5, atol=1e-5) def test_unary_identity(): for dtype in ["int16", "float32", "float64"]: for op, ref in [(relay.zeros_like, np.zeros_like), (relay.ones_like, np.ones_like)]: shape = (8, 9, 4) x = relay.var("x", relay.TensorType(shape, dtype)) y = op(x) func = relay.Function( [ x, ], y, ) x_data = np.random.rand(*shape).astype(dtype) verify_results(func, [x_data], "test_cmp_type", rtol=1e-5, atol=1e-5) def test_binary_op(): def check_binary_op(opfunc, dtype): t1 = relay.TensorType((5, 10, 5)) t2 = relay.TensorType((5, 10, 5)) x = relay.var("x", t1, dtype=dtype) y = relay.var("y", t2, dtype=dtype) z = opfunc(x, y) x_data = np.random.rand(5, 10, 5).astype(dtype) y_data = np.random.rand(5, 10, 5).astype(dtype) func = relay.Function([x, y], z) verify_results(func, [x_data, y_data], "test_binary_op", rtol=1e-5, atol=1e-5) for opfunc, ref in [ (relay.add, np.add), (relay.subtract, np.subtract), (relay.multiply, np.multiply), (relay.divide, np.divide), ]: for dtype in ["float32"]: check_binary_op(opfunc, dtype) def test_tuple_types(): def verify_tuple_types(dshape, indices_or_sections, axis=None, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.split(x, indices_or_sections, axis=axis) z = relay.concatenate(y, axis=axis) func = relay.Function([x], z) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_tuple_types", rtol=1e-5, atol=1e-5) split_z = relay.split(z, indices_or_sections, axis=axis) func = relay.Function([x], split_z.astuple()) verify_results(func, [x_data], "test_tuple_types", rtol=1e-5, atol=1e-5) out = relay.Tuple([y[0] + y[1], y[0] - y[1]]) func = relay.Function([x], out) verify_results(func, [x_data], "test_tuple_types", rtol=1e-5, atol=1e-5) z = relay.concatenate(out, axis=axis) func = relay.Function([x], z) verify_results(func, [x_data], "test_tuple_types", rtol=1e-5, atol=1e-5) verify_tuple_types((5, 5, 2, 2), 5, axis=1) verify_tuple_types((5, 5, 2, 2), 5, axis=0) verify_tuple_types((5, 5, 2, 2), [1, 3, 4], axis=0) verify_tuple_types((5, 5, 2, 2), [1, 3, 4], axis=1) def test_layout_transform(): def verify_layout_transform(dshape, src_layout, dst_layout, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.layout_transform(x, src_layout, dst_layout) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_layout_transform", rtol=1e-5, atol=1e-5) verify_layout_transform((1, 3, 8, 8), "NCHW", "NHWC") verify_layout_transform((1, 8, 8, 3), "NHWC", "NCHW") def test_clip(): def verify_clip(dshape, a_min, a_max, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.clip(x, a_min, a_max) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_clip", rtol=1e-5, atol=1e-5) verify_clip((5, 5, 2, 5), 0, 0.2) verify_clip((5, 5, 2, 5), 0.2, 0.5) def test_expand_dims(): def verify_expand_dims(dshape, axis, num_newaxis, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.expand_dims(x, axis, num_newaxis) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_expand_dims", rtol=1e-5, atol=1e-5) verify_expand_dims((1, 1001), 0, 2) verify_expand_dims((1, 1, 1001), 2, 2) def test_lrn(): def verify_lrn(xshape, size, dtype="float32"): x = relay.var("x", relay.ty.TensorType(xshape, dtype)) y = relay.nn.lrn(x, size=size, axis=1, alpha=1.0, beta=1.0, bias=1.0) func = relay.Function([x], y) x_data = np.random.uniform(size=xshape).astype(dtype) verify_results(func, [x_data], "test_lrn", rtol=1e-5, atol=1e-5) isize = [(1, 1, 480, 640), (1, 3, 224, 224)] sizes = [1, 3] for i in isize: for s in sizes: verify_lrn(i, s) def test_sigmoid(): def verify_sigmoid(dshape, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.sigmoid(x) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_sigmoid", rtol=1e-4, atol=1e-4) isize = [(1, 3, 480, 640), (1, 3, 224, 224)] for i in isize: verify_sigmoid(i) def test_copy(): def verify_copy(dshape, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.copy(x) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_copy", rtol=1e-4, atol=1e-4) isize = [(1, 3, 480, 640), (1, 3, 224, 224)] for i in isize: verify_copy(i) def test_round(): def verify_round(dshape, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.round(x) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_round", rtol=1e-4, atol=1e-4) isize = [(1, 3, 480, 640), (1, 3, 224, 224)] for i in isize: verify_round(i) def test_cast(): def verify_cast(dshape, dtype): x = relay.var("x", relay.ty.TensorType(dshape, "float32")) y = relay.cast(x, dtype) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype("float32") verify_results(func, [x_data], "test_cast", rtol=1e-4, atol=1e-4) isize = [(1, 3, 480, 640), (1, 3, 224, 224)] out_dtypes = ["int8", "int16", "uint8", "uint16"] for i in isize: for o_dtype in out_dtypes: verify_cast(i, o_dtype) def test_resize(): def verify_resize(dshape, outsize, method, coord_trans, rounding_method, dtype="float32"): x = relay.var("x", relay.ty.TensorType(dshape, dtype)) y = relay.image.resize2d( x, outsize, layout="NCHW", method=method, coordinate_transformation_mode=coord_trans, rounding_method=rounding_method, ) func = relay.Function([x], y) x_data = np.random.uniform(size=dshape).astype(dtype) verify_results(func, [x_data], "test_resize", rtol=1e-4, atol=1e-4) method = ["nearest_neighbor", "linear", "cubic"] coord_trans = ["half_pixel", "align_corners", "asymmetric"] rounding_method = ["round", "floor", "ceil"] isize = (1, 3, 480, 640) osize = (240, 320) for i in method: for j in coord_trans: for k in rounding_method: if (i == "nearest_neighbor" and j == "align_corners") or ( i == "cubic" and j in ["half_pixel", "align_corners"] ): continue verify_resize(isize, osize, method=i, coord_trans=j, rounding_method=k) osize = (960, 1280) for i in method: for j in coord_trans: for k in rounding_method: if (i == "nearest_neighbor" and j == "align_corners") or (i == "cubic"): continue verify_resize(isize, osize, method=i, coord_trans=j, rounding_method=k) if __name__ == "__main__": test_add() test_bias_add() test_conv2d() test_conv2d_transpose() test_reshape() test_transpose() test_dense() test_max_pool() test_batch_flatten() test_batch_norm() test_pad() test_mean() test_split() test_concatenate() test_sofmax() test_squeeze() test_strided_slice() test_cmp_type() test_binary_op() test_tuple_types() test_layout_transform() test_clip() test_expand_dims() test_lrn() test_sigmoid() test_copy() test_round() test_cast() test_resize()
true
true
1c2d0113353ee68262971a2f20cd036da0ee374d
67
py
Python
tests/test_main.py
grahamhome/pifx
0f9aad667ff216aa00a883fc5efddbf147905d53
[ "Apache-2.0" ]
52
2015-12-16T22:59:36.000Z
2021-04-13T07:10:24.000Z
tests/test_main.py
grahamhome/pifx
0f9aad667ff216aa00a883fc5efddbf147905d53
[ "Apache-2.0" ]
13
2015-12-22T00:28:37.000Z
2021-08-08T01:48:25.000Z
tests/test_main.py
grahamhome/pifx
0f9aad667ff216aa00a883fc5efddbf147905d53
[ "Apache-2.0" ]
7
2016-10-11T20:41:51.000Z
2021-08-08T01:39:42.000Z
import sys sys.path.insert(1, '..') from pifx import PIFX # TODO
9.571429
24
0.671642
import sys sys.path.insert(1, '..') from pifx import PIFX
true
true
1c2d03c1316c9260d3a78c67330574544c2622e0
13,476
py
Python
src/tests/test_utils.py
juanalvarezg/script-server
bb0927ada44b6979240cea62a8103eb00abf5627
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/tests/test_utils.py
juanalvarezg/script-server
bb0927ada44b6979240cea62a8103eb00abf5627
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/tests/test_utils.py
juanalvarezg/script-server
bb0927ada44b6979240cea62a8103eb00abf5627
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
import json import os import shutil import stat import threading import uuid from copy import copy from unittest.case import TestCase from unittest.mock import MagicMock import utils.file_utils as file_utils import utils.os_utils as os_utils from execution.process_base import ProcessWrapper from model.script_config import ConfigModel, ParameterModel from react.properties import ObservableDict from utils import audit_utils temp_folder = 'tests_temp' _original_env = {} def create_file(filepath, *, overwrite=False, text='test text'): if not os.path.exists(temp_folder): os.makedirs(temp_folder) filename = os.path.basename(filepath) folder = os.path.join(temp_folder, os.path.dirname(filepath)) if not os.path.exists(folder): os.makedirs(folder) file_path = os.path.join(folder, filename) if os.path.exists(file_path) and not overwrite: raise Exception('File ' + file_path + ' already exists') file_utils.write_file(file_path, text) return file_path def create_files(names, dir=None): for name in names: if dir is not None: create_file(os.path.join(dir, name)) else: create_file(name) def create_dir(dir_path): if not os.path.exists(temp_folder): os.makedirs(temp_folder) full_path = os.path.join(temp_folder, dir_path) if not os.path.exists(full_path): os.makedirs(full_path) return full_path def setup(): if os.path.exists(temp_folder): _rmtree(temp_folder) os.makedirs(temp_folder) def cleanup(): if os.path.exists(temp_folder): _rmtree(temp_folder) os_utils.reset_os() for key, value in _original_env.items(): if value is None: del os.environ[key] else: os.environ[key] = value _original_env.clear() def _rmtree(folder): exception = None def on_rm_error(func, path, exc_info): try: os.chmod(path, stat.S_IWRITE | stat.S_IEXEC | stat.S_IREAD) os.remove(path) except Exception as e: print('Failed to remove path ' + path + ': ' + str(e)) nonlocal exception if exception is None: exception = e shutil.rmtree(folder, onerror=on_rm_error) if exception: raise exception def set_linux(): os_utils.set_linux() def set_win(): os_utils.set_win() def mock_object(): return type('', (), {})() def write_script_config(conf_object, filename, config_folder=None): if config_folder is None: config_folder = os.path.join(temp_folder, 'runners') file_path = os.path.join(config_folder, filename + '.json') config_json = json.dumps(conf_object) file_utils.write_file(file_path, config_json) return file_path def create_script_param_config( param_name, *, type=None, default=None, required=None, secure=None, param=None, env_var=None, no_value=None, constant=None, multiselect_separator=None, multiselect_argument_type=None, min=None, max=None, allowed_values=None, values_script=None, file_dir=None, file_recursive=None, file_type=None, file_extensions=None, excluded_files=None, same_arg_param=None, values_script_shell=None): conf = {'name': param_name} if type is not None: conf['type'] = type if values_script is not None: conf['values'] = {'script': values_script} if values_script_shell is not None: conf['values']['shell'] = values_script_shell if default is not None: conf['default'] = default if required is not None: conf['required'] = required if secure is not None: conf['secure'] = secure if param is not None: conf['param'] = param if env_var is not None: conf['env_var'] = env_var if no_value is not None: conf['no_value'] = no_value if constant is not None: conf['constant'] = constant if multiselect_separator is not None: conf['separator'] = multiselect_separator if multiselect_argument_type is not None: conf['multiselect_argument_type'] = multiselect_argument_type if min is not None: conf['min'] = min if max is not None: conf['max'] = max if allowed_values is not None: conf['values'] = list(allowed_values) if file_dir is not None: conf['file_dir'] = file_dir if file_recursive is not None: conf['file_recursive'] = file_recursive if file_extensions is not None: conf['file_extensions'] = file_extensions if file_type is not None: conf['file_type'] = file_type if excluded_files is not None: conf['excluded_files'] = excluded_files if same_arg_param is not None: conf['same_arg_param'] = same_arg_param return conf def create_config_model(name, *, config=None, username='user1', audit_name='127.0.0.1', path=None, parameters=None, parameter_values=None, script_command='ls', output_files=None, requires_terminal=None, schedulable=True): result_config = {} if config: result_config.update(config) result_config['name'] = name if parameters is not None: result_config['parameters'] = parameters if path is None: path = name if output_files is not None: result_config['output_files'] = output_files if requires_terminal is not None: result_config['requires_terminal'] = requires_terminal if schedulable is not None: result_config['scheduling'] = {'enabled': schedulable} result_config['script_path'] = script_command model = ConfigModel(result_config, path, username, audit_name) if parameter_values is not None: model.set_all_param_values(model) return model def create_parameter_model(name=None, *, type=None, values_script=None, default=None, required=None, secure=None, param=None, env_var=None, no_value=None, constant=None, multiselect_separator=None, multiselect_argument_type=None, min=None, max=None, allowed_values=None, username='user1', audit_name='127.0.0.1', all_parameters=None, file_dir=None, file_recursive=None, other_param_values: ObservableDict = None, values_script_shell=None): config = create_script_param_config( name, type=type, values_script=values_script, default=default, required=required, secure=secure, param=param, env_var=env_var, no_value=no_value, constant=constant, multiselect_separator=multiselect_separator, multiselect_argument_type=multiselect_argument_type, min=min, max=max, allowed_values=allowed_values, file_dir=file_dir, file_recursive=file_recursive, values_script_shell=values_script_shell) if all_parameters is None: all_parameters = [] return ParameterModel(config, username, audit_name, lambda: all_parameters, other_param_values=other_param_values) def create_simple_parameter_configs(names): return {name: {'name': name} for name in names} def create_parameter_model_from_config(config, *, username='user1', audit_name='127.0.0.1', working_dir=None, all_parameters=None): if all_parameters is None: all_parameters = [] if config is None: config = {} return ParameterModel(config, username, audit_name, all_parameters, working_dir=working_dir) def create_audit_names(ip=None, auth_username=None, proxy_username=None, hostname=None): result = {} if ip is not None: result[audit_utils.IP] = ip if auth_username is not None: result[audit_utils.AUTH_USERNAME] = auth_username if proxy_username is not None: result[audit_utils.PROXIED_USERNAME] = proxy_username if hostname is not None: result[audit_utils.HOSTNAME] = hostname return result def set_env_value(key, value): if key not in _original_env: if key in os.environ: _original_env[key] = value else: _original_env[key] = None os.environ[key] = value def assert_large_dict_equal(expected, actual, testcase): if len(expected) < 20 and len(actual) < 20: testcase.assertEqual(expected, actual) return if expected == actual: return diff_expected = {} diff_actual = {} too_large_diff = False all_keys = set() all_keys.update(expected.keys()) all_keys.update(actual.keys()) for key in all_keys: expected_value = expected.get(key) actual_value = actual.get(key) if expected_value == actual_value: continue diff_expected[key] = expected_value diff_actual[key] = actual_value if len(diff_expected) >= 50: too_large_diff = True break message = 'Showing only different elements' if too_large_diff: message += ' (limited to 50)' testcase.assertEqual(diff_expected, diff_actual, message) def wait_observable_close_notification(observable, timeout): close_condition = threading.Event() observable.subscribe_on_close(lambda: close_condition.set()) close_condition.wait(timeout) def mock_request_handler(*, arguments: dict = None, method='GET', headers=None): if headers is None: headers = {} request_handler = mock_object() def get_argument(arg_name): if arguments is None: return None return arguments.get(arg_name) request_handler.get_argument = get_argument request_handler.request = mock_object() request_handler.request.method = method request_handler.request.headers = headers return request_handler def assert_dir_files(expected_files, dir_path, test_case: TestCase): expected_files_sorted = sorted(copy(expected_files)) actual_files = sorted(os.listdir(dir_path)) test_case.assertSequenceEqual(expected_files_sorted, actual_files) class _MockProcessWrapper(ProcessWrapper): def __init__(self, executor, command, working_directory, env_variables): super().__init__(command, working_directory, env_variables) self.exit_code = None self.finished = False self.process_id = int.from_bytes(uuid.uuid1().bytes, byteorder='big') self.finish_condition = threading.Condition() def get_process_id(self): return self.process_id # method for tests def finish(self, exit_code): if self.is_finished(): raise Exception('Cannot finish a script twice') self.__finish(exit_code) # method for tests def write_output(self, output): self._write_script_output(output) def stop(self): self.__finish(9) def kill(self): self.__finish(15) def __finish(self, exit_code): if self.finished: return with self.finish_condition: self.exit_code = exit_code self.finished = True self.output_stream.close() self.finish_condition.notify_all() self.notify_finish_thread.join() def is_finished(self): return self.finished def get_return_code(self): return self.exit_code def pipe_process_output(self): pass def start_execution(self, command, working_directory): pass def wait_finish(self): with self.finish_condition: while not self.finished: self.finish_condition.wait(0.01) def write_to_input(self, value): pass class AnyUserAuthorizer: def is_allowed_in_app(self, user_id): return True def is_allowed(self, user_id, allowed_users): return True def is_admin(self, user_id): return True class _IdGeneratorMock: def __init__(self) -> None: super().__init__() self.generated_ids = [] self._next_id = 123 def next_id(self): id = str(self._next_id) self._next_id += 1 self.generated_ids.append(id) return id class AsyncMock(MagicMock): async def __call__(self, *args, **kwargs): return super(AsyncMock, self).__call__(*args, **kwargs)
26.632411
96
0.608712
import json import os import shutil import stat import threading import uuid from copy import copy from unittest.case import TestCase from unittest.mock import MagicMock import utils.file_utils as file_utils import utils.os_utils as os_utils from execution.process_base import ProcessWrapper from model.script_config import ConfigModel, ParameterModel from react.properties import ObservableDict from utils import audit_utils temp_folder = 'tests_temp' _original_env = {} def create_file(filepath, *, overwrite=False, text='test text'): if not os.path.exists(temp_folder): os.makedirs(temp_folder) filename = os.path.basename(filepath) folder = os.path.join(temp_folder, os.path.dirname(filepath)) if not os.path.exists(folder): os.makedirs(folder) file_path = os.path.join(folder, filename) if os.path.exists(file_path) and not overwrite: raise Exception('File ' + file_path + ' already exists') file_utils.write_file(file_path, text) return file_path def create_files(names, dir=None): for name in names: if dir is not None: create_file(os.path.join(dir, name)) else: create_file(name) def create_dir(dir_path): if not os.path.exists(temp_folder): os.makedirs(temp_folder) full_path = os.path.join(temp_folder, dir_path) if not os.path.exists(full_path): os.makedirs(full_path) return full_path def setup(): if os.path.exists(temp_folder): _rmtree(temp_folder) os.makedirs(temp_folder) def cleanup(): if os.path.exists(temp_folder): _rmtree(temp_folder) os_utils.reset_os() for key, value in _original_env.items(): if value is None: del os.environ[key] else: os.environ[key] = value _original_env.clear() def _rmtree(folder): exception = None def on_rm_error(func, path, exc_info): try: os.chmod(path, stat.S_IWRITE | stat.S_IEXEC | stat.S_IREAD) os.remove(path) except Exception as e: print('Failed to remove path ' + path + ': ' + str(e)) nonlocal exception if exception is None: exception = e shutil.rmtree(folder, onerror=on_rm_error) if exception: raise exception def set_linux(): os_utils.set_linux() def set_win(): os_utils.set_win() def mock_object(): return type('', (), {})() def write_script_config(conf_object, filename, config_folder=None): if config_folder is None: config_folder = os.path.join(temp_folder, 'runners') file_path = os.path.join(config_folder, filename + '.json') config_json = json.dumps(conf_object) file_utils.write_file(file_path, config_json) return file_path def create_script_param_config( param_name, *, type=None, default=None, required=None, secure=None, param=None, env_var=None, no_value=None, constant=None, multiselect_separator=None, multiselect_argument_type=None, min=None, max=None, allowed_values=None, values_script=None, file_dir=None, file_recursive=None, file_type=None, file_extensions=None, excluded_files=None, same_arg_param=None, values_script_shell=None): conf = {'name': param_name} if type is not None: conf['type'] = type if values_script is not None: conf['values'] = {'script': values_script} if values_script_shell is not None: conf['values']['shell'] = values_script_shell if default is not None: conf['default'] = default if required is not None: conf['required'] = required if secure is not None: conf['secure'] = secure if param is not None: conf['param'] = param if env_var is not None: conf['env_var'] = env_var if no_value is not None: conf['no_value'] = no_value if constant is not None: conf['constant'] = constant if multiselect_separator is not None: conf['separator'] = multiselect_separator if multiselect_argument_type is not None: conf['multiselect_argument_type'] = multiselect_argument_type if min is not None: conf['min'] = min if max is not None: conf['max'] = max if allowed_values is not None: conf['values'] = list(allowed_values) if file_dir is not None: conf['file_dir'] = file_dir if file_recursive is not None: conf['file_recursive'] = file_recursive if file_extensions is not None: conf['file_extensions'] = file_extensions if file_type is not None: conf['file_type'] = file_type if excluded_files is not None: conf['excluded_files'] = excluded_files if same_arg_param is not None: conf['same_arg_param'] = same_arg_param return conf def create_config_model(name, *, config=None, username='user1', audit_name='127.0.0.1', path=None, parameters=None, parameter_values=None, script_command='ls', output_files=None, requires_terminal=None, schedulable=True): result_config = {} if config: result_config.update(config) result_config['name'] = name if parameters is not None: result_config['parameters'] = parameters if path is None: path = name if output_files is not None: result_config['output_files'] = output_files if requires_terminal is not None: result_config['requires_terminal'] = requires_terminal if schedulable is not None: result_config['scheduling'] = {'enabled': schedulable} result_config['script_path'] = script_command model = ConfigModel(result_config, path, username, audit_name) if parameter_values is not None: model.set_all_param_values(model) return model def create_parameter_model(name=None, *, type=None, values_script=None, default=None, required=None, secure=None, param=None, env_var=None, no_value=None, constant=None, multiselect_separator=None, multiselect_argument_type=None, min=None, max=None, allowed_values=None, username='user1', audit_name='127.0.0.1', all_parameters=None, file_dir=None, file_recursive=None, other_param_values: ObservableDict = None, values_script_shell=None): config = create_script_param_config( name, type=type, values_script=values_script, default=default, required=required, secure=secure, param=param, env_var=env_var, no_value=no_value, constant=constant, multiselect_separator=multiselect_separator, multiselect_argument_type=multiselect_argument_type, min=min, max=max, allowed_values=allowed_values, file_dir=file_dir, file_recursive=file_recursive, values_script_shell=values_script_shell) if all_parameters is None: all_parameters = [] return ParameterModel(config, username, audit_name, lambda: all_parameters, other_param_values=other_param_values) def create_simple_parameter_configs(names): return {name: {'name': name} for name in names} def create_parameter_model_from_config(config, *, username='user1', audit_name='127.0.0.1', working_dir=None, all_parameters=None): if all_parameters is None: all_parameters = [] if config is None: config = {} return ParameterModel(config, username, audit_name, all_parameters, working_dir=working_dir) def create_audit_names(ip=None, auth_username=None, proxy_username=None, hostname=None): result = {} if ip is not None: result[audit_utils.IP] = ip if auth_username is not None: result[audit_utils.AUTH_USERNAME] = auth_username if proxy_username is not None: result[audit_utils.PROXIED_USERNAME] = proxy_username if hostname is not None: result[audit_utils.HOSTNAME] = hostname return result def set_env_value(key, value): if key not in _original_env: if key in os.environ: _original_env[key] = value else: _original_env[key] = None os.environ[key] = value def assert_large_dict_equal(expected, actual, testcase): if len(expected) < 20 and len(actual) < 20: testcase.assertEqual(expected, actual) return if expected == actual: return diff_expected = {} diff_actual = {} too_large_diff = False all_keys = set() all_keys.update(expected.keys()) all_keys.update(actual.keys()) for key in all_keys: expected_value = expected.get(key) actual_value = actual.get(key) if expected_value == actual_value: continue diff_expected[key] = expected_value diff_actual[key] = actual_value if len(diff_expected) >= 50: too_large_diff = True break message = 'Showing only different elements' if too_large_diff: message += ' (limited to 50)' testcase.assertEqual(diff_expected, diff_actual, message) def wait_observable_close_notification(observable, timeout): close_condition = threading.Event() observable.subscribe_on_close(lambda: close_condition.set()) close_condition.wait(timeout) def mock_request_handler(*, arguments: dict = None, method='GET', headers=None): if headers is None: headers = {} request_handler = mock_object() def get_argument(arg_name): if arguments is None: return None return arguments.get(arg_name) request_handler.get_argument = get_argument request_handler.request = mock_object() request_handler.request.method = method request_handler.request.headers = headers return request_handler def assert_dir_files(expected_files, dir_path, test_case: TestCase): expected_files_sorted = sorted(copy(expected_files)) actual_files = sorted(os.listdir(dir_path)) test_case.assertSequenceEqual(expected_files_sorted, actual_files) class _MockProcessWrapper(ProcessWrapper): def __init__(self, executor, command, working_directory, env_variables): super().__init__(command, working_directory, env_variables) self.exit_code = None self.finished = False self.process_id = int.from_bytes(uuid.uuid1().bytes, byteorder='big') self.finish_condition = threading.Condition() def get_process_id(self): return self.process_id def finish(self, exit_code): if self.is_finished(): raise Exception('Cannot finish a script twice') self.__finish(exit_code) def write_output(self, output): self._write_script_output(output) def stop(self): self.__finish(9) def kill(self): self.__finish(15) def __finish(self, exit_code): if self.finished: return with self.finish_condition: self.exit_code = exit_code self.finished = True self.output_stream.close() self.finish_condition.notify_all() self.notify_finish_thread.join() def is_finished(self): return self.finished def get_return_code(self): return self.exit_code def pipe_process_output(self): pass def start_execution(self, command, working_directory): pass def wait_finish(self): with self.finish_condition: while not self.finished: self.finish_condition.wait(0.01) def write_to_input(self, value): pass class AnyUserAuthorizer: def is_allowed_in_app(self, user_id): return True def is_allowed(self, user_id, allowed_users): return True def is_admin(self, user_id): return True class _IdGeneratorMock: def __init__(self) -> None: super().__init__() self.generated_ids = [] self._next_id = 123 def next_id(self): id = str(self._next_id) self._next_id += 1 self.generated_ids.append(id) return id class AsyncMock(MagicMock): async def __call__(self, *args, **kwargs): return super(AsyncMock, self).__call__(*args, **kwargs)
true
true
1c2d045bc4ec3a10a114a1b4f089c05bb207e42c
3,003
py
Python
telemetry/telemetry/internal/platform/gpu_info_unittest.py
BearerPipelineTest/catapult
3800a67cd916200046a50748893bbd0dcf3d7f4a
[ "BSD-3-Clause" ]
1,894
2015-04-17T18:29:53.000Z
2022-03-28T22:41:06.000Z
telemetry/telemetry/internal/platform/gpu_info_unittest.py
BearerPipelineTest/catapult
3800a67cd916200046a50748893bbd0dcf3d7f4a
[ "BSD-3-Clause" ]
4,640
2015-07-08T16:19:08.000Z
2019-12-02T15:01:27.000Z
telemetry/telemetry/internal/platform/gpu_info_unittest.py
atuchin-m/catapult
108ea3e2ec108e68216b1250a3d79cc642600294
[ "BSD-3-Clause" ]
698
2015-06-02T19:18:35.000Z
2022-03-29T16:57:15.000Z
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import unittest from telemetry.internal.platform import gpu_device from telemetry.internal.platform import gpu_info class TestGPUInfo(unittest.TestCase): def testConstruction(self): data = { 'devices': [ {'vendor_id': 1000, 'device_id': 2000, 'vendor_string': 'a', 'device_string': 'b'}, {'vendor_id': 3000, 'device_id': 4000, 'vendor_string': 'k', 'device_string': 'l'} ], 'aux_attributes': { 'optimus': False, 'amd_switchable': False, 'driver_vendor': 'c', 'driver_version': 'd', 'driver_date': 'e', 'gl_version_string': 'g', 'gl_vendor': 'h', 'gl_renderer': 'i', 'gl_extensions': 'j', } } info = gpu_info.GPUInfo.FromDict(data) self.assertTrue(len(info.devices) == 2) self.assertTrue(isinstance(info.devices[0], gpu_device.GPUDevice)) self.assertEqual(info.devices[0].vendor_id, 1000) self.assertEqual(info.devices[0].device_id, 2000) self.assertEqual(info.devices[0].vendor_string, 'a') self.assertEqual(info.devices[0].device_string, 'b') self.assertTrue(isinstance(info.devices[1], gpu_device.GPUDevice)) self.assertEqual(info.devices[1].vendor_id, 3000) self.assertEqual(info.devices[1].device_id, 4000) self.assertEqual(info.devices[1].vendor_string, 'k') self.assertEqual(info.devices[1].device_string, 'l') self.assertEqual(info.aux_attributes['optimus'], False) self.assertEqual(info.aux_attributes['amd_switchable'], False) self.assertEqual(info.aux_attributes['driver_vendor'], 'c') self.assertEqual(info.aux_attributes['driver_version'], 'd') self.assertEqual(info.aux_attributes['driver_date'], 'e') self.assertEqual(info.aux_attributes['gl_version_string'], 'g') self.assertEqual(info.aux_attributes['gl_vendor'], 'h') self.assertEqual(info.aux_attributes['gl_renderer'], 'i') self.assertEqual(info.aux_attributes['gl_extensions'], 'j') def testMissingAttrsFromDict(self): data = { 'devices': [{'vendor_id': 1000, 'device_id': 2000, 'vendor_string': 'a', 'device_string': 'b'}] } for k in data: data_copy = data.copy() del data_copy[k] try: gpu_info.GPUInfo.FromDict(data_copy) self.fail('Should raise exception if attribute "%s" is missing' % k) except AssertionError: raise except KeyError: pass def testMissingDevices(self): data = { 'devices': [] } try: gpu_info.GPUInfo.FromDict(data) self.fail('Should raise exception if devices array is empty') except AssertionError: raise except Exception: # pylint: disable=broad-except pass
35.75
76
0.646021
from __future__ import absolute_import import unittest from telemetry.internal.platform import gpu_device from telemetry.internal.platform import gpu_info class TestGPUInfo(unittest.TestCase): def testConstruction(self): data = { 'devices': [ {'vendor_id': 1000, 'device_id': 2000, 'vendor_string': 'a', 'device_string': 'b'}, {'vendor_id': 3000, 'device_id': 4000, 'vendor_string': 'k', 'device_string': 'l'} ], 'aux_attributes': { 'optimus': False, 'amd_switchable': False, 'driver_vendor': 'c', 'driver_version': 'd', 'driver_date': 'e', 'gl_version_string': 'g', 'gl_vendor': 'h', 'gl_renderer': 'i', 'gl_extensions': 'j', } } info = gpu_info.GPUInfo.FromDict(data) self.assertTrue(len(info.devices) == 2) self.assertTrue(isinstance(info.devices[0], gpu_device.GPUDevice)) self.assertEqual(info.devices[0].vendor_id, 1000) self.assertEqual(info.devices[0].device_id, 2000) self.assertEqual(info.devices[0].vendor_string, 'a') self.assertEqual(info.devices[0].device_string, 'b') self.assertTrue(isinstance(info.devices[1], gpu_device.GPUDevice)) self.assertEqual(info.devices[1].vendor_id, 3000) self.assertEqual(info.devices[1].device_id, 4000) self.assertEqual(info.devices[1].vendor_string, 'k') self.assertEqual(info.devices[1].device_string, 'l') self.assertEqual(info.aux_attributes['optimus'], False) self.assertEqual(info.aux_attributes['amd_switchable'], False) self.assertEqual(info.aux_attributes['driver_vendor'], 'c') self.assertEqual(info.aux_attributes['driver_version'], 'd') self.assertEqual(info.aux_attributes['driver_date'], 'e') self.assertEqual(info.aux_attributes['gl_version_string'], 'g') self.assertEqual(info.aux_attributes['gl_vendor'], 'h') self.assertEqual(info.aux_attributes['gl_renderer'], 'i') self.assertEqual(info.aux_attributes['gl_extensions'], 'j') def testMissingAttrsFromDict(self): data = { 'devices': [{'vendor_id': 1000, 'device_id': 2000, 'vendor_string': 'a', 'device_string': 'b'}] } for k in data: data_copy = data.copy() del data_copy[k] try: gpu_info.GPUInfo.FromDict(data_copy) self.fail('Should raise exception if attribute "%s" is missing' % k) except AssertionError: raise except KeyError: pass def testMissingDevices(self): data = { 'devices': [] } try: gpu_info.GPUInfo.FromDict(data) self.fail('Should raise exception if devices array is empty') except AssertionError: raise except Exception: pass
true
true
1c2d05f12b56ab3ee8ae1e1ddbc441a5723ef576
4,595
py
Python
tests/unit/test_organization.py
joeseggie/resourceidea
aae6120e3ec84f3fc7e1ab1bc833ce37bd06685f
[ "MIT" ]
null
null
null
tests/unit/test_organization.py
joeseggie/resourceidea
aae6120e3ec84f3fc7e1ab1bc833ce37bd06685f
[ "MIT" ]
21
2019-01-26T20:39:34.000Z
2019-06-20T10:09:57.000Z
tests/unit/test_organization.py
joeseggie/resourceidea
aae6120e3ec84f3fc7e1ab1bc833ce37bd06685f
[ "MIT" ]
null
null
null
from faker import Faker from faker.providers import address from faker.providers import company import pytest from werkzeug.exceptions import NotFound from app.organization.repositories import OrganizationRepository from app.organization.models import Organization from app.organization.utils import create_organization from app.organization.utils import delete_organization from app.organization.utils import get_organizations from app.organization.utils import get_organization from app.organization.utils import update_organization from app.organization.utils import get_name_slug def test_create(session): # Arrange fake = Faker() fake.add_provider(company) fake.add_provider(address) organization_name = fake.company() organization_name_slug = get_name_slug(organization_name) new_organization = Organization( name=organization_name, name_slug=organization_name_slug, address=fake.street_name()) # Act new_organization = OrganizationRepository.create(new_organization) # Assert assert isinstance(new_organization.id, str) def test_get_by_id(session): test_organization = OrganizationRepository.get_all( sort_key='name', sort_order='asc' )[0] result = OrganizationRepository.get_one_by_id(test_organization.id) assert isinstance(result, Organization) assert result.id == test_organization.id assert result.name == test_organization.name assert result.name_slug == test_organization.name_slug assert result.address == test_organization.address assert result.status == test_organization.status def test_get_all(session): assert isinstance(OrganizationRepository.get_all( sort_key='name', sort_order='asc'), list) def test_update_by_id(session): # Arrange test_organization = OrganizationRepository.get_all( sort_key='name', sort_order='asc' )[0] # Act result = OrganizationRepository.update( model_id=test_organization.id, name='Organization name 1', name_slug='organization-name-1', address='Organization address 1') # Assert assert isinstance(result, Organization) assert result.name == 'Organization name 1' assert result.name_slug == 'organization-name-1' assert result.address == 'Organization address 1' assert result.id == test_organization.id def test_delete_by_id(session): # Arrange test_stub = OrganizationRepository.create( Organization(name='Test org', name_slug='test-org')) # Act result = OrganizationRepository.delete_by_id( test_stub.id) # Assert assert result == 1 def test_update_when_not_found_raises_not_found_exception(session): # Assert with pytest.raises(NotFound): OrganizationRepository.update( model_id='71c4b0b8-cf93-4b0b-8986-58c94aa2c578', name='Organization name 1', name_slug='organization-name-1', address='Organization address 1') def test_delete_when_not_found_returns_zero(session): # Act result = OrganizationRepository\ .delete_by_id('91c4b0b8-cf93-4b0b-8986-58c94aa2c578') # Assert assert result == 0 def test_model_repr(session): new_organization = Organization( name='Organization 1', name_slug='organization-1', address='Organization address') # Assert repr(new_organization) == '<Organization Organization 1>' def test_utils_get_organizations(session): assert isinstance( get_organizations(sort_key='name', sort_order='asc'), list) def test_utils_get_organization(session): # Arrange test_organization = OrganizationRepository.get_all( sort_key='name', sort_order='asc' )[0] assert isinstance( get_organization(test_organization.id), Organization) def test_utils_update_organization(session): test_organization = OrganizationRepository.get_all( sort_key='name', sort_order='asc' )[0] assert isinstance(update_organization( model_id=test_organization.id, name='Organization name', address='Organization address'), Organization) def test_utils_create_organization(session): assert isinstance(create_organization( organization_name='Organization name', address='Organization address'), Organization) def test_utils_delete_organization(session): assert isinstance( delete_organization('91c4b0b8-cf94-4b0b-8986-58c94aa2c578'), int)
29.837662
72
0.717519
from faker import Faker from faker.providers import address from faker.providers import company import pytest from werkzeug.exceptions import NotFound from app.organization.repositories import OrganizationRepository from app.organization.models import Organization from app.organization.utils import create_organization from app.organization.utils import delete_organization from app.organization.utils import get_organizations from app.organization.utils import get_organization from app.organization.utils import update_organization from app.organization.utils import get_name_slug def test_create(session): fake = Faker() fake.add_provider(company) fake.add_provider(address) organization_name = fake.company() organization_name_slug = get_name_slug(organization_name) new_organization = Organization( name=organization_name, name_slug=organization_name_slug, address=fake.street_name()) new_organization = OrganizationRepository.create(new_organization) assert isinstance(new_organization.id, str) def test_get_by_id(session): test_organization = OrganizationRepository.get_all( sort_key='name', sort_order='asc' )[0] result = OrganizationRepository.get_one_by_id(test_organization.id) assert isinstance(result, Organization) assert result.id == test_organization.id assert result.name == test_organization.name assert result.name_slug == test_organization.name_slug assert result.address == test_organization.address assert result.status == test_organization.status def test_get_all(session): assert isinstance(OrganizationRepository.get_all( sort_key='name', sort_order='asc'), list) def test_update_by_id(session): test_organization = OrganizationRepository.get_all( sort_key='name', sort_order='asc' )[0] result = OrganizationRepository.update( model_id=test_organization.id, name='Organization name 1', name_slug='organization-name-1', address='Organization address 1') assert isinstance(result, Organization) assert result.name == 'Organization name 1' assert result.name_slug == 'organization-name-1' assert result.address == 'Organization address 1' assert result.id == test_organization.id def test_delete_by_id(session): test_stub = OrganizationRepository.create( Organization(name='Test org', name_slug='test-org')) result = OrganizationRepository.delete_by_id( test_stub.id) assert result == 1 def test_update_when_not_found_raises_not_found_exception(session): with pytest.raises(NotFound): OrganizationRepository.update( model_id='71c4b0b8-cf93-4b0b-8986-58c94aa2c578', name='Organization name 1', name_slug='organization-name-1', address='Organization address 1') def test_delete_when_not_found_returns_zero(session): result = OrganizationRepository\ .delete_by_id('91c4b0b8-cf93-4b0b-8986-58c94aa2c578') assert result == 0 def test_model_repr(session): new_organization = Organization( name='Organization 1', name_slug='organization-1', address='Organization address') repr(new_organization) == '<Organization Organization 1>' def test_utils_get_organizations(session): assert isinstance( get_organizations(sort_key='name', sort_order='asc'), list) def test_utils_get_organization(session): test_organization = OrganizationRepository.get_all( sort_key='name', sort_order='asc' )[0] assert isinstance( get_organization(test_organization.id), Organization) def test_utils_update_organization(session): test_organization = OrganizationRepository.get_all( sort_key='name', sort_order='asc' )[0] assert isinstance(update_organization( model_id=test_organization.id, name='Organization name', address='Organization address'), Organization) def test_utils_create_organization(session): assert isinstance(create_organization( organization_name='Organization name', address='Organization address'), Organization) def test_utils_delete_organization(session): assert isinstance( delete_organization('91c4b0b8-cf94-4b0b-8986-58c94aa2c578'), int)
true
true
1c2d0684c89b81f50f514cc0436a71df4e75e4cf
5,057
py
Python
mmdet/models/detectors/querytrack.py
Joanna0123/QueryInst
6f75240610439e92bca5398054e3f7adc37bfd53
[ "MIT" ]
null
null
null
mmdet/models/detectors/querytrack.py
Joanna0123/QueryInst
6f75240610439e92bca5398054e3f7adc37bfd53
[ "MIT" ]
null
null
null
mmdet/models/detectors/querytrack.py
Joanna0123/QueryInst
6f75240610439e92bca5398054e3f7adc37bfd53
[ "MIT" ]
null
null
null
from ..builder import DETECTORS from .two_stage import TwoStageDetector @DETECTORS.register_module() class QueryTrack(TwoStageDetector): r"""Implementation of `QueryTrack: Parallelly Supervised Mask Query for Instance Segmentation <https://arxiv.org/abs/2105.01928>`, based on SparseRCNN detector. """ def __init__(self, *args, **kwargs): super(QueryTrack, self).__init__(*args, **kwargs) assert self.with_rpn, 'QueryTrack do not support external proposals' def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None, proposals=None, **kwargs): """ Args: img (Tensor): of shape (N, C, H, W) encoding input images. Typically these should be mean centered and std scaled. img_metas (list[dict]): list of image info dict where each dict has: 'img_shape', 'scale_factor', 'flip', and may also contain 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'. For details on the values of these keys see :class:`mmdet.datasets.pipelines.Collect`. gt_bboxes (list[Tensor]): Ground truth bboxes for each image with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format. gt_labels (list[Tensor]): class indices corresponding to each box gt_bboxes_ignore (None | list[Tensor): specify which bounding boxes can be ignored when computing the loss. gt_masks (List[Tensor], optional) : Segmentation masks for each box. But we don't support it in this architecture. proposals (List[Tensor], optional): override rpn proposals with custom proposals. Use when `with_rpn` is False. Returns: dict[str, Tensor]: a dictionary of loss components """ assert proposals is None, 'QueryTrack does not support' \ ' external proposals' assert gt_masks is not None, 'QueryTrack needs mask groundtruth annotations' \ ' for instance segmentation' x = self.extract_feat(img) proposal_boxes, proposal_features, imgs_whwh = \ self.rpn_head.forward_train(x, img_metas) roi_losses = self.roi_head.forward_train( x, proposal_boxes, proposal_features, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=gt_bboxes_ignore, gt_masks=gt_masks, imgs_whwh=imgs_whwh) return roi_losses def simple_test(self, img, img_metas, rescale=False): """Test function without test time augmentation. Args: imgs (list[torch.Tensor]): List of multiple images img_metas (list[dict]): List of image information. rescale (bool): Whether to rescale the results. Defaults to False. Returns: list[list[np.ndarray]]: BBox results of each image and classes. The outer list corresponds to each image. The inner list corresponds to each class. """ x = self.extract_feat(img) proposal_boxes, proposal_features, imgs_whwh = \ self.rpn_head.simple_test_rpn(x, img_metas) results = self.roi_head.simple_test( x, proposal_boxes, proposal_features, img_metas, imgs_whwh=imgs_whwh, rescale=rescale) return results def aug_test(self, imgs, img_metas, rescale=False): """Test with augmentations. If rescale is False, then returned bboxes and masks will fit the scale of imgs[0]. """ x = self.extract_feats(imgs) proposal_boxes, proposal_features, imgs_whwh = \ self.rpn_head.aug_test_rpn(x, img_metas) results = self.roi_head.aug_test( x, proposal_boxes, proposal_features, img_metas, aug_imgs_whwh=imgs_whwh, rescale=rescale) return results def forward_dummy(self, img): """Used for computing network flops. See `mmdetection/tools/analysis_tools/get_flops.py` """ # backbone x = self.extract_feat(img) # rpn num_imgs = len(img) dummy_img_metas = [ dict(img_shape=(800, 1333, 3)) for _ in range(num_imgs) ] proposal_boxes, proposal_features, imgs_whwh = \ self.rpn_head.simple_test_rpn(x, dummy_img_metas) # roi_head roi_outs = self.roi_head.forward_dummy(x, proposal_boxes, proposal_features, dummy_img_metas) return roi_outs
38.603053
86
0.57366
from ..builder import DETECTORS from .two_stage import TwoStageDetector @DETECTORS.register_module() class QueryTrack(TwoStageDetector): def __init__(self, *args, **kwargs): super(QueryTrack, self).__init__(*args, **kwargs) assert self.with_rpn, 'QueryTrack do not support external proposals' def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None, proposals=None, **kwargs): assert proposals is None, 'QueryTrack does not support' \ ' external proposals' assert gt_masks is not None, 'QueryTrack needs mask groundtruth annotations' \ ' for instance segmentation' x = self.extract_feat(img) proposal_boxes, proposal_features, imgs_whwh = \ self.rpn_head.forward_train(x, img_metas) roi_losses = self.roi_head.forward_train( x, proposal_boxes, proposal_features, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=gt_bboxes_ignore, gt_masks=gt_masks, imgs_whwh=imgs_whwh) return roi_losses def simple_test(self, img, img_metas, rescale=False): x = self.extract_feat(img) proposal_boxes, proposal_features, imgs_whwh = \ self.rpn_head.simple_test_rpn(x, img_metas) results = self.roi_head.simple_test( x, proposal_boxes, proposal_features, img_metas, imgs_whwh=imgs_whwh, rescale=rescale) return results def aug_test(self, imgs, img_metas, rescale=False): x = self.extract_feats(imgs) proposal_boxes, proposal_features, imgs_whwh = \ self.rpn_head.aug_test_rpn(x, img_metas) results = self.roi_head.aug_test( x, proposal_boxes, proposal_features, img_metas, aug_imgs_whwh=imgs_whwh, rescale=rescale) return results def forward_dummy(self, img): x = self.extract_feat(img) num_imgs = len(img) dummy_img_metas = [ dict(img_shape=(800, 1333, 3)) for _ in range(num_imgs) ] proposal_boxes, proposal_features, imgs_whwh = \ self.rpn_head.simple_test_rpn(x, dummy_img_metas) roi_outs = self.roi_head.forward_dummy(x, proposal_boxes, proposal_features, dummy_img_metas) return roi_outs
true
true
1c2d06962ad333a36d67b09c592fec2e4a657d7e
6,137
py
Python
jina/drivers/helper.py
xubiuit/jina
4ab91693c2d51a35eca3cf6c187034e0568b0ac9
[ "Apache-2.0" ]
null
null
null
jina/drivers/helper.py
xubiuit/jina
4ab91693c2d51a35eca3cf6c187034e0568b0ac9
[ "Apache-2.0" ]
null
null
null
jina/drivers/helper.py
xubiuit/jina
4ab91693c2d51a35eca3cf6c187034e0568b0ac9
[ "Apache-2.0" ]
null
null
null
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import mimetypes import os import urllib.parse import urllib.request from typing import Dict, Any, Iterable, Tuple, Union, List, Callable import numpy as np from ..proto import jina_pb2 def pb2array(blob: 'jina_pb2.NdArray') -> 'np.ndarray': """Convert a blob protobuf to a numpy ndarray. Note if the argument ``quantize`` is specified in :func:`array2pb` then the returned result may be lossy. Nonetheless, it will always in original ``dtype``, i.e. ``float32`` or ``float64`` :param blob: a blob described in protobuf """ x = np.frombuffer(blob.buffer, dtype=blob.dtype) if blob.quantization == jina_pb2.NdArray.FP16: x = x.astype(blob.original_dtype) elif blob.quantization == jina_pb2.NdArray.UINT8: x = x.astype(blob.original_dtype) * blob.scale + blob.min_val return x.reshape(blob.shape) def array2pb(x: 'np.ndarray', quantize: str = None) -> 'jina_pb2.NdArray': """Convert a numpy ndarray to blob protobuf. :param x: the target ndarray :param quantize: the quantization method used when converting to protobuf. Availables are ``fp16``, ``uint8``, default is None. Remarks on quantization: The quantization only works when ``x`` is in ``float32`` or ``float64``. The motivation is to save the network bandwidth by using less bits to store the numpy array in the protobuf. - ``fp16`` quantization is lossless, can be used widely. Each float is represented by 16 bits. - ``uint8`` quantization is lossy. Each float is represented by 8 bits. The algorithm behind is standard scaling. There is no need to specify the quantization type in :func:`pb2array`, as the quantize type is stored and the blob is self-contained to recover the original numpy array """ blob = jina_pb2.NdArray() quantize = os.environ.get('JINA_ARRAY_QUANT', quantize) if quantize == 'fp16' and (x.dtype == np.float32 or x.dtype == np.float64): blob.quantization = jina_pb2.NdArray.FP16 blob.original_dtype = x.dtype.name x = x.astype(np.float16) elif quantize == 'uint8' and (x.dtype == np.float32 or x.dtype == np.float64 or x.dtype == np.float16): blob.quantization = jina_pb2.NdArray.UINT8 blob.max_val, blob.min_val = x.max(), x.min() blob.original_dtype = x.dtype.name blob.scale = (blob.max_val - blob.min_val) / 256 x = ((x - blob.min_val) / blob.scale).astype(np.uint8) else: blob.quantization = jina_pb2.NdArray.NONE blob.buffer = x.tobytes() blob.shape.extend(list(x.shape)) blob.dtype = x.dtype.name return blob def extract_chunks(docs: Iterable['jina_pb2.Document'], chunks_iter_fn: Callable, filter_by: Union[Tuple[str], List[str]], embedding: bool) -> Tuple: """Iterate over a list of protobuf documents and extract chunk-level information from them :param docs: an iterable of protobuf documents :param embedding: an indicator of extracting embedding or not. If ``True`` then all chunk-level embedding are extracted. If ``False`` then ``text``, ``buffer``, ``blob`` info of each chunks are extracted :param filter_by: a list of service names to wait :return: A tuple of four pieces: - a numpy ndarray of extracted info - the corresponding chunk references - the doc_id list where the doc has no chunk, useful for debugging - the chunk_id list where the chunk has no contents, useful for debugging """ _contents = [] chunk_pts = [] no_chunk_docs = [] bad_chunk_ids = [] if embedding: _extract_fn = lambda c: c.embedding.buffer and pb2array(c.embedding) else: _extract_fn = lambda c: c.text or c.buffer or (c.blob and pb2array(c.blob)) for d in docs: has_chunk = False for c in chunks_iter_fn(d): _c = _extract_fn(c) if filter_by and (c.field_name not in filter_by): continue if _c is not None: _contents.append(_c) chunk_pts.append(c) has_chunk = True else: bad_chunk_ids.append((d.doc_id, c.chunk_id)) if not has_chunk: no_chunk_docs.append(d.doc_id) contents = np.stack(_contents) if len(_contents) > 0 else None return contents, chunk_pts, no_chunk_docs, bad_chunk_ids def routes2str(msg: 'jina_pb2.Message', flag_current: bool = False) -> str: """Get the string representation of the routes in a message. :param msg: a protobuf message :param flag_current: flag the current :class:`BasePod` as ``⚐`` """ route_str = [r.pod for r in msg.envelope.routes] if flag_current: route_str.append('⚐') from ..helper import colored return colored('▸', 'green').join(route_str) def add_route(evlp: 'jina_pb2.Envelope', name: str, identity: str) -> None: """Add a route to the envelope :param evlp: the envelope to modify :param name: the name of the pod service :param identity: the identity of the pod service """ r = evlp.routes.add() r.pod = name r.start_time.GetCurrentTime() r.pod_id = identity def pb_obj2dict(obj, keys: Iterable[str]) -> Dict[str, Any]: """Convert a protobuf object to a Dict by selected keys :param obj: a protobuf object :param keys: an iterable of keys for extraction """ return {k: getattr(obj, k) for k in keys if hasattr(obj, k)} def guess_mime(uri): # guess when uri points to a local file m_type = mimetypes.guess_type(uri)[0] # guess when uri points to a remote file if not m_type and urllib.parse.urlparse(uri).scheme in {'http', 'https', 'data'}: page = urllib.request.Request(uri, headers={'User-Agent': 'Mozilla/5.0'}) tmp = urllib.request.urlopen(page) m_type = tmp.info().get_content_type() return m_type
37.193939
125
0.648851
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import mimetypes import os import urllib.parse import urllib.request from typing import Dict, Any, Iterable, Tuple, Union, List, Callable import numpy as np from ..proto import jina_pb2 def pb2array(blob: 'jina_pb2.NdArray') -> 'np.ndarray': x = np.frombuffer(blob.buffer, dtype=blob.dtype) if blob.quantization == jina_pb2.NdArray.FP16: x = x.astype(blob.original_dtype) elif blob.quantization == jina_pb2.NdArray.UINT8: x = x.astype(blob.original_dtype) * blob.scale + blob.min_val return x.reshape(blob.shape) def array2pb(x: 'np.ndarray', quantize: str = None) -> 'jina_pb2.NdArray': blob = jina_pb2.NdArray() quantize = os.environ.get('JINA_ARRAY_QUANT', quantize) if quantize == 'fp16' and (x.dtype == np.float32 or x.dtype == np.float64): blob.quantization = jina_pb2.NdArray.FP16 blob.original_dtype = x.dtype.name x = x.astype(np.float16) elif quantize == 'uint8' and (x.dtype == np.float32 or x.dtype == np.float64 or x.dtype == np.float16): blob.quantization = jina_pb2.NdArray.UINT8 blob.max_val, blob.min_val = x.max(), x.min() blob.original_dtype = x.dtype.name blob.scale = (blob.max_val - blob.min_val) / 256 x = ((x - blob.min_val) / blob.scale).astype(np.uint8) else: blob.quantization = jina_pb2.NdArray.NONE blob.buffer = x.tobytes() blob.shape.extend(list(x.shape)) blob.dtype = x.dtype.name return blob def extract_chunks(docs: Iterable['jina_pb2.Document'], chunks_iter_fn: Callable, filter_by: Union[Tuple[str], List[str]], embedding: bool) -> Tuple: _contents = [] chunk_pts = [] no_chunk_docs = [] bad_chunk_ids = [] if embedding: _extract_fn = lambda c: c.embedding.buffer and pb2array(c.embedding) else: _extract_fn = lambda c: c.text or c.buffer or (c.blob and pb2array(c.blob)) for d in docs: has_chunk = False for c in chunks_iter_fn(d): _c = _extract_fn(c) if filter_by and (c.field_name not in filter_by): continue if _c is not None: _contents.append(_c) chunk_pts.append(c) has_chunk = True else: bad_chunk_ids.append((d.doc_id, c.chunk_id)) if not has_chunk: no_chunk_docs.append(d.doc_id) contents = np.stack(_contents) if len(_contents) > 0 else None return contents, chunk_pts, no_chunk_docs, bad_chunk_ids def routes2str(msg: 'jina_pb2.Message', flag_current: bool = False) -> str: route_str = [r.pod for r in msg.envelope.routes] if flag_current: route_str.append('⚐') from ..helper import colored return colored('▸', 'green').join(route_str) def add_route(evlp: 'jina_pb2.Envelope', name: str, identity: str) -> None: r = evlp.routes.add() r.pod = name r.start_time.GetCurrentTime() r.pod_id = identity def pb_obj2dict(obj, keys: Iterable[str]) -> Dict[str, Any]: return {k: getattr(obj, k) for k in keys if hasattr(obj, k)} def guess_mime(uri): m_type = mimetypes.guess_type(uri)[0] if not m_type and urllib.parse.urlparse(uri).scheme in {'http', 'https', 'data'}: page = urllib.request.Request(uri, headers={'User-Agent': 'Mozilla/5.0'}) tmp = urllib.request.urlopen(page) m_type = tmp.info().get_content_type() return m_type
true
true
1c2d06c3fd512f60866a1355b452fca5d3c88d9a
14,273
py
Python
pymatgen/alchemy/materials.py
anjlip/pymatgen
62ecae1c7382a41861e3a5d9b9c8dd1207472409
[ "MIT" ]
2
2017-10-02T03:11:47.000Z
2018-12-02T12:56:12.000Z
pymatgen/alchemy/materials.py
darnoceloc/pymatgen
5cc42912a12a265a603df7e34c856561f76edc1f
[ "MIT" ]
3
2017-07-18T01:13:41.000Z
2019-04-29T18:17:30.000Z
pymatgen/alchemy/materials.py
darnoceloc/pymatgen
5cc42912a12a265a603df7e34c856561f76edc1f
[ "MIT" ]
2
2016-06-15T00:12:59.000Z
2018-12-02T12:56:47.000Z
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import os import re import json import datetime from copy import deepcopy from monty.json import MontyDecoder, jsanitize from pymatgen.core.structure import Structure from pymatgen.io.cif import CifParser from pymatgen.io.vasp.inputs import Poscar from monty.json import MSONable from pymatgen.io.vasp.sets import MPRelaxSet from warnings import warn """ This module provides various representations of transformed structures. A TransformedStructure is a structure that has been modified by undergoing a series of transformations. """ __author__ = "Shyue Ping Ong, Will Richards" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "1.0" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __date__ = "Mar 2, 2012" dec = MontyDecoder() class TransformedStructure(MSONable): """ Container object for new structures that include history of transformations. Each transformed structure is made up of a sequence of structures with associated transformation history. """ def __init__(self, structure, transformations=None, history=None, other_parameters=None): """ Initializes a transformed structure from a structure. Args: structure (Structure): Input structure transformations ([Transformations]): List of transformations to apply. history (list): Previous history. other_parameters (dict): Additional parameters to be added. """ self.final_structure = structure self.history = history or [] self.other_parameters = other_parameters or {} self._undone = [] transformations = transformations or [] for t in transformations: self.append_transformation(t) def undo_last_change(self): """ Undo the last change in the TransformedStructure. Raises: IndexError: If already at the oldest change. """ if len(self.history) == 0: raise IndexError("Can't undo. Already at oldest change.") if 'input_structure' not in self.history[-1]: raise IndexError("Can't undo. Latest history has no " "input_structure") h = self.history.pop() self._undone.append((h, self.final_structure)) s = h["input_structure"] if isinstance(s, dict): s = Structure.from_dict(s) self.final_structure = s def redo_next_change(self): """ Redo the last undone change in the TransformedStructure. Raises: IndexError: If already at the latest change. """ if len(self._undone) == 0: raise IndexError("Can't redo. Already at latest change.") h, s = self._undone.pop() self.history.append(h) self.final_structure = s def __getattr__(self, name): s = object.__getattribute__(self, 'final_structure') return getattr(s, name) def __len__(self): return len(self.history) def append_transformation(self, transformation, return_alternatives=False, clear_redo=True): """ Appends a transformation to the TransformedStructure. Args: transformation: Transformation to append return_alternatives: Whether to return alternative TransformedStructures for one-to-many transformations. return_alternatives can be a number, which stipulates the total number of structures to return. clear_redo: Boolean indicating whether to clear the redo list. By default, this is True, meaning any appends clears the history of undoing. However, when using append_transformation to do a redo, the redo list should not be cleared to allow multiple redos. """ if clear_redo: self._undone = [] if return_alternatives and transformation.is_one_to_many: ranked_list = transformation.apply_transformation( self.final_structure, return_ranked_list=return_alternatives) input_structure = self.final_structure.as_dict() alts = [] for x in ranked_list[1:]: s = x.pop("structure") actual_transformation = x.pop("transformation", transformation) hdict = actual_transformation.as_dict() hdict["input_structure"] = input_structure hdict["output_parameters"] = x self.final_structure = s d = self.as_dict() d['history'].append(hdict) d['final_structure'] = s.as_dict() alts.append(TransformedStructure.from_dict(d)) x = ranked_list[0] s = x.pop("structure") actual_transformation = x.pop("transformation", transformation) hdict = actual_transformation.as_dict() hdict["input_structure"] = self.final_structure.as_dict() hdict["output_parameters"] = x self.history.append(hdict) self.final_structure = s return alts else: s = transformation.apply_transformation(self.final_structure) hdict = transformation.as_dict() hdict["input_structure"] = self.final_structure.as_dict() hdict["output_parameters"] = {} self.history.append(hdict) self.final_structure = s def append_filter(self, structure_filter): """ Adds a filter. Args: structure_filter (StructureFilter): A filter implementating the AbstractStructureFilter API. Tells transmuter waht structures to retain. """ hdict = structure_filter.as_dict() hdict["input_structure"] = self.final_structure.as_dict() self.history.append(hdict) def extend_transformations(self, transformations, return_alternatives=False): """ Extends a sequence of transformations to the TransformedStructure. Args: transformations: Sequence of Transformations return_alternatives: Whether to return alternative TransformedStructures for one-to-many transformations. return_alternatives can be a number, which stipulates the total number of structures to return. """ for t in transformations: self.append_transformation(t, return_alternatives=return_alternatives) def get_vasp_input(self, vasp_input_set=MPRelaxSet, **kwargs): """ Returns VASP input as a dict of vasp objects. Args: vasp_input_set (pymatgen.io.vaspio_set.VaspInputSet): input set to create vasp input files from structures """ d = vasp_input_set(self.final_structure, **kwargs).get_vasp_input() d["transformations.json"] = json.dumps(self.as_dict()) return d def write_vasp_input(self, vasp_input_set=MPRelaxSet, output_dir=".", create_directory=True, **kwargs): """ Writes VASP input to an output_dir. Args: vasp_input_set: pymatgen.io.vaspio_set.VaspInputSet like object that creates vasp input files from structures output_dir: Directory to output files create_directory: Create the directory if not present. Defaults to True. \\*\\*kwargs: All keyword args supported by the VASP input set. """ vasp_input_set(self.final_structure, **kwargs).write_input( output_dir, make_dir_if_not_present=create_directory) with open(os.path.join(output_dir, "transformations.json"), "w") as fp: json.dump(self.as_dict(), fp) def __str__(self): output = ["Current structure", "------------", str(self.final_structure), "\nHistory", "------------"] for h in self.history: h.pop('input_structure', None) output.append(str(h)) output.append("\nOther parameters") output.append("------------") output.append(str(self.other_parameters)) return "\n".join(output) def set_parameter(self, key, value): self.other_parameters[key] = value @property def was_modified(self): """ Boolean describing whether the last transformation on the structure made any alterations to it one example of when this would return false is in the case of performing a substitution transformation on the structure when the specie to replace isn't in the structure. """ return not self.final_structure == self.structures[-2] @property def structures(self): """ Copy of all structures in the TransformedStructure. A structure is stored after every single transformation. """ hstructs = [Structure.from_dict(s['input_structure']) for s in self.history if 'input_structure' in s] return hstructs + [self.final_structure] @staticmethod def from_cif_string(cif_string, transformations=None, primitive=True, occupancy_tolerance=1.): """ Generates TransformedStructure from a cif string. Args: cif_string (str): Input cif string. Should contain only one structure. For cifs containing multiple structures, please use CifTransmuter. transformations ([Transformations]): Sequence of transformations to be applied to the input structure. primitive (bool): Option to set if the primitive cell should be extracted. Defaults to True. However, there are certain instances where you might want to use a non-primitive cell, e.g., if you are trying to generate all possible orderings of partial removals or order a disordered structure. occupancy_tolerance (float): If total occupancy of a site is between 1 and occupancy_tolerance, the occupancies will be scaled down to 1. Returns: TransformedStructure """ parser = CifParser.from_string(cif_string, occupancy_tolerance) raw_string = re.sub(r"'", "\"", cif_string) cif_dict = parser.as_dict() cif_keys = list(cif_dict.keys()) s = parser.get_structures(primitive)[0] partial_cif = cif_dict[cif_keys[0]] if "_database_code_ICSD" in partial_cif: source = partial_cif["_database_code_ICSD"] + "-ICSD" else: source = "uploaded cif" source_info = {"source": source, "datetime": str(datetime.datetime.now()), "original_file": raw_string, "cif_data": cif_dict[cif_keys[0]]} return TransformedStructure(s, transformations, history=[source_info]) @staticmethod def from_poscar_string(poscar_string, transformations=None): """ Generates TransformedStructure from a poscar string. Args: poscar_string (str): Input POSCAR string. transformations ([Transformations]): Sequence of transformations to be applied to the input structure. """ p = Poscar.from_string(poscar_string) if not p.true_names: raise ValueError("Transformation can be craeted only from POSCAR " "strings with proper VASP5 element symbols.") raw_string = re.sub(r"'", "\"", poscar_string) s = p.structure source_info = {"source": "POSCAR", "datetime": str(datetime.datetime.now()), "original_file": raw_string} return TransformedStructure(s, transformations, history=[source_info]) def as_dict(self): """ Dict representation of the TransformedStructure. """ d = self.final_structure.as_dict() d["@module"] = self.__class__.__module__ d["@class"] = self.__class__.__name__ d["history"] = jsanitize(self.history) d["version"] = __version__ d["last_modified"] = str(datetime.datetime.utcnow()) d["other_parameters"] = jsanitize(self.other_parameters) return d @classmethod def from_dict(cls, d): """ Creates a TransformedStructure from a dict. """ s = Structure.from_dict(d) return cls(s, history=d["history"], other_parameters=d.get("other_parameters", None)) def to_snl(self, authors, projects=None, references='', remarks=None, data=None, created_at=None): if self.other_parameters: warn('Data in TransformedStructure.other_parameters discarded ' 'during type conversion to SNL') hist = [] for h in self.history: snl_metadata = h.pop('_snl', {}) hist.append({'name': snl_metadata.pop('name', 'pymatgen'), 'url': snl_metadata.pop( 'url', 'http://pypi.python.org/pypi/pymatgen'), 'description': h}) from pymatgen.util.provenance import StructureNL return StructureNL(self.final_structure, authors, projects, references, remarks, data, hist, created_at) @classmethod def from_snl(cls, snl): """ Create TransformedStructure from SNL. Args: snl (StructureNL): Starting snl Returns: TransformedStructure """ hist = [] for h in snl.history: d = h.description d['_snl'] = {'url': h.url, 'name': h.name} hist.append(d) return cls(snl.structure, history=hist)
38.061333
79
0.605899
import os import re import json import datetime from copy import deepcopy from monty.json import MontyDecoder, jsanitize from pymatgen.core.structure import Structure from pymatgen.io.cif import CifParser from pymatgen.io.vasp.inputs import Poscar from monty.json import MSONable from pymatgen.io.vasp.sets import MPRelaxSet from warnings import warn __author__ = "Shyue Ping Ong, Will Richards" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "1.0" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __date__ = "Mar 2, 2012" dec = MontyDecoder() class TransformedStructure(MSONable): def __init__(self, structure, transformations=None, history=None, other_parameters=None): self.final_structure = structure self.history = history or [] self.other_parameters = other_parameters or {} self._undone = [] transformations = transformations or [] for t in transformations: self.append_transformation(t) def undo_last_change(self): if len(self.history) == 0: raise IndexError("Can't undo. Already at oldest change.") if 'input_structure' not in self.history[-1]: raise IndexError("Can't undo. Latest history has no " "input_structure") h = self.history.pop() self._undone.append((h, self.final_structure)) s = h["input_structure"] if isinstance(s, dict): s = Structure.from_dict(s) self.final_structure = s def redo_next_change(self): if len(self._undone) == 0: raise IndexError("Can't redo. Already at latest change.") h, s = self._undone.pop() self.history.append(h) self.final_structure = s def __getattr__(self, name): s = object.__getattribute__(self, 'final_structure') return getattr(s, name) def __len__(self): return len(self.history) def append_transformation(self, transformation, return_alternatives=False, clear_redo=True): if clear_redo: self._undone = [] if return_alternatives and transformation.is_one_to_many: ranked_list = transformation.apply_transformation( self.final_structure, return_ranked_list=return_alternatives) input_structure = self.final_structure.as_dict() alts = [] for x in ranked_list[1:]: s = x.pop("structure") actual_transformation = x.pop("transformation", transformation) hdict = actual_transformation.as_dict() hdict["input_structure"] = input_structure hdict["output_parameters"] = x self.final_structure = s d = self.as_dict() d['history'].append(hdict) d['final_structure'] = s.as_dict() alts.append(TransformedStructure.from_dict(d)) x = ranked_list[0] s = x.pop("structure") actual_transformation = x.pop("transformation", transformation) hdict = actual_transformation.as_dict() hdict["input_structure"] = self.final_structure.as_dict() hdict["output_parameters"] = x self.history.append(hdict) self.final_structure = s return alts else: s = transformation.apply_transformation(self.final_structure) hdict = transformation.as_dict() hdict["input_structure"] = self.final_structure.as_dict() hdict["output_parameters"] = {} self.history.append(hdict) self.final_structure = s def append_filter(self, structure_filter): hdict = structure_filter.as_dict() hdict["input_structure"] = self.final_structure.as_dict() self.history.append(hdict) def extend_transformations(self, transformations, return_alternatives=False): for t in transformations: self.append_transformation(t, return_alternatives=return_alternatives) def get_vasp_input(self, vasp_input_set=MPRelaxSet, **kwargs): d = vasp_input_set(self.final_structure, **kwargs).get_vasp_input() d["transformations.json"] = json.dumps(self.as_dict()) return d def write_vasp_input(self, vasp_input_set=MPRelaxSet, output_dir=".", create_directory=True, **kwargs): vasp_input_set(self.final_structure, **kwargs).write_input( output_dir, make_dir_if_not_present=create_directory) with open(os.path.join(output_dir, "transformations.json"), "w") as fp: json.dump(self.as_dict(), fp) def __str__(self): output = ["Current structure", "------------", str(self.final_structure), "\nHistory", "------------"] for h in self.history: h.pop('input_structure', None) output.append(str(h)) output.append("\nOther parameters") output.append("------------") output.append(str(self.other_parameters)) return "\n".join(output) def set_parameter(self, key, value): self.other_parameters[key] = value @property def was_modified(self): return not self.final_structure == self.structures[-2] @property def structures(self): hstructs = [Structure.from_dict(s['input_structure']) for s in self.history if 'input_structure' in s] return hstructs + [self.final_structure] @staticmethod def from_cif_string(cif_string, transformations=None, primitive=True, occupancy_tolerance=1.): parser = CifParser.from_string(cif_string, occupancy_tolerance) raw_string = re.sub(r"'", "\"", cif_string) cif_dict = parser.as_dict() cif_keys = list(cif_dict.keys()) s = parser.get_structures(primitive)[0] partial_cif = cif_dict[cif_keys[0]] if "_database_code_ICSD" in partial_cif: source = partial_cif["_database_code_ICSD"] + "-ICSD" else: source = "uploaded cif" source_info = {"source": source, "datetime": str(datetime.datetime.now()), "original_file": raw_string, "cif_data": cif_dict[cif_keys[0]]} return TransformedStructure(s, transformations, history=[source_info]) @staticmethod def from_poscar_string(poscar_string, transformations=None): p = Poscar.from_string(poscar_string) if not p.true_names: raise ValueError("Transformation can be craeted only from POSCAR " "strings with proper VASP5 element symbols.") raw_string = re.sub(r"'", "\"", poscar_string) s = p.structure source_info = {"source": "POSCAR", "datetime": str(datetime.datetime.now()), "original_file": raw_string} return TransformedStructure(s, transformations, history=[source_info]) def as_dict(self): d = self.final_structure.as_dict() d["@module"] = self.__class__.__module__ d["@class"] = self.__class__.__name__ d["history"] = jsanitize(self.history) d["version"] = __version__ d["last_modified"] = str(datetime.datetime.utcnow()) d["other_parameters"] = jsanitize(self.other_parameters) return d @classmethod def from_dict(cls, d): s = Structure.from_dict(d) return cls(s, history=d["history"], other_parameters=d.get("other_parameters", None)) def to_snl(self, authors, projects=None, references='', remarks=None, data=None, created_at=None): if self.other_parameters: warn('Data in TransformedStructure.other_parameters discarded ' 'during type conversion to SNL') hist = [] for h in self.history: snl_metadata = h.pop('_snl', {}) hist.append({'name': snl_metadata.pop('name', 'pymatgen'), 'url': snl_metadata.pop( 'url', 'http://pypi.python.org/pypi/pymatgen'), 'description': h}) from pymatgen.util.provenance import StructureNL return StructureNL(self.final_structure, authors, projects, references, remarks, data, hist, created_at) @classmethod def from_snl(cls, snl): hist = [] for h in snl.history: d = h.description d['_snl'] = {'url': h.url, 'name': h.name} hist.append(d) return cls(snl.structure, history=hist)
true
true
1c2d06cb9879281b595716f3fff3696c7b8d7bce
373
py
Python
main.py
cr0mbly/TTGO-esp32-micropython-watch
3378ea3b15e19f6bab405b6fc07759f17dd6213d
[ "MIT" ]
6
2020-09-10T20:04:49.000Z
2021-10-10T06:26:05.000Z
main.py
cr0mbly/TTGO-esp32-micropython-watch
3378ea3b15e19f6bab405b6fc07759f17dd6213d
[ "MIT" ]
null
null
null
main.py
cr0mbly/TTGO-esp32-micropython-watch
3378ea3b15e19f6bab405b6fc07759f17dd6213d
[ "MIT" ]
null
null
null
from apps.watch import WatchDisplay from lcd_display import LcdDisplay from system import SystemManager # Setup internal system system_manager = SystemManager() system_manager.update_system() # Setup LCD and eventsB lcd_display = LcdDisplay(system_manager).setup() lcd_display.register_touch_event() # Display initial app WatchDisplay(system_manager, lcd_display).run()
24.866667
48
0.831099
from apps.watch import WatchDisplay from lcd_display import LcdDisplay from system import SystemManager system_manager = SystemManager() system_manager.update_system() lcd_display = LcdDisplay(system_manager).setup() lcd_display.register_touch_event() WatchDisplay(system_manager, lcd_display).run()
true
true
1c2d072085abfe36d7e843393f0e22f4fede76ae
9,187
py
Python
tests/hazmat/primitives/test_aes.py
spagh-eddie/cryptography
8572a9d82e254d348aa674d37d1c19fee8831b19
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause" ]
4,492
2015-01-02T23:02:52.000Z
2022-03-31T12:59:57.000Z
tests/hazmat/primitives/test_aes.py
spagh-eddie/cryptography
8572a9d82e254d348aa674d37d1c19fee8831b19
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause" ]
3,692
2015-01-01T03:16:56.000Z
2022-03-31T19:20:25.000Z
tests/hazmat/primitives/test_aes.py
sailfishos-mirror/cryptography
bab6faa2622e6ae33ceab40117dbd00f3b0cc9a1
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause" ]
1,155
2015-01-09T00:48:05.000Z
2022-03-31T23:46:43.000Z
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. import binascii import os import pytest from cryptography.hazmat.primitives.ciphers import algorithms, base, modes from .utils import _load_all_params, generate_encrypt_test from ...doubles import DummyMode from ...utils import load_nist_vectors @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 32), modes.XTS(b"\x00" * 16) ), skip_message="Does not support AES XTS", ) class TestAESModeXTS(object): def test_xts_vectors(self, backend, subtests): # This list comprehension excludes any vector that does not have a # data unit length that is divisible by 8. The NIST vectors include # tests for implementations that support encryption of data that is # not divisible modulo 8, but OpenSSL is not such an implementation. vectors = [ x for x in _load_all_params( os.path.join("ciphers", "AES", "XTS", "tweak-128hexstr"), ["XTSGenAES128.rsp", "XTSGenAES256.rsp"], load_nist_vectors, ) if int(x["dataunitlen"]) / 8.0 == int(x["dataunitlen"]) // 8 ] for vector in vectors: with subtests.test(): key = binascii.unhexlify(vector["key"]) tweak = binascii.unhexlify(vector["i"]) pt = binascii.unhexlify(vector["pt"]) ct = binascii.unhexlify(vector["ct"]) cipher = base.Cipher( algorithms.AES(key), modes.XTS(tweak), backend ) enc = cipher.encryptor() computed_ct = enc.update(pt) + enc.finalize() assert computed_ct == ct dec = cipher.decryptor() computed_pt = dec.update(ct) + dec.finalize() assert computed_pt == pt def test_xts_too_short(self, backend): key = b"thirty_two_byte_keys_are_great!!" tweak = b"\x00" * 16 cipher = base.Cipher(algorithms.AES(key), modes.XTS(tweak)) enc = cipher.encryptor() with pytest.raises(ValueError): enc.update(b"0" * 15) @pytest.mark.supported( only_if=lambda backend: ( backend._lib.CRYPTOGRAPHY_OPENSSL_111D_OR_GREATER ), skip_message="duplicate key encryption error added in OpenSSL 1.1.1d", ) def test_xts_no_duplicate_keys_encryption(self, backend): key = bytes(range(16)) * 2 tweak = b"\x00" * 16 cipher = base.Cipher(algorithms.AES(key), modes.XTS(tweak)) with pytest.raises(ValueError, match="duplicated keys"): cipher.encryptor() @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.CBC(b"\x00" * 16) ), skip_message="Does not support AES CBC", ) class TestAESModeCBC(object): test_cbc = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CBC"), [ "CBCGFSbox128.rsp", "CBCGFSbox192.rsp", "CBCGFSbox256.rsp", "CBCKeySbox128.rsp", "CBCKeySbox192.rsp", "CBCKeySbox256.rsp", "CBCVarKey128.rsp", "CBCVarKey192.rsp", "CBCVarKey256.rsp", "CBCVarTxt128.rsp", "CBCVarTxt192.rsp", "CBCVarTxt256.rsp", "CBCMMT128.rsp", "CBCMMT192.rsp", "CBCMMT256.rsp", ], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.ECB() ), skip_message="Does not support AES ECB", ) class TestAESModeECB(object): test_ecb = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "ECB"), [ "ECBGFSbox128.rsp", "ECBGFSbox192.rsp", "ECBGFSbox256.rsp", "ECBKeySbox128.rsp", "ECBKeySbox192.rsp", "ECBKeySbox256.rsp", "ECBVarKey128.rsp", "ECBVarKey192.rsp", "ECBVarKey256.rsp", "ECBVarTxt128.rsp", "ECBVarTxt192.rsp", "ECBVarTxt256.rsp", "ECBMMT128.rsp", "ECBMMT192.rsp", "ECBMMT256.rsp", ], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda **kwargs: modes.ECB(), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.OFB(b"\x00" * 16) ), skip_message="Does not support AES OFB", ) class TestAESModeOFB(object): test_ofb = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "OFB"), [ "OFBGFSbox128.rsp", "OFBGFSbox192.rsp", "OFBGFSbox256.rsp", "OFBKeySbox128.rsp", "OFBKeySbox192.rsp", "OFBKeySbox256.rsp", "OFBVarKey128.rsp", "OFBVarKey192.rsp", "OFBVarKey256.rsp", "OFBVarTxt128.rsp", "OFBVarTxt192.rsp", "OFBVarTxt256.rsp", "OFBMMT128.rsp", "OFBMMT192.rsp", "OFBMMT256.rsp", ], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.CFB(b"\x00" * 16) ), skip_message="Does not support AES CFB", ) class TestAESModeCFB(object): test_cfb = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CFB"), [ "CFB128GFSbox128.rsp", "CFB128GFSbox192.rsp", "CFB128GFSbox256.rsp", "CFB128KeySbox128.rsp", "CFB128KeySbox192.rsp", "CFB128KeySbox256.rsp", "CFB128VarKey128.rsp", "CFB128VarKey192.rsp", "CFB128VarKey256.rsp", "CFB128VarTxt128.rsp", "CFB128VarTxt192.rsp", "CFB128VarTxt256.rsp", "CFB128MMT128.rsp", "CFB128MMT192.rsp", "CFB128MMT256.rsp", ], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.CFB8(b"\x00" * 16) ), skip_message="Does not support AES CFB8", ) class TestAESModeCFB8(object): test_cfb8 = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CFB"), [ "CFB8GFSbox128.rsp", "CFB8GFSbox192.rsp", "CFB8GFSbox256.rsp", "CFB8KeySbox128.rsp", "CFB8KeySbox192.rsp", "CFB8KeySbox256.rsp", "CFB8VarKey128.rsp", "CFB8VarKey192.rsp", "CFB8VarKey256.rsp", "CFB8VarTxt128.rsp", "CFB8VarTxt192.rsp", "CFB8VarTxt256.rsp", "CFB8MMT128.rsp", "CFB8MMT192.rsp", "CFB8MMT256.rsp", ], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CFB8(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.CTR(b"\x00" * 16) ), skip_message="Does not support AES CTR", ) class TestAESModeCTR(object): test_ctr = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CTR"), ["aes-128-ctr.txt", "aes-192-ctr.txt", "aes-256-ctr.txt"], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CTR(binascii.unhexlify(iv)), ) @pytest.mark.parametrize( "mode", [ modes.CBC(bytearray(b"\x00" * 16)), modes.CTR(bytearray(b"\x00" * 16)), modes.OFB(bytearray(b"\x00" * 16)), modes.CFB(bytearray(b"\x00" * 16)), modes.CFB8(bytearray(b"\x00" * 16)), modes.XTS(bytearray(b"\x00" * 16)), # Add a dummy mode for coverage of the cipher_supported check. DummyMode(), ], ) def test_buffer_protocol_alternate_modes(mode, backend): data = bytearray(b"sixteen_byte_msg") key = algorithms.AES(bytearray(os.urandom(32))) if not backend.cipher_supported(key, mode): pytest.skip("AES in {} mode not supported".format(mode.name)) cipher = base.Cipher(key, mode, backend) enc = cipher.encryptor() ct = enc.update(data) + enc.finalize() dec = cipher.decryptor() pt = dec.update(ct) + dec.finalize() assert pt == data
33.166065
79
0.579188
import binascii import os import pytest from cryptography.hazmat.primitives.ciphers import algorithms, base, modes from .utils import _load_all_params, generate_encrypt_test from ...doubles import DummyMode from ...utils import load_nist_vectors @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 32), modes.XTS(b"\x00" * 16) ), skip_message="Does not support AES XTS", ) class TestAESModeXTS(object): def test_xts_vectors(self, backend, subtests): vectors = [ x for x in _load_all_params( os.path.join("ciphers", "AES", "XTS", "tweak-128hexstr"), ["XTSGenAES128.rsp", "XTSGenAES256.rsp"], load_nist_vectors, ) if int(x["dataunitlen"]) / 8.0 == int(x["dataunitlen"]) // 8 ] for vector in vectors: with subtests.test(): key = binascii.unhexlify(vector["key"]) tweak = binascii.unhexlify(vector["i"]) pt = binascii.unhexlify(vector["pt"]) ct = binascii.unhexlify(vector["ct"]) cipher = base.Cipher( algorithms.AES(key), modes.XTS(tweak), backend ) enc = cipher.encryptor() computed_ct = enc.update(pt) + enc.finalize() assert computed_ct == ct dec = cipher.decryptor() computed_pt = dec.update(ct) + dec.finalize() assert computed_pt == pt def test_xts_too_short(self, backend): key = b"thirty_two_byte_keys_are_great!!" tweak = b"\x00" * 16 cipher = base.Cipher(algorithms.AES(key), modes.XTS(tweak)) enc = cipher.encryptor() with pytest.raises(ValueError): enc.update(b"0" * 15) @pytest.mark.supported( only_if=lambda backend: ( backend._lib.CRYPTOGRAPHY_OPENSSL_111D_OR_GREATER ), skip_message="duplicate key encryption error added in OpenSSL 1.1.1d", ) def test_xts_no_duplicate_keys_encryption(self, backend): key = bytes(range(16)) * 2 tweak = b"\x00" * 16 cipher = base.Cipher(algorithms.AES(key), modes.XTS(tweak)) with pytest.raises(ValueError, match="duplicated keys"): cipher.encryptor() @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.CBC(b"\x00" * 16) ), skip_message="Does not support AES CBC", ) class TestAESModeCBC(object): test_cbc = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CBC"), [ "CBCGFSbox128.rsp", "CBCGFSbox192.rsp", "CBCGFSbox256.rsp", "CBCKeySbox128.rsp", "CBCKeySbox192.rsp", "CBCKeySbox256.rsp", "CBCVarKey128.rsp", "CBCVarKey192.rsp", "CBCVarKey256.rsp", "CBCVarTxt128.rsp", "CBCVarTxt192.rsp", "CBCVarTxt256.rsp", "CBCMMT128.rsp", "CBCMMT192.rsp", "CBCMMT256.rsp", ], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.ECB() ), skip_message="Does not support AES ECB", ) class TestAESModeECB(object): test_ecb = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "ECB"), [ "ECBGFSbox128.rsp", "ECBGFSbox192.rsp", "ECBGFSbox256.rsp", "ECBKeySbox128.rsp", "ECBKeySbox192.rsp", "ECBKeySbox256.rsp", "ECBVarKey128.rsp", "ECBVarKey192.rsp", "ECBVarKey256.rsp", "ECBVarTxt128.rsp", "ECBVarTxt192.rsp", "ECBVarTxt256.rsp", "ECBMMT128.rsp", "ECBMMT192.rsp", "ECBMMT256.rsp", ], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda **kwargs: modes.ECB(), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.OFB(b"\x00" * 16) ), skip_message="Does not support AES OFB", ) class TestAESModeOFB(object): test_ofb = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "OFB"), [ "OFBGFSbox128.rsp", "OFBGFSbox192.rsp", "OFBGFSbox256.rsp", "OFBKeySbox128.rsp", "OFBKeySbox192.rsp", "OFBKeySbox256.rsp", "OFBVarKey128.rsp", "OFBVarKey192.rsp", "OFBVarKey256.rsp", "OFBVarTxt128.rsp", "OFBVarTxt192.rsp", "OFBVarTxt256.rsp", "OFBMMT128.rsp", "OFBMMT192.rsp", "OFBMMT256.rsp", ], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.CFB(b"\x00" * 16) ), skip_message="Does not support AES CFB", ) class TestAESModeCFB(object): test_cfb = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CFB"), [ "CFB128GFSbox128.rsp", "CFB128GFSbox192.rsp", "CFB128GFSbox256.rsp", "CFB128KeySbox128.rsp", "CFB128KeySbox192.rsp", "CFB128KeySbox256.rsp", "CFB128VarKey128.rsp", "CFB128VarKey192.rsp", "CFB128VarKey256.rsp", "CFB128VarTxt128.rsp", "CFB128VarTxt192.rsp", "CFB128VarTxt256.rsp", "CFB128MMT128.rsp", "CFB128MMT192.rsp", "CFB128MMT256.rsp", ], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.CFB8(b"\x00" * 16) ), skip_message="Does not support AES CFB8", ) class TestAESModeCFB8(object): test_cfb8 = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CFB"), [ "CFB8GFSbox128.rsp", "CFB8GFSbox192.rsp", "CFB8GFSbox256.rsp", "CFB8KeySbox128.rsp", "CFB8KeySbox192.rsp", "CFB8KeySbox256.rsp", "CFB8VarKey128.rsp", "CFB8VarKey192.rsp", "CFB8VarKey256.rsp", "CFB8VarTxt128.rsp", "CFB8VarTxt192.rsp", "CFB8VarTxt256.rsp", "CFB8MMT128.rsp", "CFB8MMT192.rsp", "CFB8MMT256.rsp", ], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CFB8(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.CTR(b"\x00" * 16) ), skip_message="Does not support AES CTR", ) class TestAESModeCTR(object): test_ctr = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CTR"), ["aes-128-ctr.txt", "aes-192-ctr.txt", "aes-256-ctr.txt"], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CTR(binascii.unhexlify(iv)), ) @pytest.mark.parametrize( "mode", [ modes.CBC(bytearray(b"\x00" * 16)), modes.CTR(bytearray(b"\x00" * 16)), modes.OFB(bytearray(b"\x00" * 16)), modes.CFB(bytearray(b"\x00" * 16)), modes.CFB8(bytearray(b"\x00" * 16)), modes.XTS(bytearray(b"\x00" * 16)), DummyMode(), ], ) def test_buffer_protocol_alternate_modes(mode, backend): data = bytearray(b"sixteen_byte_msg") key = algorithms.AES(bytearray(os.urandom(32))) if not backend.cipher_supported(key, mode): pytest.skip("AES in {} mode not supported".format(mode.name)) cipher = base.Cipher(key, mode, backend) enc = cipher.encryptor() ct = enc.update(data) + enc.finalize() dec = cipher.decryptor() pt = dec.update(ct) + dec.finalize() assert pt == data
true
true
1c2d073e9e36ccc9b40cc4d130871100baffaf06
750
py
Python
src/explore/data_structure_tree/inorder_traversal.py
Jiezhi/myleetcode
b346e94c46da2a3033ebc8ff50e621aa179c4f62
[ "MIT" ]
1
2022-03-03T15:11:48.000Z
2022-03-03T15:11:48.000Z
src/explore/data_structure_tree/inorder_traversal.py
Jiezhi/myleetcode
b346e94c46da2a3033ebc8ff50e621aa179c4f62
[ "MIT" ]
null
null
null
src/explore/data_structure_tree/inorder_traversal.py
Jiezhi/myleetcode
b346e94c46da2a3033ebc8ff50e621aa179c4f62
[ "MIT" ]
2
2022-01-20T22:49:58.000Z
2022-01-20T22:53:13.000Z
#!/usr/bin/env python """ Github: https://github.com/Jiezhi/myleetcode Created on 2019-03-24 Leetcode: https://leetcode.com/explore/learn/card/data-structure-tree/134/traverse-a-tree/929/ Same as: 94 https://leetcode.com/problems/binary-tree-inorder-traversal/ """ from tree_node import * class Solution: def inorderTraversal(self, root: TreeNode) -> list: ret = [] if not root: return ret if root.left: ret = ret + self.inorderTraversal(root.left) ret.append(root.val) if root.right: ret = ret + self.inorderTraversal(root.right) return ret if __name__ == '__main__': assert Solution().inorderTraversal(build_tree_node([1, None, 2, 3])) == [1, 3, 2]
25.862069
94
0.642667
from tree_node import * class Solution: def inorderTraversal(self, root: TreeNode) -> list: ret = [] if not root: return ret if root.left: ret = ret + self.inorderTraversal(root.left) ret.append(root.val) if root.right: ret = ret + self.inorderTraversal(root.right) return ret if __name__ == '__main__': assert Solution().inorderTraversal(build_tree_node([1, None, 2, 3])) == [1, 3, 2]
true
true
1c2d08db4f64008bdec6d59094e5b421b130255a
2,442
py
Python
Motif_Analysis/Code/optimizer.py
tanfei2007/DeepM6A
ac8b5543db292516ce10cf42b7506004140d4d41
[ "Apache-2.0" ]
8
2020-08-09T02:21:24.000Z
2022-03-17T03:01:08.000Z
Motif_Analysis/Code/optimizer.py
Cmanco/DeepM6A
ac8b5543db292516ce10cf42b7506004140d4d41
[ "Apache-2.0" ]
null
null
null
Motif_Analysis/Code/optimizer.py
Cmanco/DeepM6A
ac8b5543db292516ce10cf42b7506004140d4d41
[ "Apache-2.0" ]
5
2020-11-30T01:53:38.000Z
2021-07-21T04:08:47.000Z
#********************* # Fei Tan # ft54@njit.edu # March 28, 2017 #******************** import numpy as np import pprint from keras import backend as K from collections import OrderedDict class Optimizer(object): def __init__(self, seq_input, losses, wrt=None): self.seq = seq_input self.loss_functions = [] self.wrt = self.seq if wrt is None else wrt overall_loss = K.variable(0.) for loss, weight in losses: if weight != 0: loss_fn = weight * loss.build_loss() overall_loss += loss_fn # learning phase: 0 (test), 1(train) self.loss_functions.append( ( loss.name, K.function( [self.seq, K.learning_phase()], [loss_fn]) ) ) grads = K.gradients(overall_loss, self.wrt)[0] grads = grads / (K.sqrt(K.mean(K.square(grads))) + K.epsilon()) self.overall_loss_grad_wrt_fn = K.function([self.seq, K.learning_phase()], [overall_loss, grads, self.wrt]) def eval_losses(self, seq): losses = OrderedDict() for name, fn in self.loss_functions: losses[name] = fn([seq, 0]) return losses def rmsprop(self, grads, cache=None, decay_rate=0.95): if cache is None: cache = np.zeros_like(grads) cache = decay_rate * cache + (1 - decay_rate) * (grads ** 2) step = -grads / np.sqrt(cache + K.epsilon()) return step, cache def get_seed_seq(self, seed_seq): sample_size, filter_length, nucleotide_size = self.seq._keras_shape print(filter_length, nucleotide_size) if seed_seq is None: seed_seq = np.ones((filter_length, nucleotide_size))/4. seed_seq = np.array([seed_seq], dtype=np.float32) return seed_seq def minimize(self, seed_seq=None, max_iter=200, lr = 0.1, verbose=True): """Performs gradient descent on the input sequenc with respect to defined losses""" seed_seq = self.get_seed_seq(seed_seq) cache = None best_loss = float('inf') best_seq = None grads = None for i in range(max_iter): overall_loss, grads, wrt_value = self.overall_loss_grad_wrt_fn([seed_seq, 0]) if verbose: losses = self.eval_losses(seed_seq) print('Interation: {}, losses: {}, overall loss: {}'.format(i+1, pprint.pformat(losses), overall_loss)) #gradient descent update if self.wrt is self.seq: step, cache = self.rmsprop(grads, cache) #to be revised later seed_seq += lr * step if overall_loss < best_loss: best_loss = overall_loss best_seq = seed_seq.copy() return best_seq[0], grads, wrt_value
25.978723
109
0.673628
import numpy as np import pprint from keras import backend as K from collections import OrderedDict class Optimizer(object): def __init__(self, seq_input, losses, wrt=None): self.seq = seq_input self.loss_functions = [] self.wrt = self.seq if wrt is None else wrt overall_loss = K.variable(0.) for loss, weight in losses: if weight != 0: loss_fn = weight * loss.build_loss() overall_loss += loss_fn self.loss_functions.append( ( loss.name, K.function( [self.seq, K.learning_phase()], [loss_fn]) ) ) grads = K.gradients(overall_loss, self.wrt)[0] grads = grads / (K.sqrt(K.mean(K.square(grads))) + K.epsilon()) self.overall_loss_grad_wrt_fn = K.function([self.seq, K.learning_phase()], [overall_loss, grads, self.wrt]) def eval_losses(self, seq): losses = OrderedDict() for name, fn in self.loss_functions: losses[name] = fn([seq, 0]) return losses def rmsprop(self, grads, cache=None, decay_rate=0.95): if cache is None: cache = np.zeros_like(grads) cache = decay_rate * cache + (1 - decay_rate) * (grads ** 2) step = -grads / np.sqrt(cache + K.epsilon()) return step, cache def get_seed_seq(self, seed_seq): sample_size, filter_length, nucleotide_size = self.seq._keras_shape print(filter_length, nucleotide_size) if seed_seq is None: seed_seq = np.ones((filter_length, nucleotide_size))/4. seed_seq = np.array([seed_seq], dtype=np.float32) return seed_seq def minimize(self, seed_seq=None, max_iter=200, lr = 0.1, verbose=True): seed_seq = self.get_seed_seq(seed_seq) cache = None best_loss = float('inf') best_seq = None grads = None for i in range(max_iter): overall_loss, grads, wrt_value = self.overall_loss_grad_wrt_fn([seed_seq, 0]) if verbose: losses = self.eval_losses(seed_seq) print('Interation: {}, losses: {}, overall loss: {}'.format(i+1, pprint.pformat(losses), overall_loss)) if self.wrt is self.seq: step, cache = self.rmsprop(grads, cache) seed_seq += lr * step if overall_loss < best_loss: best_loss = overall_loss best_seq = seed_seq.copy() return best_seq[0], grads, wrt_value
true
true
1c2d0986479155b099c8c5b721fa03b080e59510
248
py
Python
hard-gists/69f4acd1fc094c66ba73/snippet.py
jjhenkel/dockerizeme
eaa4fe5366f6b9adf74399eab01c712cacaeb279
[ "Apache-2.0" ]
21
2019-07-08T08:26:45.000Z
2022-01-24T23:53:25.000Z
hard-gists/69f4acd1fc094c66ba73/snippet.py
jjhenkel/dockerizeme
eaa4fe5366f6b9adf74399eab01c712cacaeb279
[ "Apache-2.0" ]
5
2019-06-15T14:47:47.000Z
2022-02-26T05:02:56.000Z
hard-gists/69f4acd1fc094c66ba73/snippet.py
jjhenkel/dockerizeme
eaa4fe5366f6b9adf74399eab01c712cacaeb279
[ "Apache-2.0" ]
17
2019-05-16T03:50:34.000Z
2021-01-14T14:35:12.000Z
#!/usr/bin/env python3 import time import cron def do_stuff1(): print('stuff1!') def do_stuff2(): #1 / 0 print('stuff2!') cron.init() cron.schedule(5, do_stuff1) #time.sleep(1) #cron.schedule(2, do_stuff2) cron.wait() print('done!')
13.777778
28
0.657258
import time import cron def do_stuff1(): print('stuff1!') def do_stuff2(): print('stuff2!') cron.init() cron.schedule(5, do_stuff1) cron.wait() print('done!')
true
true
1c2d0adc348a4f74b5082e2c56fef04d70aaafb4
3,272
py
Python
Libraries/Python/Turta_Digital.py
Turta-io/LoRaHAT
4f2bc28c2bddde928bb2279a2c519ed163defff9
[ "MIT" ]
1
2021-03-22T22:45:29.000Z
2021-03-22T22:45:29.000Z
Libraries/Python/Turta_Digital.py
Turta-io/LoRaHAT
4f2bc28c2bddde928bb2279a2c519ed163defff9
[ "MIT" ]
null
null
null
Libraries/Python/Turta_Digital.py
Turta-io/LoRaHAT
4f2bc28c2bddde928bb2279a2c519ed163defff9
[ "MIT" ]
1
2020-03-28T21:32:35.000Z
2020-03-28T21:32:35.000Z
# Turta LoRa HAT Helper for Raspbian. # Distributed under the terms of the MIT license. # Python Library for Digital IO Ports. # Version 1.0.0 # Released: November 5th, 2019 # Visit https://docs.turta.io for documentation. import RPi.GPIO as GPIO class DigitalPort(object): """Digital IO Ports.""" #Variables is_initialized = False #Port Pins d1, d2, d3, d4 = 21, 22, 23, 24 def __init__(self, d1In = True, d2In = True, d3In = True, d4In = True): """Initiates the GPIO pins. Parameters: d1In (bool): Pin 1 direction (True for input, False for output, True is default) d2In (bool): Pin 2 direction (True for input, False for output, True is default) d3In (bool): Pin 3 direction (True for input, False for output, True is default) d4In (bool): Pin 4 direction (True for input, False for output, True is default)""" GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) if (d1In): GPIO.setup(self.d1, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) else: GPIO.setup(self.d1, GPIO.OUT) GPIO.output(self.d1, GPIO.LOW) if (d2In): GPIO.setup(self.d2, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) else: GPIO.setup(self.d2, GPIO.OUT) GPIO.output(self.d2, GPIO.LOW) if (d3In): GPIO.setup(self.d3, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) else: GPIO.setup(self.d3, GPIO.OUT) GPIO.output(self.d3, GPIO.LOW) if (d4In): GPIO.setup(self.d4, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) else: GPIO.setup(self.d4, GPIO.OUT) GPIO.output(self.d4, GPIO.LOW) self.is_initialized = True return #GPIO Read and Write Methods def read(self, ch): """Reads the digital input. Parameters: ch (byte): IO Channel (1 to 4) Returns: bool: Pin input state (True for high, False for low)""" if (ch == 1): return GPIO.input(self.d1) elif (ch == 2): return GPIO.input(self.d2) elif (ch == 3): return GPIO.input(self.d3) elif (ch == 4): return GPIO.input(self.d4) else: return 0 def write(self, ch, st): """Sets the digital output. Parameters: ch (byte): IO Channel (1 to 4) st (bool): Pin output state (True for high, False for low)""" if (ch == 1): GPIO.output(self.d1, GPIO.HIGH if st else GPIO.LOW) elif (ch == 2): GPIO.output(self.d2, GPIO.HIGH if st else GPIO.LOW) elif (ch == 3): GPIO.output(self.d3, GPIO.HIGH if st else GPIO.LOW) elif (ch == 4): GPIO.output(self.d4, GPIO.HIGH if st else GPIO.LOW) return def toggle(self, ch): """Inverts the digital output. Parameters: ch (byte): IO Channel (1 to 4)""" self.write(ch, not self.read(ch)) return #Disposal def __del__(self): """Releases the resources.""" try: if self.is_initialized: GPIO.cleanup() del self.is_initialized except: pass
27.495798
91
0.552873
import RPi.GPIO as GPIO class DigitalPort(object): is_initialized = False d1, d2, d3, d4 = 21, 22, 23, 24 def __init__(self, d1In = True, d2In = True, d3In = True, d4In = True): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) if (d1In): GPIO.setup(self.d1, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) else: GPIO.setup(self.d1, GPIO.OUT) GPIO.output(self.d1, GPIO.LOW) if (d2In): GPIO.setup(self.d2, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) else: GPIO.setup(self.d2, GPIO.OUT) GPIO.output(self.d2, GPIO.LOW) if (d3In): GPIO.setup(self.d3, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) else: GPIO.setup(self.d3, GPIO.OUT) GPIO.output(self.d3, GPIO.LOW) if (d4In): GPIO.setup(self.d4, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) else: GPIO.setup(self.d4, GPIO.OUT) GPIO.output(self.d4, GPIO.LOW) self.is_initialized = True return def read(self, ch): if (ch == 1): return GPIO.input(self.d1) elif (ch == 2): return GPIO.input(self.d2) elif (ch == 3): return GPIO.input(self.d3) elif (ch == 4): return GPIO.input(self.d4) else: return 0 def write(self, ch, st): if (ch == 1): GPIO.output(self.d1, GPIO.HIGH if st else GPIO.LOW) elif (ch == 2): GPIO.output(self.d2, GPIO.HIGH if st else GPIO.LOW) elif (ch == 3): GPIO.output(self.d3, GPIO.HIGH if st else GPIO.LOW) elif (ch == 4): GPIO.output(self.d4, GPIO.HIGH if st else GPIO.LOW) return def toggle(self, ch): self.write(ch, not self.read(ch)) return def __del__(self): try: if self.is_initialized: GPIO.cleanup() del self.is_initialized except: pass
true
true
1c2d0b25119761370d81f6070e27d83543d0b4a7
5,267
py
Python
pysnmp-with-texts/DLINK-3100-SOCKET-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
8
2019-05-09T17:04:00.000Z
2021-06-09T06:50:51.000Z
pysnmp-with-texts/DLINK-3100-SOCKET-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
4
2019-05-31T16:42:59.000Z
2020-01-31T21:57:17.000Z
pysnmp-with-texts/DLINK-3100-SOCKET-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module DLINK-3100-SOCKET-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLINK-3100-SOCKET-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:49:02 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) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion") rnd, = mibBuilder.importSymbols("DLINK-3100-MIB", "rnd") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") IpAddress, Bits, Counter32, NotificationType, ObjectIdentity, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, ModuleIdentity, MibIdentifier, Gauge32, Counter64, iso, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Bits", "Counter32", "NotificationType", "ObjectIdentity", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "ModuleIdentity", "MibIdentifier", "Gauge32", "Counter64", "iso", "Integer32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") rlSocket = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85)) rlSocket.setRevisions(('2007-01-02 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: rlSocket.setRevisionsDescriptions(('Initial revision.',)) if mibBuilder.loadTexts: rlSocket.setLastUpdated('200701020000Z') if mibBuilder.loadTexts: rlSocket.setOrganization('Dlink, Inc. Dlink Semiconductor, Inc.') if mibBuilder.loadTexts: rlSocket.setContactInfo('www.dlink.com') if mibBuilder.loadTexts: rlSocket.setDescription('This private MIB module defines socket private MIBs.') rlSocketMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlSocketMibVersion.setStatus('current') if mibBuilder.loadTexts: rlSocketMibVersion.setDescription("MIB's version, the current version is 1.") rlSocketTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2), ) if mibBuilder.loadTexts: rlSocketTable.setStatus('current') if mibBuilder.loadTexts: rlSocketTable.setDescription('The (conceptual) table listing the sockets which are currently open in the system.') rlSocketEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2, 1), ).setIndexNames((0, "DLINK-3100-SOCKET-MIB", "rlSocketId")) if mibBuilder.loadTexts: rlSocketEntry.setStatus('current') if mibBuilder.loadTexts: rlSocketEntry.setDescription('An entry (conceptual row) in the SocketTable.') rlSocketId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlSocketId.setStatus('current') if mibBuilder.loadTexts: rlSocketId.setDescription('The value of the id of the socket. ') rlSocketType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("stream", 1), ("dgram", 2), ("raw", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: rlSocketType.setStatus('current') if mibBuilder.loadTexts: rlSocketType.setDescription('Specifies the type of the socket. ') rlSocketState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("connected", 1), ("notConnected", 2), ("recvClosed", 3), ("sendClosed", 4), ("closed", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: rlSocketState.setStatus('current') if mibBuilder.loadTexts: rlSocketState.setDescription('Specifies the state in which the socket is in. ') rlSocketBlockMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("blocking", 1), ("nonBlocking", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: rlSocketBlockMode.setStatus('current') if mibBuilder.loadTexts: rlSocketBlockMode.setDescription('Specifies the blocking mode of the socket. ') rlSocketUpTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2, 1, 5), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlSocketUpTime.setStatus('current') if mibBuilder.loadTexts: rlSocketUpTime.setDescription('The time elapsed since this socket was created.') mibBuilder.exportSymbols("DLINK-3100-SOCKET-MIB", PYSNMP_MODULE_ID=rlSocket, rlSocketMibVersion=rlSocketMibVersion, rlSocket=rlSocket, rlSocketId=rlSocketId, rlSocketBlockMode=rlSocketBlockMode, rlSocketState=rlSocketState, rlSocketEntry=rlSocketEntry, rlSocketUpTime=rlSocketUpTime, rlSocketTable=rlSocketTable, rlSocketType=rlSocketType)
107.489796
477
0.764382
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion") rnd, = mibBuilder.importSymbols("DLINK-3100-MIB", "rnd") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") IpAddress, Bits, Counter32, NotificationType, ObjectIdentity, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, ModuleIdentity, MibIdentifier, Gauge32, Counter64, iso, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Bits", "Counter32", "NotificationType", "ObjectIdentity", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "ModuleIdentity", "MibIdentifier", "Gauge32", "Counter64", "iso", "Integer32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") rlSocket = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85)) rlSocket.setRevisions(('2007-01-02 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: rlSocket.setRevisionsDescriptions(('Initial revision.',)) if mibBuilder.loadTexts: rlSocket.setLastUpdated('200701020000Z') if mibBuilder.loadTexts: rlSocket.setOrganization('Dlink, Inc. Dlink Semiconductor, Inc.') if mibBuilder.loadTexts: rlSocket.setContactInfo('www.dlink.com') if mibBuilder.loadTexts: rlSocket.setDescription('This private MIB module defines socket private MIBs.') rlSocketMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlSocketMibVersion.setStatus('current') if mibBuilder.loadTexts: rlSocketMibVersion.setDescription("MIB's version, the current version is 1.") rlSocketTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2), ) if mibBuilder.loadTexts: rlSocketTable.setStatus('current') if mibBuilder.loadTexts: rlSocketTable.setDescription('The (conceptual) table listing the sockets which are currently open in the system.') rlSocketEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2, 1), ).setIndexNames((0, "DLINK-3100-SOCKET-MIB", "rlSocketId")) if mibBuilder.loadTexts: rlSocketEntry.setStatus('current') if mibBuilder.loadTexts: rlSocketEntry.setDescription('An entry (conceptual row) in the SocketTable.') rlSocketId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlSocketId.setStatus('current') if mibBuilder.loadTexts: rlSocketId.setDescription('The value of the id of the socket. ') rlSocketType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("stream", 1), ("dgram", 2), ("raw", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: rlSocketType.setStatus('current') if mibBuilder.loadTexts: rlSocketType.setDescription('Specifies the type of the socket. ') rlSocketState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("connected", 1), ("notConnected", 2), ("recvClosed", 3), ("sendClosed", 4), ("closed", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: rlSocketState.setStatus('current') if mibBuilder.loadTexts: rlSocketState.setDescription('Specifies the state in which the socket is in. ') rlSocketBlockMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("blocking", 1), ("nonBlocking", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: rlSocketBlockMode.setStatus('current') if mibBuilder.loadTexts: rlSocketBlockMode.setDescription('Specifies the blocking mode of the socket. ') rlSocketUpTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 85, 2, 1, 5), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlSocketUpTime.setStatus('current') if mibBuilder.loadTexts: rlSocketUpTime.setDescription('The time elapsed since this socket was created.') mibBuilder.exportSymbols("DLINK-3100-SOCKET-MIB", PYSNMP_MODULE_ID=rlSocket, rlSocketMibVersion=rlSocketMibVersion, rlSocket=rlSocket, rlSocketId=rlSocketId, rlSocketBlockMode=rlSocketBlockMode, rlSocketState=rlSocketState, rlSocketEntry=rlSocketEntry, rlSocketUpTime=rlSocketUpTime, rlSocketTable=rlSocketTable, rlSocketType=rlSocketType)
true
true
1c2d0b4a226a5bf9b9851cd369c7c9a0c8439cf0
5,034
py
Python
source/conf.py
stefbaldipr/iPressDocs
3cc5aa6e579b4fa3c3e3e88245db52d02146881d
[ "MIT" ]
null
null
null
source/conf.py
stefbaldipr/iPressDocs
3cc5aa6e579b4fa3c3e3e88245db52d02146881d
[ "MIT" ]
1
2018-03-12T04:31:09.000Z
2018-03-12T04:31:09.000Z
source/conf.py
stefbaldipr/iPressDocs
3cc5aa6e579b4fa3c3e3e88245db52d02146881d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/stable/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = u'iPress API' copyright = u'2018, Stefano Ubaldi' author = u'Stefano Ubaldi' # The short X.Y version version = u'2.0' # The full version, including alpha/beta/rc tags release = u'2.0' # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.imgmath', 'sphinxcontrib.httpdomain', 'sphinxcontrib.httpexample', 'sphinx-jsonschema' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = u'it' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path . exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'iPressAPIdoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'iPressAPI.tex', u'iPress API v2', u'Stefano Ubaldi', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'ipressapi', u'iPress API v2', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'iPressAPI', u'iPress API v2', author, 'iPressAPI', 'API per l\'utilizzo delle api per la piattaforma iPress.', 'Miscellaneous'), ] # -- Extension configuration ------------------------------------------------- # -- Curl and rest ----------------------------------------------------------- httpexample_scheme = 'https'
30.325301
85
0.640644
project = u'iPress API' copyright = u'2018, Stefano Ubaldi' author = u'Stefano Ubaldi' version = u'2.0' release = u'2.0' extensions = [ 'sphinx.ext.imgmath', 'sphinxcontrib.httpdomain', 'sphinxcontrib.httpexample', 'sphinx-jsonschema' ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' language = u'it' exclude_patterns = [] pygments_style = 'sphinx' html_theme = 'sphinx_rtd_theme' html_static_path = ['_static'] # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'iPressAPIdoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'iPressAPI.tex', u'iPress API v2', u'Stefano Ubaldi', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'ipressapi', u'iPress API v2', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'iPressAPI', u'iPress API v2', author, 'iPressAPI', 'API per l\'utilizzo delle api per la piattaforma iPress.', 'Miscellaneous'), ] httpexample_scheme = 'https'
true
true
1c2d0ca7f4a4ea84b33b558ae0ff250d88a809be
5,276
py
Python
tests/adapters/test_postgres_adapter.py
pietervans/viewflow
3123b1e36ca4b9464d4a8cdf13c520384b71c600
[ "MIT" ]
106
2021-03-25T12:38:54.000Z
2022-03-10T02:56:37.000Z
tests/adapters/test_postgres_adapter.py
pietervans/viewflow
3123b1e36ca4b9464d4a8cdf13c520384b71c600
[ "MIT" ]
null
null
null
tests/adapters/test_postgres_adapter.py
pietervans/viewflow
3123b1e36ca4b9464d4a8cdf13c520384b71c600
[ "MIT" ]
7
2021-04-03T13:30:36.000Z
2021-08-28T03:11:21.000Z
from datetime import datetime from unittest.mock import Mock import jinja2 import viewflow from airflow import DAG from airflow.models import TaskInstance, Connection from airflow.providers.postgres.hooks.postgres import PostgresHook from airflow import settings from airflow.utils import db def _create_postgres_session(): session = settings.Session() conn = Connection( conn_id="postgres_viewflow", conn_type="postgres", login="user", password="passw0rd", schema="viewflow", host="localhost", port=5432, ) db.merge_conn(conn, session) return session def test_postgres_adapter(monkeypatch): session = _create_postgres_session() dag = viewflow.create_dag("./tests/projects/postgresql/simple_dag") task = dag.get_task("task_1") ti = TaskInstance(task, datetime(2020, 1, 1)) with PostgresHook(postgres_conn_id="postgres_viewflow").get_conn() as conn: with conn.cursor() as cur: cur.execute("DROP TABLE IF EXISTS viewflow.task_1") ti.run(ignore_task_deps=True, ignore_ti_state=True, test_mode=True, session=session) with PostgresHook(postgres_conn_id="postgres_viewflow").get_conn() as conn: with conn.cursor() as cur: cur.execute("SELECT COUNT(*) FROM viewflow.task_1") (count,) = cur.fetchone() assert count == 8 cur.execute("SELECT __view_generated_at FROM viewflow.task_1") res = cur.fetchone() assert len(res) == 1 def test_postgres_with_alias(): params_mock = Mock() params_mock.params = { "task_id": "task_1", "query": "SELECT user_id, email FROM main_app.users limit 1", "fields": {}, "description": "This is a very simple Postgres task with an alias", "schema": "viewflow", "alias": "task_1_aliased", } with open("./viewflow//adapters/postgresql/template.sql", "r") as f: template = jinja2.Template(f.read()) sql = template.render(params=params_mock.params) expected_sql = "DROPTABLEIFEXISTSviewflow.task_1_tmp;DROPTABLEIFEXISTSviewflow.task_1_old;CREATETABLEviewflow.task_1_tmpAS(SELECTuser_id,emailFROMmain_app.userslimit1);--Ifit'sthefirsttimeaviewiscreate,thefirstaltertableinthetransactionwillfailbecausethetabledoesn'texistCREATETABLEIFNOTEXISTSviewflow.task_1(LIKEviewflow.task_1_tmp);begintransaction;ALTERTABLEviewflow.task_1RENAMETOtask_1_old;ALTERTABLEviewflow.task_1_tmpRENAMETOtask_1;endtransaction;DROPTABLEviewflow.task_1_old;--Createaliases--CreatethetmpviewCREATEORREPLACEVIEWviewflow.task_1_aliasedAS(SELECT*FROMviewflow.task_1)WITHNOSCHEMABINDING;--Commentthetable--NOTE:Addmoremetadata:owner,tags,aliasCOMMENTONTABLEviewflow.task_1IS'ThisisaverysimplePostgrestaskwithanalias';" assert "".join(sql.split()) == expected_sql def test_postgres_without_alias(monkeypatch): dag_1 = viewflow.create_dag("./tests/projects/postgresql/simple_dag") task_1 = dag_1.get_task("task_1") ti_1 = TaskInstance(task_1, datetime(2020, 1, 1)) task_1.render_template_fields(ti_1.get_template_context()) assert "Create aliases" not in task_1.sql def test_postgres_adapter_comments(): session = _create_postgres_session() dag = viewflow.create_dag("./tests/projects/postgresql/simple_dag_comments") task = dag.get_task("task_1") ti = TaskInstance(task, datetime(2020, 1, 1)) with PostgresHook(postgres_conn_id="postgres_viewflow").get_conn() as conn: with conn.cursor() as cur: cur.execute("DROP TABLE IF EXISTS viewflow.task_1") ti.run(ignore_task_deps=True, ignore_ti_state=True, test_mode=True, session=session) with PostgresHook(postgres_conn_id="postgres_viewflow").get_conn() as conn: with conn.cursor() as cur: sql_table_comments = """ SELECT cols.table_name, cols.column_name, pg_catalog.col_description(c.oid, cols.ordinal_position::int) FROM pg_catalog.pg_class c, information_schema.columns cols WHERE cols.table_catalog = 'viewflow' AND cols.table_schema = 'viewflow' AND cols.table_name = 'task_1' AND cols.table_name = c.relname; """ cur.execute(sql_table_comments) results = cur.fetchall() assert ("task_1", "user_id", "User ID") in results assert ("task_1", "email", "Email") in results with conn.cursor() as cur: sql_table_description = ( "select obj_description('viewflow.task_1'::regclass);" ) cur.execute(sql_table_description) results = cur.fetchall() assert ("Description",) in results def test_sql_templating(): dag = viewflow.create_dag("./tests/projects/postgresql/templated") task_1 = dag.get_task("task_1") ti_1 = TaskInstance(task_1, datetime(2020, 1, 1)) task_1.render_template_fields(ti_1.get_template_context()) assert "SELECT user_id, email FROM viewflow.users WHERE user_id=1" in task_1.sql assert "SELECT user_id, email FROM viewflow.users WHERE user_id=2" in task_1.sql assert "SELECT user_id, email FROM viewflow.users WHERE user_id=3" in task_1.sql
41.543307
743
0.700531
from datetime import datetime from unittest.mock import Mock import jinja2 import viewflow from airflow import DAG from airflow.models import TaskInstance, Connection from airflow.providers.postgres.hooks.postgres import PostgresHook from airflow import settings from airflow.utils import db def _create_postgres_session(): session = settings.Session() conn = Connection( conn_id="postgres_viewflow", conn_type="postgres", login="user", password="passw0rd", schema="viewflow", host="localhost", port=5432, ) db.merge_conn(conn, session) return session def test_postgres_adapter(monkeypatch): session = _create_postgres_session() dag = viewflow.create_dag("./tests/projects/postgresql/simple_dag") task = dag.get_task("task_1") ti = TaskInstance(task, datetime(2020, 1, 1)) with PostgresHook(postgres_conn_id="postgres_viewflow").get_conn() as conn: with conn.cursor() as cur: cur.execute("DROP TABLE IF EXISTS viewflow.task_1") ti.run(ignore_task_deps=True, ignore_ti_state=True, test_mode=True, session=session) with PostgresHook(postgres_conn_id="postgres_viewflow").get_conn() as conn: with conn.cursor() as cur: cur.execute("SELECT COUNT(*) FROM viewflow.task_1") (count,) = cur.fetchone() assert count == 8 cur.execute("SELECT __view_generated_at FROM viewflow.task_1") res = cur.fetchone() assert len(res) == 1 def test_postgres_with_alias(): params_mock = Mock() params_mock.params = { "task_id": "task_1", "query": "SELECT user_id, email FROM main_app.users limit 1", "fields": {}, "description": "This is a very simple Postgres task with an alias", "schema": "viewflow", "alias": "task_1_aliased", } with open("./viewflow//adapters/postgresql/template.sql", "r") as f: template = jinja2.Template(f.read()) sql = template.render(params=params_mock.params) expected_sql = "DROPTABLEIFEXISTSviewflow.task_1_tmp;DROPTABLEIFEXISTSviewflow.task_1_old;CREATETABLEviewflow.task_1_tmpAS(SELECTuser_id,emailFROMmain_app.userslimit1);--Ifit'sthefirsttimeaviewiscreate,thefirstaltertableinthetransactionwillfailbecausethetabledoesn'texistCREATETABLEIFNOTEXISTSviewflow.task_1(LIKEviewflow.task_1_tmp);begintransaction;ALTERTABLEviewflow.task_1RENAMETOtask_1_old;ALTERTABLEviewflow.task_1_tmpRENAMETOtask_1;endtransaction;DROPTABLEviewflow.task_1_old;--Createaliases--CreatethetmpviewCREATEORREPLACEVIEWviewflow.task_1_aliasedAS(SELECT*FROMviewflow.task_1)WITHNOSCHEMABINDING;--Commentthetable--NOTE:Addmoremetadata:owner,tags,aliasCOMMENTONTABLEviewflow.task_1IS'ThisisaverysimplePostgrestaskwithanalias';" assert "".join(sql.split()) == expected_sql def test_postgres_without_alias(monkeypatch): dag_1 = viewflow.create_dag("./tests/projects/postgresql/simple_dag") task_1 = dag_1.get_task("task_1") ti_1 = TaskInstance(task_1, datetime(2020, 1, 1)) task_1.render_template_fields(ti_1.get_template_context()) assert "Create aliases" not in task_1.sql def test_postgres_adapter_comments(): session = _create_postgres_session() dag = viewflow.create_dag("./tests/projects/postgresql/simple_dag_comments") task = dag.get_task("task_1") ti = TaskInstance(task, datetime(2020, 1, 1)) with PostgresHook(postgres_conn_id="postgres_viewflow").get_conn() as conn: with conn.cursor() as cur: cur.execute("DROP TABLE IF EXISTS viewflow.task_1") ti.run(ignore_task_deps=True, ignore_ti_state=True, test_mode=True, session=session) with PostgresHook(postgres_conn_id="postgres_viewflow").get_conn() as conn: with conn.cursor() as cur: sql_table_comments = """ SELECT cols.table_name, cols.column_name, pg_catalog.col_description(c.oid, cols.ordinal_position::int) FROM pg_catalog.pg_class c, information_schema.columns cols WHERE cols.table_catalog = 'viewflow' AND cols.table_schema = 'viewflow' AND cols.table_name = 'task_1' AND cols.table_name = c.relname; """ cur.execute(sql_table_comments) results = cur.fetchall() assert ("task_1", "user_id", "User ID") in results assert ("task_1", "email", "Email") in results with conn.cursor() as cur: sql_table_description = ( "select obj_description('viewflow.task_1'::regclass);" ) cur.execute(sql_table_description) results = cur.fetchall() assert ("Description",) in results def test_sql_templating(): dag = viewflow.create_dag("./tests/projects/postgresql/templated") task_1 = dag.get_task("task_1") ti_1 = TaskInstance(task_1, datetime(2020, 1, 1)) task_1.render_template_fields(ti_1.get_template_context()) assert "SELECT user_id, email FROM viewflow.users WHERE user_id=1" in task_1.sql assert "SELECT user_id, email FROM viewflow.users WHERE user_id=2" in task_1.sql assert "SELECT user_id, email FROM viewflow.users WHERE user_id=3" in task_1.sql
true
true
1c2d0e451151d8512422ba9f290e51f88c58564a
4,078
py
Python
src/test-apps/happy/tests/standalone/wdmNext/test_weave_wdm_next_mutual_subscribe_12.py
robszewczyk/openweave-core
f452cc55859daea83b3ce7af158c8e78b05cc3bc
[ "Apache-2.0" ]
249
2017-09-18T17:48:34.000Z
2022-02-02T06:46:21.000Z
src/test-apps/happy/tests/standalone/wdmNext/test_weave_wdm_next_mutual_subscribe_12.py
robszewczyk/openweave-core
f452cc55859daea83b3ce7af158c8e78b05cc3bc
[ "Apache-2.0" ]
501
2017-11-10T11:25:32.000Z
2022-02-01T10:43:13.000Z
src/test-apps/happy/tests/standalone/wdmNext/test_weave_wdm_next_mutual_subscribe_12.py
robszewczyk/openweave-core
f452cc55859daea83b3ce7af158c8e78b05cc3bc
[ "Apache-2.0" ]
116
2017-09-20T07:06:55.000Z
2022-01-08T13:41:15.000Z
#!/usr/bin/env python3 # # Copyright (c) 2016-2017 Nest Labs, Inc. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # @file # Calls Weave WDM mutual subscribe between nodes. # F08: Mutual Subscribe: Root path. Null Version. Mutate data in initiator. Publisher in initiator aborts # M12: Stress Mutual Subscribe: Root path. Null Version. Mutate data in initiator. Publisher in initiator aborts # from __future__ import absolute_import from __future__ import print_function import unittest import set_test_path from weave_wdm_next_test_base import weave_wdm_next_test_base import WeaveUtilities class test_weave_wdm_next_mutual_subscribe_12(weave_wdm_next_test_base): def test_weave_wdm_next_mutual_subscribe_12(self): wdm_next_args = {} wdm_next_args['wdm_option'] = "mutual_subscribe" wdm_next_args['total_client_count'] = 2 wdm_next_args['final_client_status'] = 3 wdm_next_args['timer_client_period'] = 5000 wdm_next_args['test_client_iterations'] = 5 wdm_next_args['test_client_delay'] = 35000 wdm_next_args['enable_client_flip'] = 1 wdm_next_args['total_server_count'] = 0 wdm_next_args['final_server_status'] = 4 wdm_next_args['timer_server_period'] = 0 wdm_next_args['enable_server_flip'] = 0 wdm_next_args['client_clear_state_between_iterations'] = True wdm_next_args['server_clear_state_between_iterations'] = True wdm_next_args['client_log_check'] = [('Client\[0\] \[(ALIVE|CONFM)\] bound mutual subscription is going away', wdm_next_args['test_client_iterations']), ('Handler\[0\] \[(ALIVE|CONFM)\] AbortSubscription Ref\(\d+\)', wdm_next_args['test_client_iterations']), ('Client->kEvent_OnNotificationProcessed', wdm_next_args['test_client_iterations']), ('Client\[0\] moving to \[ FREE\] Ref\(0\)', wdm_next_args['test_client_iterations']), ('Handler\[0\] Moving to \[ FREE\] Ref\(0\)', wdm_next_args['test_client_iterations'])] wdm_next_args['server_log_check'] = [('TimerEventHandler Ref\(\d+\) Timeout', wdm_next_args['test_client_iterations']), ('Client->kEvent_OnNotificationProcessed', wdm_next_args['test_client_iterations'] * (wdm_next_args['total_client_count'] + 1)), ('bound mutual subscription is going away', wdm_next_args['test_client_iterations']), ('Handler\[0\] \[(ALIVE|CONFM)\] TerminateSubscription ', wdm_next_args['test_client_iterations']), ('Client\[0\] moving to \[ FREE\] Ref\(0\)', wdm_next_args['test_client_iterations']), ('Handler\[0\] Moving to \[ FREE\] Ref\(0\)', wdm_next_args['test_client_iterations'])] wdm_next_args['test_tag'] = self.__class__.__name__[19:].upper() wdm_next_args['test_case_name'] = ['M12: Stress Mutual Subscribe: Root path. Null Version. Mutate data in initiator.Publisher in initiator aborts'] print('test file: ' + self.__class__.__name__) print("weave-wdm-next test F08 and M12") super(test_weave_wdm_next_mutual_subscribe_12, self).weave_wdm_next_test_base(wdm_next_args) if __name__ == "__main__": WeaveUtilities.run_unittest()
50.975
173
0.655959
from __future__ import absolute_import from __future__ import print_function import unittest import set_test_path from weave_wdm_next_test_base import weave_wdm_next_test_base import WeaveUtilities class test_weave_wdm_next_mutual_subscribe_12(weave_wdm_next_test_base): def test_weave_wdm_next_mutual_subscribe_12(self): wdm_next_args = {} wdm_next_args['wdm_option'] = "mutual_subscribe" wdm_next_args['total_client_count'] = 2 wdm_next_args['final_client_status'] = 3 wdm_next_args['timer_client_period'] = 5000 wdm_next_args['test_client_iterations'] = 5 wdm_next_args['test_client_delay'] = 35000 wdm_next_args['enable_client_flip'] = 1 wdm_next_args['total_server_count'] = 0 wdm_next_args['final_server_status'] = 4 wdm_next_args['timer_server_period'] = 0 wdm_next_args['enable_server_flip'] = 0 wdm_next_args['client_clear_state_between_iterations'] = True wdm_next_args['server_clear_state_between_iterations'] = True wdm_next_args['client_log_check'] = [('Client\[0\] \[(ALIVE|CONFM)\] bound mutual subscription is going away', wdm_next_args['test_client_iterations']), ('Handler\[0\] \[(ALIVE|CONFM)\] AbortSubscription Ref\(\d+\)', wdm_next_args['test_client_iterations']), ('Client->kEvent_OnNotificationProcessed', wdm_next_args['test_client_iterations']), ('Client\[0\] moving to \[ FREE\] Ref\(0\)', wdm_next_args['test_client_iterations']), ('Handler\[0\] Moving to \[ FREE\] Ref\(0\)', wdm_next_args['test_client_iterations'])] wdm_next_args['server_log_check'] = [('TimerEventHandler Ref\(\d+\) Timeout', wdm_next_args['test_client_iterations']), ('Client->kEvent_OnNotificationProcessed', wdm_next_args['test_client_iterations'] * (wdm_next_args['total_client_count'] + 1)), ('bound mutual subscription is going away', wdm_next_args['test_client_iterations']), ('Handler\[0\] \[(ALIVE|CONFM)\] TerminateSubscription ', wdm_next_args['test_client_iterations']), ('Client\[0\] moving to \[ FREE\] Ref\(0\)', wdm_next_args['test_client_iterations']), ('Handler\[0\] Moving to \[ FREE\] Ref\(0\)', wdm_next_args['test_client_iterations'])] wdm_next_args['test_tag'] = self.__class__.__name__[19:].upper() wdm_next_args['test_case_name'] = ['M12: Stress Mutual Subscribe: Root path. Null Version. Mutate data in initiator.Publisher in initiator aborts'] print('test file: ' + self.__class__.__name__) print("weave-wdm-next test F08 and M12") super(test_weave_wdm_next_mutual_subscribe_12, self).weave_wdm_next_test_base(wdm_next_args) if __name__ == "__main__": WeaveUtilities.run_unittest()
true
true
1c2d0f4e0c15a4c07fa29575d460cd7acb1f0253
10,709
py
Python
rllite/common/gym_utils.py
ZJU-RL/zjurl
6aab83aaba7249bc43d112f21787c45b111d8aa4
[ "MIT" ]
3
2019-03-07T13:24:21.000Z
2019-08-08T12:49:51.000Z
rllite/common/gym_utils.py
tyGavinZJU/rllite
5c85eb11babb69a09604a04f0eb7bdc5a96f08f0
[ "MIT" ]
null
null
null
rllite/common/gym_utils.py
tyGavinZJU/rllite
5c85eb11babb69a09604a04f0eb7bdc5a96f08f0
[ "MIT" ]
null
null
null
import gym import numpy as np import torch from collections import deque device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class NormalizedActions(gym.ActionWrapper): def action(self, action): low = self.action_space.low high = self.action_space.high action = low + (action + 1.0) * 0.5 * (high - low) action = np.clip(action, low, high) return action def reverse_action(self, action): low = self.action_space.low high = self.action_space.high action = 2 * (action - low) / (high - low) - 1 action = np.clip(action, low, high) return action def make_env(env_name): def _thunk(): env = gym.make(env_name) return env return _thunk class NoopResetEnv(gym.Wrapper): def __init__(self, env, noop_max=30): """Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0. """ gym.Wrapper.__init__(self, env) self.noop_max = noop_max self.override_num_noops = None self.noop_action = 0 assert env.unwrapped.get_action_meanings()[0] == 'NOOP' def reset(self, **kwargs): """ Do no-op action for a number of steps in [1, noop_max].""" self.env.reset(**kwargs) if self.override_num_noops is not None: noops = self.override_num_noops else: noops = self.unwrapped.np_random.randint(1, self.noop_max + 1) # pylint: disable=E1101 assert noops > 0 obs = None for _ in range(noops): obs, _, done, _ = self.env.step(self.noop_action) if done: obs = self.env.reset(**kwargs) return obs def step(self, ac): return self.env.step(ac) class FireResetEnv(gym.Wrapper): def __init__(self, env): """Take action on reset for environments that are fixed until firing.""" gym.Wrapper.__init__(self, env) assert env.unwrapped.get_action_meanings()[1] == 'FIRE' assert len(env.unwrapped.get_action_meanings()) >= 3 def reset(self, **kwargs): self.env.reset(**kwargs) obs, _, done, _ = self.env.step(1) if done: self.env.reset(**kwargs) obs, _, done, _ = self.env.step(2) if done: self.env.reset(**kwargs) return obs def step(self, ac): return self.env.step(ac) class EpisodicLifeEnv(gym.Wrapper): def __init__(self, env): """Make end-of-life == end-of-episode, but only reset on true game over. Done by DeepMind for the DQN and co. since it helps value estimation. """ gym.Wrapper.__init__(self, env) self.lives = 0 self.was_real_done = True def step(self, action): obs, reward, done, info = self.env.step(action) self.was_real_done = done # check current lives, make loss of life terminal, # then update lives to handle bonus lives lives = self.env.unwrapped.ale.lives() if lives < self.lives and lives > 0: # for Qbert sometimes we stay in lives == 0 condtion for a few frames # so its important to keep lives > 0, so that we only reset once # the environment advertises done. done = True self.lives = lives return obs, reward, done, info def reset(self, **kwargs): """Reset only when lives are exhausted. This way all states are still reachable even though lives are episodic, and the learner need not know about any of this behind-the-scenes. """ if self.was_real_done: obs = self.env.reset(**kwargs) else: # no-op step to advance from terminal/lost life state obs, _, _, _ = self.env.step(0) self.lives = self.env.unwrapped.ale.lives() return obs class MaxAndSkipEnv(gym.Wrapper): def __init__(self, env, skip=4): """Return only every `skip`-th frame""" gym.Wrapper.__init__(self, env) # most recent raw observations (for max pooling across time steps) self._obs_buffer = np.zeros((2,) + env.observation_space.shape, dtype=np.uint8) self._skip = skip def step(self, action): """Repeat action, sum reward, and max over last observations.""" total_reward = 0.0 done = None for i in range(self._skip): obs, reward, done, info = self.env.step(action) if i == self._skip - 2: self._obs_buffer[0] = obs if i == self._skip - 1: self._obs_buffer[1] = obs total_reward += reward if done: break # Note that the observation on the done=True frame # doesn't matter max_frame = self._obs_buffer.max(axis=0) return max_frame, total_reward, done, info def reset(self, **kwargs): return self.env.reset(**kwargs) class ClipRewardEnv(gym.RewardWrapper): def __init__(self, env): gym.RewardWrapper.__init__(self, env) def reward(self, reward): """Bin reward to {+1, 0, -1} by its sign.""" return np.sign(reward) class WarpFrame(gym.ObservationWrapper): def __init__(self, env): """Warp frames to 84x84 as done in the Nature paper and later work.""" gym.ObservationWrapper.__init__(self, env) self.width = 84 self.height = 84 self.observation_space = gym.spaces.Box(low=0, high=255, shape=(self.height, self.width, 1), dtype=np.uint8) def observation(self, frame): import cv2 cv2.ocl.setUseOpenCL(False) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame = cv2.resize(frame, (self.width, self.height), interpolation=cv2.INTER_AREA) return frame[:, :, None] class FrameStack(gym.Wrapper): def __init__(self, env, k): """Stack k last frames. Returns lazy array, which is much more memory efficient. See Also -------- baselines.common.atari_wrappers.LazyFrames """ gym.Wrapper.__init__(self, env) self.k = k self.frames = deque([], maxlen=k) shp = env.observation_space.shape self.observation_space = gym.spaces.Box(low=0, high=255, shape=(shp[0], shp[1], shp[2] * k), dtype=np.uint8) def reset(self): ob = self.env.reset() for _ in range(self.k): self.frames.append(ob) return self._get_ob() def step(self, action): ob, reward, done, info = self.env.step(action) self.frames.append(ob) return self._get_ob(), reward, done, info def _get_ob(self): assert len(self.frames) == self.k return LazyFrames(list(self.frames)) class ScaledFloatFrame(gym.ObservationWrapper): def __init__(self, env): gym.ObservationWrapper.__init__(self, env) def observation(self, observation): # careful! This undoes the memory optimization, use # with smaller replay buffers only. return np.array(observation).astype(np.float32) / 255.0 class LazyFrames(object): def __init__(self, frames): """This object ensures that common frames between the observations are only stored once. It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay buffers. This object should only be converted to numpy array before being passed to the model. You'd not believe how complex the previous solution was.""" self._frames = frames self._out = None def _force(self): if self._out is None: self._out = np.concatenate(self._frames, axis=2) self._frames = None return self._out def __array__(self, dtype=None): out = self._force() if dtype is not None: out = out.astype(dtype) return out def __len__(self): return len(self._force()) def __getitem__(self, i): return self._force()[i] def make_atari(env_id): env = gym.make(env_id) assert 'NoFrameskip' in env.spec.id env = NoopResetEnv(env, noop_max=30) env = MaxAndSkipEnv(env, skip=4) return env def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False): """Configure environment for DeepMind-style Atari. """ if episode_life: env = EpisodicLifeEnv(env) if 'FIRE' in env.unwrapped.get_action_meanings(): env = FireResetEnv(env) env = WarpFrame(env) if scale: env = ScaledFloatFrame(env) if clip_rewards: env = ClipRewardEnv(env) if frame_stack: env = FrameStack(env, 4) return env class ImageToPyTorch(gym.ObservationWrapper): """ Image shape to num_channels x weight x height """ def __init__(self, env): super(ImageToPyTorch, self).__init__(env) old_shape = self.observation_space.shape self.observation_space = gym.spaces.Box(low=0.0, high=1.0, shape=(old_shape[-1], old_shape[0], old_shape[1]), dtype=np.uint8) def observation(self, observation): return np.swapaxes(observation, 2, 0) def wrap_pytorch(env): return ImageToPyTorch(env) class GymDelay(gym.Wrapper): def __init__(self, env, act_delay=0, obs_delay=0): """ Create a delay system, with act_delay steps action delay, and obs_delay steps observation delay. The 'step' function's argument(action) should be a list. This wrapper just supports continuous action and state for now. """ gym.Wrapper.__init__(self, env) self.act_delay = act_delay self.obs_delay = obs_delay self.act_dim = self.action_space.shape[0] self.obs_dim = self.observation_space.shape[0] self._max_episode_steps = self.env._max_episode_steps init_state = self.reset() self.act_buffer = [ [0]*self.act_dim ]*self.act_delay self.obs_buffer = [ [ init_state, 0, False, None ] ]*self.obs_delay def reset(self, **kwargs): self.act_buffer = [ [0]*self.act_dim ]*self.act_delay self.obs_buffer = [ [ [0]*self.obs_dim, 0, False, {} ] ]*self.obs_delay return self.env.reset(**kwargs) def step(self, action): self.act_buffer.append(action) old_action = self.act_buffer.pop(0) new_obs, reward, done, info = self.env.step(old_action) self.obs_buffer.append([new_obs, reward, done, info]) return self.obs_buffer.pop(0)
33.361371
117
0.609954
import gym import numpy as np import torch from collections import deque device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class NormalizedActions(gym.ActionWrapper): def action(self, action): low = self.action_space.low high = self.action_space.high action = low + (action + 1.0) * 0.5 * (high - low) action = np.clip(action, low, high) return action def reverse_action(self, action): low = self.action_space.low high = self.action_space.high action = 2 * (action - low) / (high - low) - 1 action = np.clip(action, low, high) return action def make_env(env_name): def _thunk(): env = gym.make(env_name) return env return _thunk class NoopResetEnv(gym.Wrapper): def __init__(self, env, noop_max=30): gym.Wrapper.__init__(self, env) self.noop_max = noop_max self.override_num_noops = None self.noop_action = 0 assert env.unwrapped.get_action_meanings()[0] == 'NOOP' def reset(self, **kwargs): self.env.reset(**kwargs) if self.override_num_noops is not None: noops = self.override_num_noops else: noops = self.unwrapped.np_random.randint(1, self.noop_max + 1) assert noops > 0 obs = None for _ in range(noops): obs, _, done, _ = self.env.step(self.noop_action) if done: obs = self.env.reset(**kwargs) return obs def step(self, ac): return self.env.step(ac) class FireResetEnv(gym.Wrapper): def __init__(self, env): gym.Wrapper.__init__(self, env) assert env.unwrapped.get_action_meanings()[1] == 'FIRE' assert len(env.unwrapped.get_action_meanings()) >= 3 def reset(self, **kwargs): self.env.reset(**kwargs) obs, _, done, _ = self.env.step(1) if done: self.env.reset(**kwargs) obs, _, done, _ = self.env.step(2) if done: self.env.reset(**kwargs) return obs def step(self, ac): return self.env.step(ac) class EpisodicLifeEnv(gym.Wrapper): def __init__(self, env): gym.Wrapper.__init__(self, env) self.lives = 0 self.was_real_done = True def step(self, action): obs, reward, done, info = self.env.step(action) self.was_real_done = done lives = self.env.unwrapped.ale.lives() if lives < self.lives and lives > 0: done = True self.lives = lives return obs, reward, done, info def reset(self, **kwargs): if self.was_real_done: obs = self.env.reset(**kwargs) else: obs, _, _, _ = self.env.step(0) self.lives = self.env.unwrapped.ale.lives() return obs class MaxAndSkipEnv(gym.Wrapper): def __init__(self, env, skip=4): gym.Wrapper.__init__(self, env) self._obs_buffer = np.zeros((2,) + env.observation_space.shape, dtype=np.uint8) self._skip = skip def step(self, action): total_reward = 0.0 done = None for i in range(self._skip): obs, reward, done, info = self.env.step(action) if i == self._skip - 2: self._obs_buffer[0] = obs if i == self._skip - 1: self._obs_buffer[1] = obs total_reward += reward if done: break max_frame = self._obs_buffer.max(axis=0) return max_frame, total_reward, done, info def reset(self, **kwargs): return self.env.reset(**kwargs) class ClipRewardEnv(gym.RewardWrapper): def __init__(self, env): gym.RewardWrapper.__init__(self, env) def reward(self, reward): return np.sign(reward) class WarpFrame(gym.ObservationWrapper): def __init__(self, env): gym.ObservationWrapper.__init__(self, env) self.width = 84 self.height = 84 self.observation_space = gym.spaces.Box(low=0, high=255, shape=(self.height, self.width, 1), dtype=np.uint8) def observation(self, frame): import cv2 cv2.ocl.setUseOpenCL(False) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame = cv2.resize(frame, (self.width, self.height), interpolation=cv2.INTER_AREA) return frame[:, :, None] class FrameStack(gym.Wrapper): def __init__(self, env, k): gym.Wrapper.__init__(self, env) self.k = k self.frames = deque([], maxlen=k) shp = env.observation_space.shape self.observation_space = gym.spaces.Box(low=0, high=255, shape=(shp[0], shp[1], shp[2] * k), dtype=np.uint8) def reset(self): ob = self.env.reset() for _ in range(self.k): self.frames.append(ob) return self._get_ob() def step(self, action): ob, reward, done, info = self.env.step(action) self.frames.append(ob) return self._get_ob(), reward, done, info def _get_ob(self): assert len(self.frames) == self.k return LazyFrames(list(self.frames)) class ScaledFloatFrame(gym.ObservationWrapper): def __init__(self, env): gym.ObservationWrapper.__init__(self, env) def observation(self, observation): # careful! This undoes the memory optimization, use # with smaller replay buffers only. return np.array(observation).astype(np.float32) / 255.0 class LazyFrames(object): def __init__(self, frames): self._frames = frames self._out = None def _force(self): if self._out is None: self._out = np.concatenate(self._frames, axis=2) self._frames = None return self._out def __array__(self, dtype=None): out = self._force() if dtype is not None: out = out.astype(dtype) return out def __len__(self): return len(self._force()) def __getitem__(self, i): return self._force()[i] def make_atari(env_id): env = gym.make(env_id) assert 'NoFrameskip' in env.spec.id env = NoopResetEnv(env, noop_max=30) env = MaxAndSkipEnv(env, skip=4) return env def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False): if episode_life: env = EpisodicLifeEnv(env) if 'FIRE' in env.unwrapped.get_action_meanings(): env = FireResetEnv(env) env = WarpFrame(env) if scale: env = ScaledFloatFrame(env) if clip_rewards: env = ClipRewardEnv(env) if frame_stack: env = FrameStack(env, 4) return env class ImageToPyTorch(gym.ObservationWrapper): def __init__(self, env): super(ImageToPyTorch, self).__init__(env) old_shape = self.observation_space.shape self.observation_space = gym.spaces.Box(low=0.0, high=1.0, shape=(old_shape[-1], old_shape[0], old_shape[1]), dtype=np.uint8) def observation(self, observation): return np.swapaxes(observation, 2, 0) def wrap_pytorch(env): return ImageToPyTorch(env) class GymDelay(gym.Wrapper): def __init__(self, env, act_delay=0, obs_delay=0): gym.Wrapper.__init__(self, env) self.act_delay = act_delay self.obs_delay = obs_delay self.act_dim = self.action_space.shape[0] self.obs_dim = self.observation_space.shape[0] self._max_episode_steps = self.env._max_episode_steps init_state = self.reset() self.act_buffer = [ [0]*self.act_dim ]*self.act_delay self.obs_buffer = [ [ init_state, 0, False, None ] ]*self.obs_delay def reset(self, **kwargs): self.act_buffer = [ [0]*self.act_dim ]*self.act_delay self.obs_buffer = [ [ [0]*self.obs_dim, 0, False, {} ] ]*self.obs_delay return self.env.reset(**kwargs) def step(self, action): self.act_buffer.append(action) old_action = self.act_buffer.pop(0) new_obs, reward, done, info = self.env.step(old_action) self.obs_buffer.append([new_obs, reward, done, info]) return self.obs_buffer.pop(0)
true
true