def __delitem__(self, i): if sys.version_info < (3, ) and isinstance(i, slice): start, stop, _ = i.indices(len(self)) UserList.__delslice__(self, start, stop) else: UserList.__delitem__(self, i) self._changed()
def testSequenceArrayConversionTypeChecking(self): """Test error handling for sequence conversion to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam if six.PY3: from collections import UserList else: from UserList import UserList # This should work, because null / None is a valid value in an # array of reference types. items = UserList() for i in range(10): items.append(Spam(str(i))) items[1] = None result = ArrayConversionTest.EchoRange(items) self.assertTrue(result[0].__class__ == Spam) self.assertTrue(result[1] == None) self.assertTrue(len(result) == 10) def test(items=items): items[1] = 1 result = ArrayConversionTest.EchoRange(items) self.assertRaises(TypeError, test) def test(items=items): items[1] = "spam" result = ArrayConversionTest.EchoRange(items) self.assertRaises(TypeError, test)
async def get_messages(self, *args, **kwargs): """ Same as :meth:`iter_messages`, but returns a list instead with an additional ``.total`` attribute on the list. If the `limit` is not set, it will be 1 by default unless both `min_id` **and** `max_id` are set (as *named* arguments), in which case the entire range will be returned. This is so because any integer limit would be rather arbitrary and it's common to only want to fetch one message, but if a range is specified it makes sense that it should return the entirety of it. If `ids` is present in the *named* arguments and is not a list, a single :tl:`Message` will be returned for convenience instead of a list. """ total = [0] kwargs['_total'] = total if len(args) == 1 and 'limit' not in kwargs: if 'min_id' in kwargs and 'max_id' in kwargs: kwargs['limit'] = None else: kwargs['limit'] = 1 msgs = UserList() async for x in self.iter_messages(*args, **kwargs): msgs.append(x) msgs.total = total[0] if 'ids' in kwargs and not utils.is_list_like(kwargs['ids']): return msgs[0] return msgs
def __init__ (self, args = (), undefined = None) : """Construct a new `PL_List' with elements specified as optional arguments `args' and undefined value `undefined'. """ UserList.__init__ (self) self.data = list (args) self.body = self.data ### alias name for `self.data' self.undefined = undefined
def find_peak(dset): totLstPeaks = UserList() with futures.ProcessPoolExecutor(max_workers=4) as executer: for _ret in executer.map(find_peak_concurrent,list(dset)): totLstPeaks.append(_ret) return totLstPeaks
def __init__(self, l=None): if isinstance(l, str): UserList.__init__(self) self.add(l) return elif l: l = [PBXType.Convert(v) for v in l] UserList.__init__(self, l)
async def get_dialogs(self, *args, **kwargs): """ Same as :meth:`iter_dialogs`, but returns a list instead with an additional ``.total`` attribute on the list. """ total = [0] kwargs['_total'] = total dialogs = UserList() async for x in self.iter_dialogs(*args, **kwargs): dialogs.append(x) dialogs.total = total[0] return dialogs
def removeOutlier(dsets,resdb,_limit, _slope): logging.info('Remove Outlier(minmax: %f, steepslope: %f)', str(_limit), str(_slope)) concurrResults = UserList() loopCount = 0 with futures.ProcessPoolExecutor(max_workers=4) as executor: for _dset in executor.map(removeOutlierDset, dsets): #logging.debug('Remove Outlier - Exp Num: %s, ISI num: %s', str(_dic['studentno']),str(_dic['isi'])) concurrResults.append(_dset) resdb.create_dataset('d'+str(100+loopCount),data=_dset,dtype=np.float16) loopCount = loopCount + 1 print('loopCount: ' + str(loopCount)) return concurrResults
def extractAlphaOnly(arrExperiment): """ 실험데이터중 alpha파만 분리하여 저장 :param arrExperiment: 3차원 실험데이터 [채널:실험:관측치] :return: """ merged_lstAlpha = UserList() with futures.ProcessPoolExecutor(max_workers=4) as executor: #for j in range(arrExperiment.shape[0]): # number of channels for userlist in executor.map(bandPassFilterConcurrent, arrExperiment.tolist()): merged_lstAlpha.append(userlist) return merged_lstAlpha
def __init__(self, initlist=None, hook_when_init=True): """ :param initlist: iterable object :param hook_when_init: run hook points when it is True """ UserList.__init__(self) if initlist: if hook_when_init: self.extend(initlist) else: self.data.extend(initlist)
def __init__(self, font): self.di = DI() self.register_services() self.screen_height = 60 self.screen_width = 100 self.gamefont = sys.path[0] + '/data/fonts/' + font self.map = Map(80,45) self.fov_recompute = True self.game_state = "playing" self.player_action = None #create the root console libtcod.console_set_custom_font(self.gamefont.encode('utf-8'), libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_ASCII_INROW) libtcod.console_init_root(self.screen_width, self.screen_height, 'crogue'.encode('utf-8'), False) #Create a console to draw to the screen self.con = libtcod.console_new(self.screen_width, self.screen_height) self.player = Player(self.map.starting_pos[0], self.map.starting_pos[1]) self.objects = UserList() self.objects.append(self.player) self.Messages = self.di.Request("Console") self.Messages.add_message("Game has been started.") self.load_monsters() self.add_monsters() self.add_items()
def __getitem__(self, i): if sys.version_info < (3, ): if isinstance(i, slice): # TODO Return just a list. Why? return [self[i] for i in range(*i.indices(len(self)))] # return UserList([self[i] for i in range(*i.indices(len(self)))]) return UserList.__getitem__(self, i)
def __getitem__(self, item): result = UserList.__getitem__(self, item) if type(result) is list: if len(result) > 1: return USBackItemList(self._usr, result) else: return result
def testSequenceArrayConversion(self): """Test conversion of sequence-like objects to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam if six.PY3: from collections import UserList else: from UserList import UserList items = UserList() for i in range(10): items.append(Spam(str(i))) result = ArrayConversionTest.EchoRange(items) self.assertTrue(result[0].__class__ == Spam) self.assertTrue(len(result) == 10)
def __init__(self, data=None, elementType=None, stringRepr=None, comments="", keywords=[]): if data is not None and len(data)!=0: assert( hasattr(data[0], '__class__') ) if elementType is not None: assert( isinstance(data[0], elementType) ) UserList.__init__(self, data) # save call to __setattr__ self.__dict__['elementType'] = elementType #self.elementType = elementType # class of elements in that set self.stringRepr = stringRepr # this will hold a concise string repr of # the set of objects in that list self.__dict__['comments'] = comments self.__dict__['keywords'] = keywords self.selector = None
def test_cmp(self): self.assertEqual(cmp(-1, 1), -1) self.assertEqual(cmp(1, -1), 1) self.assertEqual(cmp(1, 1), 0) # verify that circular objects are not handled a = []; a.append(a) b = []; b.append(b) from collections import UserList c = UserList(); c.append(c) self.assertRaises(RuntimeError, cmp, a, b) self.assertRaises(RuntimeError, cmp, b, c) self.assertRaises(RuntimeError, cmp, c, a) self.assertRaises(RuntimeError, cmp, a, c) # okay, now break the cycles a.pop(); b.pop(); c.pop() self.assertRaises(TypeError, cmp)
def __getslice__(self, i, j): # fix UserList - don't return a new list of the same type but just the # normal list item if sys.version_info < (3, ): i = max(i, 0) j = max(j, 0) return self.data[i:j] return UserList.__getitem__(self, slice(i, j))
def test_file(): import _pyio as pyio # Python implementation. file_name = "dump.txt" unlink(file_name) try: # verify weak references from array import array from weakref import proxy from collections import UserList f = pyio.open(file_name, "wb") p = proxy(f) p.write(b'teststring') assert f.tell() == p.tell() f.close() f = None # TODO: since weakref is not yet properly implemented this will not work # assert_raises(ReferenceError, getattr, p, 'tell') # verify expected attributes exist f = pyio.open(file_name, "wb") f.name # merely shouldn't blow up f.mode # ditto f.closed # ditto f.close() # verify writelines with instance sequence f = pyio.open(file_name, "wb") l = UserList([b'1', b'2']) f.writelines(l) f.close() f = pyio.open(file_name, 'rb') buf = f.read() assert buf == b'12' f.close() # verify writelines with integers f = pyio.open(file_name, "wb") assert_raises(TypeError, f.writelines, [1, 2, 3]) f.close() # verify writelines with integers in UserList f = pyio.open(file_name, "wb") l = UserList([1, 2, 3]) assert_raises(TypeError, f.writelines, l) f.close() # verify writelines with non-string object class NonString: pass f = pyio.open(file_name, "wb") assert_raises(TypeError, f.writelines, [NonString(), NonString()]) f.close() f = pyio.open(file_name, "wb") assert f.name == file_name assert not f.isatty() assert not f.closed f.close() assert f.closed finally: unlink(file_name)
from django.http import HttpResponseRedirect from django.contrib.auth.models import User @api_view(['GET']) def current_user( request ): # Determine the current user by their token, and return their data serializer = UserSerializer(request.user) return Response(serializer.data) class UserList( APIView ): # 'UserList' because normally we'd have a get method here too, for retrieving a list of all User objects. permission_classes = ( permissions.AllowAny, ) #permissions.AllowAny, because otherwise, the user would have to be logged in before they could sign up def post(self, request, format=None): serializer = UserSerializerWithToken(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) create_user = UserList.as_view()
def __setitem__(self, i, item): UserList.__setitem__(self, i, item) self.unique = False
def __setslice__(self, i, j, other): UserList.__setslice__(self, i, j, other) self.unique = False
def __init__(self, seq = []): UserList.__init__(self, seq) self.unique = True
def __len__(self): self.__make_unique() return UserList.__len__(self)
def __init__(self): super(BaseModule, self).__init__() self.options = UserList() self.register_options()
# make sure all call counts are correct # 1 __init__ per loads(), plus original object = 3 # 1 __getinitargs__ per dumps(), plus 2 extra calls per test = 6 if COUNT_INIT != 3 or COUNT_GETARGS != 6: raise "ERROR(3)" # do a multilevel object to test all three cases # (toplevel, attr, item) # toplevel f = Foo(1, 2, 3, 4) # first level attr f.x = Foo(5, 6, 7, 8) # as item in a UserList f.y = UserList(['x', 'y', 'z']) f.y += [Foo(9, 10, 11, 12), UserList(['a', 'b', 'c'])] # list inside list f.z = [1, 2, 3, UserList([4, 5, Foo(13, 14, 15, 16)])] x = xml_pickle.dumps(f) o = xml_pickle.loads(x) # check all check_foo(f, o, 4) check_foo(f.x, o.x, 5) check_foo(f.y[3], o.y[3], 5) check_foo(f.z[3][2], o.z[3][2], 6) print("** OK **")
def __init__(self, value=None, tag=None): BERStructured.__init__(self, tag) assert value is not None UserList.__init__(self, value)
def __init__(self, items=None, eol=None, path=None, encoding='utf-8'): UserList.__init__(self, items or []) self._eol = eol self.path = path self.encoding = encoding
def get_message_history(self, entity, limit=20, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0): """ Gets the message history for the specified entity Args: entity (:obj:`entity`): The entity from whom to retrieve the message history. limit (:obj:`int` | :obj:`None`, optional): Number of messages to be retrieved. Due to limitations with the API retrieving more than 3000 messages will take longer than half a minute (or even more based on previous calls). The limit may also be ``None``, which would eventually return the whole history. offset_date (:obj:`datetime`): Offset date (messages *previous* to this date will be retrieved). Exclusive. offset_id (:obj:`int`): Offset message ID (only messages *previous* to the given ID will be retrieved). Exclusive. max_id (:obj:`int`): All the messages with a higher (newer) ID or equal to this will be excluded min_id (:obj:`int`): All the messages with a lower (older) ID or equal to this will be excluded. add_offset (:obj:`int`): Additional message offset (all of the specified offsets + this offset = older messages). Returns: A list of messages with extra attributes: * ``.total`` = (on the list) total amount of messages sent. * ``.sender`` = entity of the sender. * ``.fwd_from.sender`` = if fwd_from, who sent it originally. * ``.fwd_from.channel`` = if fwd_from, original channel. * ``.to`` = entity to which the message was sent. """ entity = self.get_input_entity(entity) limit = float('inf') if limit is None else int(limit) if limit == 0: # No messages, but we still need to know the total message count result = self( GetHistoryRequest(peer=entity, limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0)) return getattr(result, 'count', len(result.messages)), [], [] total_messages = 0 messages = UserList() entities = {} while len(messages) < limit: # Telegram has a hard limit of 100 real_limit = min(limit - len(messages), 100) result = self( GetHistoryRequest(peer=entity, limit=real_limit, offset_date=offset_date, offset_id=offset_id, max_id=max_id, min_id=min_id, add_offset=add_offset, hash=0)) messages.extend(m for m in result.messages if not isinstance(m, MessageEmpty)) total_messages = getattr(result, 'count', len(result.messages)) # TODO We can potentially use self.session.database, but since # it might be disabled, use a local dictionary. for u in result.users: entities[utils.get_peer_id(u)] = u for c in result.chats: entities[utils.get_peer_id(c)] = c if len(result.messages) < real_limit: break offset_id = result.messages[-1].id offset_date = result.messages[-1].date # Telegram limit seems to be 3000 messages within 30 seconds in # batches of 100 messages each request (since the FloodWait was # of 30 seconds). If the limit is greater than that, we will # sleep 1s between each request. if limit > 3000: time.sleep(1) # Add a few extra attributes to the Message to make it friendlier. messages.total = total_messages for m in messages: # TODO Better way to return a total without tuples? m.sender = (None if not m.from_id else entities[utils.get_peer_id( m.from_id)]) if getattr(m, 'fwd_from', None): m.fwd_from.sender = (None if not m.fwd_from.from_id else entities[utils.get_peer_id( m.fwd_from.from_id)]) m.fwd_from.channel = (None if not m.fwd_from.channel_id else entities[utils.get_peer_id( PeerChannel(m.fwd_from.channel_id))]) m.to = entities[utils.get_peer_id(m.to_id)] return messages
def get_dialogs(self, limit=10, offset_date=None, offset_id=0, offset_peer=InputPeerEmpty()): """ Gets N "dialogs" (open "chats" or conversations with other people). Args: limit (:obj:`int` | :obj:`None`): How many dialogs to be retrieved as maximum. Can be set to ``None`` to retrieve all dialogs. Note that this may take whole minutes if you have hundreds of dialogs, as Telegram will tell the library to slow down through a ``FloodWaitError``. offset_date (:obj:`datetime`, optional): The offset date to be used. offset_id (:obj:`int`, optional): The message ID to be used as an offset. offset_peer (:obj:`InputPeer`, optional): The peer to be used as an offset. Returns: A list dialogs, with an additional .total attribute on the list. """ limit = float('inf') if limit is None else int(limit) if limit == 0: # Special case, get a single dialog and determine count dialogs = self( GetDialogsRequest(offset_date=offset_date, offset_id=offset_id, offset_peer=offset_peer, limit=1)) result = UserList() result.total = getattr(dialogs, 'count', len(dialogs.dialogs)) return result total_count = 0 dialogs = OrderedDict() # Use peer id as identifier to avoid dupes while len(dialogs) < limit: real_limit = min(limit - len(dialogs), 100) r = self( GetDialogsRequest(offset_date=offset_date, offset_id=offset_id, offset_peer=offset_peer, limit=real_limit)) total_count = getattr(r, 'count', len(r.dialogs)) messages = {m.id: m for m in r.messages} entities = { utils.get_peer_id(x): x for x in itertools.chain(r.users, r.chats) } for d in r.dialogs: dialogs[utils.get_peer_id(d.peer)] = \ Dialog(self, d, entities, messages) if len(r.dialogs) < real_limit or not isinstance(r, DialogsSlice): # Less than we requested means we reached the end, or # we didn't get a DialogsSlice which means we got all. break offset_date = r.messages[-1].date offset_peer = entities[utils.get_peer_id(r.dialogs[-1].peer)] offset_id = r.messages[-1].id & 4294967296 # Telegram/danog magic dialogs = UserList( itertools.islice(dialogs.values(), min(limit, len(dialogs)))) dialogs.total = total_count return dialogs
i = obj.mcall("inc",args); result[1] = i; obj.set_attr("val",5); i = obj.attr("val"); result[2] = i; return_val = result; """ print('initial, inc(2), set(5)/get:', weave.inline(code, ['obj'])) #---------------------------------------------------------------------------- # indexing of values. #---------------------------------------------------------------------------- from collections import UserList obj = UserList([1, [1, 2], "hello"]) code = """ int i; // find obj length and access each of its items //std::cout << "UserList items: "; //for(i = 0; i < obj.length(); i++) // std::cout << obj[i].str() << " "; //std::cout << std::endl; // assign new values to each of its items for(i = 0; i < obj.length(); i++) obj[i] = "goodbye"; """ weave.inline(code, ['obj']) print("obj with new values:", obj)
def __imul__(self, other): result = UserList.__imul__(self, other) result.unique = False return result
def __init__(self, req): self.height = req.height self.width = req.width UserList.__init__(self, [self.width, self.height])
def insert(self, i): UserList.insert(self, i) self.unique = False
def index(self, item): self.__make_unique() return UserList.index(self, item)
def __radd__(self, other): return UserList.__radd__(self, CLVar(other))
def sort(self, *args, **kwds): self.__make_unique() return UserList.sort(self, *args, **kwds)
def __cmp__(self, other): self.__make_unique() return UserList.__cmp__(self, other)
def __init__(self, seq = []): UserList.__init__(self, Split(seq))
def __getitem__(self, i): self.__make_unique() return UserList.__getitem__(self, i)
def __init__(self,items=[]): UserList.__init__(self,items)
def __getslice__(self, i, j): self.__make_unique() return UserList.__getslice__(self, i, j)
class BaseModule(object): def __init__(self): super(BaseModule, self).__init__() self.options = UserList() self.register_options() def show_info(self): # current = Framework._current try: # output a empty line for beauty print('') for item in ['name', 'path', 'author', 'version']: val = self.meta.get(item) if val: print('%s: %s' % (item.title().rjust(10), val)) # description print('') if 'description' in self.meta: desc = self.meta['description'] print('Description:') print('%s%s' % (' ' * 2, textwrap.fill(desc, 80))) print('') # options print('Options:') self.show_options() except Exception as e: self.perror('%s' % e) return def show_options(self): """ List options """ options = self.options print('') if options: v_mxlen = max([ len(i['value']) if i['value'] and len(i['value']) > 13 else 13 for i in options ]) n_mxlen = max( [len(i['name']) if len(i['name']) > 4 else 4 for i in options]) pattern = ' {} {} {} {}' print( pattern.format('Name'.ljust(n_mxlen), 'Current Value'.ljust(v_mxlen), 'Required'.ljust(8), 'Description')) print( pattern.format('-' * n_mxlen, '-' * v_mxlen, '-' * 8, '-' * 11)) for item in options: key = item['name'] val = item['value'] or 'NULL' rqd = 'YES' if item['required'] else 'NO' desc = item['description'] print( pattern.format(key.ljust(n_mxlen), val.ljust(v_mxlen), rqd.ljust(8), desc)) else: print(" No options found!") print('') def module_pre(self): pass def module_run(self, args): pass def module_post(self): pass def register_options(self): pass def register_option(self, name, value=None, required=False, description=''): if not value: value = 'NULL' if isinstance(value, int): value = str(value) option = Option(name=name, value=value, required=required, description=description) self.options.append(option) def set_option(self, args): k = args.key v = args.value or 'NULL' keys = [x['name'] for x in self.options] if args.key not in keys: print("The Key is not correct.Please use a correct key") return for item in self.options: if item['name'] == k: item['value'] = v def run(self): """ Run the module """ namespace = Namespace() for item in self.options: setattr(namespace, item['name'], item['value']) self.module_pre() self.module_run(namespace) self.module_post()
def __add__(self, other): result = UserList.__add__(self, other) result.unique = False return result
def reverse(self): self.__make_unique() UserList.reverse(self)
def __init__(self, alist): UserList.__init__(self, alist)
def extend(self, other): UserList.extend(self, other) self.unique = False
def append(self, item): UserList.append(self, item) self.unique = False
def count(self, item): self.__make_unique() return UserList.count(self, item)
def __init__(self, data=None): UserList.__init__(self, data) self.tList = self.data
def __init__(self): UserList.__init__(self) self.current_deck = None self.reload()