예제 #1
0
 def create_request_entity(username,
                           title,
                           category,
                           price,
                           origin_city,
                           origin_desc,
                           destination_city,
                           destination_desc,
                           description,
                           img_url,
                           expired_date,
                           thumb_url,
                           price_currency=1,
                           id=None,
                           status=Enum.REQUEST_STATUS.Active):
     request_entity = RequestEntity()
     request_entity.request_id = id
     request_entity.username = username
     request_entity.title = title
     request_entity.category = utils.convert_string_list_to_enum_category_list(
         category)
     request_entity.price = price
     request_entity.price_currency = Enum.CURRENCY(int(price_currency))
     request_entity.origin_city = Enum.CITY(int(origin_city))
     request_entity.origin_address = origin_desc
     request_entity.destination_city = Enum.CITY(int(destination_city))
     request_entity.destination_address = destination_desc
     request_entity.description = description
     request_entity.image_url = utils.convert_string_to_list(img_url)
     request_entity.expired_date = expired_date
     request_entity.thumb_url = utils.convert_string_to_list(thumb_url)
     request_entity.status = status
     return request_entity
예제 #2
0
def UpdateContactOption():
    print(Enum.UpdateContactInfo)
    data = Data.GetDb()
    selection = 0
    Console.PrintSelectedContact(data, selection)
    while True:
        keycode = Console.GetInput()
        if keycode == Enum.DownArrow:
            selection += 1
        elif keycode == Enum.UpArrow:
            selection -= 1
        elif keycode == Enum.Enter:
            Console.Clear()
            person = data[selection]
            print("NOTE: Empty inputs will change to old ones!")
            Console.Print(Enum.EnterNameUpdate(person.name))
            nameUpdate = Console.GetPersonName(True, Regex.NameSkip)

            Console.Print(Enum.EnterCityUpdate(person.city))
            cityUpdate = Console.GetCityName(True, Regex.CitySkip)

            Console.Print(Enum.EnterNumberUpdate(person.phoneNumber))
            numberUpdate = Console.GetPhoneNumber(True, Regex.NumberSkip)

            nameUpdate = person.name if nameUpdate == "" else nameUpdate
            cityUpdate = person.city if cityUpdate == "" else cityUpdate
            numberUpdate = person.phoneNumber if numberUpdate == "" else numberUpdate

            if Console.ConfirmUpdate(person, nameUpdate, cityUpdate,
                                     numberUpdate):
                if Data.UpdateContact(selection, nameUpdate, cityUpdate,
                                      numberUpdate):
                    print(Enum.ContactUpdated)
                    print(Enum.EnterForMainMenu)
                    Console.WaitForEnter()
                    return
                else:
                    print(
                        f"{Fore.YELLOW}*** Contact didn't updated! ***{Fore.YELLOW}{Fore.WHITE}"
                    )
                    print(Enum.EnterForMainMenu)
                    Console.WaitForEnter()
                    return
            else:
                print(
                    f"{Fore.YELLOW}*** Contact didn't updated! ***{Fore.YELLOW}{Fore.WHITE}"
                )
                print(Enum.EnterForMainMenu)
                Console.WaitForEnter()
                return

        if selection < 0:
            selection = 0
        if selection >= len(data) - 1:
            selection = len(data) - 1
        Console.Clear()
        print(Enum.UpdateContactInfo)
        Console.PrintSelectedContact(data, selection)
예제 #3
0
class ShipmentCreated(Event):
    identifier = "shipment_created"
    name = _("Shipment Created")

    order = Variable(_("Order"), type=Model("E-Commerce.Order"))
    customer_email = Variable(_("Customer Email"), type=Email)
    customer_phone = Variable(_("Customer Phone"), type=Phone)
    language = Variable(_("Language"), type=Language)

    shipment = Variable(_("Shipment"), type=Model("E-Commerce.Shipment"))
    shipping_status = Variable(_("Order Shipping Status"), type=Enum(ShippingStatus))
    shipment_status = Variable(_("Shipment Status"), type=Enum(ShipmentStatus))
예제 #4
0
    def __init__(self, name, parent, namer, header_provider, flags_assigner, blacklist):
        self.name = name
        self.parent = parent

        self.namer = namer
        self.header_provider = header_provider
        self.flags_assigner = flags_assigner
        self.blacklist = blacklist

        self.processing_done_listener = None

        self.submodules = {}
        self.classes = {}
        self.global_constants = {}
        self.enums = Enum.Enum()
        self.free_functions = MethodJar.MethodJar()
        self.header_jar = HeaderJar.HeaderJar()
        self.header_jar.add_headers(self.header_provider.module(self.name))

        self.modified = True

        # Only effective while processing a specified header
        self.root = None
        self.id = None
        self.file_node = None
        self.header_decl = None
예제 #5
0
 def agregarEnum(self, nuevo: Enum):
     if self.primero is None:
         self.primero = nuevo
         self.ultimo = nuevo
     else:
         self.ultimo.siguiente = nuevo
         nuevo.anterior = self.ultimo
         self.ultimo = nuevo
예제 #6
0
def AddContact(name, city, number):
    person = Person(name, city, number)
    data = GetDb()
    if IsPersonInDb(data, person):
        return AddException(Enum.ContactExist(name, city, number))
    else:
        data.append(person)
    SaveDb(data)
예제 #7
0
파일: Node.py 프로젝트: gitGNU/gnu_dnt
    def __init__(self):
        self.__children = []
        #        self.__iterator  = 0
        self.__parent = None
        self.__allflags = Enum.Enum('visible', 'collapsed', 'parent')
        self.__flags = []
        self.__depth = 0

        debug("Node `" + str(self) + "' created successfully")
예제 #8
0
class RefundCreated(Event):
    identifier = "refund_created"
    name = _("Refund Created")

    order = Variable(_("Order"), type=Model("E-Commerce.Order"))
    customer_email = Variable(_("Customer Email"), type=Email)
    customer_phone = Variable(_("Customer Phone"), type=Phone)
    language = Variable(_("Language"), type=Language)

    payment_status = Variable(_("Order Payment Status"), type=Enum(PaymentStatus))
예제 #9
0
class AddNotification(Action):
    identifier = "add_notification"
    recipient_type = Binding(
        "Recipient Type",
        type=Enum(RecipientType),
        constant_use=ConstantUse.CONSTANT_ONLY,
        default=RecipientType.ADMINS
    )
    recipient = Binding(
        "Recipient",
        type=Model(settings.AUTH_USER_MODEL),
        constant_use=ConstantUse.VARIABLE_OR_CONSTANT,
        required=False
    )
    priority = Binding("Priority", type=Enum(Priority), constant_use=ConstantUse.CONSTANT_ONLY, default=Priority.NORMAL)
    message = TemplatedBinding("Message", type=Text, constant_use=ConstantUse.CONSTANT_ONLY, required=True)
    message_identifier = Binding("Message Identifier", Text, constant_use=ConstantUse.CONSTANT_ONLY, required=False)
    url = Binding("URL", type=URL, constant_use=ConstantUse.VARIABLE_OR_CONSTANT)

    def execute(self, context):
        """
        :type context: E-Commerce.notify.script.Context
        """
        values = self.get_values(context)
        if values["recipient_type"] == RecipientType.SPECIFIC_USER:
            if not values["recipient"]:
                context.log(logging.WARN, "Misconfigured AddNotification -- no recipient for specific user")
                return
        Notification.objects.create(
            recipient_type=values["recipient_type"],
            recipient=values["recipient"],
            priority=values["priority"],
            identifier=values.get("message_identifier"),
            message=values["message"][:140],
            url=values["url"],
            shop=context.shop
        )
예제 #10
0
    def __init__(self, root, node, module, dummy_def=None):
        assert node is not None or dummy_def is not None

        # Only effective while processing
        self.root = root
        self.node = node

        self.namer = module.namer
        self.header_provider = module.header_provider
        self.flags_assigner = module.flags_assigner
        self.blacklist = module.blacklist

        self.all_bases = None
        self.master_bases = None

        self.has_public_copy_ctor = True
        self.final = False

        # No accessible canonical ctors -> disallow subclassing
        # `canonical ctor` refers to a ctor that is not a copy ctor
        self.no_accessible_canonical_ctors = False

        # If true, requires a wrapper class
        # We only save constructors' params, so we can't determine
        # whether the class has any protected constructor when
        # generating the output
        self.has_protected_ctor = False

        # Instantiatable (new-able) != delete-able
        self.dtor_access_type = Access.PUBLIC

        self.protected_nonvirtual_members = set()
        self.public_nonvirtual_methods = []
        self.virtual_members = []
        self.base_vm_collected = False

        self.enums = Enum.Enum()

        self.ctors = []
        self.methods = MethodJar.MethodJar()
        self.fields = []
        self.fptrs = Fptr.FptrManager()

        self.header_jar = HeaderJar.HeaderJar()
        self.header_jar.add_headers((
            "_Python.hxx",
            "_Common.hxx",
        ))
        if module.header_decl:
            self.header_jar.add_headers((module.header_decl, ))

        # These properties only accessed by the Module class
        self.modified = True
        self.m = None

        # For temporary use only, avoid passing it everywhere
        self.block = CodeBlock.CodeBlock()

        if dummy_def is not None:
            self.name = dummy_def.name
            self.full_name = dummy_def.full_name

            self.enum_class = dummy_def.enum_class

            self.nester = dummy_def.nester
            self.direct_bases = []

            # TODO: namespace alias
            if (not dummy_def.namespace and not dummy_def.nester
                    and not dummy_def.enum_class):
                assert self.name == self.full_name

                self.header_jar.add_global(
                    "%s %s;" %
                    ("struct" if dummy_def.is_struct else "class", self.name))

            # Instantiating, destroying, copying or inheriting
            # a dummy class (object) is not allowed

            self.has_public_copy_ctor = False
            self.final = True

            self.no_accessible_canonical_ctors = True
            self.dtor_access_type = Access.PRIVATE
        else:
            Session.begin(self.header_jar)

            self.name = node.attrib["name"]
            self.full_name = node.attrib["demangled"]

            self.enum_class = False

            self.nester = self._get_nester_class()
            self.direct_bases = self._collect_direct_bases()

            self.final = node.attrib.get("final") == "1"

            self._constructors()
            self._destructor()  # Check dtor's access type

            self._methods()
            self._enums(module)
            self._fields()

            Session.end()
예제 #11
0
def test_enum_type():
    enum_type = Enum(StepConditionOperator)
    assert enum_type.unserialize(StepConditionOperator.ANY) == StepConditionOperator.ANY
    assert enum_type.unserialize("any") == StepConditionOperator.ANY
    assert not enum_type.unserialize("herp")
예제 #12
0
 def createEnum(self, nombre: str, tipos: list):
     nuevo = Enum.Enum(nombre, tipos)
     self.agregarEnum(nuevo)
예제 #13
0
import Enum

TRS = Enum.enum(EN=0, CH=1, LEN=2)


def printParagraph(paragraphs):
    description = ""  #"Title:%s\n" % self.title
    for i in paragraphs:
        description += i.__str__() + '\n'
    print description


def diffTime(paragraphSRC, paragraphDST):
    return paragraphDST.endTime - paragraphSRC.endTime


def overTime(paragraphSRC, paragraphDST):
    return paragraphDST.endTime > paragraphSRC.endTime


def mergeParagraph(paragaph, src, dst):
    for i in xrange(src + 1, dst):
        paragaph[src].extendContent(paragaph[i])
    return paragaph[src]


def MergeSubtitles(enParagraph, chParagraph):
    newParagraph = [[], []]
    indexLen = [len(enParagraph), len(chParagraph)]
    indexSRC = [0, 0]
    indexDST = [0, 0]
예제 #14
0
import Enum

RF = Enum.enum(ORIGINAL=0, PIECE=1, EN_LINE1=2, EN_LINE2=3) 

def refactWithLine(talk, countOfLine):
	count = 0
	talk.ResetStartOfParagraph(False)
	subtitle = talk.subtitles
	subtitle[0].startOfParagraph = True 
	for i in xrange(1,len(subtitle)):
	  if(subtitle[i].content[-1] == "." or subtitle[i].content[-1] == "?"):
	    count = count + 1
	    if(i < len(subtitle)-1 and count == countOfLine):
	      subtitle[i+1].startOfParagraph = True
	      count = 0 

def methodOriginal(enTalk, chTalk):
	return

def methodPIECE(enTalk, chTalk):
	chTalk.ResetStartOfParagraph(True)
	enTalk.ResetStartOfParagraph(True)	    

def methodEN_LINE1(enTalk, chTalk):
	chTalk.ResetStartOfParagraph(True)
	refactWithLine(enTalk, 1)     

def methodEN_LINE2(enTalk, chTalk):
	chTalk.ResetStartOfParagraph(True)
	refactWithLine(enTalk, 2)         
예제 #15
0
from xml.etree import ElementTree
import Enum

AttribType = Enum.enum(STRING=0, INT=1, BOOL=2)





#returns the root of the file
def root(xmlFile):    
    tree = ElementTree.parse(xmlFile.fileHandler())            
    root = tree.getroot()
        
    root.file = xmlFile     #need to have reference back to the file    
            
    return root
        

#returns all the roots of all the files in a given folder
def rootsAndSubfolders(xmlFolder):
    roots = []
    
    xmlFiles, subfolders = xmlFolder.listFolder()    
    for xmlFile in xmlFiles:
        fileRoot = root(xmlFile)
        roots.append(fileRoot)
        
    return roots, subfolders
    
        
예제 #16
0
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 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, see <http://www.gnu.org/licenses/>

import cairo
import Enum

keytypes = Enum.Enum("SIMPLE SPECIAL").vals(illegal=255)
alignments = Enum.Enum("LEFT CENTRE RIGHT").vals(illegal=255)
keysegments = Enum.Enum("ALL ONE TWO THREE FOUR NONE").vals(illegal=255)
keyvaluetype = Enum.Enum(
    "UNICHAR CODEPOINT KEYSYM CONSTANT DEADKEY ANY VOIDSYMBOL NOSYMBOL NOACTION VERBATIM"
).vals(illegal=255)

keysegmentslist = [
    keysegments.ONE, keysegments.TWO, keysegments.THREE, keysegments.FOUR
]
keysegmentslistreverse = list(keysegmentslist)
keysegmentslistreverse.reverse()

fontname = "Sans"
fontstyle = cairo.FONT_SLANT_NORMAL
fontweight = cairo.FONT_WEIGHT_NORMAL
예제 #17
0
def ElmDefs(expr):

    errors = []
    elmdefs = []
    elmdef = None

    states = Enum('name,type,modifiers,precision,dimension,skipping')
    state = states.name
    depth = []
    error = None
    dimension = None
    precision = None

    try:
        words = list(ElmDefWords(expr))
    except SyntaxError as err:
        return ([err], [])

    word = None

    for thisWord in words:

        prevword = word

        if thisWord is None:
            line = col = word = None
        else:
            line, col, word = thisWord

        try:

            if word == ')' and (not depth or depth[-1][2] != '('):
                raise SyntaxError(line, col, "Misplaced ')'")
            if word == ']' and (not depth or depth[-1][2] != '['):
                raise SyntaxError(line, col, "Misplaced ']'")
            if word == ';' and depth:
                raise SyntaxError(
                    line, col,
                    "Seperator ';' only valid on Element Definition level")

            if state == states.name:
                if word is None or not IsValidName(word):
                    error = (line, col, "Expected element name here")
                    datatype = None
                    if word in ',;':
                        state = states.name
                    else:
                        state = states.skipping
                    continue
                elmdef = ElmDef()
                elmdef.name = word
                state = states.type
                continue

            # If skipping...
            if state == states.skipping:
                if word is None:
                    break
                if word == '<eol>' or (not depth and word in (',', ';')):
                    state = states.name
                elif len(word) == 1:
                    if word in '[(':
                        depth.append((line, col, word))
                    elif word in '])':
                        depth.pop()
                continue

            # Handle truncated definition...
            atend = word in (',', ';', '<eol>', None) and len(depth) == 0
            if atend:
                elmdefs.append(elmdef)
                elmdef = None
                state = states.name
                if word is None:
                    break
                continue

            # Handle optional states
            if state == states.type:

                if not word in datatypes:
                    raise SyntaxError(line, col, "Expected Type here")
                elmdef.datatype = word
                state = states.modifiers

            elif state == states.modifiers:

                if word in '([':
                    depth.append((line, col, word))
                    if word == '(':
                        if len(depth) > 1:
                            raise SyntaxError(line, col, "Nested precision")
                        if elmdef.precision != None:
                            raise SyntaxError(line, col,
                                              "Precision already specified")
                        state = states.precision
                        if elmdef.precision is None:
                            elmdef.precision = []
                        elmdef.precision.append(None)
                    else:
                        if len(depth) > 1:
                            raise SyntaxError(line, col, "Nested dimension")
                        #if elmdef.dimension != None:
                        #  raise SyntaxError(line,col,"Dimension already specified")
                        state = states.dimension
                        if elmdef.dimension is None:
                            elmdef.dimension = []
                        elmdef.dimension.append(None)
                    continue

                else:

                    # Make sure modifier's known
                    if not word in modifiers:
                        raise SyntaxError(line, col, "Expected modifier here")

                    # Get member/value
                    member, value = modifiers[word]

                    # Make sure member not already set...
                    if elmdef.__dict__[member] != None and elmdef.__dict__[
                            member] != value:
                        raise SyntaxError(line, col, "Conflicting modifier")

                    # Set it
                    elmdef.__dict__[member] = value

                if not atend and not word in modifiers:
                    raise SyntaxError(line, col, "Expected modifier here")

            elif state == states.precision or state == states.dimension:

                if word == ',':
                    if state == states.precision:
                        if len(elmdef.precision) >= 2:
                            raise SyntaxError(
                                line, col, "Only <precision>/<scale> accepted")
                        elmdef.precision.append(None)
                    else:
                        elmdef.dimension.append(None)
                    continue

                if word == ']':
                    if state != states.dimension:
                        raise SyntaxError(line, col, "Misplaced ']'")
                    state = states.modifiers
                    depth.pop()
                    continue
                if word == ')':
                    if state != states.precision:
                        raise SyntaxError(line, col, "Misplaced ')'")
                    while len(elmdef.precision) < 2:
                        elmdef.precision.append(None)
                    state = states.modifiers
                    depth.pop()
                    continue

                if not is_int(word):
                    raise SyntaxError(line, col, "Expected integer here")

                if state == states.precision:
                    lst = elmdef.precision
                else:
                    lst = elmdef.dimension

                if lst and prevword not in "([,":
                    raise SyntaxError(line, col, "Expected ',' here")

                x = lst.pop()
                if x != None:
                    raise InternalError("Expected lst.pop() to be None")
                lst.append(int(word))

            continue

        except SyntaxError as err:

            elmdef = None
            errors.append(err)
            if word in (',', '<eol>') and not depth:
                state = states.name
            else:
                state = states.skipping
            continue

    if elmdef:
        elmdefs.append(elmdef)

    return errors, elmdefs
예제 #18
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#JAN = 1
#FEB = 2
#MAR = 3
#...
#DEC = 12
import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
                       'Sep', 'Oct', 'Nov', 'Dec'))
print Month.Jan
예제 #19
0
def set_age(self, age):
...     self.age = age
s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
s.set_age(25) # 调用实例方法,给一个实例绑定的方法,对另一个实例是不起作用的
Student.set_score = set_score#为了给所有实例都绑定方法,可以给class绑定方法
							 #通常是在类的定义中绑定方法,动态绑定允许我们在程序运行的过程中动态给class加上功能
class Student(object):
    __slots__ = ('name', 'age') # 用tuple定义在运行过程中允许绑定的属性名称,__slots__只对当前类有效,对子类无效。


### 2.2 使用@property
class Student(object):

    @property   #@property装饰器:把一个方法变成属性调用;把一个getter方法变成属性,只需要加上@property就可以了
    def score(self):
        return self._score

    @score.setter  #@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value
>>> s.score = 60 # OK,实际转化为s.set_score(60)
>>> s.score # OK,实际转化为s.get_score()

### 2.3 多重继承
class Dog(Animal, Runnable): #dog同时继承animal和Runnerble的功能,主线是Animal,为了更好的看出继承关系,我们把主线之外的继承加上MixIn。
    pass
class Dog(Mammal, RunnableMixIn, CarnivorousMixIn)#多重继承
    pass

### 2.4 定制类
# 2.4.1 __str__
class Student(object):
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return 'Student object (name=%s)' % self.name
    __repr__ = __str__
>>> print(Student('Michael'))#调用__str__(),返回用户看到的字符串
>>> s = Student('Michael')
>>> s                         #调用__repr__(),返回程序开发者看到的字符串

# 2.4.2 __iter__
class Fib(object):
    def __init__(self):
        self.a, self.b = 0, 1 # 初始化两个计数器a,b

    def __iter__(self): #让类可以用于for循环
        return self # 实例本身就是迭代对象,故返回自己。

    def __next__(self):
        self.a, self.b = self.b, self.a + self.b # 计算下一个值
        if self.a > 100000: # 退出循环的条件
            raise StopIteration()
        return self.a # 返回下一个值
>>> for n in Fib():   #把Fib实例作用于for循环
...     print(n)

# 2.4.3 __getitem__
class Fib(object):
    def __getitem__(self, n):   #让类像list一样,可通过下标取出元素
        a, b = 1, 1
        for x in range(n):
            a, b = b, a + b
        return a
>>> f = Fib()
>>> f[0]
1
>>> f[1]

# 2.4.4 __getattr__
class Student(object):

    def __init__(self):
        self.name = 'Michael'

    def __getattr__(self, attr):
        if attr=='score':
            return 99
>>> s = Student()
>>> s.name
'Michael'
>>> s.score #当调用不存在的属性时,Python解释器会试图调用__getattr__(self, 'score')来尝试获得属性
99          #这样,我们就有机会返回score的值

# 2.4.5 __call__
class Student(object):
    def __init__(self, name):
        self.name = name

    def __call__(self):  #让类可以直接对实例进行调用
        print('My name is %s.' % self.name)

>>> s = Student('Michael')
>>> s() # self参数不要传入
My name is Michael.

>>> callable(Student()) #callable(),判断一个对象是否是“可调用”对象
True

### 2.5 使用枚举类
import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
#Month类型的枚举类,可以直接使用Month.Jan来引用一个常量,或者枚举它的所有成员
>>> day1 = Weekday.Mon
>>> print(day1)
Weekday.Mon
>>> print(Weekday.Tue)
Weekday.Tue
예제 #20
0
import Enum

AttachmentType = Enum.enum(region=0, 
                           regionSequence=1)

class AttachmentLoader(object):
    def __init__(self):
        super(AttachmentLoader, self).__init__()

    def newAttachment(type, name):
        pass

import Enum 

TRS = Enum.enum(EN=0, CH=1, LEN=2)

def printParagraph(paragraphs):
  description = "" #"Title:%s\n" % self.title
  for i in paragraphs:
    description += i.__str__() + '\n'
  print description 

def diffTime(paragraphSRC, paragraphDST): 
  return paragraphDST.endTime - paragraphSRC.endTime

def overTime(paragraphSRC, paragraphDST): 
  return paragraphDST.endTime > paragraphSRC.endTime 
 
def mergeParagraph(paragaph, src, dst): 
  for i in xrange(src+1, dst):
    paragaph[src].extendContent(paragaph[i]);
  return paragaph[src]
 
def MergeSubtitles(enParagraph, chParagraph):
  newParagraph = [[],[]]
  indexLen = [len(enParagraph), len(chParagraph)]
  indexSRC = [0, 0]
  indexDST = [0, 0]
  pParagraph = [enParagraph, chParagraph]
  end = False
  while(end==False):
    diff = diffTime(pParagraph[TRS.EN][indexSRC[TRS.EN]], pParagraph[TRS.CH][indexSRC[TRS.CH]])
    if(abs(diff) < 500):
예제 #22
0
from bs4 import BeautifulSoup
import Enum

AttribType = Enum.enum(STRING=0, INT=1, BOOL=2)





#returns the root of the file
def root(xmlFile):
    soup =  BeautifulSoup(xmlFile.contents())   
    root = soup.contents[0]
    
        
    root.file = xmlFile     #need to have reference back to the file    
            
    return root
        

#returns all the roots of all the files in a given folder
def rootsAndSubfolders(xmlFolder):
    roots = []
    
    xmlFiles, subfolders = xmlFolder.listFolder()    
    for xmlFile in xmlFiles:
        fileRoot = root(xmlFile)
        roots.append(fileRoot)
        
    return roots, subfolders
    
예제 #23
0
import Enum

AttachmentType = Enum.enum(region=0, regionSequence=1)


class AttachmentLoader(object):
    def __init__(self):
        super(AttachmentLoader, self).__init__()

    def newAttachment(type, name):
        pass
예제 #24
0
        print ret
        if ret == 0:
            # all okay
            return True
        raise OperationException
    else:
        # don't know what to do with this db type
        raise DBTypeNotSupported


if __name__ == "__main__":
    # called from cmd line, set up arg parsing and return codes
    import Enum
    import sys
    RET_CODE = Enum.Enumeration(
        'Return Codes',
        (('NO_ERROR', 0), 'NO_INIT', 'DB_TYPE_NOT_SUPPORTED',
         'OPERATION_ERROR', 'MISSING_PARM', 'BAD_FILENAME', 'UNKNOWN_ERROR'))

    def exit(code):
        ''' Exit with the supplied code. Print code and Enum if instructed
        '''
        if DEBUG:
            print RET_CODE.whatis(code)
        sys.exit(code)

    def init_wrap(args):
        ''' Call init, interpreting appropriate argparse args
        '''
        try:
            init(ini_file=args.config_file)
            exit(RET_CODE.NO_ERROR)
예제 #25
0
import os
import db
import email_sender
import settings
from Enum import *
""" 
Severity Definition:
# CRITICAL: Unable to start. DOWN state.
# MEDIUM: Not used in WatchTower, for future use
# LOW: Not used in WatchTower, for future use
# INFO: Not used in WatchTower, for future use
"""

module_name = os.path.basename(__file__)

ALERT_LEVEL = Enum(["CRITICAL", "WARNING", "ERROR", "INFO"])

TEMPLATE = Enum([
    "WATCHLIST_FILE_READ_ERROR", "WATCHLIST_FILE_EMPTY", "FILE_CHANGED",
    "NEW_FILE_DETECTED", "FILE_DELETED", "FILE_RENAMED",
    "WATCHLIST_FILE_NOT_FOUND"
])

ALERT_TEMPLATE_FILE = {
    TEMPLATE.WATCHLIST_FILE_READ_ERROR:
    "email_templates/watchlist_read_error.txt",
    TEMPLATE.WATCHLIST_FILE_NOT_FOUND:
    "email_templates/watchlist_not_found.txt",
    TEMPLATE.WATCHLIST_FILE_EMPTY: "email_templates/watchlist_file_empty.txt",
    TEMPLATE.FILE_DELETED: "email_templates/file_deleted.txt",
    TEMPLATE.FILE_CHANGED: "email_templates/file_changed.txt",