rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.__init()
def children(self): self.__init() retval = []
self.__parse() def __parse(self):
def _init(self):
def __init__(self,level,pointer,tag,value,dict): Element.__init__(self,level,pointer,tag,value,dict)
self.__parse()
def husband(self): """ Return husband this family """ self.__parse() #__init__ didn't run parse, I don't know why return self.__husband
self.__parse()
def wife(self): """ Return wife this family """ self.__parse() #__init__ didn't run parse, I don't know why return self.__wife
self.__parse()
def parents(self): """ Return list of parents in this family """ self.__parse() #__init__ didn't run parse, I don't know why return [self.__husband, self.__wife]
while(me['new'] != [] and him['new'] != []):
while(me['new'] != [] or him['new'] != []):
def common_ancestor(self, relative): """ Find a common ancestor with a relative """
print self.children()
def parse(self): print self.children() for e in self.children(): if e.value() != None: if e.tag() == "HUSB": self.__husband = e.value() elif e.tag() == "WIFE": self.__wife = e.value() elif e.tag() == "CHIL": self.__children.append(e.value())
self.__children = [] self.__parse() def __parse(self):
def __init__(self,level,pointer,tag,value,dict): Element.__init__(self,level,pointer,tag,value,dict)
elif e.tag() == "CHIL": self.__children.append(e.value())
def __parse(self): for e in self.children(): if e.value() != None: if e.tag() == "HUSB": self.__husband = e.value() elif e.tag() == "WIFE": self.__wife = e.value() elif e.tag() == "CHIL": self.__children.append(e.value())
self._parse_line(number,line)
self._parse_line(number,line.decode("utf-8"))
def _parse(self,file): # open file # go through the lines f = open(file) number = 1 for line in f.readlines(): self._parse_line(number,line) number += 1
error = "Gedcom format error on line " + str(number) + ': ' + text
error = "Gedcom format error on line " + unicode(number) + ': ' + text
def _error(self,number,text): error = "Gedcom format error on line " + str(number) + ': ' + text raise GedcomParseError(error)
print string.join([str(e.level()),e.xref(),e.tag(),e.value()])
print string.join([unicode(e.level()),e.xref(),e.tag(),e.value()])
def _print(self): for e in self.line_list: print string.join([str(e.level()),e.xref(),e.tag(),e.value()])
result = str(self)
result = unicode(self)
def gedcom(self): """ Return GEDCOM code for this line and all of its sub-lines """ result = str(self) for e in self.children_lines(): result += '\n' + e.gedcom() return result
result = str(self.level())
result = unicode(self.level())
def __str__(self): """ Format this line as its original string """ result = str(self.level()) if self.xref() != "": result += ' ' + self.xref() result += ' ' + self.tag() if self.value() != "": result += ' ' + self.value() return result
self.g = Gedcom('/home/nick/code/gedrep/test/mcintyre.ged')
self.g = Gedcom(os.path.abspath('test/mcintyre.ged'))
def setUp(self): self.g = Gedcom('/home/nick/code/gedrep/test/mcintyre.ged')
command = "scsi_id -g -u -s /block/%s" % os.path.realpath(dev_disk_by_path).split('/dev/')[1]
command = "scsi_id -g -u /dev/%s" % os.path.realpath(dev_disk_by_path).split('/dev/')[1]
def getMultiPathDevice(dev_disk_by_path): # input: /dev/disk/by-path/ip-10.100.10.3:3260-iscsi-iqn.2009-06.jp.co.valinux:00000006-lun-1 # output: /dev/mapper/mpath5 dev_path = '' # iSCSI device path --> wwid wwid = '' command = "scsi_id -g -u -s /block/%s" % os.path.realpath(dev_disk_by_path).split('/dev/')[1] condit...
insert_str2 += "%s%%s" % (comma)
insert_str2 += "%s'%%s'" % (comma)
def __init__(self, table_def, db_file): self.db_name = table_def['name'] self.primary_key = table_def['primary_key'] keys = [] insert_str1 = "insert into %s (" % self.db_name insert_str2 = " values(" create_str = "create table %s (" % self.db_name comma = "" for key, type in table_def['fields']: keys.append(key) insert...
self.c.execute(self.sql_insert_str, args)
self.c.execute(self.sql_insert_str % args)
def put_row(self, args): self.c.execute(self.sql_insert_str, args)
if self.c.rowcount == 0:
if self.c.rowcount <= 0:
def get_svr_by_ip_data(self, ip_data): self.c.execute("select * from %s where ip_data_1 in (%r, %r) or ip_data_2 in (%r, %r)" % (self.db_name, ip_data[0], ip_data[1], ip_data[0], ip_data[1])) if self.c.rowcount > 1: raise Exception, "IP address confliction" if self.c.rowcount == 0: return None row = dict(zip(self.db_ke...
self.assertEquals(where.as_sql(), "(cn=test)")
self.assertEquals(where.as_sql(), ("(cn=test)", []))
def test_char_field_exact(self): where = WhereNode() where.add((Constraint("cn", "cn", CharField()), 'exact', "test"), AND) self.assertEquals(where.as_sql(), "(cn=test)")
self.assertEquals(where.as_sql(), "(cn=\\28test\\29)")
self.assertEquals(where.as_sql(), ("(cn=\\28test\\29)", []))
def test_char_field_exact(self): where = WhereNode() where.add((Constraint("cn", "cn", CharField()), 'exact', "test"), AND) self.assertEquals(where.as_sql(), "(cn=test)")
self.assertEquals(where.as_sql(), "(|(cn=foo)(cn=bar))")
self.assertEquals(where.as_sql(), ("(|(cn=foo)(cn=bar))", []))
def test_char_field_in(self): where = WhereNode() where.add((Constraint("cn", "cn", CharField()), 'in', ["foo", "bar"]), AND) self.assertEquals(where.as_sql(), "(|(cn=foo)(cn=bar))")
self.assertEquals(where.as_sql(), "(|(cn=\\28foo\\29)(cn=\\28bar\\29))")
self.assertEquals(where.as_sql(), ("(|(cn=\\28foo\\29)(cn=\\28bar\\29))", []))
def test_char_field_in(self): where = WhereNode() where.add((Constraint("cn", "cn", CharField()), 'in', ["foo", "bar"]), AND) self.assertEquals(where.as_sql(), "(|(cn=foo)(cn=bar))")
self.assertEquals(where.as_sql(), "(cn=test*)")
self.assertEquals(where.as_sql(), ("(cn=test*)", []))
def test_char_field_startswith(self): where = WhereNode() where.add((Constraint("cn", "cn", CharField()), 'startswith', "test"), AND) self.assertEquals(where.as_sql(), "(cn=test*)")
self.assertEquals(where.as_sql(), "(cn=te\\2ast*)")
self.assertEquals(where.as_sql(), ("(cn=te\\2ast*)", []))
def test_char_field_startswith(self): where = WhereNode() where.add((Constraint("cn", "cn", CharField()), 'startswith', "test"), AND) self.assertEquals(where.as_sql(), "(cn=test*)")
self.assertEquals(where.as_sql(), "(cn=*test)")
self.assertEquals(where.as_sql(), ("(cn=*test)", []))
def test_char_field_endswith(self): where = WhereNode() where.add((Constraint("cn", "cn", CharField()), 'endswith', "test"), AND) self.assertEquals(where.as_sql(), "(cn=*test)")
self.assertEquals(where.as_sql(), "(cn=*te\\2ast)")
self.assertEquals(where.as_sql(), ("(cn=*te\\2ast)", []))
def test_char_field_endswith(self): where = WhereNode() where.add((Constraint("cn", "cn", CharField()), 'endswith', "test"), AND) self.assertEquals(where.as_sql(), "(cn=*test)")
self.assertEquals(where.as_sql(), "(cn=*test*)")
self.assertEquals(where.as_sql(), ("(cn=*test*)", []))
def test_char_field_contains(self): where = WhereNode() where.add((Constraint("cn", "cn", CharField()), 'contains', "test"), AND) self.assertEquals(where.as_sql(), "(cn=*test*)")
self.assertEquals(where.as_sql(), "(cn=*te\\2ast*)")
self.assertEquals(where.as_sql(), ("(cn=*te\\2ast*)", []))
def test_char_field_contains(self): where = WhereNode() where.add((Constraint("cn", "cn", CharField()), 'contains', "test"), AND) self.assertEquals(where.as_sql(), "(cn=*test*)")
self.assertEquals(where.as_sql(), "(uid=1)")
self.assertEquals(where.as_sql(), ("(uid=1)", []))
def test_integer_field(self): where = WhereNode() where.add((Constraint("uid", "uid", IntegerField()), 'exact', 1), AND) self.assertEquals(where.as_sql(), "(uid=1)")
self.assertEquals(where.as_sql(), "(uid>=1)")
self.assertEquals(where.as_sql(), ("(uid>=1)", []))
def test_integer_field(self): where = WhereNode() where.add((Constraint("uid", "uid", IntegerField()), 'exact', 1), AND) self.assertEquals(where.as_sql(), "(uid=1)")
self.assertEquals(where.as_sql(), "(uid<=1)")
self.assertEquals(where.as_sql(), ("(uid<=1)", []))
def test_integer_field(self): where = WhereNode() where.add((Constraint("uid", "uid", IntegerField()), 'exact', 1), AND) self.assertEquals(where.as_sql(), "(uid=1)")
self.assertEquals(where.as_sql(), "(memberUid=foouser)")
self.assertEquals(where.as_sql(), ("(memberUid=foouser)", []))
def test_list_field_contains(self): where = WhereNode() where.add((Constraint("memberUid", "memberUid", ListField()), 'contains', 'foouser'), AND) self.assertEquals(where.as_sql(), "(memberUid=foouser)")
self.assertEquals(where.as_sql(), "(memberUid=\\28foouser\\29)")
self.assertEquals(where.as_sql(), ("(memberUid=\\28foouser\\29)", []))
def test_list_field_contains(self): where = WhereNode() where.add((Constraint("memberUid", "memberUid", ListField()), 'contains', 'foouser'), AND) self.assertEquals(where.as_sql(), "(memberUid=foouser)")
self.assertEquals(where.as_sql(), "(&(cn=foo)(givenName=bar))")
self.assertEquals(where.as_sql(), ("(&(cn=foo)(givenName=bar))", []))
def test_and(self): where = WhereNode() where.add((Constraint("cn", "cn", CharField()), 'exact', "foo"), AND) where.add((Constraint("givenName", "givenName", CharField()), 'exact', "bar"), AND) self.assertEquals(where.as_sql(), "(&(cn=foo)(givenName=bar))")
attr_x = field.from_ldap(x[1].get(field.db_column, []), connection=self.connection).lower() attr_y = field.from_ldap(y[1].get(field.db_column, []), connection=self.connection).lower()
attr_x = field.from_ldap(x[1].get(field.db_column, []), connection=self.connection) attr_y = field.from_ldap(y[1].get(field.db_column, []), connection=self.connection) if hasattr(attr_x, 'lower'): attr_x = attr_x.lower() if hasattr(attr_y, 'lower'): attr_y = attr_y.lower()
def cmpvals(x, y): for fieldname in ordering: if fieldname.startswith('-'): fieldname = fieldname[1:] negate = True else: negate = False field = query.model._meta.get_field(fieldname) attr_x = field.from_ldap(x[1].get(field.db_column, []), connection=self.connection).lower() attr_y = field.from_ldap(y[1].get(field.db_c...
def getkey(x): keys = [] for k in ordering: attr = self.model._meta.get_field(k).db_column keys.append(x[1].get(attr, '').lower()) return keys vals = sorted(vals, key=lambda x: getkey(x))
def cmpvals(x, y): for field in ordering: if field.startswith('-'): field = field[1:] negate = True else: negate = False attr = self.model._meta.get_field(field).db_column attr_x = x[1].get(attr, '').lower() attr_y = y[1].get(attr, '').lower() val = negate and cmp(attr_y, attr_x) or cmp(attr_x, attr_y) if val: return v...
def getkey(x): keys = [] for k in ordering: attr = self.model._meta.get_field(k).db_column keys.append(x[1].get(attr, '').lower()) return keys
for field in ordering: if field.startswith('-'): field = field[1:]
for fieldname in ordering: if fieldname.startswith('-'): fieldname = fieldname[1:]
def cmpvals(x, y): for field in ordering: if field.startswith('-'): field = field[1:] negate = True else: negate = False attr = query.model._meta.get_field(field).db_column attr_x = x[1].get(attr, '').lower() attr_y = y[1].get(attr, '').lower() val = negate and cmp(attr_y, attr_x) or cmp(attr_x, attr_y) if val: return ...
attr = query.model._meta.get_field(field).db_column attr_x = x[1].get(attr, '').lower() attr_y = y[1].get(attr, '').lower()
field = query.model._meta.get_field(fieldname) attr_x = field.from_ldap(x[1].get(field.db_column, []), connection=self.connection).lower() attr_y = field.from_ldap(y[1].get(field.db_column, []), connection=self.connection).lower()
def cmpvals(x, y): for field in ordering: if field.startswith('-'): field = field[1:] negate = True else: negate = False attr = query.model._meta.get_field(field).db_column attr_x = x[1].get(attr, '').lower() attr_y = y[1].get(attr, '').lower() val = negate and cmp(attr_y, attr_x) or cmp(attr_x, attr_y) if val: return ...
return value.replace('\\', '\\5c') .replace('*', '\\2a') .replace('(', '\\28') .replace(')', '\\29')
return value.replace('\\', '\\5c') \ .replace('*', '\\2a') \ .replace('(', '\\28') \ .replace(')', '\\29') \
def get_db_prep_value(self, value): """Returns field's value prepared for interacting with the database backend.
vals = self.connection.search_s(
vals = ldapdb.connection.search_s(
def get_count(self, using=None): filterstr = ''.join(['(objectClass=%s)' % cls for cls in self.model.object_classes]) sql, params = self.where.as_sql() filterstr += sql filterstr = '(&%s)' % filterstr
if DATABASE_EXTRAS.get('like', 'LIKEC') != 'LIKEC': for key in ['contains','icontains', 'startswith','istartswith', 'endswith','iendswith']: self.operators[key] = self.operators[key].replace('LIKEC',DATABASE_EXTRAS['like'])
def __init__(self, *args, **kwargs): """ Set up the various database components Oracle prefixed classes use the standard Oracle version - tested with both 1.0 and 1.2 """ super(DatabaseWrapper, self).__init__(*args, **kwargs)
response.content = response.content.replace('</body>', "%s%s" % (content,'</body>'))
try: response.content = response.content.replace('</body>', u"%s%s" % (content,'</body>')) except: pass
def process_response ( self, request, response ): """ SQL logging to screen switched on by settings.DEBUG SQL logging to log dependent on database logger level ie. EXTRAS['log'] = 10 Use case is need to turn on debug SQL logging on production installs occasionally - whilst DEBUG is only for development """ if settings....
if not settings_dict:
if not settings_dict.get('NAME',''):
def _get_pool (self): """ Get the connection pool or create it if it doesnt exist Add thread lock to prevent server initial heavy load creating multiple pools """ if not hasattr (self.__class__, '_pool'): lock = thread.allocate_lock() lock.acquire() if not hasattr (self.__class__, '_pool'): if DATABASE_EXTRAS['threaded...
if getattr(self, 'referencesSortable', None) == None: self.referencesSortable = False
def get(self, instance, aslist=False, **kwargs): """get() returns the list of objects referenced under the relationship """ res = instance.getRefs(relationship=self.relationship)
if getattr(self, 'referencesSortable', None) == None: self.referencesSortable = False
def set(self, instance, value, **kwargs): """Mutator.
if getattr(self, 'referencesSortable', None) == None: self.referencesSortable = False
def getRaw(self, instance, aslist=False, **kwargs): """Return the list of UIDs referenced under this fields relationship """ rc = getToolByName(instance, REFERENCE_CATALOG) brains = rc(sourceUID=instance.UID(), relationship=self.relationship) res = [b.targetUID for b in brains] if not self.multiValued and not aslist: i...
if ampm and ampm == 'PM':
if ampm and ampm == 'PM' and hour != '12':
def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False, validating=True): """Basic impl for form processing in a widget"""
assert(len(targetBrains) == 1,'catalog query for OLD uid (%s) returned %d results instead of 1' % (targetUID,len(targetBrains)))
assert len(targetBrains) == 1, 'catalog query for OLD uid (%s) returned %d results instead of 1' % (targetUID,len(targetBrains))
def migrateReferences(portal, out): # FIRST # a 1.2 -> 1.3 (new annotation style) migration path at = getToolByName(portal, TOOL_NAME) rc = getToolByName(portal, REFERENCE_CATALOG) uc = getToolByName(portal, UID_CATALOG) count=0 # Old 1.2 style references are stored inside archetype_tool on the 'ref' # attribute ref...
sm = component.getSiteManager() sm.registerAdapter(factory=wrapper.IndexableObjectWrapper, required=(interface.Interface, IZCatalog), provided=IIndexableObject)
def getId(self): return self.id
[]
[15]
... def getCharset(self):
integerKeys[key] = key
def getSelected(self, vocab, value): context = aq_inner(self.context)
elif integerKeys: try: int_value = int(value) except ValueError: continue ov = integerKeys.get(int_value) if ov: selected.append((pos, ov))
def getSelected(self, vocab, value): context = aq_inner(self.context)
warn('The method \'%s\' was already protected by a ' 'different permission than the one declared ' 'on the field. Assuming that the explicit ' 'permission declared is the correct one and ' 'has preference over the permission declared ' 'on the field.' % methodName, UserWarning, 3)
log('The method \'%s\' was already protected by a ' 'different permission than the one declared ' 'on the field. Assuming that the explicit ' 'permission declared is the correct one and ' 'has preference over the permission declared ' 'on the field.' % methodName, level=logging.DEBUG)
def updateSecurity(self, klass, field, mode, methodName): security = _getSecurity(klass)
except ValueError:
except (ValueError, TypeError):
def getSelected(self, vocab, value):
original = value
date_re = re.match('(?P<YEAR>[0-9]{4})-(?P<MONTH>[0-9]{1,2})-'+ '(?P<DAY>[0-9]{1,2})(?P<OTHER>.*)', value) if date_re: value = date_re.group('YEAR') + '/' + \ date_re.group('MONTH') + '/' + \ date_re.group('DAY') + \ date_re.group('OTHER')
def set(self, instance, value, **kwargs): """ Check if value is an actual date/time value. If not, attempt to convert it to one; otherwise, set to None. Assign all properties passed as kwargs to object. """ if not value: value = None elif not isinstance(value, DateTime): try: # strings returned from the widget need a t...
local = DateTime() if value.tzoffset() == 0 and local.tzoffset() != 0: value = DateTime(original + ' ' + local.timezone())
def set(self, instance, value, **kwargs): """ Check if value is an actual date/time value. If not, attempt to convert it to one; otherwise, set to None. Assign all properties passed as kwargs to object. """ if not value: value = None elif not isinstance(value, DateTime): try: # strings returned from the widget need a t...
value += ' ' + DateTime().timezone()
original = value
def set(self, instance, value, **kwargs): """ Check if value is an actual date/time value. If not, attempt to convert it to one; otherwise, set to None. Assign all properties passed as kwargs to object. """ if not value: value = None elif not isinstance(value, DateTime): try: # strings returned from the widget need a t...
warn(msg, UserWarning, level=level)
warn(msg, UserWarning, stacklevel=level)
def __init__(self, *args, **kwargs): """ Initialize a Schema.
if (meta is None and isinstance(doc, file) or
if (meta is None and (isinstance(doc, file) or
def _serialize_document(self, doc): """ Serialize a object tree into xml. """
not doc.startswith('<?xml'))):
not doc.startswith('<?xml')))):
def _serialize_document(self, doc): """ Serialize a object tree into xml. """
return uri[len(self._client.baseURI)-1:]
return uri[len(self._client.baseURI):]
def _normalize_uri(self, uri): """ Make sure uri is based at the baseUri and shorten to be appened on the baseUri. """
return response.model
return response._model
def getModel(self, uri): response = self.getResponse(uri) return response.model
serverClass=RESTServer):
serverClass=RESTServer, debug=True):
def StartServer(port=8080, fork=True, handlerClass=RESTRequestHandler, serverClass=RESTServer): """ Start a REST Server on the given port. """ server_address = ('', port) server = serverClass(server_address, handlerClass) sn = server.socket.getsockname() print 'starting server on %s port %s' % (sn[0], sn[1]) if for...
serverClass=RESTServer):
serverClass=RESTServer, debug=False):
def ThreadServer(port=8080, handlerClass=RESTRequestHandler, serverClass=RESTServer): class Server(Thread, serverClass): def __init__(self, server_address, handlerClass): Thread.__init__(self) serverClass.__init__(self, server_address, handlerClass) self.daemon = True def run(self): self.serve_forever() server_addr...
print 'starting server on %s port %s' % (sn[0], sn[1])
log.debug('starting server on %s port %s' % (sn[0], sn[1]))
def run(self): self.serve_forever()
self.server = testserver.ThreadServer(port=ports[0])
self.server = testserver.ThreadServer(port=ports[0], debug=self._debug_flag)
def setUp(self): testhelp.TestCase.setUp(self)
pathManager.addResourcePath('TEST_PATH', os.path.join(robjPath, 'test'))
robjTestPath = pathManager.addExecPath('ROBJ_TEST_PATH') pathManager.addExecPath('TEST_PATH', path=robjTestPath)
def setup(): pathManager.addExecPath('XOBJ_PATH') robjPath = pathManager.addExecPath('ROBJ_PATH') pathManager.addResourcePath('TEST_PATH', os.path.join(robjPath, 'test')) pathManager.addResourcePath('ROBJ_ARCHIVE_PATH', path=os.path.join(robjPath, 'test', 'archive'))
path=os.path.join(robjPath, 'test', 'archive'))
path=os.path.join(robjTestPath, 'archive'))
def setup(): pathManager.addExecPath('XOBJ_PATH') robjPath = pathManager.addExecPath('ROBJ_PATH') pathManager.addResourcePath('TEST_PATH', os.path.join(robjPath, 'test')) pathManager.addResourcePath('ROBJ_ARCHIVE_PATH', path=os.path.join(robjPath, 'test', 'archive'))
raise TypeError
raise TypeError, 'A list type is required for this method.'
def wrapper(self, *args, **kwargs): if not self._isCollection: raise TypeError return func(self, *args, **kwargs)
@param parent: Parent rObj instance.
@param parent: Parent rObj instance (optional).
def wrapper(self, *args, **kwargs): if not self._isCollection: raise TypeError return func(self, *args, **kwargs)
'_dirty', '_dl', '_childTag', )
'_dirty_flag', '_dl', '_childTag', '_local_cache')
def wrapper(self, *args, **kwargs): if not self._isCollection: raise TypeError return func(self, *args, **kwargs)
self._dl = RLock()
self._local_cache = {}
def __init__(self, uri, client, root, parent=None): self._uri = uri self._client = client self._root = root
self._dirty = False
def _set_dirty(self, value): if self._isChild: self._parent._dirty_flag = value self._dirty_flag = value def _get_dirty(self): return self._dirty_flag _dirty = property(_get_dirty, _set_dirty)
def __init__(self, uri, client, root, parent=None): self._uri = uri self._client = client self._root = root
def isCollection(self): return self._isCollection @property def parent(self): return self._parent @property def childTag(self): return self._childTag
def _isChild(self): if self._parent and self._uri == self._parent._uri: return True return False
def isCollection(self): return self._isCollection
if isinstance(value, xobj.XObj): doc = xobj.Document() doc._xobj.elements.append(name) setattr(doc, name, value) return self.__class__(value.id, self._client, doc, parent=self)
return self._client.cache(value.id, self._client, value, parent=self)
def _getObj(self, name, value): # Wrap this instance with an rObj. if hasattr(value, 'id'): # Wrap the xobj in an xobj document so that it can be serialized # later. if isinstance(value, xobj.XObj): doc = xobj.Document() doc._xobj.elements.append(name) setattr(doc, name, value) return self.__class__(value.id, self._cli...
return self.__class__(self._uri, self._client, value, parent=self)
if name not in self._local_cache: self._local_cache[name] = self.__class__(self._uri, self._client, value, parent=self) return self._local_cache[name]
def _getObj(self, name, value): # Wrap this instance with an rObj. if hasattr(value, 'id'): # Wrap the xobj in an xobj document so that it can be serialized # later. if isinstance(value, xobj.XObj): doc = xobj.Document() doc._xobj.elements.append(name) setattr(doc, name, value) return self.__class__(value.id, self._cli...
if not name.startswith('_'):
try:
def __getattr__(self, name): if not name.startswith('_'): val = getattr(self._root, name) obj = self._getObj(name, val) if obj: return obj else: return val else: return object.__getattribute__(self, name)
obj = self._getObj(name, val) if obj: return obj else: return val else: return object.__getattribute__(self, name)
except AttributeError: raise AttributeError, "'%r' has no attribute '%s'" % (self, name) obj = self._getObj(name, val) if obj is not None: return obj else: return val
def __getattr__(self, name): if not name.startswith('_'): val = getattr(self._root, name) obj = self._getObj(name, val) if obj: return obj else: return val else: return object.__getattribute__(self, name)
if self._isCollection: self._dl.acquire() l = len(self._root) self._dl.release() return l else: return True
self._dl.acquire() l = len(self._root) self._dl.release() return l
def __len__(self): if self._isCollection: self._dl.acquire() l = len(self._root) self._dl.release() return l else: return True
self._dirty = False self._client.do_PUT(self._uri, self._root)
self._dirty_flag = False if self._isChild: self._parent.persist() else: self._client.do_PUT(self._uri, self._root)
def persist(self): """ Update the server with any modifications that have been made to this instance. """
Refresh the instance from the server if it is not marked as dirty.
Refresh the instance from the server if it has not been modified.
def refresh(self, force=False): """ Refresh the instance from the server if it is not marked as dirty. @param force: Optional parameter (defaults to False) to force the refresh even if the instance is marked as dirty. @type force: boolean """
refresh even if the instance is marked as dirty.
refresh even if the instance has been modified locally.
def refresh(self, force=False): """ Refresh the instance from the server if it is not marked as dirty. @param force: Optional parameter (defaults to False) to force the refresh even if the instance is marked as dirty. @type force: boolean """
self._client.do_GET(self._uri)
self._client.do_GET(self._uri, cache=False)
def refresh(self, force=False): """ Refresh the instance from the server if it is not marked as dirty. @param force: Optional parameter (defaults to False) to force the refresh even if the instance is marked as dirty. @type force: boolean """
except httplib.BadStatusLine, e:
except httplib.BadStatusLine:
def handleRequest(self, req): """ Process one client request. """
self._debug_flag = True
def run(self, results=None): if results is not None: self._debug_flag = results.debug self._debug_flag = True return testhelp.TestCase.run(self, results)
os.system('mkdir -p Processed/s%d' % (fileProcess.dirID) ) timeID = 1
timeID = 0
def GetHeaderInfo(self): fileID = 2*nslice*(necho*1+iecho+noffset) + 1 fileName = "%s/s%d/i%d.MRDC.%d" % (ExamPath,DirId,DirId+fileID,fileID) # call base class to get basic header info AcquisitionBaseClass.GetHeaderInfo(self,fileName)
os.system('mkdir -p Processed/s%d' % (fileProcess.dirID) )
os.system('mkdir -p %s/Processed/s%d' % (fileProcess.ExamPath,fileProcess.dirID) )
def GetHeaderInfo(self): fileID = 2*nslice*(necho*1+iecho+noffset) + 1 fileName = "%s/s%d/i%d.MRDC.%d" % (ExamPath,DirId,DirId+fileID,fileID) # call base class to get basic header info AcquisitionBaseClass.GetHeaderInfo(self,fileName)
while (timeID < ntime):
while (timeID <= ntime):
def GetHeaderInfo(self): fileID = 2*nslice*(necho*1+iecho+noffset) + 1 fileName = "%s/s%d/i%d.MRDC.%d" % (ExamPath,DirId,DirId+fileID,fileID) # call base class to get basic header info AcquisitionBaseClass.GetHeaderInfo(self,fileName)
os.system( "%s %s --output Processed/s%d/image -timeid %d" % ( fileProcess.DicomToComplex , FileList, fileProcess.dirID, timeID ) )
os.system( "%s %s --output %s/Processed/s%d/image -timeid %d" % ( fileProcess.DicomToComplex , FileList, fileProcess.ExamPath, fileProcess.dirID, timeID ) )
def GetHeaderInfo(self): fileID = 2*nslice*(necho*1+iecho+noffset) + 1 fileName = "%s/s%d/i%d.MRDC.%d" % (ExamPath,DirId,DirId+fileID,fileID) # call base class to get basic header info AcquisitionBaseClass.GetHeaderInfo(self,fileName)
p = Popen(['/bin/bash', '-c', 'source %s; echo %s' % (path, value)],
p = Popen(['/bin/bash', '-c', 'source %s > /dev/null; echo %s' % (path, value)],
def echo_bash_vars(path, value): """Return a variable from a bash file.""" # Check if the value is an array if '[@]' in value: array = True else: array = False p = Popen(['/bin/bash', '-c', 'source %s; echo %s' % (path, value)], stdout=PIPE, stderr=PIPE) out = p.stdout.read() out = out.strip() if array: out = out.sp...
commands = ['/bin/bash', '-c', 'source %s; echo -e "%s\n%s\n%s"' % (
commands = ['/bin/bash', '-c', 'source %s > /dev/null; echo -e "%s\n%s\n%s"' % (
def get_depends(pkgbuild, makedeps='makedepends', deps='depends', optdeps='optdepends'): commands = ['/bin/bash', '-c', 'source %s; echo -e "%s\n%s\n%s"' % ( pkgbuild, bash_array(makedeps), bash_array(deps), bash_array(optdeps))] p = Popen(commands, stdout=PIPE, stderr=PIPE) out = p.stdout.read() err = p.stderr.read(...
if combo.get_active == 0: ctx = ''
def context_filter_cb(self, combo): """ Filter search results by selected context """ ctx= combo.get_active_text() #treeview.get_selection().get_selected() if combo.get_active == 0: ctx = '' self.IconDB.set_context_filter(ctx) self.search_and_display(self.Gui.text_entry) return
self.ctx_filter = "<b>All Contexts</b>"
self.ctx_filter = "All Contexts"
def __init__(self): """ Both the DB and pixbuf cache are filled. """ self.conn = None self.cursor = None self.length = 0 self.model = None self.results = None self.standard_only = False self.inherited_only = False self.ctx_filter = "<b>All Contexts</b>" return
if self.ctx_filter != "<b>All Contexts</b>":
if self.ctx_filter != "All Contexts":
def make_query( self, term ): if term != "": qterm = "\"%" + term + "%\"" query = "SELECT * FROM theme WHERE name LIKE %s" % qterm if self.standard_only: query += " AND standard" if self.inherited_only: query += " AND inherited" if self.ctx_filter != "<b>All Contexts</b>": query += " AND context=\"%s\" ORDER BY name" %...
HTTP.SetCacheTime(CACHE_1HOUR) HTTP.SetHeader('User-agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6')
HTTP.CacheTime = 3600 HTTP.Headers['User-agent'] = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4'
def Start(): Plugin.AddPrefixHandler(PLUGIN_PREFIX, MainMenu, PLUGIN_TITLE, ICON_DEFAULT) Plugin.AddViewGroup('Category', viewMode='List', mediaType='items') Plugin.AddViewGroup('Details', viewMode='InfoList', mediaType='items') # Set the default MediaContainer attributes MediaContainer.title1 = PLUGIN_TITLE MediaC...
content = HTML.ElementFromURL(url, errors='ignore') programs = content.xpath(XPATH_PROGRAMS)
programmes = HTML.ElementFromURL(url, errors='ignore').xpath(XPATH_PROGRAMS) for p in programmes: title = p.xpath('./text()')[0].strip()
def Programs(sender, c): dir = MediaContainer(title2=c, art=R(CHANNELS[c]['art'])) url = CHANNELS[c]['base'] + CHANNELS[c]['home'] content = HTML.ElementFromURL(url, errors='ignore') programs = content.xpath(XPATH_PROGRAMS) for p in programs: title = p.xpath('./text()')[0].strip() programUrl = p.get('href') if title...
for p in programs: title = p.xpath('./text()')[0].strip() programUrl = p.get('href')
if title.find('Wimbledon') == -1: programUrl = p.get('href')
def Programs(sender, c): dir = MediaContainer(title2=c, art=R(CHANNELS[c]['art'])) url = CHANNELS[c]['base'] + CHANNELS[c]['home'] content = HTML.ElementFromURL(url, errors='ignore') programs = content.xpath(XPATH_PROGRAMS) for p in programs: title = p.xpath('./text()')[0].strip() programUrl = p.get('href') if title...
eps = HTTP.Request(url, errors='ignore').content episodes = HTML.ElementFromString(eps).xpath(XPATH_EPISODES) for episode in episodes: epTitle = episode.xpath('./div[@class="title"]/a/span')[0].text epAirtime = episode.xpath('./div[@class="airtime"]/a/span')[0].text epSummary = episode.xpath('./div[@class="text"]/a/spa...
episodes = HTML.ElementFromURL(url, errors='ignore').xpath(XPATH_EPISODES) for e in episodes: ep_title = e.xpath('./div[@class="title"]/a/span')[0].text airtime = e.xpath('./div[@class="airtime"]/a/span')[0].text summary = e.xpath('./div[@class="text"]/a/span')[0].text thumb = CHANNELS[c]['base'] + e.xpath('./div[@clas...
def Episodes(sender, title, url, c): dir = MediaContainer(viewGroup='Details', title2=title, art=R(CHANNELS[c]['art'])) eps = HTTP.Request(url, errors='ignore').content episodes = HTML.ElementFromString(eps).xpath(XPATH_EPISODES) for episode in episodes: epTitle = episode.xpath('./div[@class="title"]/a/span')[0].text ...
next = HTML.ElementFromString(eps).xpath('/html/body//span[@class="next"]/a')
next = HTML.ElementFromURL(url, errors='ignore').xpath('/html/body//span[@class="next"]/a')
def Episodes(sender, title, url, c): dir = MediaContainer(viewGroup='Details', title2=title, art=R(CHANNELS[c]['art'])) eps = HTTP.Request(url, errors='ignore').content episodes = HTML.ElementFromString(eps).xpath(XPATH_EPISODES) for episode in episodes: epTitle = episode.xpath('./div[@class="title"]/a/span')[0].text ...