def __init__(self, line, source): """ Argument: re match object """ Definition.__init__(self, line, '<([A-Z][a-zA-Z0-9]+)>$') Object.__init__(self, self.matches.group(1), source)
def __init__(self, line, source): """ Argument: re match object """ Definition.__init__( self, line, '\\[([A-Z][a-zA-Z0-9]+)(>[A-Z][a-zA-Z0-9]+|)(\\:SINGLE|)\\] *$') PhysicsObject._known_objects.append(self) # is this a singlet? if self.matches.group(3) == ':SINGLE': self.parent = 'Singlet' self._singlet = True else: self.parent = 'Element' self._singlet = False # if >parent is present, update the parent class name if self.matches.group(2): self.parent = self.matches.group(2)[1:] self._singlet = None Object.__init__(self, self.matches.group(1), source) if len([f for f in self.functions if f.is_pure_virtual]) == 0: self.instantiable = True else: self.instantiable = False
def test_uuid(self): o = Object() p = o.save() uuid1 = p.split(os.sep)[1] p = o.save() uuid2 = p.split(os.sep)[1] self.assertEqual(uuid1, uuid2)
def test_last2(self): o = Object() o.save() uuid1 = o.__stp__.split(os.sep)[1] last(o) uuid2 = o.__stp__.split(os.sep)[1] self.assertEqual(uuid1, uuid2)
def getnames(pkgs): res = Object() for pkg in spl(pkgs): for mod in getmods(pkg): n = findnames(mod) res.update(n) return res
class Names(Object): names = Default({}) modules = Object({}) inits = Object({}) @staticmethod def getnames(nm, dft=None): return Names.names.get(nm, dft) @staticmethod def getmodule(mn): return Names.modules.get(mn, None) @staticmethod def getinit(mn): return Names.inits.get(mn, None) @staticmethod def tbl(tbl): Names.names.update(tbl["names"]) Names.modules.update(tbl["modules"]) Names.inits.update(tbl["inits"])
class Table(Object): cmds = Object() fulls = Object() names = Default() modules = Object() table = Object() @staticmethod def addcmd(func): n = func.__name__ Table.modules[n] = func.__module__ Table.cmds[n] = func @staticmethod def addcls(clz): n = clz.__name__.lower() if n not in Table.names: Table.names[n] = [] nn = "%s.%s" % (clz.__module__, clz.__name__) if nn not in Table.names[n]: Table.names[n].append(nn) @staticmethod def addmod(mod): n = mod.__spec__.name Table.fulls[n.split(".")[-1]] = n Table.table[n] = mod @staticmethod def getcls(name): if "." in name: mn, clsn = name.rsplit(".", 1) else: raise NoClass(name) mod = Table.getmod(mn) return getattr(mod, clsn, None) @staticmethod def getcmd(c): return Table.cmds.get(c, None) @staticmethod def getfull(c): return Table.fulls.get(c, None) @staticmethod def getmod(mn): return Table.table.get(mn, None) @staticmethod def getnames(nm, dft=None): return Table.names.get(nm, dft) @staticmethod def getmodule(mn, dft): return Table.modules.get(mn, dft)
def test_nested(self): o = Object() o.o = Object() o.o.o = Object() o.o.o.test = "bla" p = o.save() oo = Object() oo.load(p) self.assertEqual(o.o.o.test, "bla")
def __init__(self, line, source): Definition.__init__(self, line, '\\{([A-Z][a-zA-Z0-9]+)(>[A-Z][a-zA-Z0-9]+|)\\}$') Object.__init__(self, self.matches.group(1), source) if self.matches.group(2): self.parent = self.matches.group(2)[1:] else: self.parent = 'TreeEntry'
def __init__(self, line, source): Definition.__init__(self, line, '\\{([A-Z][a-zA-Z0-9]+)(>[A-Z][a-zA-Z0-9]+|)\\}$') Object.__init__(self, self.matches.group(1), source) Inheritable.__init__(self) Tree._known_objects.append(self) if self.matches.group(2): self.parent = self.matches.group(2)[1:] else: self.parent = 'TreeEntry'
def test_attribute(self): o = Object() o.bla = "test" p = o.save() oo = Object() oo.load(p) self.assertEqual(oo.bla, "test")
def hook(hfn): if hfn.count(os.sep) > 3: oname = hfn.split(os.sep)[-4:] else: oname = hfn.split(os.sep) cname = oname[0] fn = os.sep.join(oname) t = Kernel.getcls(cname) if fn: o = Object() o.__otype__ = t o.load(fn) return o else: raise ENOTYPE(cname)
def __init__(self): Client.__init__(self) Output.__init__(self) self.buffer = [] self.cfg = Cfg() self.connected = threading.Event() self.channels = [] self.sock = None self.joined = threading.Event() self.keeprunning = False self.outqueue = queue.Queue() self.speed = "slow" self.state = Object() self.state.needconnect = False self.state.error = "" self.state.last = 0 self.state.lastline = "" self.state.nrconnect = 0 self.state.nrerror = 0 self.state.nrsend = 0 self.state.pongcheck = False self.threaded = False self.users = Users() self.zelf = "" self.register("cmd", docmd) self.register("ERROR", ERROR) self.register("LOG", LOG) self.register("NOTICE", NOTICE) self.register("PRIVMSG", PRIVMSG) self.register("QUIT", QUIT)
class Loader(Object): table = Object() @staticmethod def boot(name=None, wd=None): if len(sys.argv) >= 1: parseargs(cfg, " ".join(sys.argv[1:])) cfg.update(cfg.sets) cfg.name = name or cfg.name cfg.wd = wd or cfg.wd def load(self, mnn): if mnn in Loader.table: return self.table[mnn] Loader.table[mnn] = direct(mnn) return Loader.table[mnn] def init(self, mns): for mn in spl(mns): m = Names.getinit(mn) if not m: continue mod = self.load(m) if mod and "init" in dir(mod): mod.init(self)
def __init__(self): super().__init__() self.cbs = Object() self.queue = queue.Queue() self.speed = "normal" self.stopped = threading.Event() self.register("cmd", Handler.dispatch)
def __init__(self): self.name = "BlocksWorld" # define objects A = Object("A") B = Object("B") C = Object("C") floor = Object("Fl") blocks = [A, B, C] self.A = A self.B = B self.C = C self.floor = floor # define goal (C on B on A on floor) goalLiterals = [] goalLiterals.append(On(A, floor)) goalLiterals.append(On(B, A)) goalLiterals.append(On(C, B)) self.goal = State(goalLiterals) # define initial state (C on B, B on floor, A on floor) initStateLiterals = [] initStateLiterals.append(On(C, B)) initStateLiterals.append(On(B, floor)) initStateLiterals.append(On(A, floor)) initStateLiterals.append(Clear(A)) initStateLiterals.append(Clear(C)) self.initialState = State(initStateLiterals) # create actions self.actions = [] for b in blocks: for bprime in blocks: if not (bprime == b): # move to floor self.actions.append(MoveToFloor(b, bprime, floor)) # move from floor self.actions.append(Move(b, floor, bprime)) for bpp in blocks: if not (bprime == b) and not (bprime == bpp) and not (b == bpp): self.actions.append(Move(b, bprime, bpp))
def getfeed(url): got = False if gotparser: try: result = geturl(url) if not result: got = False else: result = feedparser.parse(result.data) if result and "entries" in result: got = True for entry in result["entries"]: yield entry except (ValueError, HTTPError, URLError): pass if not got: return [Object(), Object()]
def findfuncs(mod): funcs = Object() for key, o in inspect.getmembers(mod, inspect.isfunction): if "event" in o.__code__.co_varnames: if o.__code__.co_argcount == 1: if key not in funcs: funcs[key] = "%s.%s" % (o.__module__, o.__name__) return funcs
def __init__(self, sleep, func, *args, name=None): super().__init__() self.args = args self.func = func self.sleep = sleep self.name = name or "" self.state = Object() self.timer = None
def findnames(mod): tps = Object() for _key, o in inspect.getmembers(mod, inspect.isclass): if issubclass(o, Object): t = "%s.%s" % (o.__module__, o.__name__) if t not in tps: tps[o.__name__.lower()] = t return tps
def findcmds(mod): cmds = Object() for key, o in inspect.getmembers(mod, inspect.isfunction): if "event" in o.__code__.co_varnames: if o.__code__.co_argcount == 1: if key not in cmds: cmds[key] = o return cmds
def get(self, obj, fields=None): if isinstance(obj, int): objid = obj obj = self._query_single( 'SELECT obj FROM obj WHERE objid = ?', (objid,)) else: objid = self._query_single( 'SELECT objid FROM obj WHERE obj = ?', (obj,)) obj = Object(obj) query = "SELECT key, timestamp, listid FROM map NATURAL JOIN key WHERE objid = ?" if fields is not None: query += " AND key IN (" + ', '.join(('?',) * len(fields)) + ")" for key, timestamp, listid in self._query_all(query, (objid,) + tuple(fields or ())): if listid is None: continue obj._dict[key] = ValueSet(v=(x for x, in self._query_all( "SELECT value FROM list WHERE listid = ?", (listid,))), t=timestamp) return obj
def test_last(self): o = Object() o.bla = "test" o.save() oo = Object() last(oo) self.assertEqual(oo.bla, "test")
def parse_obj_par(line): """Take object characteristis from string. Input string format: X_coord Y_coord Velocity_X Velocity_Y Mass Radius Color Parametrs: **line** — string with object characteristics. """ color = cl.Colors() obj = Object() obj.coords[0] = float(line.split()[0]) obj.coords[1] = float(line.split()[1]) obj.vel[0] = float(line.split()[2]) obj.vel[1] = float(line.split()[3]) obj.mass = float(line.split()[4]) obj.rad = float(line.split()[5]) obj.color = color.COLORS[int(line.split()[6])] return obj
def thr(event): psformat = "%s %s" result = [] for thr in sorted(threading.enumerate(), key=lambda x: x.getName()): if str(thr).startswith("<_"): continue o = Object() o.update(vars(thr)) if o.get("sleep", None): up = o.sleep - int(time.time() - o.state.latest) else: up = int(time.time() - starttime) thrname = thr.getName() if not thrname: continue if thrname: result.append((up, thrname)) res = [] for up, txt in sorted(result, key=lambda x: x[0]): res.append("%s(%s)" % (txt, elapsed(up))) if res: event.reply(" ".join(res))
def getfeed(url): try: import feedparser except ModuleNotFoundError: return [Object(), Object()] try: result = geturl(url) except (ValueError, HTTPError, URLError) as ex: return [Object(), Object()] if not result: return [Object(), Object()] else: result = feedparser.parse(result.data) if result and "entries" in result: for entry in result["entries"]: yield entry
class Users(Object): userhosts = Object() def allowed(self, origin, perm): perm = perm.upper() origin = getattr(self.userhosts, origin, origin) user = self.get_user(origin) if user: if perm in user.perms: return True return False def delete(self, origin, perm): for user in self.get_users(origin): try: user.perms.remove(perm) user.save() return True except ValueError: pass def get_users(self, origin=""): s = {"user": origin} return find("user", s) def get_user(self, origin): u = list(self.get_users(origin)) if u: return u[-1][-1] def perm(self, origin, permission): user = self.get_user(origin) if not user: raise ENOUSER(origin) if permission.upper() not in user.perms: user.perms.append(permission.upper()) user.save() return user
def test_stamp(self): o = Object() o.save() self.assertTrue(o.__stp__)
def test_changeattr(self): o = Object() o.bla = "test" p = o.save() oo = Object() oo.load(p) oo.bla = "mekker" pp = oo.save() ooo = Object() ooo.load(pp) self.assertEqual(ooo.bla, "mekker")
import numpy as np import cv2 import skimage.measure import subprocess, time import Faulhaber as FH import datetime, os, math from typing import List, Optional from obj import Object ########################################## ident = Object() ident.edge_counter = 0 ident.Tturn = 30 # Czas od ostatniego zobaczenia markera do awaryjnej zmiany kierunku ########################################## can0 = FH.Initialize() node_id = 5 print("Uruchamianie sterownika...") FH.SendNodeStartCommand(can0, node_id) time.sleep(1) print("Restart stopnia mocy...") FH.SendCommandToServomotor(can0, node_id, FH.Command.DI_DisableDrive, []) time.sleep(1) FH.SendCommandToServomotor(can0, node_id, FH.Command.EN_EnableDrive, []) time.sleep(1) FH.FindHomePosition(can0, 5)
def read(self, read_all=False, to_python=False): # "to_python" cannot be set without "read_all" assert read_all or not to_python self._skip_whitespace() # None if self._skip_if_next('null'): return None # False if self._skip_if_next('false'): return False # True if self._skip_if_next('true'): return True # Number if self._peek() in '-0123456789': num = self._get() # Check sign if num == '-': num += self._get() # Read integer part if num[-1] != '0': while self._peek() in '0123456789': num += self._get() # Read possible decimal part and convert to float if self._peek() == '.': self._get() num += '.' + self._get() if num[-1] not in '01234567890': raise Exception(u'Expected digit after dot!') while self._peek() in '0123456789': num += self._get() num = float(num) else: num = int(num) # Read possible exponent if self._peek() in 'eE': self._get() exp = self._get() exp_neg = False if exp == '-': exp_neg = True exp = self._get() elif exp == '+': exp = self._get() while self._peek() in '0123456789': exp += self._get() exp = int(exp) exp = 10 ** exp if exp_neg: num = float(num) / exp else: num *= exp return num # String if self._skip_if_next('"'): string = u'' while True: c = self._get() if c == u'"': break if c == u'\\': c = self._get() if c == u'"': string += u'"' elif c == u'\\': string += u'\\' elif c == u'/': string += u'/' elif c == u'b': string += u'\b' elif c == u'f': string += u'\f' elif c == u'n': string += u'\n' elif c == u'r': string += u'\r' elif c == u't': string += u'\t' elif c == u'u': unicode_bytes = self._read(4) string += ('\\u' + unicode_bytes).decode('unicode_escape') else: raise Exception(u'Unexpected {} in backslash encoding!'.format(c)) else: string += c return string # Array if self._peek() == '[': if to_python: array = Array(self, False) return array.to_python() else: return Array(self, read_all) # Object if self._peek() == '{': if to_python: obj = Object(self, False) return obj.to_python() else: return Object(self, read_all) raise Exception(u'Unexpected bytes!')
tar = control_target(tar, ti, sigma_ax, sigma_ay) targets[4 * j + 0, i] = tar[0, 0] targets[4 * j + 1, i] = tar[1, 0] targets[4 * j + 2, i] = tar[2, 0] targets[4 * j + 3, i] = tar[3, 0] # 初始化量测列表 objs_observed = [] # 获取量测 for j in range(nt): tar = np.array([[targets[4 * j + 0, i]], [targets[4 * j + 1, i]], [targets[4 * j + 2, i]], [targets[4 * j + 3, i]]]) x, y, flag = observe(tar, arange, sigma_ox, sigma_oy) if flag: obj = Object() obj.xref = x obj.yref = y objs_observed.append(obj) objs_observed_copy = objs_observed.copy() # 数据关联与跟踪 num = len(objs) for j in range(num): flag = False idx = 0 ddm = float('inf') n = len(objs_observed) for k in range(n): zx = objs_observed[k].xref