rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
f.write('INT_VERSION = %s\n' % iversion)
f.write('FLOAT_VERSION = %s\n' % iversion)
def _find_packages(kwargs, dirname, files): """ Helper function to create 'packages' and 'package_dir'. """ if not '__init__.py' in files: return python_dirname = 'kaa.' + kwargs['module'] + \ dirname[3:].replace('/', '.') kwargs['package_dir'][python_dirname] = dirname kwargs['packages'].append(python_dirname)
result_cb(result)
result_cb(self._proxy_data(result))
def handle_packet(self, seq, packet_type, payload): # Untaint packet_type. if len(packet_type) <= 4 or packet_type[:3] not in ("REP", "REQ") or \ not packet_type[4:].isalpha(): log.warning("Bad request from remote; disconnecting.") return self.handle_close()
return logging.LogRecord(name, level, fn, lno, msg, args, *_args, **_kwargs)
return self._makeRecord(name, level, fn, lno, msg, args, *_args, **_kwargs)
def make_record(self, name, level, fn, lno, msg, args, *_args, **_kwargs): """ A special makeRecord class for the logger to convert msg and args into strings using the correct encoding if they are unicode strings. This function also makes sure we have at least a basic handler. """ if len(self.root.handlers) == 0: # cre...
elif flag == Signal.SIGNAL_DISCONNETED and signal.count() == 0:
elif flag == Signal.SIGNAL_DISCONNECTED and signal.count() == 0:
def _idle_signal_changed(signal, flag, pos): if flag == Signal.SIGNAL_CONNECTED and signal.count() == 1: notifier.addDispatcher(signal.emit) elif flag == Signal.SIGNAL_DISCONNETED and signal.count() == 0: notifier.removeDispatcher(signal.emit)
objectcount = int(row[0])
objectcount = int(float(row[0]))
def _query_keywords(self, words, limit = 100, object_type = None): """ Queries the database for the keywords supplied in the words strings. (Search terms are delimited by spaces.)
cb.set_weakref_destroy_cb(destroy_cb)
cb.set_weakref_destroyed_cb(destroy_cb) cb.set_ignore_caller_args()
def weakref_data(data, destroy_cb = None): if type(data) in (str, int, long, types.NoneType): # Naive optimization for common immutable cases. return data elif type(data) == types.MethodType: cb = WeakCallback(data) if destroy_cb: cb.set_weakref_destroy_cb(destroy_cb) return cb elif type(data) in (list, tuple): d = [] ...
print "DESTROY CB", data, destroy_cb
def weakref_data(data, destroy_cb = None): if type(data) in (str, int, long, types.NoneType): # Naive optimization for common immutable cases. return data elif type(data) == types.MethodType: cb = WeakCallback(data) if destroy_cb: cb.set_weakref_destroy_cb(destroy_cb) return cb elif type(data) in (list, tuple): d = [] ...
return self._weakref_destroyed_user_cb(self, object)
return self._weakref_destroyed_user_cb(object)
def _weakref_destroyed(self, object): if self and self._weakref_destroyed_user_cb: return self._weakref_destroyed_user_cb(self, object)
callback.set_weakref_destroyed_cb(self._weakref_destroyed) data_cb = Callback(self._weakref_destroyed, callback) data_cb.set_user_args_first() args, kwargs = weakref_data(args, data_cb), weakref_data(kwargs, data_cb)
destroy_cb = Callback(self._weakref_destroyed, callback) destroy_cb.set_user_args_first() callback.set_weakref_destroyed_cb(destroy_cb) args = weakref_data(args, destroy_cb) kwargs = weakref_data(kwargs, destroy_cb)
def _connect(self, callback, args = (), kwargs = {}, once = False, weak = False, pos = -1):
result = dict(zip(col_desc, row))
result = attrs_defaults[type_name].copy() result.update(dict(zip(col_desc, row)))
def normalize_query_results(self, (query_info, results)): """ Takes a results tuple as returned from query() and converts to a list of dicts. Each result dict is given a "type" entry which corresponds to the type name of that object. This function also unpickles the pickle contained in the row, and creates a "parent"...
if "pickle" in result: result.update(attrs_defaults[type_name]) if result["pickle"]: pickle = cPickle.loads(str(result["pickle"])) result.update(pickle) del result["pickle"]
if result["pickle"]: pickle = cPickle.loads(str(result["pickle"])) result.update(pickle) del result["pickle"]
def normalize_query_results(self, (query_info, results)): """ Takes a results tuple as returned from query() and converts to a list of dicts. Each result dict is given a "type" entry which corresponds to the type name of that object. This function also unpickles the pickle contained in the row, and creates a "parent"...
def check(self, minver):
def versionnum(self, version, numelements): re_elements = re.compile('([0-9]+)') elements = re_elements.findall(version) num = 0 for i in range(0,numelements): num = num * 10 num = num + (i < len(elements) and int(elements[i]) or 0) return num def check(self, minver, numelements=3):
def check(self, minver): """ Check dependencies add add the flags to include_dirs, library_dirs and libraries. The basic logic is taken from pygame. """ print 'checking for', self.name, '>=', minver, '...', sys.__stdout__.flush()
if minver and version < minver: print 'no (%s)' % version return False
if minver: minnum = self.versionnum(minver, numelements) vernum = self.versionnum(version, numelements) if vernum < minnum: print 'no (%s)' % version return False
def check(self, minver): """ Check dependencies add add the flags to include_dirs, library_dirs and libraries. The basic logic is taken from pygame. """ print 'checking for', self.name, '>=', minver, '...', sys.__stdout__.flush()
self.descr = unicode(self.descr, ENCODING, 'r')
self.descr = unicode(self.descr, ENCODING, 'replace')
def __init__(self, name, type='', descr=u'', default=None): self.name = name self.type = type self.descr = descr self.default = default self.value = default if type == '': if default == None: raise AttributeError('define type or default') self.type = default.__class__ if not descr and hasattr(default, '_descr'): self.d...
descr = '
descr = ' replace('\n', '\n
def _cfg_string(self, prefix, print_descr=True): if not prefix.endswith(']'): prefix = prefix + self.name if hasattr(self.value, '_cfg_string'): return self.value._cfg_string(prefix, print_descr) descr = newline = '' if print_descr: descr = '# %s\n' % self.descr.encode(ENCODING, 'r').replace('\n', '\n# ') newline = '\n...
value = self.value.encode(ENCODING, 'r')
value = self.value.encode(ENCODING, 'replace')
def _cfg_string(self, prefix, print_descr=True): if not prefix.endswith(']'): prefix = prefix + self.name if hasattr(self.value, '_cfg_string'): return self.value._cfg_string(prefix, print_descr) descr = newline = '' if print_descr: descr = '# %s\n' % self.descr.encode(ENCODING, 'r').replace('\n', '\n# ') newline = '\n...
self._descr = unicode(self._descr, ENCODING, 'r')
self._descr = unicode(self._descr, ENCODING, 'replace')
def __init__(self, schema, descr=u'', name=''): self._dict = {} self._vars = [] self._descr = descr self._name = name for data in copy.deepcopy(schema): if not isinstance(data, Var): if not data._name: raise AttributeError('Inline Group needs name') data = Var(name=data._name, default=data) self._dict[data.name] = d...
desc = self._descr.encode(ENCODING, 'r').replace('\n', '\n
desc = self._descr.encode(ENCODING, 'replace').replace('\n', '\n
def _cfg_string(self, prefix, print_descr=True): ret = [] desc = self._descr.encode(ENCODING, 'r').replace('\n', '\n# ') if prefix: if print_descr: ret.append('#\n# %s\n# %s\n#\n' % (prefix, desc)) prefix += '.' for name in self._vars: var = self._dict[name] ret.append(var._cfg_string(prefix, print_descr)) return '\n'...
self._descr = unicode(self._descr, ENCODING, 'r')
self._descr = unicode(self._descr, ENCODING, 'replace')
def __init__(self, schema, descr=u'', name='', type=unicode): if not isinstance(schema, Var): schema = Var(name=name, default=schema) self._schema = copy.deepcopy(schema) self._dict = {} self._type = type self._descr = descr self._name = name if isinstance(self._descr, str): self._descr = unicode(self._descr, ENCOD...
index = unicode(index, ENCODING, 'r')
index = unicode(index, ENCODING, 'replace')
def __setitem__(self, index, value): if not isinstance(index, self._type): # this could crash, we don't care. if self._type == unicode and type(index) == str: index = unicode(index, ENCODING, 'r') elif self._type == str and type(index) == unicode: index = index.encode(ENCODING, 'r') index = self._type(index) if not ind...
index = index.encode(ENCODING, 'r')
index = index.encode(ENCODING, 'replace')
def __setitem__(self, index, value): if not isinstance(index, self._type): # this could crash, we don't care. if self._type == unicode and type(index) == str: index = unicode(index, ENCODING, 'r') elif self._type == str and type(index) == unicode: index = index.encode(ENCODING, 'r') index = self._type(index) if not ind...
(prefix, self._descr.encode(ENCODING, 'r')))
(prefix, self._descr.encode(ENCODING, 'replace')))
def _cfg_string(self, prefix, print_descr=True): ret = [] if type(self._schema) == Var and print_descr: ret.append('#\n# %s\n# %s\n#\n' % \ (prefix, self._descr.encode(ENCODING, 'r'))) print_descr = False
key = key.encode(ENCODING, 'r')
key = key.encode(ENCODING, 'replace')
def _cfg_string(self, prefix, print_descr=True): ret = [] if type(self._schema) == Var and print_descr: ret.append('#\n# %s\n# %s\n#\n' % \ (prefix, self._descr.encode(ENCODING, 'r'))) print_descr = False
if os.system("%s-config --version &>/dev/null" % name) == 0:
if os.system("pkg-config %s --exists &>/dev/null" % name) == 0: command = "pkg-config %s %%s 2>/dev/null" % name if minver: if not os.system(command % '--atleast-version %s' % minver) == 0: err= 'requires %s version %s' % (name, minver) raise ValueError, err elif os.system("%s-config --version &>/dev/null" % name) == ...
def check_library(self, name, minver): """ Check dependencies add add the flags to include_dirs, library_dirs and libraries. The basic logic is taken from pygame. """ try: if os.system("%s-config --version &>/dev/null" % name) == 0: # Use foo-config if it exists. command = "%s-config %%s 2>/dev/null" % name version_arg...
version_arg = "--version" elif os.system("pkg-config %s --exists &>/dev/null" % name) == 0: command = "pkg-config %s %%s 2>/dev/null" % name version_arg = "--modversion"
version = os.popen(command % '--version').read().strip() if len(version) == 0: raise ValueError, 'command not found' if minver and version < minver: err= 'requires %s version %s (%s found)' % \ (name, minver, version) raise ValueError, err
def check_library(self, name, minver): """ Check dependencies add add the flags to include_dirs, library_dirs and libraries. The basic logic is taken from pygame. """ try: if os.system("%s-config --version &>/dev/null" % name) == 0: # Use foo-config if it exists. command = "%s-config %%s 2>/dev/null" % name version_arg...
raise Exception, "not found" version = os.popen(command % version_arg).read().strip() if len(version) == 0: raise ValueError, 'command not found' if minver and version < minver: err= 'requires %s version %s (%s found)' % \ (name, minver, version) raise ValueError, err
raise ValueError, "%s is not installed" % name
def check_library(self, name, minver): """ Check dependencies add add the flags to include_dirs, library_dirs and libraries. The basic logic is taken from pygame. """ try: if os.system("%s-config --version &>/dev/null" % name) == 0: # Use foo-config if it exists. command = "%s-config %%s 2>/dev/null" % name version_arg...
log.error("New connection %s", client_sock)
log.info("New connection %s", client_sock)
def _new_connection(self): """ Callback when a new client connects. """ client_sock = self.socket.accept()[0] client_sock.setblocking(False) log.error("New connection %s", client_sock) client = Channel(socket = client_sock, auth_secret = self._auth_secret) for obj in self.objects: client.connect(obj) self.signals["clie...
self.configfile = config
self.configfile = os.path.abspath(config)
def __init__(self, output, files, include_dirs=[], library_dirs=[], libraries=[], config=None): """ Init the Extention object. """ self.output = output self.files = files self.include_dirs = include_dirs self.library_dirs = library_dirs self.libraries = libraries if config: self.configfile = config else: self.configfil...
if line[10:-1] == kwargs['version']:
if line[11:-2] == kwargs['version']:
def _find_packages(kwargs, dirname, files): """ Helper function to create 'packages' and 'package_dir'. """ if not '__init__.py' in files: return python_dirname = 'kaa.' + kwargs['module'] + \ dirname[3:].replace('/', '.') kwargs['package_dir'][python_dirname] = dirname kwargs['packages'].append(python_dirname)
import socket, os, select, time, types, struct, cPickle, thread, sys
import socket, os, select, time, types, struct, cPickle, thread, sys, sha
# def bar(self):
IPC_DEFAULT_TIMEOUT = 5.0 DEBUG=1
# def bar(self):
def __init__(self, address):
def __init__(self, address, auth_secret = None): self._auth_secret = auth_secret
def __init__(self, address): if type(address) in types.StringTypes: if address.find('/') == -1: # create socket in kaa temp dir address = '%s/%s' % (kaa.TEMP, address) if os.path.exists(address): # maybe a server is already running at this address, test it try: s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.c...
client = IPCChannel(self, client_sock)
client = IPCChannel(self, auth_secret = self._auth_secret, sock = client_sock)
def handle_connection(self): client_sock = self.socket.accept()[0] client_sock.setblocking(False) _debug(1, "New connection", client_sock) client = IPCChannel(self, client_sock) self.clients[client_sock] = client self.signals["client_connected"].emit(client)
del self.clients[client.socket]
if client.socket in self.clients: del self.clients[client.socket]
def close_connection(self, client): if client.socket: client.socket.close() del self.clients[client.socket] client.socket = None self.signals["client_closed"].emit(client)
def __init__(self, server_or_address, sock = None):
def __init__(self, server_or_address, auth_secret = None, sock = None):
def __init__(self, server_or_address, sock = None): if not sock: if type(server_or_address) in types.StringTypes: server_or_address = '%s/%s' % (kaa.TEMP, server_or_address) self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) if type(server_or_address) == tuple: self.socket = socket.socket(socket.AF_INET, s...
self._default_timeout = 2.0 self.signals = { "closed": kaa.notifier.Signal() }
self._default_timeout = IPC_DEFAULT_TIMEOUT self._auth_secret = auth_secret self._authenticated = False self.authenticate() def _get_auth_challenge(self): return file("/dev/urandom").read(64) def _get_challenge_response(self, challenge): m = self._auth_secret + challenge return sha.sha(sha.sha(m).digest() + m).diges...
def __init__(self, server_or_address, sock = None): if not sock: if type(server_or_address) in types.StringTypes: server_or_address = '%s/%s' % (kaa.TEMP, server_or_address) self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) if type(server_or_address) == tuple: self.socket = socket.socket(socket.AF_INET, s...
if timeout == None:
if timeout == reply_cb == None:
def _send_packet(self, packet_type, data, seq = 0, timeout = None, reply_cb = None): if not self.socket: return
self._wait_queue[seq] = [data, False, None, time.time(), reply_cb] if timeout == 0: self._wait_queue[seq][1] = None
self._wait_queue[seq] = [data, None, None, time.time(), reply_cb] if timeout > 0: self._wait_queue[seq][1] = False
def _send_packet(self, packet_type, data, seq = 0, timeout = None, reply_cb = None): if not self.socket: return
if timeout == None:
if timeout == reply_cb == None:
def request(self, type, data, timeout = None, reply_cb = None): if timeout == None: timeout = self._default_timeout
clstype = type(value) newclass = classobj("VarProxy", (clstype, cls), {})
clstype = realclass = type(value) if clstype == bool: clstype = int newclass = classobj("VarProxy", (clstype, cls), { "__getattribute__": cls.__getattribute__, "__str__": cls.__str__, })
def __new__(cls, value = None, monitors = [], parent = None): clstype = type(value) newclass = classobj("VarProxy", (clstype, cls), {}) if value: return newclass(value) else: return newclass()
return newclass(value)
self = newclass(value)
def __new__(cls, value = None, monitors = [], parent = None): clstype = type(value) newclass = classobj("VarProxy", (clstype, cls), {}) if value: return newclass(value) else: return newclass()
return newclass()
self = newclass() self._class = realclass return self
def __new__(cls, value = None, monitors = [], parent = None): clstype = type(value) newclass = classobj("VarProxy", (clstype, cls), {}) if value: return newclass(value) else: return newclass()
if self._instance():
if self._instance() != None:
def _get_callback(self): if self._instance: if self._instance(): return getattr(self._instance(), self._callback) else: return self._callback
cb_callback = cb_callback._get_callback() cb_args, cb_kwargs = unweakref_data((cb_args, cb_kwargs)) if (cb_callback == callback and len(args) == 0) or \ (cb_callback, cb_args, cb_kwargs) == (callback, args, kwargs):
cb_callback_u = cb_callback._get_callback() cb_args_u, cb_kwargs_u = unweakref_data((cb_args, cb_kwargs)) else: cb_callback_u = cb_args_u = cb_kwargs_u = None if (callback in (cb_callback, cb_callback_u) and len(args) == 0) or \ (cb_callback, cb_args, cb_kwargs) == (callback, args, kwargs) or \ (cb_callback_u, cb_args...
def _disconnect(self, callback, args, kwargs): new_callbacks = [] for cb in self._callbacks[:]: cb_callback, cb_args, cb_kwargs, cb_once, cb_weak = cb if cb_weak: cb_callback = cb_callback._get_callback() cb_args, cb_kwargs = unweakref_data((cb_args, cb_kwargs))
self._disconnect(callback, None, None)
self._disconnect(callback, (), None)
def _weakref_destroyed(self, callback, weakref): if Signal and self: self._disconnect(callback, None, None)
monitor = kaa.notifier.SocketDispatcher(self.handle_connection) monitor.register(self.socket)
self._monitor = kaa.notifier.SocketDispatcher(self.handle_connection) self._monitor.register(self.socket.fileno())
def __init__(self, address, auth_secret = None): self._auth_secret = auth_secret if type(address) in types.StringTypes: if address.find('/') == -1: # create socket in kaa temp dir address = '%s/%s' % (kaa.TEMP, address) if os.path.exists(address): # maybe a server is already running at this address, test it try: s = s...
def close_connection(self, client): if client.socket: client.socket.close() if client.socket in self.clients: del self.clients[client.socket] client.socket = None
def client_closed(self, client): if client.socket in self.clients: del self.clients[client.socket]
def close_connection(self, client): if client.socket: client.socket.close() if client.socket in self.clients: del self.clients[client.socket] client.socket = None self.signals["client_closed"].emit(client)
self.close_connection(client)
client.handle_close()
def close(self): for client in self.clients.values(): self.close_connection(client)
if self.server: self.server.close_connection(self) else:
if self.socket:
def handle_close(self): _debug(1, "Client closed", self.socket) _debug(1, "Current proxied objects", self._proxied_objects) self._rmon.unregister() self._wmon.unregister() if self.server: self.server.close_connection(self) else: self.socket.close() self.socket = None
self._db.row_factory = kaa._objectrow.ObjectRow
self._db.row_factory = ObjectRow
def _open_db(self): self._db = sqlite.connect(self._dbfile) self._cursor = self._db.cursor() self._cursor.execute("PRAGMA synchronous=OFF") #self._cursor.execute("PRAGMA temp_store=MEMORY") self._cursor.execute("PRAGMA count_changes=OFF") self._cursor.execute("PRAGMA cache_size=50000")
return kaa._objectrow.ObjectRow(DummyCursor(), row, attrs)
return ObjectRow(DummyCursor(), row, attrs)
def add_object(self, object_type, parent = None, **attrs): """ Adds an object of type 'object_type' to the database. Parent is a (type, id) tuple which refers to the object's parent. 'object_type' and 'type' is a type name as given to register_object_type_attrs(). attrs kwargs will vary based on object type. ATTR_SI...
def _handle_stdin_keypress(fd):
def _handle_stdin_keypress():
def _handle_stdin_keypress(fd): ch = getch() kaa.signals["stdin_key_press_event"].emit(ch) return True
self._watch_timer = WeakTimer(self._check_file_changed) try: self._inotify = INotify() except SystemError: self._inotify = None
self._watch_timer = NoCopyCallback(WeakTimer(self._check_file_changed))
def __init__(self, schema, desc=u'', name=''): Group.__init__(self, schema, desc, name) self._filename = None self._bad_lines = []
if self._inotify: self._inotify.ignore(self._filename)
if _inotify: _inotify.ignore(self._filename)
def watch(self, watch = True): """ If argument is True (default), adds a watch to the config file and will reload the config if it changes. If INotify is available, use that, otherwise stat the file every 3 seconds.
if self._inotify:
if _inotify:
def watch(self, watch = True): """ If argument is True (default), adds a watch to the config file and will reload the config if it changes. If INotify is available, use that, otherwise stat the file every 3 seconds.
signal = self._inotify.watch(self._filename)
signal = _inotify.watch(self._filename)
def watch(self, watch = True): """ If argument is True (default), adds a watch to the config file and will reload the config if it changes. If INotify is available, use that, otherwise stat the file every 3 seconds.
if self._inotify:
if _inotify:
def _check_file_changed(self): try: mtime = os.stat(self._filename)[stat.ST_MTIME] except: # Config file not available. return
DEBUG=0
# def bar(self):
self.wait_queue = {}
self._wait_queue = {}
def __init__(self, server_or_address, sock = None): if not sock: if type(server_or_address) in types.StringTypes: server_or_address = '%s/%s' % (kaa.TEMP, server_or_address) self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) if type(server_or_address) == tuple: self.socket = socket.socket(socket.AF_INET, s...
self.socket = None
self.handle_close()
def handle_write(self): if not self.writable(): return
if seq not in self.wait_queue:
if seq not in self._wait_queue:
def handle_packet(self, packet): # FIXME: loads() could raise an exception if trying to unpickle an # unknown object (like an exception). (seq, packet_type, data) = cPickle.loads(packet) if packet_type[:3] == "REP": _debug(1, "-> REPLY: seq=%d, type=%s, data=%d" % (seq, packet_type, len(packet))) if seq not in self.wai...
if self.wait_queue[seq][1] == False:
if self._wait_queue[seq][1] == False:
def handle_packet(self, packet): # FIXME: loads() could raise an exception if trying to unpickle an # unknown object (like an exception). (seq, packet_type, data) = cPickle.loads(packet) if packet_type[:3] == "REP": _debug(1, "-> REPLY: seq=%d, type=%s, data=%d" % (seq, packet_type, len(packet))) if seq not in self.wai...
self.wait_queue[seq][1] = True self.wait_queue[seq][2] = (seq, packet_type, data)
self._wait_queue[seq][1] = True self._wait_queue[seq][2] = (seq, packet_type, data)
def handle_packet(self, packet): # FIXME: loads() could raise an exception if trying to unpickle an # unknown object (like an exception). (seq, packet_type, data) = cPickle.loads(packet) if packet_type[:3] == "REP": _debug(1, "-> REPLY: seq=%d, type=%s, data=%d" % (seq, packet_type, len(packet))) if seq not in self.wai...
del self.wait_queue[seq]
del self._wait_queue[seq]
def handle_packet(self, packet): # FIXME: loads() could raise an exception if trying to unpickle an # unknown object (like an exception). (seq, packet_type, data) = cPickle.loads(packet) if packet_type[:3] == "REP": _debug(1, "-> REPLY: seq=%d, type=%s, data=%d" % (seq, packet_type, len(packet))) if seq not in self.wai...
raise IPCDisconnectedError("Remote end no longer connected")
return
def _send_packet(self, packet_type, data, seq = 0, timeout = None): if not self.socket: raise IPCDisconnectedError("Remote end no longer connected") if timeout == None: timeout = self._default_timeout if seq == 0: seq = self.last_seq = self.last_seq + 1
self.wait_queue[seq] = [data, False, None]
self._wait_queue[seq] = [data, False, None, time.time()]
def _send_packet(self, packet_type, data, seq = 0, timeout = None): if not self.socket: raise IPCDisconnectedError("Remote end no longer connected") if timeout == None: timeout = self._default_timeout if seq == 0: seq = self.last_seq = self.last_seq + 1
self.wait_queue[seq][1] = None
self._wait_queue[seq][1] = None
def _send_packet(self, packet_type, data, seq = 0, timeout = None): if not self.socket: raise IPCDisconnectedError("Remote end no longer connected") if timeout == None: timeout = self._default_timeout if seq == 0: seq = self.last_seq = self.last_seq + 1
while self.wait_queue[seq][1] == False and time.time() - t0 < timeout and self.socket:
while self._wait_queue[seq][1] == False and time.time() - t0 < timeout and self.socket:
def _send_packet(self, packet_type, data, seq = 0, timeout = None): if not self.socket: raise IPCDisconnectedError("Remote end no longer connected") if timeout == None: timeout = self._default_timeout if seq == 0: seq = self.last_seq = self.last_seq + 1
if timeout > 0 and self.wait_queue[seq][1]: seq, type, (resultcode, data) = self.wait_queue[seq][2] del self.wait_queue[seq]
if timeout > 0 and self._wait_queue[seq][1]: seq, type, (resultcode, data) = self._wait_queue[seq][2] del self._wait_queue[seq]
def request(self, type, data, timeout = None): if timeout == None: timeout = self._default_timeout
_debug(1, "-> Refcount-- on object", objid)
_debug(1, "-> Refcount-- on local object", objid)
def handle_request_decref(self, objid): if objid not in self._proxied_objects: return _debug(1, "-> Refcount-- on object", objid) self._decref_proxied_object(objid)
_debug(1, "-> Refcount++ on object", objid)
_debug(1, "-> Refcount++ on local object", objid)
def handle_request_incref(self, objid): if objid not in self._proxied_objects: return _debug(1, "-> Refcount++ on object", objid) self._incref_proxied_object(objid)
_debug(1, "-> Refcount=0; EXPIRING object", objid, type(self._proxied_objects[objid][0]))
_debug(1, "-> Refcount=0; EXPIRING local proxied object", objid, type(self._proxied_objects[objid][0]))
def _decref_proxied_object(self, objid): if objid in self._proxied_objects: self._proxied_objects[objid][1] -= 1 if self._proxied_objects[objid][1] == 0: _debug(1, "-> Refcount=0; EXPIRING object", objid, type(self._proxied_objects[objid][0])) del self._proxied_objects[objid] else: _debug(1, "<- Refcount-- on object", ...
_debug(1, "<- Refcount-- on object", objid)
_debug(1, "<- Refcount-- on remote object", objid)
def _decref_proxied_object(self, objid): if objid in self._proxied_objects: self._proxied_objects[objid][1] -= 1 if self._proxied_objects[objid][1] == 0: _debug(1, "-> Refcount=0; EXPIRING object", objid, type(self._proxied_objects[objid][0])) del self._proxied_objects[objid] else: _debug(1, "<- Refcount-- on object", ...
if self._ipc_obj in self._ipc_client._proxied_objects: self._ipc_client._decref_proxied_object(self._ipc_obj) elif self._ipc_client.socket: self._ipc_client.request("DECREF", self._ipc_obj, timeout = 0)
self._ipc_client._decref_proxied_object(self._ipc_obj)
def __del__(self): # Test _debug function too. If it's None it means we're on shutdown. # This is just a hack to silence "ignored exception" messages. if not self._ipc_client or not _debug: return
def __init__(self, _obj=None):
def __init__(self, _obj=None, content=None, **attrs):
def __init__(self, _obj=None): if isinstance(_obj, (str, unicode)): _obj = libxml2mod.xmlNewNode(_obj) if type(_obj).__name__ != 'PyCObject': raise TypeError, 'Node needs a PyCObject argument' self._o = _obj
libxml2mod.xmlNodeSetContent(self._o, content.encode('utf-8'))
if isinstance(content, unicode): content = content.encode('utf-8') if not isinstance(content, str): content = str(content) content = content.replace('&', '&amp;') libxml2mod.xmlNodeSetContent(self._o, content) def set_content_raw(self, content): if isinstance(content, unicode): content = content.encode('utf-8') if not...
def set_content(self, content): libxml2mod.xmlNodeSetContent(self._o, content.encode('utf-8'))
if isinstance(content, unicode): content = content.encode('utf-8') if content and not isinstance(content, str): content = str(content)
if hasattr(name_or_child, '__xml__'): ret = libxml2mod.xmlAddChild(self._o, name_or_child.__xml__()._o) if ret is None: raise TreeError('xmlAddChild() failed') return Node(_obj=ret) if content: if isinstance(content, unicode): content = content.encode('utf-8') if not isinstance(content, str): content = str(content) co...
def add_child(self, name_or_child, content=None, **attrs): if isinstance(name_or_child, Node): ret = libxml2mod.xmlAddChild(self._o, name_or_child._o) if ret is None: raise TreeError('xmlAddChild() failed') return Node(_obj=ret)
return libxml2mod.xmlSaveFormatFile(filename, self._doc._o, 1)
return self._doc.save(filename)
def save(self, filename): if self._doc: # this is not real doc, it is the root node return libxml2mod.xmlSaveFormatFile(filename, self._doc._o, 1) # delete old file (just in case) if os.path.isfile(filename): os.unlink(filename) return libxml2mod.xmlSaveFormatFile(filename, self._o, 1)
return libxml2mod.xmlSaveFormatFile(filename, self._o, 1)
return libxml2mod.xmlSaveFormatFileEnc(filename, self._o, 'UTF-8', 1)
def save(self, filename): if self._doc: # this is not real doc, it is the root node return libxml2mod.xmlSaveFormatFile(filename, self._doc._o, 1) # delete old file (just in case) if os.path.isfile(filename): os.unlink(filename) return libxml2mod.xmlSaveFormatFile(filename, self._o, 1)
DEBUG=1
DEBUG=0
# def bar(self):
kaa.signals["shutdown"].connect(lambda file: os.unlink(file), address)
kaa.signals["shutdown"].connect_weak(self.close)
def __init__(self, address): if type(address) in types.StringTypes: if address.find('/') == -1: # create socket in kaa temp dir address = '%s/%s' % (kaa.TEMP, address) if os.path.exists(address): # maybe a server is already running at this address, test it try: s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.c...
client.socket.close() del self.clients[client.socket]
if client.socket: client.socket.close() del self.clients[client.socket]
def close_connection(self, client): client.socket.close() del self.clients[client.socket] client.socket = None self.signals["client_closed"].emit(client)
client.socket.close() self.socket.close()
self.close_connection(client) if self.socket: self.socket.close()
def close(self): for client in self.clients.values(): client.socket.close() self.socket.close() if type(self.address) in types.StringTypes and os.path.exists(self.address): os.unlink(self.address)
while self._wait_queue[seq][1] == False and time.time() - t0 < timeout and self.socket:
while self.socket and self._wait_queue[seq][1] == False and time.time() - t0 < timeout:
def _send_packet(self, packet_type, data, seq = 0, timeout = None): if not self.socket: return
self._ipc_client._decref_proxied_object(self._ipc_obj)
try: self._ipc_client._decref_proxied_object(self._ipc_obj) except IPCDisconnectedError: pass
def __del__(self): # Test _debug function too. If it's None it means we're on shutdown. # This is just a hack to silence "ignored exception" messages. if not self._ipc_client or not _debug: return
print key
def iter_raw_data((query_info, rows), columns): """ Takes query data (the tuple returned by Database.query_raw()) and returns a generator that iterates over the rows in the result set, where each iteration provides a tuple of attributes corresponding to the tuple of column names in the columns parameter. e.g. for foo,...
print extra
def iter_raw_data((query_info, rows), columns): """ Takes query data (the tuple returned by Database.query_raw()) and returns a generator that iterates over the rows in the result set, where each iteration provides a tuple of attributes corresponding to the tuple of column names in the columns parameter. e.g. for foo,...
return cmp(self._get_callback(), func)
return cmp(id(self), id(func)) or cmp(self._get_callback(), func)
def __cmp__(self, func): """ Compares the given function with the callback function we're wrapping. """ return cmp(self._get_callback(), func)
if self and self._weakref_destroyed_user_cb: return self._weakref_destroyed_user_cb(object)
try: if self and self._weakref_destroyed_user_cb: return self._weakref_destroyed_user_cb(object) except: log.exception("Exception raised during weakref destroyed callback")
def _weakref_destroyed(self, object): if self and self._weakref_destroyed_user_cb: return self._weakref_destroyed_user_cb(object)
assert(callback != None)
assert(callable(callback))
def _disconnect(self, callback, args, kwargs): assert(callback != None) new_callbacks = [] for cb in self._callbacks[:]: cb_callback, cb_args, cb_kwargs, cb_once, cb_weak = cb if cb_weak: cb_callback_u = cb_callback._get_callback() cb_args_u, cb_kwargs_u = unweakref_data((cb_args, cb_kwargs)) else: cb_callback_u = cb_a...
is_move = None
def _handle_data(self): data = os.read(self._fd, 32768) self._read_buffer += data is_move = None
if is_move: wd, mask, cookie, path = is_move self._watches[wd][0].emit(mask, path) self.signals["event"].emit(mask, path)
if self._move_state: self._moved_timer.start(0.1)
def _handle_data(self): data = os.read(self._fd, 32768) self._read_buffer += data is_move = None
is_move = wd, mask, cookie, path
self._move_state = wd, mask, cookie, path
def _handle_data(self): data = os.read(self._fd, 32768) self._read_buffer += data is_move = None
if is_move: if mask & INotify.MOVED_TO and cookie == is_move[2]: mask |= INotify.MOVED_FROM self._watches[is_move[0]][0].emit(mask, is_move[3], path) self._watches[wd][0].emit(mask, is_move[3], path) self.signals["event"].emit(mask, is_move[3], path) is_move = None continue wd, cookie, path = is_move self._watches...
def _handle_data(self): data = os.read(self._fd, 32768) self._read_buffer += data is_move = None
log.debug('calling callback on inactive timer (%s)' % repr(self))
log.error('calling callback on inactive timer (%s)' % repr(self))
def __call__(self, *args, **kwargs): if not self.active(): # This happens if previous timer that has been called during the # same notifier step has stopped us. This is a workaround to a # bug that exists in notifier. log.debug('calling callback on inactive timer (%s)' % repr(self)) return False
log.error('calling inactivate callback for %s', self) import traceback traceback.print_stack()
log.debug('calling callback on inactive timer (%s)' % repr(self))
def __call__(self, *args, **kwargs): if not self.active(): # This should not happen, but it does. Somewhere deep inside the # notifier code is a bug log.error('calling inactivate callback for %s', self) import traceback traceback.print_stack() return False
__dispatcher.remove( method )
__dispatchers.remove( method )
def dispatcher_remove( method ): """Removes an external dispatcher function from the list""" global __dispatchers if method in __dispatchers: __dispatcher.remove( method )
DEBUG=2
DEBUG=1
# def bar(self):
packet_len = struct.unpack("l", self.read_buffer[0][:4])[0]
packet_len = struct.unpack("I", self.read_buffer[0][:4])[0]
def handle_read(self): try: data = self.socket.recv(1024*1024) except socket.error, (errno, msg): if errno == 11: # Resource temporarily unavailable -- we are trying to read # data on a socket when none is available. return # If we're here, then the socket is likely disconnected. data = None
packet_len = struct.unpack("l", strbuf[:4])[0]
packet_len = struct.unpack("I", strbuf[:4])[0]
def handle_read(self): try: data = self.socket.recv(1024*1024) except socket.error, (errno, msg): if errno == 11: # Resource temporarily unavailable -- we are trying to read # data on a socket when none is available. return # If we're here, then the socket is likely disconnected. data = None