def dump_rest(self): for (page_id, [incoming_list, outgoing_list]) in self.mapping.items(): incoming_list = incoming_list if incoming_list is not None else OrderedSet( ) outgoing_list = outgoing_list if outgoing_list is not None else OrderedSet( ) print(format_values(page_id, incoming_list, outgoing_list))
def __init__(self): # Initialize self.services = (OrderedSet(), OrderedSet()) self.currentServiceRef = None self.forcedScan = False self.isrunning = False self.doStopRunningRefresh = False self.session = None self.beginOfTimespan = 0 self.refreshAdapter = None # to call additional tasks (from other plugins) self.finishNotifiers = {} # Mtime of configuration files self.configMtime = -1 # Todos after finish self._initFinishTodos() # Read in Configuration self.readConfiguration() # Initialise myEpgCacheInstance self.myEpgCacheInstance = None # timeout timer for eEPGCache-signal based refresh self.epgTimeoutTimer = eTimer() self.epgTimeoutTimer_conn = self.epgTimeoutTimer.timeout.connect( self.epgTimeout)
def adjust_history(self, comp, history): with autolock(self.lock): cands = OrderedSet() for h in history: cands.add(self.rules[comp][h]) cands |= OrderedSet(self.rules[comp]) self.rules[comp] = tuple(cands) self.__save_comp(comp)
def ExtendInstanceByEdge(instance, edge): """Create and return new instance built from given instance and adding given edge and vertices of edge if new.""" newInstance = Instance() newInstance.vertices = OrderedSet(instance.vertices) newInstance.edges = OrderedSet(instance.edges) newInstance.edges.add(edge) newInstance.vertices.add(edge.source) newInstance.vertices.add(edge.target) return newInstance
def __init__(self): ''' pre: None post: An initial empty OrderedSet (the collection of CounterEvents later) ''' #Construct the Empty CounterSim Object #Initialize the virtual time self.event = OrderedSet() self.t = 0.0
def add_incoming(self, to, incoming_list): self.mapping[to][0] = OrderedSet(incoming_list) while self.first_page_id() < to and self.first_value()[0] is None: _, outgoing_list = self.first_value() print( format_values(self.first_page_id(), OrderedSet(), outgoing_list)) del self.mapping[self.first_page_id()] self._cleanup(to)
def set_history(self, comp, idx): with autolock(self.lock): if comp not in self.rules: if idx != 0: self.rules[comp] = OrderedSet() else: return set_ = OrderedSet((idx, )) self.rules[comp] = set_ | self.rules[comp] _g_ime_quail.adjust_history(comp, list(self.rules[comp])) del self.rules[comp]
def __init__(self, button_handler_queue, motion_controller): # set of incoming aims self.aim_set = OrderedSet() self.aims_intermediate = [] # heap of intermediate aims self.aim_main = None self.is_main_finished = False # aim from the passengers inside the lift self.aim_internal_last = None self.button_handler_queue = button_handler_queue self.motion_controller = motion_controller
def add_outgoing(self, from_page, outgoing_list): self.mapping[from_page][1] = OrderedSet(outgoing_list) while self.first_page_id() < from_page and self.first_value( )[1] is None: incoming_list, _ = self.first_value() print( format_values(self.first_page_id(), incoming_list, OrderedSet())) del self.mapping[self.first_page_id()] self._cleanup(from_page)
def testRemove_Exception(self): '''Test wether the right type of excpetion is raised when thing to be removed not inside the set''' #Case1 Starting from empty #--------------------------------------------------------------------------------- try: a = OrderedSet() a.remove(3) self.assertTrue( False, 'No excpetion/or no right type of exception raised') except IndexError: pass
def crossReference(features): id2feature = index(features) # for f in features: f.__dict__["parents"] = OrderedSet() f.__dict__["children"] = OrderedSet() pIds = f.attributes.get("Parent", []) if type(pIds) is str: pIds = [pIds] for pid in pIds: parent = id2feature[pid] f.parents.add(parent) parent.children.add(f) return id2feature
def __init__(self): # Initialize self.services = (OrderedSet(), OrderedSet()) self.forcedScan = False self.session = None self.beginOfTimespan = 0 self.refreshAdapter = None # Mtime of configuration files self.configMtime = -1 # Read in Configuration self.readConfiguration()
def testInsert_CounterEvent_reposition(self): '''Test Case for insertion------When thing to be inserted already in the set''' a = OrderedSet() event1 = CounterEvent(2) event2 = CounterEvent(1) event3 = CounterEvent(0.5) event4 = CounterEvent(4.5) #Insert Events in first #Check the result #Change Event 3 #Check again(Event Time Is changed/ Event Order is not chagned (wrong order)) #Insert Event 3 #Check again (Now ORder Should be Corrected) #--------------------------------------------------------------------------------- a.insert(event1) a.insert(event2) a.insert(event3) a.insert(event4) self.assertEqual( '[<Event: 0.5>*, <Event: 1.0>, <Event: 2.0>, <Event: 4.5>]', str(a)) event3.item = 4.75 self.assertEqual( '[<Event: 4.75>*, <Event: 1.0>, <Event: 2.0>, <Event: 4.5>]', str(a)) print(a) a.insert(event3) self.assertEqual( '[<Event: 1.0>*, <Event: 2.0>, <Event: 4.5>, <Event: 4.75>]', str(a))
def render(self, req): req.setResponseCode(http.OK) req.setHeader('Content-type', 'application/xhtml+xml') req.setHeader('charset', 'UTF-8') if 'sref' in req.args: services = OrderedSet() bouquets = OrderedSet() for sref in req.args.get('sref'): sref = unquote(sref) ref = eServiceReference(sref) if not ref.valid(): services = bouquets = None break elif (ref.flags & 7) == 7: epgservice = EPGRefreshService(sref, None) if epgservice not in bouquets: bouquets.add(epgservice) else: if not (ref.flags & eServiceReference.isGroup): # strip all after last : pos = sref.rfind(':') if pos != -1: if sref[pos - 1] == ':': pos -= 1 sref = sref[:pos + 1] epgservice = EPGRefreshService(sref, None) if epgservice not in services: services.add(epgservice) if services is not None and bouquets is not None: scanServices = epgrefresh.generateServicelist( services, bouquets) else: scanServices = [] else: scanServices = epgrefresh.generateServicelist( epgrefresh.services[0], epgrefresh.services[1]) returnlist = [ "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<e2servicelist>" ] extend = returnlist.extend for serviceref in scanServices: ref = ServiceReference(str(serviceref)) returnlist.extend(( ' <e2service>\n', ' <e2servicereference>', stringToXML(str(serviceref)), '</e2servicereference>\n', ' <e2servicename>', stringToXML(ref.getServiceName().replace('\xc2\x86', '').replace( '\xc2\x87', '')), '</e2servicename>\n', ' </e2service>\n', )) returnlist.append('\n</e2servicelist>') return ''.join(returnlist)
def _setMotif(self, stageMatrix, BASE): segment_set = OrderedSet() for i in range(len(stageMatrix[BASE])): for hk in stageMatrix: segment_set.add(tuple(stageMatrix[hk][i])) # print("total segment:", len(segment_set) ) #apiparam set apiparam_set = set() for hk in stageMatrix: for seg in stageMatrix[hk]: for a in seg: apiparam_set.add(a) #label each segment (motif) lb2seg_dict = dict() for i in range(len(segment_set)): lb2seg_dict['M' + str(i + 1)] = tuple(list(segment_set)[i]) seg2lb_dict = dict() for k in lb2seg_dict: seg2lb_dict[lb2seg_dict[k]] = k #set stageMatrixIndex #record every motif in the every stage of a hooklog; the start&end indext of hk is for API deduplication stageMatrixIndex = dict() for hklg in stageMatrix: idxtuple_list = [] last_start = 0 last_end = 0 for motif in stageMatrix[hklg]: if motif == ['=']: idxtuple_list.append((-1, -1)) continue last_end = last_start + len(motif) - 1 idxtuple_list.append((last_start, last_end)) last_start = last_end + 1 stageMatrixIndex[hklg] = idxtuple_list self.motif_apiparam = apiparam_set self.motif_lb2seg = lb2seg_dict self.motif_seg2lb = seg2lb_dict self.motif_stageMatrixIndex = stageMatrixIndex if tuple(['=']) not in seg2lb_dict.keys(): self.motif_gaplb = 'NONE' # print("No Gap.") else: self.motif_gaplb = seg2lb_dict[tuple(['='])] self.totalStageLen = len(stageMatrix[BASE])
def testInsert_number(self): '''test the insert method---number(float and integer)''' a = OrderedSet() b = [] #Generating Random Numbers to insert #so use getset method to check the result(cannot check the string representation for i in range(10): c = random.random() * random.randrange(100) a.insert(c) b.append(c) b = sorted(b) self.assertEqual(a.getset(), b)
def __init__(self, name): """Initialize the MoleculeType container Args: name (str): the name of the moleculetype to add """ self.name = name self.moleculeSet = OrderedSet() self.bondForceSet = HashMap() self.pairForceSet = HashMap() self.angleForceSet = HashMap() self.dihedralForceSet = HashMap() self.constraints = HashMap() self.exclusions = HashMap() self.settles = None self.nrexcl = None
def __init__(self): self.services = (OrderedSet(), OrderedSet()) self.forcedScan = False self.isrunning = False self.DontShutdown = False self.session = None self.checkTimer = eTimer() self.check_finish = False self.wait = eTimer() self.wait.timeout.get().append(self.refresh) self.autotimer_pause = eTimer() self.autotimer_pause.timeout.get().append(self.finish) self.beginOfTimespan = 0 self.refreshAdapter = None self.configMtime = -1 self.readConfiguration()
def __init__(self, keystr): self.special_keys = special_keys.special_keys keys = keystr.split() mods = keys[:-1] mods = ''.join(mods) mods = list(mods) mods.sort() mods = OrderedSet(mods) self.mods = ''.join(mods) assert self.mods in ime_keyboard.all_mods, "invalid modifiers" self.key = keys[-1] assert len(self.key), "empty keys" if len(self.key) == 1: assert isgraph( self.key), "key not graphic" #' ' is 'space', see below else: #assert self.key in self.special_keys, "key is not special function, like in emacs" pass if self.key == 'space': self.key = ' '
def testLen(self): s = OrderedSet() self.assertEqual(len(s), 0) s.insert(3) self.assertEqual(len(s), 1) s.insert(5) self.assertEqual(len(s), 2) s.insert(7) self.assertEqual(len(s), 3)
def testInsertOneEvent(self): S = OrderedSet() evt = Event(5) S.insert(evt) self.assertEqual(str(S), '[<Event: 5.0>*]') S = OrderedSet() evt = Event(1.5) S.insert(evt) self.assertEqual(str(S), '[<Event: 1.5>*]')
def ExtendInstance(instance): """Returns list of new instances created by extending the given instance by one new edge in all possible ways.""" newInstances = [] unusedEdges = OrderedSet([e for v in instance.vertices for e in v.edges]) - instance.edges for edge in unusedEdges: newInstance = ExtendInstanceByEdge(instance, edge) newInstances.append(newInstance) return newInstances
def testLenghtMethod(self): a = OrderedSet() for i in range(10): c = random.random() * random.randrange(100) a.insert(c) self.assertEqual(10, len(a)) #--------------------------------------------------------------------------------- a = OrderedSet() for i in range(20): c = random.random() * random.randrange(100) a.insert(c) self.assertEqual(20, len(a))
def pre_process(self, data_filename): lines = OrderedSet() with open(data_filename, 'r') as data_file: for line in data_file.readlines(): # Try to stringify a hashtag if it's in camel case - e.g. #ModiInDubai => Modi In Dubai line = self.camel_case_split(line) # Replace all the hashtags with HASHTAG token for k, v in self.config['replace_tokens'].items(): line = re.sub(v, k, line) # Replacing the emoticons with their title. for title, icons in self.config['emoticons'].items(): for icon in icons: line = line.replace(icon, title) # Remove all the tokens specified in the configuration JSON file. for token in self.config['remove_tokens']: line = re.sub(token, ' ', line) line = re.sub(r'(\s+)', ' ', line).strip().lower() lines.add(line) return lines
def testInsertMultipleEventChangeTime(self): s = OrderedSet() evt1 = Event(5, 1) evt2 = Event(2.5, 2) evt3 = Event(4.25, 3) s.insert(evt1) s.insert(evt2) s.insert(evt3) self.assertEqual(str(s), '[<Event: 2.5 (2)>*, <Event: 4.25 (3)>, <Event: 5.0 (1)>]') evt3.t = 6.0 s.insert(evt3) self.assertEqual(str(s), '[<Event: 2.5 (2)>*, <Event: 5.0 (1)>, <Event: 6.0 (3)>]')
def __init__(self): # Initialize self.services = (OrderedSet(), OrderedSet()) self.forcedScan = False self.isrunning = False self.doStopRunningRefresh = False self.session = None self.beginOfTimespan = 0 self.refreshAdapter = None # to call additional tasks (from other plugins) self.finishNotifiers = {} # Mtime of configuration files self.configMtime = -1 # Todos after finish self._initFinishTodos() # Read in Configuration self.readConfiguration()
def testContains(self): s = OrderedSet() val1 = 2.0 val2 = 3.0 val3 = 4.0 s.insert(val1) s.insert(val2) s.insert(val3) self.assertTrue(s.__contains__(val1)) self.assertTrue(s.__contains__(val2)) self.assertTrue(s.__contains__(val3))
def testInsertTwoSameEvent(self): S = OrderedSet() val = Event(2.5) S.insert(val) self.assertEqual(str(S), '[<Event: 2.5>*]') S.insert(val) self.assertEqual(str(S), '[<Event: 2.5>*]')
def query(objs): def select(objs, attrs): '''a generator which computes the actual results''' def add(queue, u, v, i): '''adds the object v to the queue. It looks like u isn't necessary anymore. I should fix that...''' args = (v, '_objquery__i', i + 1) try: object.__setattr__(*args) except TypeError: setattr(*args) except: raise queue.appendleft(v) queue = deque() add(queue, None, type('base', (object, ), objs), -1) while len(queue) > 0: u = queue.pop() i = object.__getattribute__(u, '_objquery__i') attrname, where = attrs[i] if hasattr(u, attrname): # the current object has the attr v = getattr(u, attrname) #it is iterable if not isinstance(v, basestring) and hasattr( v, '__iter__'): for z in v: # add each child into the processing queue if isinstance(v, dict): next = KeyValuePair(z, v[z]) else: next = z # but only if its where condition is satisfied if where != None: cobjs = dict(objs) cobjs.update({'self': next}) if not where(cobjs): continue # if this is the last attribute yield the obj if i + 1 == len(attrs): yield next else: add(queue, u, next, i) # otherwise add to the queue else: #it is not iterable if where != None: cobjs = dict(objs) cobjs.update({'self': v}) if not where(cobjs): continue # if this is the last attribute yield the obj if i + 1 == len(attrs): yield v else: add(queue, u, v, i) # otherwise add to the queue return OrderedSet(select(objs, attrs))
def testInsertTwoSameInt(self): S = OrderedSet() val = 10 S.insert(val) self.assertEqual(str(S), '[10*]') S.insert(val) self.assertEqual(str(S), '[10*]') self.assertEqual(len(S), 1)