Exemplo n.º 1
0
class Target(MetaAnnotation):
    class _Enum:
        def __init__(this, value: int, name: str, checkFun: Callable[[any], bool]) -> None:
            super().__init__()
            this.value = value
            this.name = name
            this.checkFun = checkFun

        def __str__(this) -> str:
            return this.name

    CLASS = _Enum(1, "Class", Reflex.isType)
    FUNCTION = _Enum(2, "Function", lambda x: Reflex.isFunction(x) or Reflex.isGenerator(x))
    META = _Enum(3, "Meta", lambda x: isinstance(x, Annotation))
    _DEFAULT = FUNCTION

    def __init__(this, *targets: _Enum):
        if len(targets) == 0 or (len(targets) == 1 and not isinstance(targets[0], Target._Enum)):
            raise IllegalArgumentExc(f"""Argumen untuk anotasi @Target harus int setidaknya berjumlah 1.""")
        super().__init__(None, **{Meta.META_TARGETS_NAME: list(targets)})

    def isImplementationValid(this, inspectedCls: type, supers: List[type], immediateSubclasses: List[type],
                              inspectedUnit: Dict[str, Any]) -> bool:
        return super().isImplementationValid(inspectedCls, supers, immediateSubclasses, inspectedUnit)
Exemplo n.º 2
0
def main():
    database.setupDatabase()

    data = DataSet()

    reflex = Reflex(data)
    smart = Smart(data)
    ddot = DDOT(data)

    reflex.load_data(
    )  # load reflex first because the others ignore identical routes
    smart.load_data()
    ddot.load_data()

    fb.insert_data_set(data)

    print("Database saved to", current_path + "/ETADetroitDatabase.db")
Exemplo n.º 3
0
 def isImplementationValid(this, inspectedCls: type, supers: List[type],
                           immediateSubclasses: List[type],
                           inspectedUnit: Dict[str, Any]) -> bool:
     print(
         f"Final.isImplementationValid() inspectedUnit= {inspectedUnit} immediateSubclasses= {immediateSubclasses}"
     )
     name = list(inspectedUnit.keys())[0]
     unit = inspectedUnit[name]
     this._inspected = unit
     if Reflex.isType(unit):
         if len(immediateSubclasses) > 0:
             this._inspectedImpl = immediateSubclasses  #[0]
             return False
         return True
     else:
         for sub in immediateSubclasses:
             for methodName in sub.__dict__:
                 if name == methodName:
                     this._subCls = sub
                     this._inspectedImpl = sub.__dict__[methodName]
                     return False
     return True
Exemplo n.º 4
0
dick = { 'a':1 }
for d in dick:
    print(f"dick= {d}")

print(dick.keys())


print("\n=================== link =================\n")

print(C.__bases__)
print(A.ada.__dict__)
print(A.ada.__call__)
print(inspect.getsourcelines(A.ada))
print(inspect.getsourcelines(A.ada))
print(inspect.getfile(A.ada))
print(Reflex.classesTree(B))
print(Reflex.classesTree(B, False))
print(type(A.__class__).__name__)
print(type(A.ada).__name__)
print(A.ada.__class__.__name__)
print(A.ada.__name__)

print("\n=================== Final Meta =================\n")


class D(metaclass=MetaInspector):
    @Final(a=10, b="halo")
    def ada(this):
        print(f"D.ada()")

    @CallSuper
Exemplo n.º 5
0
    def __init__(cls,
                 name: str,
                 supers: Tuple[type],
                 namespace: Dict[str, Any],
                 immediateSubclasses: List[type] = []
                 ):  # **metas: MetaInspectable):
        super().__init__(name, supers, namespace)
        print(
            f"MetaInspector this= {cls} supers= {supers} this.__subclasses__()= {cls.__subclasses__()} immediateSubclasses= {immediateSubclasses}"
        )

        superList = list(supers)

        def inspectMember(inspectable: Annotation):
            inspectedMember = inspectable.content
            print(
                f"MetaInspector.init.inspectMember() inspectedMember= {inspectedMember}"
            )
            nestedMemberDict = {inspectedMember.__name__: inspectedMember}
            if not inspectable.isImplementationValid(
                    cls, superList, immediateSubclasses, nestedMemberDict):
                msg = inspectable.implementationErrorMsg().strip() \
                      or f"""Terjadi kesalahan pada kelas: "{name}" implementasi member: "{inspectedMember}" dg meta: "{inspectedMember.__class__}"."""
                msg += f"\n   {Reflex.lineInfo(inspectable.errorImplemetedMember())}"
                raise MetaInspectionExc(msg)

        # Pengecekan untuk @Target(Target.FUNCTION)
        # Pengecekan untuk @Target(Target.FUNCTION)
        # 1. Pengecekan `MetaInspectable` pada `this`, yaitu mencari member yang memiliki namespace `Meta.INSPECTABLE_PROP_NAME`.
        for memberName in namespace:
            member = namespace[memberName]
            print(f"MetaInspector member= {member} memberName= {memberName}")
            try:
                print(
                    f"MetaInspector member= {member} memberName= {memberName} dict= {member.__dict__}"
                )
            except:
                pass
            if memberName == Meta.INSPECTABLE_PROP_NAME:
                if not isinstance(member, list): continue
                isMemberAnnotated = False
                for inspectable in member:
                    if not isinstance(inspectable, Annotation): continue
                    print(
                        f"MetaInspector cls= {cls} member= {member} Meta.INSPECTABLE_PROP_NAME= {Meta.INSPECTABLE_PROP_NAME}"
                    )
                    isMemberAnnotated = True
                    inspectMember(inspectable)
                if isMemberAnnotated:
                    setattr(cls, Meta.CLASS_INSPECTABLE_MARK, True)
                    print(cls.__dict__[Meta.CLASS_INSPECTABLE_MARK])
                continue

            # 2. Pengecekan `MetaInspectable` pada nested member.
            #  Jika tidak ditemukan member dengan namespace selain `Meta.INSPECTABLE_PROP_NAME`,
            #  maka inspect membernya. Contohnya seperti member dengan tipe fungsi atau property,
            #  maka yang dicek adalah member dari fungsi atau property, atau `nested member`.
            try:
                nestedMembers = member.__dict__
            except AttributeError:
                continue

            for nestedMemberName in nestedMembers:  # Iterasi terhadap dict akan dilakukan pada key-nya.
                nestedMember = nestedMembers[nestedMemberName]
                print(
                    f"MetaInspector nestedMemberName= {nestedMemberName} nestedMember= {nestedMember} isinstance(nestedMember, MetaInspectable)= {isinstance(nestedMember, Annotation)}"
                )

                #print(f"MetaInspector nestedMember= {nestedMember} inspectables= {inspectables} isinstance(nestedMember, MetaInspectable)= {isinstance(nestedMember, MetaInspectable)}")
                if not isinstance(nestedMember, list): continue
                isMemberAnnotated = False
                for inspectable in nestedMember:
                    if not isinstance(inspectable, Annotation): continue
                    print(
                        f"MetaInspector inspectable = {inspectable} this = {cls}"
                    )
                    print(
                        f"MetaInspector inspectable.content= {inspectable.content}"
                    )
                    print(
                        f"MetaInspector _Reflex.isType(inspectable.content)= {Reflex.isType(inspectable.content)}"
                    )
                    print(
                        f"MetaInspector _Reflex.isFunction(inspectable.content)= {Reflex.isFunction(inspectable.content)}"
                    )
                    isMemberAnnotated = True
                    inspectMember(inspectable)
                if isMemberAnnotated:
                    setattr(cls, Meta.CLASS_INSPECTABLE_MARK, True)
                break

        superclassTree = Reflex.superclassesTree(cls, False)

        # 3. Cek `MetaInspectable` pada superclassTree.
        print(
            f"MetaInspector fullName= {Reflex.fullName(cls)} superclassTree= {superclassTree} dict= {cls.__dict__}"
        )
        if len(superclassTree) > 0:
            for sup in superclassTree:
                print(f"MetaInspector sup= {sup} qualname= {sup.__qualname__}")
                print(
                    f"MetaInspector sup.__subclasses__()= {sup.__subclasses__()}"
                )
                print(f"sup.__dict__= {sup.__dict__}")
                print(
                    f"MetaInspector cls not in sup.__subclasses__()= {cls not in sup.__subclasses__()}"
                )
                print(f"MetaInspector cls= {cls}")
                try:
                    if sup.__dict__[Meta.CLASS_INSPECTABLE_MARK]:
                        MetaInspector(sup.__name__, sup.__bases__,
                                      dict(sup.__dict__), [cls])
                except KeyError as e:
                    print(
                        f"MetaInspector sup= {sup} lagi error e= {e} sup.__dict__= {sup.__dict__}"
                    )
                    if Reflex.getInspectable(sup):
                        print(
                            f"MetaInspector sup= {sup} lagi error e= {e} masuk if"
                        )
                        MetaInspector(sup.__name__, sup.__bases__,
                                      dict(sup.__dict__), [cls])
Exemplo n.º 6
0
from alpha_beta import AlphaBeta


if __name__ == '__main__':
    start = time.time()
    
    # Initialize game board
    gameboard = Board()

    # Initialize red agent
    idx = input('Please choose a type for RED:\n'
                '1. Reflex\n'
                '2. Minimax\n'
                '3. Alpha Beta\n')
    if idx == '1':
        RED = Reflex('red')
    elif idx == '2':
        RED = Minimax('red')
    elif idx == '3':
        RED = AlphaBeta('red')

    # Initialize blue agent
    idx = input('Please choose a type for BLUE:\n'
                '1. Reflex\n'
                '2. Minimax\n'
                '3. Alpha Beta\n')
    if idx == '1':
        BLUE = Reflex('blue')
    elif idx == '2':
        BLUE = Minimax('blue')
    elif idx == '3':
Exemplo n.º 7
0
 def implementationErrorMsg(this) -> str:
     if Reflex.isFunction(this._inspected):
         return f"""Method: "{this._inspected}" final, namun di-override pada kelas: "{this._subCls}"."""
     elif Reflex.isType(this._inspected):
         return f"""Kelas: "{this._inspected}" final, namun di-extend oleh kelas: "{this._inspected.__subclasses__().__str__()}"."""
Exemplo n.º 8
0
def ch(fun):
    print(fun)

class C:
    @ch
    def afa(self):pass
    pro = 1

from meta.metameta.MetaAnnotation import MetaAnnotation
from meta.Final import Final
from meta.Annotation import Annotation
from reflex import Reflex

ls = []

print(Reflex.classesTree(MetaAnnotation))
print(Annotation in Reflex.classesTree(MetaAnnotation))
print(Reflex.isSuperclassOf(Annotation, MetaAnnotation))

#print(Reflex.classesTree(ls))

print(isinstance(Final, Annotation))
ann = Final()#()
print(Reflex.isAnnotation(ann))

#from stdlib import *
from sidev.stdlib import *

ls = listOf(1,2,3,4)
ls2 = ls.map(lambda x: f"x={x}")
Exemplo n.º 9
0
    def _policy(self, gameboard):
        """ Find next move in simulation

        Args:
            gameboard(Board): game board
        Returns:
            best_move(tuple): coordinate
        """
        valid_moves = self._all_valid_moves(gameboard)
        _reflex_ = Reflex(self.color)
        best_move = None
        moves = []

        # step 1, check going to win
        for x in range(gameboard.height):
            for y in range(gameboard.width):
                position = (x, y)
                temp = _reflex_.check_going_to_win(position, gameboard)
                if len(temp) != 0:
                    moves += temp

        if len(moves) > 0:
            idx = np.random.choice(len(moves), 1)[0]
            best_move = moves[idx]
            return best_move

        # step 2, check opponent 4
        for x in range(gameboard.height):
            for y in range(gameboard.width):
                position = (x, y)
                temp = _reflex_._alter_check_opponent_4(position, gameboard)
                if len(temp) != 0:
                    moves += temp

        if len(moves) > 0:
            idx = np.random.choice(len(moves), 1)[0]
            best_move = moves[idx]
            return best_move

        # step 3, check opponent 3
        for x in range(gameboard.height):
            for y in range(gameboard.width):
                position = (x, y)
                temp = _reflex_.check_opponent_3(position, gameboard)
                if len(temp) != 0:
                    moves += temp

        if len(moves) > 0:
            idx = np.random.choice(len(moves), 1)[0]
            best_move = moves[idx]
            return best_move

        # step 4, winning blocks
        for x in range(gameboard.height):
            for y in range(gameboard.width):
                position = (x, y)
                temp = _reflex_.check_winning_blocks(position, gameboard)
                if len(temp) != 0:
                    moves += temp

        if len(moves) > 0:
            moves = list(set(moves))
            moves.sort(key=lambda x: x[2], reverse=True)
            max_count = moves[0][2]
            new_moves = []

            for t in moves:
                if t[2] < max_count:
                    break
                else:
                    new_moves.append((t[0], t[1]))

            moves = new_moves.copy()

        if len(moves) > 0:
            idx = np.random.choice(len(moves), 1)[0]
            best_move = moves[idx]
            return best_move

        # step 5, random pick one
        idx = np.random.choice(len(valid_moves), 1)[0]
        return valid_moves[idx]