Search is not available for this dataset
text stringlengths 75 104k |
|---|
def syncFlags(self):
"""
Update the cached list of all enabled flags, and store it in the :attr:`flags` attribute.
"""
self.flags = set(self.skype.conn("GET", SkypeConnection.API_FLAGS,
auth=SkypeConnection.Auth.SkypeToken).json()) |
def contact(self, id):
"""
Retrieve all details for a specific contact, including fields such as birthday and mood.
Args:
id (str): user identifier to lookup
Returns:
SkypeContact: resulting contact object
"""
try:
json = self.skype.c... |
def user(self, id):
"""
Retrieve public information about a user.
Args:
id (str): user identifier to lookup
Returns:
SkypeUser: resulting user object
"""
json = self.skype.conn("POST", "{0}/batch/profiles".format(SkypeConnection.API_PROFILE),
... |
def bots(self):
"""
Retrieve a list of all known bots.
Returns:
SkypeBotUser list: resulting bot user objects
"""
json = self.skype.conn("GET", "{0}/agents".format(SkypeConnection.API_BOT),
auth=SkypeConnection.Auth.SkypeToken).json().g... |
def bot(self, id):
"""
Retrieve a single bot.
Args:
id (str): UUID or username of the bot
Returns:
SkypeBotUser: resulting bot user object
"""
json = self.skype.conn("GET", "{0}/agents".format(SkypeConnection.API_BOT), params={"agentId": id},
... |
def search(self, query):
"""
Search the Skype Directory for a user.
Args:
query (str): name to search for
Returns:
SkypeUser list: collection of possible results
"""
results = self.skype.conn("GET", SkypeConnection.API_DIRECTORY,
... |
def requests(self):
"""
Retrieve any pending contact requests.
Returns:
:class:`SkypeRequest` list: collection of requests
"""
requests = []
for json in self.skype.conn("GET", "{0}/users/{1}/invites"
.format(SkypeCon... |
def fromRaw(cls, skype=None, raw={}):
"""
Create a new instance based on the raw properties of an API response.
This can be overridden to automatically create subclass instances based on the raw content.
Args:
skype (Skype): parent Skype instance
raw (dict): raw... |
def merge(self, other):
"""
Copy properties from other into self, skipping ``None`` values. Also merges the raw data.
Args:
other (SkypeObj): second object to copy fields from
"""
for attr in self.attrs:
if not getattr(other, attr, None) is None:
... |
def merge(self, obj):
"""
Add a given object to the cache, or update an existing entry to include more fields.
Args:
obj (SkypeObj): object to add to the cache
"""
if obj.id in self.cache:
self.cache[obj.id].merge(obj)
else:
self.cache... |
def handle(*codes, **kwargs):
"""
Method decorator: if a given status code is received, re-authenticate and try again.
Args:
codes (int list): status codes to respond to
regToken (bool): whether to try retrieving a new token on error
Returns:
method:... |
def externalCall(cls, method, url, codes=(200, 201, 204, 207), **kwargs):
"""
Make a public API call without a connected :class:`.Skype` instance.
The obvious implications are that no authenticated calls are possible, though this allows accessing some public
APIs such as join URL lookup... |
def syncStateCall(self, method, url, params={}, **kwargs):
"""
Follow and track sync state URLs provided by an API endpoint, in order to implicitly handle pagination.
In the first call, ``url`` and ``params`` are used as-is. If a ``syncState`` endpoint is provided in the
response, subs... |
def setUserPwd(self, user, pwd):
"""
Replace the stub :meth:`getSkypeToken` method with one that connects via the Microsoft account flow using the
given credentials. Avoids storing the account password in an accessible way.
Args:
user (str): username or email address of the... |
def readToken(self):
"""
Attempt to re-establish a connection using previously acquired tokens.
If the Skype token is valid but the registration token is invalid, a new endpoint will be registered.
Raises:
.SkypeAuthException: if the token file cannot be used to authenticat... |
def writeToken(self):
"""
Store details of the current connection in the named file.
This can be used by :meth:`readToken` to re-authenticate at a later time.
"""
# Write token file privately.
with os.fdopen(os.open(self.tokenFile, os.O_WRONLY | os.O_CREAT, 0o600), "w") ... |
def verifyToken(self, auth):
"""
Ensure the authentication token for the given auth method is still valid.
Args:
auth (Auth): authentication type to check
Raises:
.SkypeAuthException: if Skype auth is required, and the current token has expired and can't be rene... |
def liveLogin(self, user, pwd):
"""
Obtain connection parameters from the Microsoft account login page, and perform a login with the given email
address or Skype username, and its password. This emulates a login to Skype for Web on ``login.live.com``.
.. note::
Microsoft ac... |
def guestLogin(self, url, name):
"""
Connect to Skype as a guest, joining a given conversation.
In this state, some APIs (such as contacts) will return 401 status codes. A guest can only communicate with
the conversation they originally joined.
Args:
url (str): pub... |
def refreshSkypeToken(self):
"""
Take the existing Skype token and refresh it, to extend the expiry time without other credentials.
Raises:
.SkypeAuthException: if the login request is rejected
.SkypeApiException: if the login form can't be processed
"""
... |
def getUserId(self):
"""
Ask Skype for the authenticated user's identifier, and store it on the connection object.
"""
self.userId = self("GET", "{0}/users/self/profile".format(self.API_USER),
auth=self.Auth.SkypeToken).json().get("username") |
def getRegToken(self):
"""
Acquire a new registration token.
Once successful, all tokens and expiry times are written to the token file (if specified on initialisation).
"""
self.verifyToken(self.Auth.SkypeToken)
token, expiry, msgsHost, endpoint = SkypeRegistrationToken... |
def syncEndpoints(self):
"""
Retrieve all current endpoints for the connected user.
"""
self.endpoints["all"] = []
for json in self("GET", "{0}/users/ME/presenceDocs/messagingService".format(self.msgsHost),
params={"view": "expanded"}, auth=self.Auth.RegT... |
def auth(self, user, pwd):
"""
Perform a login with the given Skype username and its password. This emulates a login to Skype for Web on
``api.skype.com``.
Args:
user (str): username of the connecting account
pwd (str): password of the connecting account
... |
def checkUser(self, user):
"""
Query a username or email address to see if a corresponding Microsoft account exists.
Args:
user (str): username or email address of an account
Returns:
bool: whether the account exists
"""
return not self.conn("POS... |
def auth(self, user, pwd):
"""
Obtain connection parameters from the Microsoft account login page, and perform a login with the given email
address or Skype username, and its password. This emulates a login to Skype for Web on ``login.live.com``.
.. note::
Microsoft account... |
def auth(self, url, name):
"""
Connect to Skype as a guest, joining a given conversation.
In this state, some APIs (such as contacts) will return 401 status codes. A guest can only communicate with
the conversation they originally joined.
Args:
url (str): public jo... |
def auth(self, token):
"""
Take an existing Skype token and refresh it, to extend the expiry time without other credentials.
Args:
token (str): existing Skype token
Returns:
(str, datetime.datetime) tuple: Skype token, and associated expiry if known
Rai... |
def auth(self, skypeToken):
"""
Request a new registration token using a current Skype token.
Args:
skypeToken (str): existing Skype token
Returns:
(str, datetime.datetime, str, SkypeEndpoint) tuple: registration token, associated expiry if known,
... |
def getMac256Hash(challenge, appId="msmsgs@msnmsgr.com", key="Q1P7W2E4J9R8U3S5"):
"""
Generate the lock-and-key response, needed to acquire registration tokens.
"""
clearText = challenge + appId
clearText += "0" * (8 - len(clearText) % 8)
def int32ToHexString(n):
... |
def config(self, name="skype"):
"""
Configure this endpoint to allow setting presence.
Args:
name (str): display name for this endpoint
"""
self.conn("PUT", "{0}/users/ME/endpoints/{1}/presenceDocs/messagingService"
.format(self.conn.msgsHost... |
def ping(self, timeout=12):
"""
Send a keep-alive request for the endpoint.
Args:
timeout (int): maximum amount of time for the endpoint to stay active
"""
self.conn("POST", "{0}/users/ME/endpoints/{1}/active".format(self.conn.msgsHost, self.id),
au... |
def subscribe(self):
"""
Subscribe to contact and conversation events. These are accessible through :meth:`getEvents`.
"""
self.conn("POST", "{0}/users/ME/endpoints/{1}/subscriptions".format(self.conn.msgsHost, self.id),
auth=SkypeConnection.Auth.RegToken,
... |
def recent(self):
"""
Retrieve a selection of conversations with the most recent activity, and store them in the cache.
Each conversation is only retrieved once, so subsequent calls will retrieve older conversations.
Returns:
:class:`SkypeChat` list: collection of recent co... |
def chat(self, id):
"""
Get a single conversation by identifier.
Args:
id (str): single or group chat identifier
"""
json = self.skype.conn("GET", "{0}/users/ME/conversations/{1}".format(self.skype.conn.msgsHost, id),
auth=SkypeConnecti... |
def create(self, members=(), admins=()):
"""
Create a new group chat with the given users.
The current user is automatically added to the conversation as an admin. Any other admin identifiers must also
be present in the member list.
Args:
members (str list): user i... |
def urlToIds(url):
"""
Resolve a ``join.skype.com`` URL and returns various identifiers for the group conversation.
Args:
url (str): public join URL, or identifier from it
Returns:
dict: related conversation's identifiers -- keys: ``id``, ``long``, ``blob``
... |
def userToId(url):
"""
Extract the username from a contact URL.
Matches addresses containing ``users/<user>`` or ``users/ME/contacts/<user>``.
Args:
url (str): Skype API URL
Returns:
str: extracted identifier
"""
match = re.search(r"user... |
def chatToId(url):
"""
Extract the conversation ID from a conversation URL.
Matches addresses containing ``conversations/<chat>``.
Args:
url (str): Skype API URL
Returns:
str: extracted identifier
"""
match = re.search(r"conversations/([... |
def initAttrs(cls):
"""
Class decorator: automatically generate an ``__init__`` method that expects args from cls.attrs and stores them.
Args:
cls (class): class to decorate
Returns:
class: same, but modified, class
"""
def __init__(self, skype=N... |
def convertIds(*types, **kwargs):
"""
Class decorator: add helper methods to convert identifier properties into SkypeObjs.
Args:
types (str list): simple field types to add properties for (``user``, ``users`` or ``chat``)
user (str list): attribute names to treat as sing... |
def truthyAttrs(cls):
"""
Class decorator: override __bool__ to set truthiness based on any attr being present.
Args:
cls (class): class to decorate
Returns:
class: same, but modified, class
"""
def __bool__(self):
return bool(any(get... |
def cacheResult(fn):
"""
Method decorator: calculate the value on first access, produce the cached value thereafter.
If the function takes arguments, the cache is a dictionary using all arguments as the key.
Args:
fn (method): function to decorate
Returns:
... |
def exhaust(fn, transform=None, *args, **kwargs):
"""
Repeatedly call a function, starting with init, until false-y, yielding each item in turn.
The ``transform`` parameter can be used to map a collection to another format, for example iterating over a
:class:`dict` by value rather than... |
def u(text, encoding='utf-8'):
"Return unicode text, no matter what"
if isinstance(text, six.binary_type):
text = text.decode(encoding)
# it's already unicode
text = text.replace('\r\n', '\n')
return text |
def detect_format(text, handlers):
"""
Figure out which handler to use, based on metadata.
Returns a handler instance or None.
``text`` should be unicode text about to be parsed.
``handlers`` is a dictionary where keys are opening delimiters
and values are handler instances.
"""
for p... |
def parse(text, encoding='utf-8', handler=None, **defaults):
"""
Parse text with frontmatter, return metadata and content.
Pass in optional metadata defaults as keyword args.
If frontmatter is not found, returns an empty metadata dictionary
(or defaults) and original text content.
::
... |
def load(fd, encoding='utf-8', handler=None, **defaults):
"""
Load and parse a file-like object or filename,
return a :py:class:`post <frontmatter.Post>`.
::
>>> post = frontmatter.load('tests/hello-world.markdown')
>>> with open('tests/hello-world.markdown') as f:
... pos... |
def loads(text, encoding='utf-8', handler=None, **defaults):
"""
Parse text (binary or unicode) and return a :py:class:`post <frontmatter.Post>`.
::
>>> with open('tests/hello-world.markdown') as f:
... post = frontmatter.loads(f.read())
"""
text = u(text, encoding)
handle... |
def dump(post, fd, encoding='utf-8', handler=None, **kwargs):
"""
Serialize :py:class:`post <frontmatter.Post>` to a string and write to a file-like object.
Text will be encoded on the way out (utf-8 by default).
::
>>> from io import BytesIO
>>> f = BytesIO()
>>> frontmatter.d... |
def dumps(post, handler=None, **kwargs):
"""
Serialize a :py:class:`post <frontmatter.Post>` to a string and return text.
This always returns unicode text, which can then be encoded.
Passing ``handler`` will change how metadata is turned into text. A handler
passed as an argument will override ``p... |
def to_dict(self):
"Post as a dict, for serializing"
d = self.metadata.copy()
d['content'] = self.content
return d |
def load(self, fm, **kwargs):
"""
Parse YAML front matter. This uses yaml.SafeLoader by default.
"""
kwargs.setdefault('Loader', SafeLoader)
return yaml.load(fm, **kwargs) |
def export(self, metadata, **kwargs):
"""
Export metadata as YAML. This uses yaml.SafeDumper by default.
"""
kwargs.setdefault('Dumper', SafeDumper)
kwargs.setdefault('default_flow_style', False)
kwargs.setdefault('allow_unicode', True)
metadata = yaml.dump(metad... |
def export(self, metadata, **kwargs):
"Turn metadata into JSON"
kwargs.setdefault('indent', 4)
metadata = json.dumps(metadata, **kwargs)
return u(metadata) |
def _match(self):
"""Return the match object for the current list."""
cache_match, cache_string = self._match_cache
string = self.string
if cache_string == string:
return cache_match
cache_match = fullmatch(
LIST_PATTERN_FORMAT.replace(b'{pattern}', self.p... |
def items(self) -> List[str]:
"""Return items as a list of strings.
Don't include sub-items and the start pattern.
"""
items = [] # type: List[str]
append = items.append
string = self.string
match = self._match
ms = match.start()
for s, e in matc... |
def sublists(
self, i: int = None, pattern: str = None
) -> List['WikiList']:
"""Return the Lists inside the item with the given index.
:param i: The index if the item which its sub-lists are desired.
The performance is likely to be better if `i` is None.
:param pattern... |
def convert(self, newstart: str) -> None:
"""Convert to another list type by replacing starting pattern."""
match = self._match
ms = match.start()
for s, e in reversed(match.spans('pattern')):
self[s - ms:e - ms] = newstart
self.pattern = escape(newstart) |
def arguments(self) -> List[Argument]:
"""Parse template content. Create self.name and self.arguments."""
shadow = self._shadow
split_spans = self._args_matcher(shadow).spans('arg')
if not split_spans:
return []
arguments = []
arguments_append = arguments.appe... |
def lists(self, pattern: str = None) -> List[WikiList]:
"""Return the lists in all arguments.
For performance reasons it is usually preferred to get a specific
Argument and use the `lists` method of that argument instead.
"""
return [
lst for arg in self.arguments fo... |
def name(self) -> str:
"""Return template's name (includes whitespace)."""
h = self._atomic_partition(self._first_arg_sep)[0]
if len(h) == len(self.string):
return h[2:-2]
return h[2:] |
def _plant_trie(strings: _List[str]) -> dict:
"""Create a Trie out of a list of words and return an atomic regex pattern.
The corresponding Regex should match much faster than a simple Regex union.
"""
# plant the trie
trie = {}
for string in strings:
d = trie
for char in string... |
def _pattern(trie: dict) -> str:
"""Convert a trie to a regex pattern."""
if '' in trie:
if len(trie) == 1:
return ''
optional = True
del trie['']
else:
optional = False
subpattern_to_chars = _defaultdict(list)
for char, sub_trie in trie.items():
... |
def _check_index(self, key: Union[slice, int]) -> (int, int):
"""Return adjusted start and stop index as tuple.
Used in __setitem__ and __delitem__.
"""
ss, se = self._span
if isinstance(key, int):
if key < 0:
key += se - ss
if key < ... |
def insert(self, index: int, string: str) -> None:
"""Insert the given string before the specified index.
This method has the same effect as ``self[index:index] = string``;
it only avoids some condition checks as it rules out the possibility
of the key being an slice, or the need to shr... |
def string(self) -> str:
"""Return str(self)."""
start, end = self._span
return self._lststr[0][start:end] |
def _atomic_partition(self, char: int) -> Tuple[str, str, str]:
"""Partition self.string where `char`'s not in atomic sub-spans."""
s, e = self._span
index = self._shadow.find(char)
if index == -1:
return self._lststr[0][s:e], '', ''
lststr0 = self._lststr[0]
... |
def _subspans(self, type_: str) -> List[List[int]]:
"""Return all the sub-span including self._span."""
return self._type_to_spans[type_] |
def _close_subspans(self, start: int, stop: int) -> None:
"""Close all sub-spans of (start, stop)."""
ss, se = self._span
for spans in self._type_to_spans.values():
b = bisect(spans, [start])
for i, (s, e) in enumerate(spans[b:bisect(spans, [stop], b)]):
i... |
def _shrink_update(self, rmstart: int, rmstop: int) -> None:
"""Update self._type_to_spans according to the removed span.
Warning: If an operation involves both _shrink_update and
_insert_update, you might wanna consider doing the
_insert_update before the _shrink_update as this functio... |
def _insert_update(self, index: int, length: int) -> None:
"""Update self._type_to_spans according to the added length."""
ss, se = self._span
for spans in self._type_to_spans.values():
for span in spans:
if index < span[1] or span[1] == index == se:
... |
def nesting_level(self) -> int:
"""Return the nesting level of self.
The minimum nesting_level is 0. Being part of any Template or
ParserFunction increases the level by one.
"""
ss, se = self._span
level = 0
type_to_spans = self._type_to_spans
for type_ i... |
def _shadow(self) -> bytearray:
"""Return a copy of self.string with specific sub-spans replaced.
Comments blocks are replaced by spaces. Other sub-spans are replaced
by underscores.
The replaced sub-spans are: (
'Template', 'WikiLink', 'ParserFunction', 'ExtensionTag',
... |
def _ext_link_shadow(self):
"""Replace the invalid chars of SPAN_PARSER_TYPES with b'_'.
For comments, all characters are replaced, but for ('Template',
'ParserFunction', 'Parameter') only invalid characters are replaced.
"""
ss, se = self._span
string = self._lststr[0][... |
def _pp_type_to_spans(self) -> Dict[str, List[List[int]]]:
"""Create the arguments for the parse function used in pformat method.
Only return sub-spans and change the them to fit the new scope, i.e
self.string.
"""
ss, se = self._span
if ss == 0 and se == len(self._lstst... |
def pprint(self, indent: str = ' ', remove_comments=False):
"""Deprecated, use self.pformat instead."""
warn(
'pprint method is deprecated, use pformat instead.',
DeprecationWarning,
)
return self.pformat(indent, remove_comments) |
def pformat(self, indent: str = ' ', remove_comments=False) -> str:
"""Return a pretty-print of self.string as string.
Try to organize templates and parser functions by indenting, aligning
at the equal signs, and adding space where appropriate.
Note that this function will not mutat... |
def parameters(self) -> List['Parameter']:
"""Return a list of parameter objects."""
_lststr = self._lststr
_type_to_spans = self._type_to_spans
return [
Parameter(_lststr, _type_to_spans, span, 'Parameter')
for span in self._subspans('Parameter')] |
def parser_functions(self) -> List['ParserFunction']:
"""Return a list of parser function objects."""
_lststr = self._lststr
_type_to_spans = self._type_to_spans
return [
ParserFunction(_lststr, _type_to_spans, span, 'ParserFunction')
for span in self._subspans('P... |
def templates(self) -> List['Template']:
"""Return a list of templates as template objects."""
_lststr = self._lststr
_type_to_spans = self._type_to_spans
return [
Template(_lststr, _type_to_spans, span, 'Template')
for span in self._subspans('Template')] |
def wikilinks(self) -> List['WikiLink']:
"""Return a list of wikilink objects."""
_lststr = self._lststr
_type_to_spans = self._type_to_spans
return [
WikiLink(_lststr, _type_to_spans, span, 'WikiLink')
for span in self._subspans('WikiLink')] |
def comments(self) -> List['Comment']:
"""Return a list of comment objects."""
_lststr = self._lststr
_type_to_spans = self._type_to_spans
return [
Comment(_lststr, _type_to_spans, span, 'Comment')
for span in self._subspans('Comment')] |
def external_links(self) -> List['ExternalLink']:
"""Return a list of found external link objects.
Note:
Templates adjacent to external links are considered part of the
link. In reality, this depends on the contents of the template:
>>> WikiText(
... ... |
def sections(self) -> List['Section']:
"""Return a list of section in current wikitext.
The first section will always be the lead section, even if it is an
empty string.
"""
sections = [] # type: List['Section']
sections_append = sections.append
type_to_spans = ... |
def tables(self) -> List['Table']:
"""Return a list of found table objects."""
tables = [] # type: List['Table']
tables_append = tables.append
type_to_spans = self._type_to_spans
lststr = self._lststr
shadow = self._shadow[:]
ss, se = self._span
spans = t... |
def lists(self, pattern: str = None) -> List['WikiList']:
r"""Return a list of WikiList objects.
:param pattern: The starting pattern for list items.
Return all types of lists (ol, ul, and dl) if pattern is None.
If pattern is not None, it will be passed to the regex engine,
... |
def tags(self, name=None) -> List['Tag']:
"""Return all tags with the given name."""
lststr = self._lststr
type_to_spans = self._type_to_spans
if name:
if name in _tag_extensions:
string = lststr[0]
return [
Tag(lststr, type... |
def _subspans(self, _type: str) -> Generator[int, None, None]:
"""Yield all the sub-span indices excluding self._span."""
ss, se = self._span
spans = self._type_to_spans[_type]
# Do not yield self._span by bisecting for s < ss.
# The second bisect is an optimization and should be... |
def ancestors(self, type_: Optional[str] = None) -> List['WikiText']:
"""Return the ancestors of the current node.
:param type_: the type of the desired ancestors as a string.
Currently the following types are supported: {Template,
ParserFunction, WikiLink, Comment, Parameter, E... |
def parent(self, type_: Optional[str] = None) -> Optional['WikiText']:
"""Return the parent node of the current object.
:param type_: the type of the desired parent object.
Currently the following types are supported: {Template,
ParserFunction, WikiLink, Comment, Parameter, Exte... |
def mode(list_: List[T]) -> T:
"""Return the most common item in the list.
Return the first one if there are more than one most common items.
Example:
>>> mode([1,1,2,2,])
1
>>> mode([1,2,2])
2
>>> mode([])
...
ValueError: max() arg is an empty sequence
"""
return max(... |
def get_arg(name: str, args: Iterable[Argument]) -> Optional[Argument]:
"""Return the first argument in the args that has the given name.
Return None if no such argument is found.
As the computation of self.arguments is a little costly, this
function was created so that other methods that have already... |
def normal_name(
self,
rm_namespaces=('Template',),
capital_links=False,
_code: str = None,
*,
code: str = None,
capitalize=False
) -> str:
"""Return normal form of self.name.
- Remove comments.
- Remove language code.
- Remove... |
def rm_first_of_dup_args(self) -> None:
"""Eliminate duplicate arguments by removing the first occurrences.
Remove the first occurrences of duplicate arguments, regardless of
their value. Result of the rendered wikitext should remain the same.
Warning: Some meaningful data may be remove... |
def rm_dup_args_safe(self, tag: str = None) -> None:
"""Remove duplicate arguments in a safe manner.
Remove the duplicate arguments only in the following situations:
1. Both arguments have the same name AND value. (Remove one of
them.)
2. Arguments have the same ... |
def set_arg(
self, name: str,
value: str,
positional: bool = None,
before: str = None,
after: str = None,
preserve_spacing: bool = True
) -> None:
"""Set the value for `name` argument. Add it if it doesn't exist.
- Use `positional`, `before` and `afte... |
def get_arg(self, name: str) -> Optional[Argument]:
"""Return the last argument with the given name.
Return None if no argument with that name is found.
"""
return get_arg(name, reversed(self.arguments)) |
def has_arg(self, name: str, value: str = None) -> bool:
"""Return true if the is an arg named `name`.
Also check equality of values if `value` is provided.
Note: If you just need to get an argument and you want to LBYL, it's
better to get_arg directly and then check if the returne... |
def del_arg(self, name: str) -> None:
"""Delete all arguments with the given then."""
for arg in reversed(self.arguments):
if arg.name.strip(WS) == name.strip(WS):
del arg[:] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.