text
stringlengths
81
112k
Collapse a private message or modmail. def collapse(self): """Collapse a private message or modmail.""" url = self.reddit_session.config['collapse_message'] self.reddit_session.request_json(url, data={'id': self.name})
Mute the sender of this modmail message. :param _unmute: Unmute the user instead. Please use :meth:`unmute_modmail_author` instead of setting this directly. def mute_modmail_author(self, _unmute=False): """Mute the sender of this modmail message. :param _unmute: Unmute the user in...
Uncollapse a private message or modmail. def uncollapse(self): """Uncollapse a private message or modmail.""" url = self.reddit_session.config['uncollapse_message'] self.reddit_session.request_json(url, data={'id': self.name})
Fetch and return the comments for a single MoreComments object. def comments(self, update=True): """Fetch and return the comments for a single MoreComments object.""" if not self._comments: if self.count == 0: # Handle 'continue this thread' type return self._continue_comme...
Friend the user. :param note: A personal note about the user. Requires reddit Gold. :param _unfriend: Unfriend the user. Please use :meth:`unfriend` instead of setting this parameter manually. :returns: The json response from the server. def friend(self, note=None, _unfriend=False...
Return a listing of the Submissions the user has downvoted. :returns: get_content generator of Submission items. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered. As a default, this listing is only accessible by the u...
Return information about this friend, including personal notes. The personal note can be added or overwritten with :meth:friend, but only if the user has reddit Gold. :returns: The json response from the server. def get_friend_info(self): """Return information about this friend, i...
Return a listing of the Submissions the user has upvoted. :returns: get_content generator of Submission items. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered. As a default, this listing is only accessible by the use...
Mark message(s) as read or unread. :returns: The json response from the server. def mark_as_read(self, messages, unread=False): """Mark message(s) as read or unread. :returns: The json response from the server. """ ids = [] if isinstance(messages, Inboxable): ...
Return a UserList of Redditors with whom the user has blocked. def get_blocked(self): """Return a UserList of Redditors with whom the user has blocked.""" url = self.reddit_session.config['blocked'] return self.reddit_session.request_json(url)
Return a cached dictionary of the user's moderated reddits. This list is used internally. Consider using the `get_my_moderation` function instead. def get_cached_moderated_reddits(self): """Return a cached dictionary of the user's moderated reddits. This list is used internally. Consi...
Return a list of MoreComments objects removed from tree. def _extract_more_comments(tree): """Return a list of MoreComments objects removed from tree.""" more_comments = [] queue = [(None, x) for x in tree] while len(queue) > 0: parent, comm = queue.pop(0) if isi...
Return an edit-only submission object based on the id. def from_id(reddit_session, subreddit_id): """Return an edit-only submission object based on the id.""" pseudo_data = {'id': subreddit_id, 'permalink': '/comments/{0}'.format(subreddit_id)} return Submission(reddit_se...
Request the url and return a Submission object. :param reddit_session: The session to make the request with. :param url: The url to build the Submission object from. :param comment_limit: The desired number of comments to fetch. If <= 0 fetch the default number for the session's use...
Comment on the submission using the specified text. :returns: A Comment object for the newly created comment. def add_comment(self, text): """Comment on the submission using the specified text. :returns: A Comment object for the newly created comment. """ # pylint: disable=W0...
Return forest of comments, with top-level comments as tree roots. May contain instances of MoreComment objects. To easily replace these objects with Comment objects, use the replace_more_comments method then fetch this attribute. Use comment replies to walk down the tree. To get an unne...
Return a get_content generator for the submission's duplicates. :returns: get_content generator iterating over Submission objects. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` and `object_filter` parameters cannot be altered. def get_duplica...
Return available link flair choices and current flair. Convenience function for :meth:`~.AuthenticatedReddit.get_flair_choices` populating both the `subreddit` and `link` parameters. :returns: The json response from the server. def get_flair_choices(self, *args, **kwargs): """...
Lock thread. Requires that the currently authenticated user has the modposts oauth scope or has user/password authentication as a mod of the subreddit. :returns: The json response from the server. def lock(self): """Lock thread. Requires that the currently authenticated user ...
Mark as Not Safe For Work. Requires that the currently authenticated user is the author of the submission, has the modposts oauth scope or has user/password authentication as a mod of the subreddit. :returns: The json response from the server. def mark_as_nsfw(self, unmark_nsfw=False)...
Update the comment tree by replacing instances of MoreComments. :param limit: The maximum number of MoreComments objects to replace. Each replacement requires 1 API request. Set to None to have no limit, or to 0 to make no extra requests. Default: 32 :param threshold: The minimu...
Set flair for this submission. Convenience function that utilizes :meth:`.ModFlairMixin.set_flair` populating both the `subreddit` and `item` parameters. :returns: The json response from the server. def set_flair(self, *args, **kwargs): """Set flair for this submission. Conve...
Set 'Suggested Sort' for the comments of the submission. Comments can be sorted in one of (confidence, top, new, hot, controversial, old, random, qa, blank). :returns: The json response from the server. def set_suggested_sort(self, sort='blank'): """Set 'Suggested Sort' for the commen...
Sticky a post in its subreddit. If there is already a stickied post in the designated slot it will be unstickied. :param bottom: Set this as the top or bottom sticky. If no top sticky exists, this submission will become the top sticky regardless. :returns: The json respons...
Lock thread. Requires that the currently authenticated user has the modposts oauth scope or has user/password authentication as a mod of the subreddit. :returns: The json response from the server. def unlock(self): """Lock thread. Requires that the currently authenticated use...
Unsticky this post. :returns: The json response from the server def unsticky(self): """Unsticky this post. :returns: The json response from the server """ url = self.reddit_session.config['sticky_submission'] data = {'id': self.fullname, 'state': False} return...
Remove all user flair on this subreddit. :returns: The json response from the server when there is flair to clear, otherwise returns None. def clear_all_flair(self): """Remove all user flair on this subreddit. :returns: The json response from the server when there is flair to ...
Return an instance of the appropriate class from the json dict. def from_api_response(cls, reddit_session, json_dict): """Return an instance of the appropriate class from the json dict.""" # The Multireddit response contains the Subreddits attribute as a list # of dicts of the form {'name': 'su...
Add a subreddit to the multireddit. :param subreddit: The subreddit name or Subreddit object to add The additional parameters are passed directly into :meth:`~praw.__init__.BaseReddit.request_json`. def add_subreddit(self, subreddit, _delete=False, *args, **kwargs): """Add a subreddit...
Copy this multireddit. Convenience function that utilizes :meth:`.MultiredditMixin.copy_multireddit` populating both the `from_redditor` and `from_name` parameters. def copy(self, to_name): """Copy this multireddit. Convenience function that utilizes :meth:`.Multireddi...
Edit this multireddit. Convenience function that utilizes :meth:`.MultiredditMixin.edit_multireddit` populating the `name` parameter. def edit(self, *args, **kwargs): """Edit this multireddit. Convenience function that utilizes :meth:`.MultiredditMixin.edit_multireddit...
Remove a subreddit from the user's multireddit. def remove_subreddit(self, subreddit, *args, **kwargs): """Remove a subreddit from the user's multireddit.""" return self.add_subreddit(subreddit, True, *args, **kwargs)
Rename this multireddit. This function is a handy shortcut to :meth:`rename_multireddit` of the reddit_session. def rename(self, new_name, *args, **kwargs): """Rename this multireddit. This function is a handy shortcut to :meth:`rename_multireddit` of the reddit_session. ...
Return a Redditor object from the data. def _convert(reddit_session, data): """Return a Redditor object from the data.""" retval = Redditor(reddit_session, data['name'], fetch=False) retval.id = data['id'].split('_')[1] # pylint: disable=C0103,W0201 return retval
Return an instance of the appropriate class from the json_dict. def from_api_response(cls, reddit_session, json_dict): """Return an instance of the appropriate class from the json_dict.""" # The WikiPage response does not contain the necessary information # in the JSON response to determine the...
Add an editor to this wiki page. :param username: The name or Redditor object of the user to add. :param _delete: If True, remove the user as an editor instead. Please use :meth:`remove_editor` rather than setting it manually. Additional parameters are passed into :meth:`~p...
Return the settings for this wiki page. Includes permission level, names of editors, and whether the page is listed on /wiki/pages. Additional parameters are passed into :meth:`~praw.__init__.BaseReddit.request_json` def get_settings(self, *args, **kwargs): """Return the setti...
Edit the wiki page. Convenience function that utilizes :meth:`.AuthenticatedReddit.edit_wiki_page` populating both the ``subreddit`` and ``page`` parameters. def edit(self, *args, **kwargs): """Edit the wiki page. Convenience function that utilizes :meth:`.Authenticate...
Edit the settings for this individual wiki page. :param permlevel: Who can edit this page? (0) use subreddit wiki permissions, (1) only approved wiki contributors for this page may edit (see :meth:`~praw.objects.WikiPage.add_editor`), (2) only mods may edit and v...
Remove an editor from this wiki page. :param username: The name or Redditor object of the user to remove. This method points to :meth:`add_editor` with _delete=True. Additional parameters are are passed to :meth:`add_editor` and subsequently into :meth:`~praw.__init__.BaseReddit.reque...
Return a WikiPage object from the data. def _convert(reddit_session, data): """Return a WikiPage object from the data.""" # TODO: The _request_url hack shouldn't be necessary # pylint: disable=W0212 subreddit = reddit_session._request_url.rsplit('/', 4)[1] # pylint: enable=W0212...
Indefinitely yield new comments from the provided subreddit. Comments are yielded from oldest to newest. :param reddit_session: The reddit_session to make requests from. In all the examples this is assigned to the variable ``r``. :param subreddit: Either a subreddit object, or the name of a ...
Indefinitely yield new submissions from the provided subreddit. Submissions are yielded from oldest to newest. :param reddit_session: The reddit_session to make requests from. In all the examples this is assigned to the variable ``r``. :param subreddit: Either a subreddit object, or the name of a ...
Return a verified list of valid Redditor instances. :param redditors: A list comprised of Redditor instances and/or strings that are to be verified as actual redditor accounts. :param sub: A Subreddit instance that the authenticated account has flair changing permission on. Note: Flair wil...
Yield submissions between two timestamps. If both ``highest_timestamp`` and ``lowest_timestamp`` are unspecified, yields all submissions in the ``subreddit``. Submissions are yielded from newest to oldest(like in the "new" queue). :param reddit_session: The reddit_session to make requests from. In al...
Given a sequence, divide it into sequences of length `chunk_length`. :param allow_incomplete: If True, allow final chunk to be shorter if the given sequence is not an exact multiple of `chunk_length`. If False, the incomplete chunk will be discarded. def chunk_sequence(sequence, chunk_length, allo...
Convert strings representing base36 numbers into an integer. def convert_id36_to_numeric_id(id36): """Convert strings representing base36 numbers into an integer.""" if not isinstance(id36, six.string_types) or id36.count("_") > 0: raise ValueError("must supply base36 string, not fullname (e.g. use " ...
Convert an integer into its base36 string representation. This method has been cleaned up slightly to improve readability. For more info see: https://github.com/reddit/reddit/blob/master/r2/r2/lib/utils/_utils.pyx https://www.reddit.com/r/redditdev/comments/n624n/submission_ids_question/ https:/...
Return a flattened version of the passed in tree. :param nested_attr: The attribute name that contains the nested items. Defaults to ``replies`` which is suitable for comments. :param depth_first: When true, add to the list in a depth-first manner rather than the default breadth-first manner. ...
Return url after stripping trailing .json and trailing slashes. def normalize_url(url): """Return url after stripping trailing .json and trailing slashes.""" if url.endswith('.json'): url = url[:-5] if url.endswith('/'): url = url[:-1] return url
Add an item to the set discarding the oldest item if necessary. def add(self, item): """Add an item to the set discarding the oldest item if necessary.""" if item in self._set: self._fifo.remove(item) elif len(self._set) == self.max_items: self._set.remove(self._fifo.pop...
Downloads an entire table as a zip file. :param str datatable_code: The datatable code to download, such as MER/F1 :param str filename: The filename for the download. \ If not specified, will download to the current working directory :param str api_key: Most databases require api_key for bulk download ...
Return dataframe of requested dataset from Quandl. :param dataset: str or list, depending on single dataset usage or multiset usage Dataset codes are available on the Quandl website :param str api_key: Downloads are limited to 50 unless api_key is specified :param str start_date, end_date: Optio...
Downloads an entire database. :param str database: The database code to download :param str filename: The filename for the download. \ If not specified, will download to the current working directory :param str api_key: Most databases require api_key for bulk download :param str download_type: 'part...
Map of json-rpc available calls. :return str: def jsonrpc_map(self): """ Map of json-rpc available calls. :return str: """ result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([ "{0}: {1}".format(fname, f.__doc__) for fname, f in self.disp...
通过hunter调用gm指令,可调用hunter指令库中定义的所有指令,也可以调用text类型的gm指令 gm指令相关功能请参考safaia GM指令扩展模块 :param cmd: 指令 :param type: 语言,默认text :return: None def command(self, cmd, type=None): """ 通过hunter调用gm指令,可调用hunter指令库中定义的所有指令,也可以调用text类型的gm指令 gm指令相关功能请参考safaia GM指令扩展模块 :p...
Add a method to the dispatcher. Parameters ---------- f : callable Callable to be added. name : str, optional Name to register (the default is function **f** name) Notes ----- When used as a decorator keeps callable object unmodified. ...
Add prototype methods to the dispatcher. Parameters ---------- prototype : object or dict Initial method mapping. If given prototype is a dictionary then all callable objects will be added to dispatcher. If given prototype is an object then all pu...
小数据片段拼接成完整数据包 如果内容足够则yield数据包 def input(self, data): """ 小数据片段拼接成完整数据包 如果内容足够则yield数据包 """ self.buf += data while len(self.buf) > HEADER_SIZE: data_len = struct.unpack('i', self.buf[0:HEADER_SIZE])[0] if len(self.buf) >= data_len + HEADER_...
content should be str def pack(content): """ content should be str """ if isinstance(content, six.text_type): content = content.encode("utf-8") return struct.pack('i', len(content)) + content
return length, content def unpack(data): """ return length, content """ length = struct.unpack('i', data[0:HEADER_SIZE]) return length[0], data[HEADER_SIZE:]
Send the start of a data fragment stream to a websocket client. Subsequent data should be sent using sendFragment(). A fragment stream is completed when sendFragmentEnd() is called. If data is a unicode object then the frame is sent as Text. If the data is a bytearray ob...
Send websocket data frame to the client. If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. def sendMessage(self, data): """ Send websocket data frame to the client. If data is a unico...
将HRpcRemoteException.NodeHasBeenRemovedException转换成PocoTargetRemovedException :param func: 仅限getattr和setattr两个接口方法 :return: def transform_node_has_been_removed_exception(func): """ 将HRpcRemoteException.NodeHasBeenRemovedException转换成PocoTargetRemovedException :param func: 仅限getattr和setattr两个接口方法 ...
Handle request data. At this moment request has correct jsonrpc format. :param dict request: data parsed from request_str. :param jsonrpc.dispatcher.Dispatcher dispatcher: .. versionadded: 1.8.0 def handle_request(cls, request, dispatcher): """ Handle request data. A...
Response to each single JSON-RPC Request. :return iterator(JSONRPC20Response): .. versionadded: 1.9.0 TypeError inside the function is distinguished from Invalid Params. def _get_responses(cls, requests, dispatcher): """ Response to each single JSON-RPC Request. :return ite...
JSON-RPC 2.0 handler. def jsonrpc(self, request): """ JSON-RPC 2.0 handler.""" if request.method != "POST": return HttpResponseNotAllowed(["POST"]) request_str = request.body.decode('utf8') try: jsonrpc_request = JSONRPCRequest.from_json(request_str) exc...
Map of json-rpc available calls. :return str: def jsonrpc_map(self, request): """ Map of json-rpc available calls. :return str: """ result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([ "{0}: {1}".format(fname, f.__doc__) for fname, f in ...
Sample this motion track into discretized motion events. Args: contact_id: contact point id accuracy: motion minimum difference in space dt: sample time difference def discretize(self, contact_id=0, accuracy=0.004, dt=0.001): """ Sample this motion track int...
Dump a hierarchy immediately from target runtime and store into a Node (subclass of :py:class:`AbstractNode <poco.sdk.AbstractNode>`) object. Returns: :py:class:`inherit from AbstractNode <Node>`: Each time a new node instance is created by latest hierarchy data. def getRoot...
Check, whether function 'func' accepts parameters 'args', 'kwargs'. NOTE: Method is called after funct(*args, **kwargs) generated TypeError, it is aimed to destinguish TypeError because of invalid parameters from TypeError from inside the function. .. versionadded: 1.9.0 def is_invalid_params(func, *...
Get the top level element for the application with the specified bundle ID, such as com.vmware.fusion. def getAppRefByBundleId(cls, bundleId): """ Get the top level element for the application with the specified bundle ID, such as com.vmware.fusion. """ ra = AppKit.NSRun...
Return the driver of this agent related to. None if the driver is not ready to bind. Returns: :py:class:`inherit from Poco <poco.pocofw.Poco>`: the driver of this agent related to. def driver(self): """ Return the driver of this agent related to. None if the driver is not ready to ...
Crawl the hierarchy tree using the simple DFS algorithm. The ``dump`` procedure is the engine independent as the hierarchy structure is wrapped by :py:class:`AbstractNode <poco.sdk.AbstractNode>` and therefore the ``dump`` procedure can be algorithmized. Following code demonstrates the simplest...
Select the direct child(ren) from the UI element(s) given by the query expression, see ``QueryCondition`` for more details about the selectors. Args: name: query expression of attribute "name", i.e. the UI elements with ``name`` name will be selected attrs: other query expressio...
Select the direct child(ren) from the UI element(s) given by the query expression, see ``QueryCondition`` for more details about the selectors. Warnings: Experimental method, may not be available for all drivers. Returns: :py:class:`UIObjectProxy <poco.proxy.UIObjectPro...
Perform the click action on the UI element(s) represented by the UI proxy. If this UI proxy represents a set of UI elements, the first one in the set is clicked and the anchor point of the UI element is used as the default one. It is also possible to click another point offset by providing ``focus`` arg...
Perform the long click action on the UI element(s) represented by the UI proxy. If this UI proxy represents a set of UI elements, the first one in the set is clicked and the anchor point of the UI element is used as the default one. Similar to click but press the screen for the given time interval and...
Perform a swipe action given by the direction from this UI element. For notices and limitations see :py:meth:`.click() <poco.proxy.UIObjectProxy.click>`. Args: direction (2-:obj:`tuple`/2-:obj:`list`/:obj:`str`): coordinates (x, y) in NormalizedCoordinate system, it can be al...
Similar to swipe action, but the end point is provide by a UI proxy or by fixed coordinates. Args: target (:py:class:`UIObjectProxy <poco.proxy.UIObjectProxy>`): a UI proxy or 2-list/2-tuple coordinates (x, y) in NormalizedCoordinate system duration (:py:obj:`float`): time ...
Simply touch down from point A and move to point B then release up finally. This action is performed within specific motion range and duration. Args: direction (:py:obj:`str`): scrolling direction. "vertical" or "horizontal" percent (:py:obj:`float`): scrolling distance percenta...
Squeezing or expanding 2 fingers on this UI with given motion range and duration. Args: direction (:py:obj:`str`): pinching direction, only "in" or "out". "in" for squeezing, "out" for expanding percent (:py:obj:`float`): squeezing range from or expanding range to of the bounds of the U...
Get a new UI proxy copy with the given focus. Return a new UI proxy object as the UI proxy is immutable. Args: f (2-:obj:`tuple`/2-:obj:`list`/:obj:`str`): the focus point, it can be specified as 2-list/2-tuple coordinates (x, y) in NormalizedCoordinate system or as 'center' or 'anchor...
Get the position of the UI elements. Args: focus: focus point of UI proxy, see :py:meth:`.focus() <poco.proxy.UIObjectProxy.focus>` for more details Returns: 2-list/2-tuple: coordinates (x, y) in NormalizedCoordinate system Raises: TypeError: raised when u...
Block and wait for max given time before the UI element appears. Args: timeout: maximum waiting time in seconds Returns: :py:class:`UIObjectProxy <poco.proxy.UIObjectProxy>`: self def wait(self, timeout=3): """ Block and wait for max given time before the UI el...
Block and wait until the UI element **disappears** within the given timeout. Args: timeout: maximum waiting time in seconds Raises: PocoTargetTimeout: when timeout def wait_for_disappearance(self, timeout=120): """ Block and wait until the UI element **disappea...
Retrieve the attribute of UI element by given attribute name. Return None if attribute does not exist. If attribute type is :obj:`str`, it is encoded to utf-8 as :obj:`str` in Python2.7. Args: name: attribute name, it can be one of the following or any other customized type...
Change the attribute value of the UI element. Not all attributes can be casted to text. If changing the immutable attributes or attributes which do not exist, the InvalidOperationException exception is raised. Args: name: attribute name val: new attribute value to cast ...
Get the parameters of bounding box of the UI element. Returns: :obj:`list` <:obj:`float`>: 4-list (top, right, bottom, left) coordinates related to the edge of screen in NormalizedCoordinate system def get_bounds(self): """ Get the parameters of bounding box of the UI e...
Args: origin (:obj:`str`): original string pattern (:obj:`str`): Regexp pattern string Returns: bool: True if matches otherwise False. def compare(self, origin, pattern): """ Args: origin (:obj:`str`): original string pattern (:obj:`s...
See Also: :py:meth:`IMatcher.match <poco.sdk.DefaultMatcher.IMatcher.match>` def match(self, cond, node): """ See Also: :py:meth:`IMatcher.match <poco.sdk.DefaultMatcher.IMatcher.match>` """ op, args = cond # 条件匹配 if op == 'and': for arg in args: ...
Wait until any of given UI proxies show up before timeout and return the first appeared UI proxy. All UI proxies will be polled periodically. See options :py:class:`poll_interval <poco.pocofw.Poco>` in ``Poco``'s initialization for more details. Args: objects (Iterable<:py:class:`UI...
Wait until all of given UI proxies show up before timeout. All UI proxies will be polled periodically. See option :py:class:`poll_interval <poco.pocofw.Poco>` in ``Poco``'s initialization for more details. Args: objects (Iterable<:py:class:`UIObjectProxy <poco.proxy.UIObjectProxy>`...
Snapshot current **hierarchy** and cache it into a new poco instance. This new poco instance is a copy from current poco instance (``self``). The hierarchy of the new poco instance is fixed and immutable. It will be super fast when calling ``dump`` function from frozen poco. See the example below. ...
Perform click (touch, tap, etc.) action on target device at given coordinates. The coordinates (x, y) are either a 2-list or 2-tuple. The coordinates values for x and y must be in the interval between 0 ~ 1 to represent the percentage of the screen. For example, the coordinates ``[0.5, 0.5]`` r...
Perform swipe action on target device from point to point given by start point and end point, or by the direction vector. At least one of the end point or direction must be provided. The coordinates (x, y) definition for points is the same as for ``click`` event. The components of the direction...
Similar to click but press the screen for the given time interval and then release Args: pos (:obj:`2-list/2-tuple`): coordinates (x, y) in range from 0 to 1 duration: duration of press the screen def long_click(self, pos, duration=2.0): """ Similar to click but press t...
Scroll from the lower part to the upper part of the entire screen. Args: direction (:py:obj:`str`): scrolling direction. "vertical" or "horizontal" percent (:py:obj:`float`): scrolling distance percentage of the entire screen height or width according to direction ...
Squeezing or expanding 2 fingers on the entire screen. Args: direction (:py:obj:`str`): pinching direction, only "in" or "out". "in" for squeezing, "out" for expanding percent (:py:obj:`float`): squeezing range from or expanding range to of the entire screen duration (:py:ob...
Similar to click but press the screen for the given time interval and then release Args: tracks (:py:obj:`list`): list of :py:class:`poco.utils.track.MotionTrack` object accuracy (:py:obj:`float`): motion accuracy for each motion steps in normalized coordinate metrics. def apply_motion_t...