repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
zulily/pudl
pudl/ad_user.py
ADUser.is_member
python
def is_member(self, group_distinguishedname): #pylint: disable=no-member if group_distinguishedname.lower() in [dn.lower() for dn in self.memberof]: #pylint: enable=no-member return True else: return False
For the current ADUser instance, determine if the user is a member of a specific group (the group DN is used). The result may not be accurate if explicit_membership_only was set to True when the object factory method (user() or users()) was called. :param str group_distinguished...
train
https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_user.py#L113-L130
null
class ADUser(ADObject): """A class to represent AD user objects. Includes a number of helper methods, particularly object-factory related. ADUser objects have minimal depth, with attributes set to strings or lists. Available attributes are dependent on the results returned by the LDAP query. ...
zulily/pudl
pudl/ad_user.py
ADUser.group_samaccountnames
python
def group_samaccountnames(self, base_dn): #pylint: disable=no-member mappings = self.samaccountnames(base_dn, self.memberof) #pylint: enable=no-member groups = [samaccountname for samaccountname in mappings.values()] if not groups: logging.info("%s - unable to retriev...
For the current ADUser instance, determine which groups the user is a member of and convert the group DistinguishedNames to sAMAccountNames. The resulting list of groups may not be complete if explicit_membership_only was set to True when the object factory method (user() or user...
train
https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_user.py#L133-L155
[ "def samaccountnames(self, base_dn, distinguished_names):\n \"\"\"Retrieve the sAMAccountNames for the specified DNs\n\n :param str base_dn: The base DN to search within\n :param list distinguished_name: A list of distinguished names for which to\n retrieve sAMAccountNames\n\n :return: Key/value ...
class ADUser(ADObject): """A class to represent AD user objects. Includes a number of helper methods, particularly object-factory related. ADUser objects have minimal depth, with attributes set to strings or lists. Available attributes are dependent on the results returned by the LDAP query. ...
zulily/pudl
pudl/helper.py
object_filter
python
def object_filter(objects, grep): filtered = [] if grep: for ad_object in objects: o_string = ' '.join([value for value in ad_object.to_dict().values() if isinstance(value, str)]) skip = False for regex in grep: if not ...
Filter out any objects that do not have attributes with values matching *all* regular expressions present in grep (AND, essentially) :param objects ADObject: A list of ADObjects :param grep list: A list of regular expressions that must match for filtering :return: A list of filtered ADObjects :rty...
train
https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/helper.py#L20-L45
null
# Copyright (C) 2015 zulily, llc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
zulily/pudl
pudl/helper.py
serialize
python
def serialize(ad_objects, output_format='json', indent=2, attributes_only=False): # If the request is to only show attributes for objects returned # in the query, overwrite ad_objects with only those attributes present in # the first object in the list if attributes_only: ad_objects = [key for ...
Serialize the object to the specified format :param ad_objects list: A list of ADObjects to serialize :param output_format str: The output format, json or yaml. Defaults to json :param indent int: The number of spaces to indent, defaults to 2 :param attributes only: Only serialize the attributes found...
train
https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/helper.py#L48-L70
null
# Copyright (C) 2015 zulily, llc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
zulily/pudl
pudl/ad_query.py
ADQuery.search
python
def search(self, base_dn, search_filter, attributes=()): results = [] page = 0 while page == 0 or self.sprc.cookie: page += 1 #pylint: disable=no-member message_id = self.ldap.search_ext(base_dn, ldap.SCOPE_SUBTREE, ...
Perform an AD search :param str base_dn: The base DN to search within :param str search_filter: The search filter to apply, such as: *objectClass=person* :param list attributes: Object attributes to populate, defaults to all
train
https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_query.py#L80-L103
null
class ADQuery(object): #pylint: disable=too-few-public-methods """Query Active directory with python-ldap. May be used directly, but is most commonly used indirectly via ADObject-based classes. All connections require TLS. """ def __init__(self, user, password, ldap_url=LDAP_URL...
zulily/pudl
pudl/ad_query.py
ADQuery._open
python
def _open(self): try: self.ldap.start_tls_s() #pylint: disable=no-member except ldap.CONNECT_ERROR: #pylint: enable=no-member logging.error('Unable to establish a connection to the LDAP server, ' + \ 'please check the connection string ' ...
Bind, use tls
train
https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_query.py#L106-L118
null
class ADQuery(object): #pylint: disable=too-few-public-methods """Query Active directory with python-ldap. May be used directly, but is most commonly used indirectly via ADObject-based classes. All connections require TLS. """ def __init__(self, user, password, ldap_url=LDAP_URL...
jd/tenacity
tenacity/after.py
after_log
python
def after_log(logger, log_level, sec_format="%0.3f"): log_tpl = ("Finished call to '%s' after " + str(sec_format) + "(s), " "this was the %s time calling it.") def log_it(retry_state): logger.log(log_level, log_tpl, _utils.get_callback_name(retry_state.fn), ...
After call strategy that logs to some logger the finished attempt.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/after.py#L24-L35
null
# Copyright 2016 Julien Danjou # Copyright 2016 Joshua Harlow # Copyright 2013-2014 Ray Holder # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #...
jd/tenacity
tenacity/__init__.py
retry
python
def retry(*dargs, **dkw): # support both @retry and @retry() as valid syntax if len(dargs) == 1 and callable(dargs[0]): return retry()(dargs[0]) else: def wrap(f): if asyncio and asyncio.iscoroutinefunction(f): r = AsyncRetrying(*dargs, **dkw) elif tor...
Wrap a function with a new `Retrying` object. :param dargs: positional arguments passed to Retrying object :param dkw: keyword arguments passed to the Retrying object
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L88-L109
[ "def retry(*dargs, **dkw):\n \"\"\"Wrap a function with a new `Retrying` object.\n\n :param dargs: positional arguments passed to Retrying object\n :param dkw: keyword arguments passed to the Retrying object\n \"\"\"\n # support both @retry and @retry() as valid syntax\n if len(dargs) == 1 and cal...
# -*- coding: utf-8 -*- # Copyright 2016-2018 Julien Danjou # Copyright 2017 Elisey Zanko # Copyright 2016 Étienne Bersac # Copyright 2016 Joshua Harlow # Copyright 2013-2014 Ray Holder # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License....
jd/tenacity
tenacity/__init__.py
BaseRetrying.copy
python
def copy(self, sleep=_unset, stop=_unset, wait=_unset, retry=_unset, before=_unset, after=_unset, before_sleep=_unset, reraise=_unset): if before_sleep is _unset: before_sleep = self.before_sleep return self.__class__( sleep=self.sleep if sleep is _unset...
Copy this object with some parameters changed if needed.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L231-L246
null
class BaseRetrying(object): def __init__(self, sleep=sleep, stop=stop_never, wait=wait_none(), retry=retry_if_exception_type(), before=before_nothing, after=after_nothing, before_sleep=None, rerai...
jd/tenacity
tenacity/__init__.py
BaseRetrying.statistics
python
def statistics(self): try: return self._local.statistics except AttributeError: self._local.statistics = {} return self._local.statistics
Return a dictionary of runtime statistics. This dictionary will be empty when the controller has never been ran. When it is running or has ran previously it should have (but may not) have useful and/or informational keys and values when running is underway and/or completed. .. ...
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L258-L283
null
class BaseRetrying(object): def __init__(self, sleep=sleep, stop=stop_never, wait=wait_none(), retry=retry_if_exception_type(), before=before_nothing, after=after_nothing, before_sleep=None, rerai...
jd/tenacity
tenacity/__init__.py
BaseRetrying.wraps
python
def wraps(self, f): @_utils.wraps(f) def wrapped_f(*args, **kw): return self.call(f, *args, **kw) def retry_with(*args, **kwargs): return self.copy(*args, **kwargs).wraps(f) wrapped_f.retry = self wrapped_f.retry_with = retry_with return wrapped...
Wrap a function for retrying. :param f: A function to wraps for retrying.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L285-L300
null
class BaseRetrying(object): def __init__(self, sleep=sleep, stop=stop_never, wait=wait_none(), retry=retry_if_exception_type(), before=before_nothing, after=after_nothing, before_sleep=None, rerai...
jd/tenacity
tenacity/__init__.py
Future.construct
python
def construct(cls, attempt_number, value, has_exception): fut = cls(attempt_number) if has_exception: fut.set_exception(value) else: fut.set_result(value) return fut
Construct a new Future object.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L388-L395
null
class Future(futures.Future): """Encapsulates a (future or past) attempted call to a target function.""" def __init__(self, attempt_number): super(Future, self).__init__() self.attempt_number = attempt_number @property def failed(self): """Return whether a exception is being he...
jd/tenacity
tenacity/before_sleep.py
before_sleep_log
python
def before_sleep_log(logger, log_level): def log_it(retry_state): if retry_state.outcome.failed: verb, value = 'raised', retry_state.outcome.exception() else: verb, value = 'returned', retry_state.outcome.result() logger.log(log_level, "Retrying %s...
Before call strategy that logs to some logger the attempt.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/before_sleep.py#L24-L37
null
# Copyright 2016 Julien Danjou # Copyright 2016 Joshua Harlow # Copyright 2013-2014 Ray Holder # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #...
jd/tenacity
tenacity/before.py
before_log
python
def before_log(logger, log_level): def log_it(retry_state): logger.log(log_level, "Starting call to '%s', this is the %s time calling it.", _utils.get_callback_name(retry_state.fn), _utils.to_ordinal(retry_state.attempt_number)) return log_it
Before call strategy that logs to some logger the attempt.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/before.py#L24-L32
null
# Copyright 2016 Julien Danjou # Copyright 2016 Joshua Harlow # Copyright 2013-2014 Ray Holder # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #...
jd/tenacity
tenacity/_utils.py
get_callback_name
python
def get_callback_name(cb): segments = [] try: segments.append(cb.__qualname__) except AttributeError: try: segments.append(cb.__name__) if inspect.ismethod(cb): try: # This attribute doesn't exist on py3.x or newer, so ...
Get a callback fully-qualified name. If no name can be produced ``repr(cb)`` is called and returned.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/_utils.py#L98-L128
null
# Copyright 2016 Julien Danjou # Copyright 2016 Joshua Harlow # Copyright 2013-2014 Ray Holder # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #...
jd/tenacity
tenacity/compat.py
make_retry_state
python
def make_retry_state(previous_attempt_number, delay_since_first_attempt, last_result=None): required_parameter_unset = (previous_attempt_number is _unset or delay_since_first_attempt is _unset) if required_parameter_unset: raise _make_unset_exception(...
Construct RetryCallState for given attempt number & delay. Only used in testing and thus is extra careful about timestamp arithmetics.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L57-L79
null
"""Utilities for providing backward compatibility.""" import inspect from fractions import Fraction from warnings import warn import six from tenacity import _utils def warn_about_non_retry_state_deprecation(cbname, func, stacklevel): msg = ( '"%s" function must accept single "retry_state" parameter,' ...
jd/tenacity
tenacity/compat.py
func_takes_last_result
python
def func_takes_last_result(waiter): if not six.callable(waiter): return False if not inspect.isfunction(waiter) and not inspect.ismethod(waiter): # waiter is a class, check dunder-call rather than dunder-init. waiter = waiter.__call__ waiter_spec = _utils.getargspec(waiter) retur...
Check if function has a "last_result" parameter. Needed to provide backward compatibility for wait functions that didn't take "last_result" in the beginning.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L82-L94
[ "def getargspec(func):\n return inspect.getfullargspec(func)\n" ]
"""Utilities for providing backward compatibility.""" import inspect from fractions import Fraction from warnings import warn import six from tenacity import _utils def warn_about_non_retry_state_deprecation(cbname, func, stacklevel): msg = ( '"%s" function must accept single "retry_state" parameter,' ...
jd/tenacity
tenacity/compat.py
stop_dunder_call_accept_old_params
python
def stop_dunder_call_accept_old_params(fn): @_utils.wraps(fn) def new_fn(self, previous_attempt_number=_unset, delay_since_first_attempt=_unset, retry_state=None): if retry_state is None: from tenacity import RetryCallState retry_state...
Decorate cls.__call__ method to accept old "stop" signature.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L97-L117
null
"""Utilities for providing backward compatibility.""" import inspect from fractions import Fraction from warnings import warn import six from tenacity import _utils def warn_about_non_retry_state_deprecation(cbname, func, stacklevel): msg = ( '"%s" function must accept single "retry_state" parameter,' ...
jd/tenacity
tenacity/compat.py
stop_func_accept_retry_state
python
def stop_func_accept_retry_state(stop_func): if not six.callable(stop_func): return stop_func if func_takes_retry_state(stop_func): return stop_func @_utils.wraps(stop_func) def wrapped_stop_func(retry_state): warn_about_non_retry_state_deprecation( 'stop', stop_fun...
Wrap "stop" function to accept "retry_state" parameter.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L120-L136
[ "def func_takes_retry_state(func):\n if not six.callable(func):\n raise Exception(func)\n return False\n if not inspect.isfunction(func) and not inspect.ismethod(func):\n # func is a callable object rather than a function/method\n func = func.__call__\n func_spec = _utils.getarg...
"""Utilities for providing backward compatibility.""" import inspect from fractions import Fraction from warnings import warn import six from tenacity import _utils def warn_about_non_retry_state_deprecation(cbname, func, stacklevel): msg = ( '"%s" function must accept single "retry_state" parameter,' ...
jd/tenacity
tenacity/compat.py
wait_func_accept_retry_state
python
def wait_func_accept_retry_state(wait_func): if not six.callable(wait_func): return wait_func if func_takes_retry_state(wait_func): return wait_func if func_takes_last_result(wait_func): @_utils.wraps(wait_func) def wrapped_wait_func(retry_state): warn_about_non...
Wrap wait function to accept "retry_state" parameter.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L164-L191
[ "def func_takes_retry_state(func):\n if not six.callable(func):\n raise Exception(func)\n return False\n if not inspect.isfunction(func) and not inspect.ismethod(func):\n # func is a callable object rather than a function/method\n func = func.__call__\n func_spec = _utils.getarg...
"""Utilities for providing backward compatibility.""" import inspect from fractions import Fraction from warnings import warn import six from tenacity import _utils def warn_about_non_retry_state_deprecation(cbname, func, stacklevel): msg = ( '"%s" function must accept single "retry_state" parameter,' ...
jd/tenacity
tenacity/compat.py
retry_dunder_call_accept_old_params
python
def retry_dunder_call_accept_old_params(fn): @_utils.wraps(fn) def new_fn(self, attempt=_unset, retry_state=None): if retry_state is None: from tenacity import RetryCallState if attempt is _unset: raise _make_unset_exception('retry', attempt=attempt) r...
Decorate cls.__call__ method to accept old "retry" signature.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L194-L212
null
"""Utilities for providing backward compatibility.""" import inspect from fractions import Fraction from warnings import warn import six from tenacity import _utils def warn_about_non_retry_state_deprecation(cbname, func, stacklevel): msg = ( '"%s" function must accept single "retry_state" parameter,' ...
jd/tenacity
tenacity/compat.py
retry_func_accept_retry_state
python
def retry_func_accept_retry_state(retry_func): if not six.callable(retry_func): return retry_func if func_takes_retry_state(retry_func): return retry_func @_utils.wraps(retry_func) def wrapped_retry_func(retry_state): warn_about_non_retry_state_deprecation( 'retry',...
Wrap "retry" function to accept "retry_state" parameter.
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L215-L228
[ "def func_takes_retry_state(func):\n if not six.callable(func):\n raise Exception(func)\n return False\n if not inspect.isfunction(func) and not inspect.ismethod(func):\n # func is a callable object rather than a function/method\n func = func.__call__\n func_spec = _utils.getarg...
"""Utilities for providing backward compatibility.""" import inspect from fractions import Fraction from warnings import warn import six from tenacity import _utils def warn_about_non_retry_state_deprecation(cbname, func, stacklevel): msg = ( '"%s" function must accept single "retry_state" parameter,' ...
jd/tenacity
tenacity/compat.py
before_func_accept_retry_state
python
def before_func_accept_retry_state(fn): if not six.callable(fn): return fn if func_takes_retry_state(fn): return fn @_utils.wraps(fn) def wrapped_before_func(retry_state): # func, trial_number, trial_time_taken warn_about_non_retry_state_deprecation('before', fn, stackl...
Wrap "before" function to accept "retry_state".
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L231-L247
[ "def func_takes_retry_state(func):\n if not six.callable(func):\n raise Exception(func)\n return False\n if not inspect.isfunction(func) and not inspect.ismethod(func):\n # func is a callable object rather than a function/method\n func = func.__call__\n func_spec = _utils.getarg...
"""Utilities for providing backward compatibility.""" import inspect from fractions import Fraction from warnings import warn import six from tenacity import _utils def warn_about_non_retry_state_deprecation(cbname, func, stacklevel): msg = ( '"%s" function must accept single "retry_state" parameter,' ...
jd/tenacity
tenacity/compat.py
after_func_accept_retry_state
python
def after_func_accept_retry_state(fn): if not six.callable(fn): return fn if func_takes_retry_state(fn): return fn @_utils.wraps(fn) def wrapped_after_sleep_func(retry_state): # func, trial_number, trial_time_taken warn_about_non_retry_state_deprecation('after', fn, sta...
Wrap "after" function to accept "retry_state".
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L250-L266
[ "def func_takes_retry_state(func):\n if not six.callable(func):\n raise Exception(func)\n return False\n if not inspect.isfunction(func) and not inspect.ismethod(func):\n # func is a callable object rather than a function/method\n func = func.__call__\n func_spec = _utils.getarg...
"""Utilities for providing backward compatibility.""" import inspect from fractions import Fraction from warnings import warn import six from tenacity import _utils def warn_about_non_retry_state_deprecation(cbname, func, stacklevel): msg = ( '"%s" function must accept single "retry_state" parameter,' ...
jd/tenacity
tenacity/compat.py
before_sleep_func_accept_retry_state
python
def before_sleep_func_accept_retry_state(fn): if not six.callable(fn): return fn if func_takes_retry_state(fn): return fn @_utils.wraps(fn) def wrapped_before_sleep_func(retry_state): # retry_object, sleep, last_result warn_about_non_retry_state_deprecation( ...
Wrap "before_sleep" function to accept "retry_state".
train
https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L269-L286
[ "def func_takes_retry_state(func):\n if not six.callable(func):\n raise Exception(func)\n return False\n if not inspect.isfunction(func) and not inspect.ismethod(func):\n # func is a callable object rather than a function/method\n func = func.__call__\n func_spec = _utils.getarg...
"""Utilities for providing backward compatibility.""" import inspect from fractions import Fraction from warnings import warn import six from tenacity import _utils def warn_about_non_retry_state_deprecation(cbname, func, stacklevel): msg = ( '"%s" function must accept single "retry_state" parameter,' ...
markreidvfx/pyaaf2
aaf2/file.py
AAFFile.save
python
def save(self): if self.mode in ("wb+", 'rb+'): if not self.is_open: raise IOError("file closed") self.write_reference_properties() self.manager.write_objects()
Writes current changes to disk and flushes modified objects in the AAFObjectManager
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/file.py#L339-L348
[ "def write_reference_properties(self):\n f = self.cfb.open(\"/referenced properties\", 'w')\n byte_order = 0x4c\n path_count = len(self.weakref_table)\n pid_count = 0\n for path in self.weakref_table:\n pid_count += len(path)\n pid_count += 1 # null byte\n\n write_u8(f, byte_order)\n...
class AAFFile(object): """ AAF File Object. This is the entry point object for most of the API. This object is designed to be like python's native open function. It is recommended to create this object with the `aaf.open` alias. It is also highly recommended to use the with statement. For examp...
markreidvfx/pyaaf2
aaf2/file.py
AAFFile.close
python
def close(self): self.save() self.manager.remove_temp() self.cfb.close() self.is_open = False self.f.close()
Close the file. A closed file cannot be read or written any more.
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/file.py#L350-L358
[ "def save(self):\n \"\"\"\n Writes current changes to disk and flushes modified objects in the\n AAFObjectManager\n \"\"\"\n if self.mode in (\"wb+\", 'rb+'):\n if not self.is_open:\n raise IOError(\"file closed\")\n self.write_reference_properties()\n self.manager.wri...
class AAFFile(object): """ AAF File Object. This is the entry point object for most of the API. This object is designed to be like python's native open function. It is recommended to create this object with the `aaf.open` alias. It is also highly recommended to use the with statement. For examp...
markreidvfx/pyaaf2
docs/source/conf.py
run_apidoc
python
def run_apidoc(_): import os dirname = os.path.dirname(__file__) ignore_paths = [os.path.join(dirname, '../../aaf2/model'),] # https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/apidoc.py argv = [ '--force', '--no-toc', '--separate', '--module-first', ...
This method is required by the setup method below.
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/docs/source/conf.py#L182-L199
null
# -*- coding: utf-8 -*- # # PyAAF documentation build configuration file, created by # sphinx-quickstart on Wed Oct 18 20:01:47 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All...
markreidvfx/pyaaf2
aaf2/mobid.py
MobID.from_dict
python
def from_dict(self, d): self.length = d.get("length", 0) self.instanceHigh = d.get("instanceHigh", 0) self.instanceMid = d.get("instanceMid", 0) self.instanceLow = d.get("instanceLow", 0) material = d.get("material", {'Data1':0, 'Data2':0, 'Data3':0, 'Data4': [0 for i in range(8...
Set MobID from a dict
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/mobid.py#L280-L296
null
class MobID(object): __slots__ = ('bytes_le') def __init__(self, mobid=None, bytes_le=None, int=None): if bytes_le: self.bytes_le = bytearray(bytes_le) else: self.bytes_le = bytearray(32) if mobid is not None: self.urn = mobid if...
markreidvfx/pyaaf2
aaf2/mobid.py
MobID.to_dict
python
def to_dict(self): material = {'Data1': self.Data1, 'Data2': self.Data2, 'Data3': self.Data3, 'Data4': list(self.Data4) } return {'material':material, 'length': self.length, 'instanceHigh': ...
MobID representation as dict
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/mobid.py#L298-L315
null
class MobID(object): __slots__ = ('bytes_le') def __init__(self, mobid=None, bytes_le=None, int=None): if bytes_le: self.bytes_le = bytearray(bytes_le) else: self.bytes_le = bytearray(32) if mobid is not None: self.urn = mobid if...
markreidvfx/pyaaf2
aaf2/mobid.py
MobID.urn
python
def urn(self): SMPTELabel = self.SMPTELabel Data4 = self.Data4 # handle case UMIDs where the material number is half swapped if (SMPTELabel[11] == 0x00 and Data4[0] == 0x06 and Data4[1] == 0x0E and Data4[2] == 0x2B and Data4[3] == 0x34 and Data4[4] =...
MobID Uniform Resource Name representation. https://en.wikipedia.org/wiki/Uniform_Resource_Name
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/mobid.py#L360-L405
null
class MobID(object): __slots__ = ('bytes_le') def __init__(self, mobid=None, bytes_le=None, int=None): if bytes_le: self.bytes_le = bytearray(bytes_le) else: self.bytes_le = bytearray(32) if mobid is not None: self.urn = mobid if...
markreidvfx/pyaaf2
aaf2/ama.py
wave_infochunk
python
def wave_infochunk(path): with open(path,'rb') as file: if file.read(4) != b"RIFF": return None data_size = file.read(4) # container size if file.read(4) != b"WAVE": return None while True: chunkid = file.read(4) sizebuf = file.read(4) ...
Returns a bytearray of the WAVE RIFF header and fmt chunk for a `WAVEDescriptor` `Summary`
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/ama.py#L329-L353
null
from __future__ import ( unicode_literals, absolute_import, print_function, division, ) import os import sys from .rational import AAFRational from . import video from . import audio from . import mxf from .auid import AUID import struct MediaContainerGUID = { "Generic" : (AUID("b22697a2-3...
markreidvfx/pyaaf2
aaf2/ama.py
create_wav_link
python
def create_wav_link(f, metadata): path = metadata['format']['filename'] master_mob = f.create.MasterMob() source_mob = f.create.SourceMob() tape_mob = f.create.SourceMob() edit_rate = metadata['streams'][0]['sample_rate'] length = metadata['streams'][0]['duration_ts'] master_m...
This will return three MOBs for the given `metadata`: master_mob, source_mob, tape_mob The parameter `metadata` is presumed to be a dictionary from a run of ffprobe. It's not clear for the purposes of Pro Tools that a tape_mob needs to be made, it'll open the AAF perfectly well without out one. A...
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/ama.py#L365-L441
[ "def create_wav_descriptor(f, source_mob, path, stream_meta):\n d = f.create.WAVEDescriptor()\n rate = stream_meta['sample_rate']\n d['SampleRate'].value = rate\n d['Summary'].value = wave_infochunk(path)\n d['Length'].value = stream_meta['duration_ts']\n d['ContainerFormat'].value = source_mob.ro...
from __future__ import ( unicode_literals, absolute_import, print_function, division, ) import os import sys from .rational import AAFRational from . import video from . import audio from . import mxf from .auid import AUID import struct MediaContainerGUID = { "Generic" : (AUID("b22697a2-3...
markreidvfx/pyaaf2
aaf2/cfb.py
DirEntry.pop
python
def pop(self): entry = self parent = self.parent root = parent.child() dir_per_sector = self.storage.sector_size // 128 max_dirs_entries = self.storage.dir_sector_count * dir_per_sector count = 0 if root.dir_id == entry.dir_id: parent.child_id = Non...
remove self from binary search tree
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L609-L664
[ "def left(self):\n return self.storage.read_dir_entry(self.left_id, self.parent)\n", "def right(self):\n return self.storage.read_dir_entry(self.right_id, self.parent)\n" ]
class DirEntry(object): __slots__ = ('storage', 'dir_id', 'parent', 'data', '__weakref__') def __init__(self, storage, dir_id, data=None): self.storage = storage self.parent = None if data is None: self.data = bytearray(128) # setting dir_id to None disable mark...
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.remove
python
def remove(self, path): entry = self.find(path) if not entry: raise ValueError("%s does not exists" % path) if entry.type == 'root storage': raise ValueError("can no remove root entry") if entry.type == "storage" and not entry.child_id is None: rai...
Removes both streams and storage DirEntry types from file. storage type entries need to be empty dirs.
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1606-L1629
[ "def free_fat_chain(self, start_sid, minifat=False):\n fat =self.fat\n if minifat:\n fat = self.minifat\n\n for sid in self.get_fat_chain(start_sid, minifat):\n fat[sid] = FREESECT\n if minifat:\n self.minifat_freelist.insert(0, sid)\n else:\n self.fat_free...
class CompoundFileBinary(object): def __init__(self, file_object, mode='rb', sector_size=4096): self.f = file_object self.difat = [[]] self.fat = array(str('I')) self.fat_freelist = [] self.minifat = array(str('I')) self.minifat_freelist = [] self.difat_ch...
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.rmtree
python
def rmtree(self, path): for root, storage, streams in self.walk(path, topdown=False): for item in streams: self.free_fat_chain(item.sector_id, item.byte_size < self.min_stream_max_size) self.free_dir_entry(item) for item in storage: self....
Removes directory structure, similar to shutil.rmtree.
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1632-L1648
[ "def free_fat_chain(self, start_sid, minifat=False):\n fat =self.fat\n if minifat:\n fat = self.minifat\n\n for sid in self.get_fat_chain(start_sid, minifat):\n fat[sid] = FREESECT\n if minifat:\n self.minifat_freelist.insert(0, sid)\n else:\n self.fat_free...
class CompoundFileBinary(object): def __init__(self, file_object, mode='rb', sector_size=4096): self.f = file_object self.difat = [[]] self.fat = array(str('I')) self.fat_freelist = [] self.minifat = array(str('I')) self.minifat_freelist = [] self.difat_ch...
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.listdir_dict
python
def listdir_dict(self, path = None): if path is None: path = self.root root = self.find(path) if root is None: raise ValueError("unable to find dir: %s" % str(path)) if not root.isdir(): raise ValueError("can only list storage types") child...
Return a dict containing the ``DirEntry`` objects in the directory given by path with name of the dir as key.
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1660-L1709
[ "def find(self, path):\n \"\"\"\n find a ``DirEntry`` located at *path*. Returns ``None`` if path\n does not exist.\n \"\"\"\n\n if isinstance(path, DirEntry):\n return path\n\n if path == \"/\":\n return self.root\n\n split_path = path.lstrip('/').split(\"/\")\n\n i = 0\n r...
class CompoundFileBinary(object): def __init__(self, file_object, mode='rb', sector_size=4096): self.f = file_object self.difat = [[]] self.fat = array(str('I')) self.fat_freelist = [] self.minifat = array(str('I')) self.minifat_freelist = [] self.difat_ch...
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.find
python
def find(self, path): if isinstance(path, DirEntry): return path if path == "/": return self.root split_path = path.lstrip('/').split("/") i = 0 root = self.root while True: children = self.listdir_dict(root) match = c...
find a ``DirEntry`` located at *path*. Returns ``None`` if path does not exist.
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1711-L1739
[ "def listdir_dict(self, path = None):\n \"\"\"\n Return a dict containing the ``DirEntry`` objects in the directory\n given by path with name of the dir as key.\n \"\"\"\n\n if path is None:\n path = self.root\n\n root = self.find(path)\n if root is None:\n raise ValueError(\"unab...
class CompoundFileBinary(object): def __init__(self, file_object, mode='rb', sector_size=4096): self.f = file_object self.difat = [[]] self.fat = array(str('I')) self.fat_freelist = [] self.minifat = array(str('I')) self.minifat_freelist = [] self.difat_ch...
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.walk
python
def walk(self, path = None, topdown=True): if path is None: path = self.root root = self.find(path) if not root.isdir(): raise ValueError("can only walk storage types") if not root.child_id: return if topdown: storage_items = [...
Similar to :func:`os.walk`, yeields a 3-tuple ``(root, storage_items, stream_items)``
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1741-L1789
[ "def find(self, path):\n \"\"\"\n find a ``DirEntry`` located at *path*. Returns ``None`` if path\n does not exist.\n \"\"\"\n\n if isinstance(path, DirEntry):\n return path\n\n if path == \"/\":\n return self.root\n\n split_path = path.lstrip('/').split(\"/\")\n\n i = 0\n r...
class CompoundFileBinary(object): def __init__(self, file_object, mode='rb', sector_size=4096): self.f = file_object self.difat = [[]] self.fat = array(str('I')) self.fat_freelist = [] self.minifat = array(str('I')) self.minifat_freelist = [] self.difat_ch...
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.makedir
python
def makedir(self, path, class_id=None): return self.create_dir_entry(path, dir_type='storage', class_id=class_id)
Create a storage DirEntry name path
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1800-L1804
[ "def create_dir_entry(self, path, dir_type='storage', class_id=None):\n\n if self.exists(path):\n raise ValueError(\"%s already exists\" % path)\n\n dirname = os.path.dirname(path)\n basename = os.path.basename(path)\n\n root = self.find(dirname)\n\n if root is None:\n raise ValueError(...
class CompoundFileBinary(object): def __init__(self, file_object, mode='rb', sector_size=4096): self.f = file_object self.difat = [[]] self.fat = array(str('I')) self.fat_freelist = [] self.minifat = array(str('I')) self.minifat_freelist = [] self.difat_ch...
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.makedirs
python
def makedirs(self, path): root = "" assert path.startswith('/') p = path.strip('/') for item in p.split('/'): root += "/" + item if not self.exists(root): self.makedir(root) return self.find(path)
Recursive storage DirEntry creation function.
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1806-L1819
[ "def find(self, path):\n \"\"\"\n find a ``DirEntry`` located at *path*. Returns ``None`` if path\n does not exist.\n \"\"\"\n\n if isinstance(path, DirEntry):\n return path\n\n if path == \"/\":\n return self.root\n\n split_path = path.lstrip('/').split(\"/\")\n\n i = 0\n r...
class CompoundFileBinary(object): def __init__(self, file_object, mode='rb', sector_size=4096): self.f = file_object self.difat = [[]] self.fat = array(str('I')) self.fat_freelist = [] self.minifat = array(str('I')) self.minifat_freelist = [] self.difat_ch...
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.move
python
def move(self, src, dst): src_entry = self.find(src) if src_entry is None: raise ValueError("src path does not exist: %s" % src) if dst.endswith('/'): dst += src_entry.name if self.exists(dst): raise ValueError("dst path already exist: %s" % dst) ...
Moves ``DirEntry`` from src to dst
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1821-L1862
[ "def find(self, path):\n \"\"\"\n find a ``DirEntry`` located at *path*. Returns ``None`` if path\n does not exist.\n \"\"\"\n\n if isinstance(path, DirEntry):\n return path\n\n if path == \"/\":\n return self.root\n\n split_path = path.lstrip('/').split(\"/\")\n\n i = 0\n r...
class CompoundFileBinary(object): def __init__(self, file_object, mode='rb', sector_size=4096): self.f = file_object self.difat = [[]] self.fat = array(str('I')) self.fat_freelist = [] self.minifat = array(str('I')) self.minifat_freelist = [] self.difat_ch...
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.open
python
def open(self, path, mode='r'): entry = self.find(path) if entry is None: if mode == 'r': raise ValueError("stream does not exists: %s" % path) entry = self.create_dir_entry(path, 'stream', None) else: if not entry.isfile(): r...
Open stream, returning ``Stream`` object
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1864-L1887
[ "def free_fat_chain(self, start_sid, minifat=False):\n fat =self.fat\n if minifat:\n fat = self.minifat\n\n for sid in self.get_fat_chain(start_sid, minifat):\n fat[sid] = FREESECT\n if minifat:\n self.minifat_freelist.insert(0, sid)\n else:\n self.fat_free...
class CompoundFileBinary(object): def __init__(self, file_object, mode='rb', sector_size=4096): self.f = file_object self.difat = [[]] self.fat = array(str('I')) self.fat_freelist = [] self.minifat = array(str('I')) self.minifat_freelist = [] self.difat_ch...
markreidvfx/pyaaf2
aaf2/properties.py
add2set
python
def add2set(self, pid, key, value): prop = self.property_entries[pid] current = prop.objects.get(key, None) current_local_key = prop.references.get(key, None) if current and current is not value: current.detach() if current_local_key is None: prop.references[key] = prop.next_free_...
low level add to StrongRefSetProperty
train
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/properties.py#L1313-L1336
null
from __future__ import ( unicode_literals, absolute_import, print_function, division, ) from io import BytesIO import weakref import struct from .utils import ( read_u8, read_u16le, read_u32le, write_u8, write_u16le, write_u32le, decode_utf16le, encode_utf16le, ...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/MatchApiV4.py
MatchApiV4.matchlist_by_account
python
def matchlist_by_account( self, region, encrypted_account_id, queue=None, begin_time=None, end_time=None, begin_index=None, end_index=None, season=None, champion=None, ): url, query = MatchApiV4Urls.matchlist_by_account( ...
Get matchlist for ranked games played on given account ID and platform ID and filtered using given filter parameters, if any A number of optional parameters are provided for filtering. It is up to the caller to ensure that the combination of filter parameters provided is valid for the requested...
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/MatchApiV4.py#L32-L88
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class MatchApiV4(NamedEndpoint): """ This class wraps the Match-v4 endpoint calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#match-v4 for more detailed information """ def __init__(self, base_api): """ Initialize a new MatchApiV4 which uses the provi...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/MatchApiV4.py
MatchApiV4.timeline_by_match
python
def timeline_by_match(self, region, match_id): url, query = MatchApiV4Urls.timeline_by_match(region=region, match_id=match_id) return self._raw_request(self.timeline_by_match.__name__, region, url, query)
Get match timeline by match ID. Not all matches have timeline data. :param string region: The region to execute this request on :param long match_id: The match ID. :returns: MatchTimelineDto
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/MatchApiV4.py#L90-L102
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class MatchApiV4(NamedEndpoint): """ This class wraps the Match-v4 endpoint calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#match-v4 for more detailed information """ def __init__(self, base_api): """ Initialize a new MatchApiV4 which uses the provi...
pseudonym117/Riot-Watcher
src/riotwatcher/Handlers/RateLimit/RateLimitHandler.py
RateLimitHandler.preview_request
python
def preview_request(self, region, endpoint_name, method_name, url, query_params): wait_until = max( [ ( limiter.wait_until(region, endpoint_name, method_name), limiter.friendly_name, ) for limiter in self._limite...
called before a request is processed. :param string region: the region of this request :param string endpoint_name: the name of the endpoint being requested :param string method_name: the name of the method being requested :param url: the URL that is being requested. :param quer...
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/Handlers/RateLimit/RateLimitHandler.py#L20-L52
null
class RateLimitHandler(RequestHandler): def __init__(self): super(RateLimitHandler, self).__init__() self._limiters = ( ApplicationRateLimiter(), MethodRateLimiter(), OopsRateLimiter(), ) def after_request(self, region, endpoint_name, method_name, u...
pseudonym117/Riot-Watcher
src/riotwatcher/Handlers/RateLimit/RateLimitHandler.py
RateLimitHandler.after_request
python
def after_request(self, region, endpoint_name, method_name, url, response): for limiter in self._limiters: limiter.update_limiter(region, endpoint_name, method_name, response) return response
Called after a response is received and before it is returned to the user. :param string region: the region of this request :param string endpoint_name: the name of the endpoint that was requested :param string method_name: the name of the method that was requested :param url: The url t...
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/Handlers/RateLimit/RateLimitHandler.py#L54-L67
null
class RateLimitHandler(RequestHandler): def __init__(self): super(RateLimitHandler, self).__init__() self._limiters = ( ApplicationRateLimiter(), MethodRateLimiter(), OopsRateLimiter(), ) def preview_request(self, region, endpoint_name, method_name, ...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/LolStatusApiV3.py
LolStatusApiV3.shard_data
python
def shard_data(self, region): url, query = LolStatusApiV3Urls.shard_data(region=region) return self._raw_request(self.shard_data.__name__, region, url, query)
Get League of Legends status for the given shard. Requests to this API are not counted against the application Rate Limits. :param string region: the region to execute this request on :returns: ShardStatus
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/LolStatusApiV3.py#L20-L31
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class LolStatusApiV3(NamedEndpoint): """ This class wraps the LoL-Status-v3 Api calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#lol-status-v3 for more detailed information """ def __init__(self, base_api): """ Initialize a new LolStatusApiV3 which u...
pseudonym117/Riot-Watcher
src/riotwatcher/Handlers/TypeCorrectorHandler.py
TypeCorrectorHandler.preview_request
python
def preview_request(self, region, endpoint_name, method_name, url, query_params): if query_params is not None: for key, value in query_params.items(): if isinstance(value, bool): query_params[key] = str(value).lower() # check to see if we have a l...
called before a request is processed. :param string endpoint_name: the name of the endpoint being requested :param string method_name: the name of the method being requested :param url: the URL that is being requested. :param query_params: dict: the parameters to the url that is being q...
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/Handlers/TypeCorrectorHandler.py#L13-L36
null
class TypeCorrectorHandler(RequestHandler): """ The TypeCorrector class is meant to correct any inconsistencies in the types of objects provided as query parameters. Currently this only involves changing boolean values into strings, as the API only accepts lower case booleans for some reason. "...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/ChampionMasteryApiV4.py
ChampionMasteryApiV4.by_summoner_by_champion
python
def by_summoner_by_champion(self, region, encrypted_summoner_id, champion_id): url, query = ChampionMasteryApiV4Urls.by_summoner_by_champion( region=region, encrypted_summoner_id=encrypted_summoner_id, champion_id=champion_id, ) return self._raw_request( ...
Get a champion mastery by player ID and champion ID. :param string region: the region to execute this request on :param string encrypted_summoner_id: Summoner ID associated with the player :param long champion_id: Champion ID to retrieve Champion Mast...
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/ChampionMasteryApiV4.py#L36-L54
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class ChampionMasteryApiV4(NamedEndpoint): """ This class wraps the Champion-Mastery-v4 Api calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#champion-mastery-v4/ for more detailed information """ def __init__(self, base_api): """ Initialize a new...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/SummonerApiV4.py
SummonerApiV4.by_account
python
def by_account(self, region, encrypted_account_id): url, query = SummonerApiV4Urls.by_account( region=region, encrypted_account_id=encrypted_account_id ) return self._raw_request(self.by_account.__name__, region, url, query)
Get a summoner by account ID. :param string region: The region to execute this request on :param string encrypted_account_id: The account ID. :returns: SummonerDTO: represents a summoner
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/SummonerApiV4.py#L20-L32
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class SummonerApiV4(NamedEndpoint): """ This class wraps the Summoner-v4 endpoint calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#summoner-v4 for more detailed information """ def __init__(self, base_api): """ Initialize a new SummonerApiV4 which us...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/SummonerApiV4.py
SummonerApiV4.by_name
python
def by_name(self, region, summoner_name): url, query = SummonerApiV4Urls.by_name( region=region, summoner_name=summoner_name ) return self._raw_request(self.by_name.__name__, region, url, query)
Get a summoner by summoner name :param string region: The region to execute this request on :param string summoner_name: Summoner Name :returns: SummonerDTO: represents a summoner
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/SummonerApiV4.py#L34-L46
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class SummonerApiV4(NamedEndpoint): """ This class wraps the Summoner-v4 endpoint calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#summoner-v4 for more detailed information """ def __init__(self, base_api): """ Initialize a new SummonerApiV4 which us...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/SummonerApiV4.py
SummonerApiV4.by_puuid
python
def by_puuid(self, region, encrypted_puuid): url, query = SummonerApiV4Urls.by_puuid( region=region, encrypted_puuid=encrypted_puuid ) return self._raw_request(self.by_puuid.__name__, region, url, query)
Get a summoner by PUUID. :param string region: The region to execute this request on :param string encrypted_puuid: PUUID :returns: SummonerDTO: represents a summoner
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/SummonerApiV4.py#L48-L60
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class SummonerApiV4(NamedEndpoint): """ This class wraps the Summoner-v4 endpoint calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#summoner-v4 for more detailed information """ def __init__(self, base_api): """ Initialize a new SummonerApiV4 which us...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/SummonerApiV4.py
SummonerApiV4.by_id
python
def by_id(self, region, encrypted_summoner_id): url, query = SummonerApiV4Urls.by_id( region=region, encrypted_summoner_id=encrypted_summoner_id ) return self._raw_request(self.by_id.__name__, region, url, query)
Get a summoner by summoner ID. :param string region: The region to execute this request on :param string encrypted_summoner_id: Summoner ID :returns: SummonerDTO: represents a summoner
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/SummonerApiV4.py#L62-L74
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class SummonerApiV4(NamedEndpoint): """ This class wraps the Summoner-v4 endpoint calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#summoner-v4 for more detailed information """ def __init__(self, base_api): """ Initialize a new SummonerApiV4 which us...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/SpectatorApiV4.py
SpectatorApiV4.featured_games
python
def featured_games(self, region): url, query = SpectatorApiV4Urls.featured_games(region=region) return self._raw_request(self.featured_games.__name__, region, url, query)
Get list of featured games. :param string region: The region to execute this request on :returns: FeaturedGames
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/SpectatorApiV4.py#L34-L43
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class SpectatorApiV4(NamedEndpoint): """ This class wraps the Spectator-v4 endpoint calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#spectator-v4 for more detailed information """ def __init__(self, base_api): """ Initialize a new SpectatorApiV3 whic...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/ThirdPartyCodeApiV4.py
ThirdPartyCodeApiV4.by_summoner
python
def by_summoner(self, region, encrypted_summoner_id): url, query = ThirdPartyCodeApiV4Urls.by_summoner( region=region, encrypted_summoner_id=encrypted_summoner_id ) return self._raw_request(self.by_summoner.__name__, region, url, query)
FOR KR SUMMONERS, A 404 WILL ALWAYS BE RETURNED. Valid codes must be no longer than 256 characters and only use valid characters: 0-9, a-z, A-Z, and - :param string region: the region to execute this request on :param string encrypted_summoner_id: Summoner ID ...
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/ThirdPartyCodeApiV4.py#L21-L37
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class ThirdPartyCodeApiV4(NamedEndpoint): """ This class wraps the ThirdPartyCode-v4 Api calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#third-party-code-v4 for more detailed information """ def __init__(self, base_api): """ Initialize a new Thi...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/NamedEndpoint.py
NamedEndpoint._raw_request
python
def _raw_request(self, method_name, region, url, query_params): return self._base_api.raw_request( self._endpoint_name, method_name, region, url, query_params )
Sends a request through the BaseApi instance provided, injecting the provided endpoint_name into the method call, so the caller doesn't have to. :param string method_name: The name of the calling method :param string region: The region to execute this request on :param string url...
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/NamedEndpoint.py#L18-L30
null
class NamedEndpoint(object): """ Helper class to inject endpoint name into calls to a BaseApi instance without the child class explicitly adding the name every time. """ def __init__(self, base_api, endpoint_name): """ Initialize a new NamedEndpoint which uses the provided base_api ...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/LeagueApiV4.py
LeagueApiV4.challenger_by_queue
python
def challenger_by_queue(self, region, queue): url, query = LeagueApiV4Urls.challenger_by_queue(region=region, queue=queue) return self._raw_request(self.challenger_by_queue.__name__, region, url, query)
Get the challenger league for a given queue. :param string region: the region to execute this request on :param string queue: the queue to get the challenger players for :returns: LeagueListDTO
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/LeagueApiV4.py#L20-L30
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class LeagueApiV4(NamedEndpoint): """ This class wraps the League-v4 Api calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#league-v4/ for more detailed information """ def __init__(self, base_api): """ Initialize a new LeagueApiV4 which uses the provi...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/LeagueApiV4.py
LeagueApiV4.masters_by_queue
python
def masters_by_queue(self, region, queue): url, query = LeagueApiV4Urls.master_by_queue(region=region, queue=queue) return self._raw_request(self.masters_by_queue.__name__, region, url, query)
Get the master league for a given queue. :param string region: the region to execute this request on :param string queue: the queue to get the master players for :returns: LeagueListDTO
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/LeagueApiV4.py#L44-L54
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class LeagueApiV4(NamedEndpoint): """ This class wraps the League-v4 Api calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#league-v4/ for more detailed information """ def __init__(self, base_api): """ Initialize a new LeagueApiV4 which uses the provi...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/LeagueApiV4.py
LeagueApiV4.by_id
python
def by_id(self, region, league_id): url, query = LeagueApiV4Urls.by_id(region=region, league_id=league_id) return self._raw_request(self.by_id.__name__, region, url, query)
Get league with given ID, including inactive entries :param string region: the region to execute this request on :param string league_id: the league ID to query :returns: LeagueListDTO
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/LeagueApiV4.py#L56-L66
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class LeagueApiV4(NamedEndpoint): """ This class wraps the League-v4 Api calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#league-v4/ for more detailed information """ def __init__(self, base_api): """ Initialize a new LeagueApiV4 which uses the provi...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/LeagueApiV4.py
LeagueApiV4.entries
python
def entries(self, region, queue, tier, division): url, query = LeagueApiV4Urls.entries( region=region, queue=queue, tier=tier, division=division ) return self._raw_request(self.entries.__name__, region, url, query)
Get all the league entries :param string region: the region to execute this request on :param string queue: the queue to query, i.e. RANKED_SOLO_5x5 :param string tier: the tier to query, i.e. DIAMOND :param string division: the division to query, i.e. III :returns: Se...
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/LeagueApiV4.py#L82-L96
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class LeagueApiV4(NamedEndpoint): """ This class wraps the League-v4 Api calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#league-v4/ for more detailed information """ def __init__(self, base_api): """ Initialize a new LeagueApiV4 which uses the provi...
pseudonym117/Riot-Watcher
src/riotwatcher/_apis/ChampionApiV3.py
ChampionApiV3.rotations
python
def rotations(self, region): url, query = ChampionApiV3Urls.rotations(region=region) return self._raw_request(self.rotations.__name__, region, url, query)
Returns champion rotations, including free-to-play and low-level free-to-play rotations. :returns: ChampionInfo
train
https://github.com/pseudonym117/Riot-Watcher/blob/21ab12453a0d824d67e30f5514d02a5c5a411dea/src/riotwatcher/_apis/ChampionApiV3.py#L20-L27
[ "def _raw_request(self, method_name, region, url, query_params):\n \"\"\"\n Sends a request through the BaseApi instance provided, injecting the provided endpoint_name\n into the method call, so the caller doesn't have to.\n\n :param string method_name: The name of the calling method\n :param string...
class ChampionApiV3(NamedEndpoint): """ This class wraps the Champion-v3 Api calls provided by the Riot API. See https://developer.riotgames.com/api-methods/#champion-v3 for more detailed information """ def __init__(self, base_api): """ Initialize a new ChampionApiV3 which uses th...
johnwmillr/LyricsGenius
lyricsgenius/api.py
API._make_request
python
def _make_request(self, path, method='GET', params_=None): uri = self.api_root + path if params_: params_['text_format'] = self.response_format else: params_ = {'text_format': self.response_format} # Make the request response = None try: ...
Make a request to the API
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L50-L69
null
class API(object): """Genius API""" # Create a persistent requests connection _session = requests.Session() _session.headers = {'application': 'LyricsGenius', 'User-Agent': 'https://github.com/johnwmillr/LyricsGenius'} _SLEEP_MIN = 0.2 # Enforce minimum wait time between API calls (seconds)...
johnwmillr/LyricsGenius
lyricsgenius/api.py
API.get_song
python
def get_song(self, id_): endpoint = "songs/{id}".format(id=id_) return self._make_request(endpoint)
Data for a specific song.
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L71-L74
[ "def _make_request(self, path, method='GET', params_=None):\n \"\"\"Make a request to the API\"\"\"\n uri = self.api_root + path\n if params_:\n params_['text_format'] = self.response_format\n else:\n params_ = {'text_format': self.response_format}\n\n # Make the request\n response =...
class API(object): """Genius API""" # Create a persistent requests connection _session = requests.Session() _session.headers = {'application': 'LyricsGenius', 'User-Agent': 'https://github.com/johnwmillr/LyricsGenius'} _SLEEP_MIN = 0.2 # Enforce minimum wait time between API calls (seconds)...
johnwmillr/LyricsGenius
lyricsgenius/api.py
API.get_artist
python
def get_artist(self, id_): endpoint = "artists/{id}".format(id=id_) return self._make_request(endpoint)
Data for a specific artist.
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L76-L79
[ "def _make_request(self, path, method='GET', params_=None):\n \"\"\"Make a request to the API\"\"\"\n uri = self.api_root + path\n if params_:\n params_['text_format'] = self.response_format\n else:\n params_ = {'text_format': self.response_format}\n\n # Make the request\n response =...
class API(object): """Genius API""" # Create a persistent requests connection _session = requests.Session() _session.headers = {'application': 'LyricsGenius', 'User-Agent': 'https://github.com/johnwmillr/LyricsGenius'} _SLEEP_MIN = 0.2 # Enforce minimum wait time between API calls (seconds)...
johnwmillr/LyricsGenius
lyricsgenius/api.py
API.get_artist_songs
python
def get_artist_songs(self, id_, sort='title', per_page=20, page=1): endpoint = "artists/{id}/songs".format(id=id_) params = {'sort': sort, 'per_page': per_page, 'page': page} return self._make_request(endpoint, params_=params)
Documents (songs) for the artist specified.
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L81-L85
[ "def _make_request(self, path, method='GET', params_=None):\n \"\"\"Make a request to the API\"\"\"\n uri = self.api_root + path\n if params_:\n params_['text_format'] = self.response_format\n else:\n params_ = {'text_format': self.response_format}\n\n # Make the request\n response =...
class API(object): """Genius API""" # Create a persistent requests connection _session = requests.Session() _session.headers = {'application': 'LyricsGenius', 'User-Agent': 'https://github.com/johnwmillr/LyricsGenius'} _SLEEP_MIN = 0.2 # Enforce minimum wait time between API calls (seconds)...
johnwmillr/LyricsGenius
lyricsgenius/api.py
API.search_genius
python
def search_genius(self, search_term): endpoint = "search/" params = {'q': search_term} return self._make_request(endpoint, params_=params)
Search documents hosted on Genius.
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L87-L91
[ "def _make_request(self, path, method='GET', params_=None):\n \"\"\"Make a request to the API\"\"\"\n uri = self.api_root + path\n if params_:\n params_['text_format'] = self.response_format\n else:\n params_ = {'text_format': self.response_format}\n\n # Make the request\n response =...
class API(object): """Genius API""" # Create a persistent requests connection _session = requests.Session() _session.headers = {'application': 'LyricsGenius', 'User-Agent': 'https://github.com/johnwmillr/LyricsGenius'} _SLEEP_MIN = 0.2 # Enforce minimum wait time between API calls (seconds)...
johnwmillr/LyricsGenius
lyricsgenius/api.py
API.search_genius_web
python
def search_genius_web(self, search_term, per_page=5): endpoint = "search/multi?" params = {'per_page': per_page, 'q': search_term} # This endpoint is not part of the API, requires different formatting url = "https://genius.com/api/" + endpoint + urlencode(params) response = requ...
Use the web-version of Genius search
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L93-L102
null
class API(object): """Genius API""" # Create a persistent requests connection _session = requests.Session() _session.headers = {'application': 'LyricsGenius', 'User-Agent': 'https://github.com/johnwmillr/LyricsGenius'} _SLEEP_MIN = 0.2 # Enforce minimum wait time between API calls (seconds)...
johnwmillr/LyricsGenius
lyricsgenius/api.py
API.get_annotation
python
def get_annotation(self, id_): endpoint = "annotations/{id}".format(id=id_) return self._make_request(endpoint)
Data for a specific annotation.
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L104-L107
[ "def _make_request(self, path, method='GET', params_=None):\n \"\"\"Make a request to the API\"\"\"\n uri = self.api_root + path\n if params_:\n params_['text_format'] = self.response_format\n else:\n params_ = {'text_format': self.response_format}\n\n # Make the request\n response =...
class API(object): """Genius API""" # Create a persistent requests connection _session = requests.Session() _session.headers = {'application': 'LyricsGenius', 'User-Agent': 'https://github.com/johnwmillr/LyricsGenius'} _SLEEP_MIN = 0.2 # Enforce minimum wait time between API calls (seconds)...
johnwmillr/LyricsGenius
lyricsgenius/api.py
Genius._scrape_song_lyrics_from_url
python
def _scrape_song_lyrics_from_url(self, url): page = requests.get(url) if page.status_code == 404: return None # Scrape the song lyrics from the HTML html = BeautifulSoup(page.text, "html.parser") div = html.find("div", class_="lyrics") if not div: ...
Use BeautifulSoup to scrape song info off of a Genius song URL :param url: URL for the web page to scrape lyrics from
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L134-L153
null
class Genius(API): """User-level interface with the Genius.com API.""" def __init__(self, client_access_token, response_format='plain', timeout=5, sleep_time=0.5, verbose=True, remove_section_headers=False, skip_non_songs=True, excluded_terms=[], ...
johnwmillr/LyricsGenius
lyricsgenius/api.py
Genius._clean_str
python
def _clean_str(self, s): return s.translate(str.maketrans('', '', punctuation)).replace('\u200b', " ").strip().lower()
Returns a lowercase string with punctuation and bad chars removed :param s: string to clean
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L155-L159
null
class Genius(API): """User-level interface with the Genius.com API.""" def __init__(self, client_access_token, response_format='plain', timeout=5, sleep_time=0.5, verbose=True, remove_section_headers=False, skip_non_songs=True, excluded_terms=[], ...
johnwmillr/LyricsGenius
lyricsgenius/api.py
Genius._result_is_lyrics
python
def _result_is_lyrics(self, song_title): default_terms = ['track\\s?list', 'album art(work)?', 'liner notes', 'booklet', 'credits', 'interview', 'skit', 'instrumental', 'setlist'] if self.excluded_terms: if self.replace_default_terms: ...
Returns False if result from Genius is not actually song lyrics Set the `excluded_terms` and `replace_default_terms` as instance variables within the Genius class.
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L161-L178
[ "def _clean_str(self, s):\n \"\"\" Returns a lowercase string with punctuation and bad chars removed\n :param s: string to clean\n \"\"\"\n return s.translate(str.maketrans('', '', punctuation)).replace('\\u200b', \" \").strip().lower()\n" ]
class Genius(API): """User-level interface with the Genius.com API.""" def __init__(self, client_access_token, response_format='plain', timeout=5, sleep_time=0.5, verbose=True, remove_section_headers=False, skip_non_songs=True, excluded_terms=[], ...
johnwmillr/LyricsGenius
lyricsgenius/api.py
Genius._get_item_from_search_response
python
def _get_item_from_search_response(self, response, type_): sections = sorted(response['sections'], key=lambda sect: sect['type'] == type_, reverse=True) for section in sections: hits = [hit for hit in section['hits'] if hit['type'] == type_...
Returns either a Song or Artist result from search_genius_web
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L180-L188
null
class Genius(API): """User-level interface with the Genius.com API.""" def __init__(self, client_access_token, response_format='plain', timeout=5, sleep_time=0.5, verbose=True, remove_section_headers=False, skip_non_songs=True, excluded_terms=[], ...
johnwmillr/LyricsGenius
lyricsgenius/api.py
Genius._result_is_match
python
def _result_is_match(self, result, title, artist=None): result_title = self._clean_str(result['title']) title_is_match = result_title == self._clean_str(title) if not artist: return title_is_match result_artist = self._clean_str(result['primary_artist']['name']) retur...
Returns True if search result matches searched song
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L190-L197
null
class Genius(API): """User-level interface with the Genius.com API.""" def __init__(self, client_access_token, response_format='plain', timeout=5, sleep_time=0.5, verbose=True, remove_section_headers=False, skip_non_songs=True, excluded_terms=[], ...
johnwmillr/LyricsGenius
lyricsgenius/api.py
Genius.search_song
python
def search_song(self, title, artist="", get_full_info=True): # Search the Genius API for the specified song if self.verbose: if artist: print('Searching for "{s}" by {a}...'.format(s=title, a=artist)) else: print('Searching for "{s}"...'.format(s=...
Search Genius.com for lyrics to a specific song :param title: Song title to search for :param artist: Name of the artist :param get_full_info: Get full info for each song (slower)
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L199-L247
[ "def get_song(self, id_):\n \"\"\"Data for a specific song.\"\"\"\n endpoint = \"songs/{id}\".format(id=id_)\n return self._make_request(endpoint)\n", "def search_genius_web(self, search_term, per_page=5):\n \"\"\"Use the web-version of Genius search\"\"\"\n endpoint = \"search/multi?\"\n params...
class Genius(API): """User-level interface with the Genius.com API.""" def __init__(self, client_access_token, response_format='plain', timeout=5, sleep_time=0.5, verbose=True, remove_section_headers=False, skip_non_songs=True, excluded_terms=[], ...
johnwmillr/LyricsGenius
lyricsgenius/api.py
Genius.search_artist
python
def search_artist(self, artist_name, max_songs=None, sort='popularity', per_page=20, get_full_info=True): if self.verbose: print('Searching for songs by {0}...\n'.format(artist_name)) # Perform a Genius API search for the artist found_artist = None res...
Search Genius.com for songs by the specified artist. Returns an Artist object containing artist's songs. :param artist_name: Name of the artist to search for :param max_songs: Maximum number of songs to search for :param sort: Sort by 'title' or 'popularity' :param per_page: Numb...
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L249-L334
[ "def get_artist(self, id_):\n \"\"\"Data for a specific artist.\"\"\"\n endpoint = \"artists/{id}\".format(id=id_)\n return self._make_request(endpoint)\n", "def get_artist_songs(self, id_, sort='title', per_page=20, page=1):\n \"\"\"Documents (songs) for the artist specified.\"\"\"\n endpoint = \"...
class Genius(API): """User-level interface with the Genius.com API.""" def __init__(self, client_access_token, response_format='plain', timeout=5, sleep_time=0.5, verbose=True, remove_section_headers=False, skip_non_songs=True, excluded_terms=[], ...
johnwmillr/LyricsGenius
lyricsgenius/api.py
Genius.save_artists
python
def save_artists(self, artists, filename="artist_lyrics", overwrite=False): if isinstance(artists, Artist): artists = [artists] # Create a temporary directory for lyrics start = time.time() tmp_dir = 'tmp_lyrics' if not os.path.isdir(tmp_dir): os.mkdir(tm...
Save lyrics from multiple Artist objects as JSON object :param artists: List of Artist objects to save lyrics from :param filename: Name of output file (json) :param overwrite: Overwrites preexisting file if True
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L336-L381
null
class Genius(API): """User-level interface with the Genius.com API.""" def __init__(self, client_access_token, response_format='plain', timeout=5, sleep_time=0.5, verbose=True, remove_section_headers=False, skip_non_songs=True, excluded_terms=[], ...
johnwmillr/LyricsGenius
lyricsgenius/song.py
Song.to_dict
python
def to_dict(self): return dict({'title': self.title, 'album': self.album, 'year': self.year, 'lyrics': self.lyrics, 'image': self.song_art_image_url})
Create a dictionary from the song object Used in save_lyrics to create json object :return: Dictionary
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/song.py#L83-L94
null
class Song(object): """A song from the Genius.com database.""" def __init__(self, json_dict, lyrics=''): """ Song Constructor Properties: title: Title of the song. artist: Primary artist on the song. lyrics: Full set of song lyrics. album: Name o...
johnwmillr/LyricsGenius
lyricsgenius/song.py
Song.save_lyrics
python
def save_lyrics(self, filename=None, extension='json', verbose=True, overwrite=None, binary_encoding=False): extension = extension.lstrip(".") assert (extension == 'json') or (extension == 'txt'), "format_ must be JSON or TXT" # Determine the filename if filename: ...
Allows user to save song lyrics from Song object to a .json or .txt file.
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/song.py#L100-L149
[ "def to_dict(self):\n \"\"\"\n Create a dictionary from the song object\n Used in save_lyrics to create json object\n\n :return: Dictionary\n \"\"\"\n return dict({'title': self.title,\n 'album': self.album,\n 'year': self.year,\n 'lyrics': self.lyri...
class Song(object): """A song from the Genius.com database.""" def __init__(self, json_dict, lyrics=''): """ Song Constructor Properties: title: Title of the song. artist: Primary artist on the song. lyrics: Full set of song lyrics. album: Name o...
johnwmillr/LyricsGenius
lyricsgenius/artist.py
Artist.add_song
python
def add_song(self, new_song, verbose=True): if any([song.title == new_song.title for song in self._songs]): if verbose: print('{s} already in {a}, not adding song.'.format(s=new_song.title, a=self.name)) ...
Add a Song object to the Artist object
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/artist.py#L50-L65
null
class Artist(object): """An artist with songs from the Genius.com database.""" def __init__(self, json_dict): """ Artist Constructor Properties: name: Artist name. image_url: URL to the artist image on Genius.com songs: List of the artist's Song objects ...
johnwmillr/LyricsGenius
lyricsgenius/artist.py
Artist.save_lyrics
python
def save_lyrics(self, extension='json', overwrite=False, verbose=True, binary_encoding=False): extension = extension.lstrip(".") assert (extension == 'json') or (extension == 'txt'), "format_ must be JSON or TXT" for song in self.songs: song.save_lyrics(extension...
Allows user to save all lyrics within an Artist object
train
https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/artist.py#L76-L83
null
class Artist(object): """An artist with songs from the Genius.com database.""" def __init__(self, json_dict): """ Artist Constructor Properties: name: Artist name. image_url: URL to the artist image on Genius.com songs: List of the artist's Song objects ...
michaelliao/sinaweibopy
snspy.py
_parse_json
python
def _parse_json(s): ''' Parse json string into JsonDict. >>> r = _parse_json(r'{"name":"Michael","score":95}') >>> r.name u'Michael' >>> r['score'] 95 ''' return json.loads(s, object_hook=lambda pairs: JsonDict(pairs.iteritems()))
Parse json string into JsonDict. >>> r = _parse_json(r'{"name":"Michael","score":95}') >>> r.name u'Michael' >>> r['score'] 95
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L77-L87
null
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = '1.0.0' __author__ = 'Liao Xuefeng (askxuefeng@gmail.com)' ''' Python client SDK for SNS API using OAuth 2. Require Python 2.6/2.7. ''' try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import time import json i...
michaelliao/sinaweibopy
snspy.py
_encode_params
python
def _encode_params(**kw): ''' Do url-encode parameters >>> _encode_params(a=1, b='R&D') 'a=1&b=R%26D' >>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123]) 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123' ''' def _encode(L, k, v): if isinstance(v, unicode): L.append('%s=%s' %...
Do url-encode parameters >>> _encode_params(a=1, b='R&D') 'a=1&b=R%26D' >>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123]) 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123'
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L90-L112
[ "def _encode(L, k, v):\n if isinstance(v, unicode):\n L.append('%s=%s' % (k, urllib.quote(v.encode('utf-8'))))\n elif isinstance(v, str):\n L.append('%s=%s' % (k, urllib.quote(v)))\n elif isinstance(v, collections.Iterable):\n for x in v:\n _encode(L, k, x)\n else:\n ...
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = '1.0.0' __author__ = 'Liao Xuefeng (askxuefeng@gmail.com)' ''' Python client SDK for SNS API using OAuth 2. Require Python 2.6/2.7. ''' try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import time import json i...
michaelliao/sinaweibopy
snspy.py
_encode_multipart
python
def _encode_multipart(**kw): ' build a multipart/form-data body with randomly generated boundary ' boundary = '----------%s' % hex(int(time.time() * 1000)) data = [] for k, v in kw.iteritems(): data.append('--%s' % boundary) if hasattr(v, 'read'): # file-like object: ...
build a multipart/form-data body with randomly generated boundary
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L115-L133
null
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = '1.0.0' __author__ = 'Liao Xuefeng (askxuefeng@gmail.com)' ''' Python client SDK for SNS API using OAuth 2. Require Python 2.6/2.7. ''' try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import time import json i...
michaelliao/sinaweibopy
snspy.py
_guess_content_type
python
def _guess_content_type(url): ''' Guess content type by url. >>> _guess_content_type('http://test/A.HTML') 'text/html' >>> _guess_content_type('http://test/a.jpg') 'image/jpeg' >>> _guess_content_type('/path.txt/aaa') 'application/octet-stream' ''' OCTET_STREAM = 'application/oc...
Guess content type by url. >>> _guess_content_type('http://test/A.HTML') 'text/html' >>> _guess_content_type('http://test/a.jpg') 'image/jpeg' >>> _guess_content_type('/path.txt/aaa') 'application/octet-stream'
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L136-L151
null
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = '1.0.0' __author__ = 'Liao Xuefeng (askxuefeng@gmail.com)' ''' Python client SDK for SNS API using OAuth 2. Require Python 2.6/2.7. ''' try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import time import json i...
michaelliao/sinaweibopy
snspy.py
_http
python
def _http(method, url, headers=None, **kw): ''' Send http request and return response text. ''' params = None boundary = None if method == 'UPLOAD': params, boundary = _encode_multipart(**kw) else: params = _encode_params(**kw) http_url = '%s?%s' % (url, params) if method...
Send http request and return response text.
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L169-L193
[ "def _encode_params(**kw):\n '''\n Do url-encode parameters\n\n >>> _encode_params(a=1, b='R&D')\n 'a=1&b=R%26D'\n >>> _encode_params(a=u'\\u4e2d\\u6587', b=['A', 'B', 123])\n 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123'\n '''\n def _encode(L, k, v):\n if isinstance(v, unicode):\n ...
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = '1.0.0' __author__ = 'Liao Xuefeng (askxuefeng@gmail.com)' ''' Python client SDK for SNS API using OAuth 2. Require Python 2.6/2.7. ''' try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import time import json i...
michaelliao/sinaweibopy
snspy.py
SinaWeiboMixin.get_authorize_url
python
def get_authorize_url(self, redirect_uri, **kw): ''' return the authorization url that the user should be redirected to. ''' redirect = redirect_uri if redirect_uri else self._redirect_uri if not redirect: raise APIError('21305', 'Parameter absent: redirect_uri', 'OAu...
return the authorization url that the user should be redirected to.
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L218-L229
[ "def _encode_params(**kw):\n '''\n Do url-encode parameters\n\n >>> _encode_params(a=1, b='R&D')\n 'a=1&b=R%26D'\n >>> _encode_params(a=u'\\u4e2d\\u6587', b=['A', 'B', 123])\n 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123'\n '''\n def _encode(L, k, v):\n if isinstance(v, unicode):\n ...
class SinaWeiboMixin(SNSMixin): def _prepare_api(self, method, path, access_token, **kw): ''' Get api url. ''' headers = None if access_token: headers = {'Authorization': 'OAuth2 %s' % access_token} if '/remind/' in path: # sina remind api ur...
michaelliao/sinaweibopy
snspy.py
SinaWeiboMixin._prepare_api
python
def _prepare_api(self, method, path, access_token, **kw): ''' Get api url. ''' headers = None if access_token: headers = {'Authorization': 'OAuth2 %s' % access_token} if '/remind/' in path: # sina remind api url is different: return met...
Get api url.
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L231-L244
null
class SinaWeiboMixin(SNSMixin): def get_authorize_url(self, redirect_uri, **kw): ''' return the authorization url that the user should be redirected to. ''' redirect = redirect_uri if redirect_uri else self._redirect_uri if not redirect: raise APIError('21305', '...
michaelliao/sinaweibopy
snspy.py
SinaWeiboMixin.request_access_token
python
def request_access_token(self, code, redirect_uri=None): ''' Return access token as a JsonDict: {"access_token":"your-access-token","expires":12345678,"uid":1234}, expires is represented using standard unix-epoch-time ''' redirect = redirect_uri or self._redirect_uri resp_text = ...
Return access token as a JsonDict: {"access_token":"your-access-token","expires":12345678,"uid":1234}, expires is represented using standard unix-epoch-time
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L246-L262
[ "def _parse_json(s):\n '''\n Parse json string into JsonDict.\n\n >>> r = _parse_json(r'{\"name\":\"Michael\",\"score\":95}')\n >>> r.name\n u'Michael'\n >>> r['score']\n 95\n '''\n return json.loads(s, object_hook=lambda pairs: JsonDict(pairs.iteritems()))\n", "def _http(method, url, h...
class SinaWeiboMixin(SNSMixin): def get_authorize_url(self, redirect_uri, **kw): ''' return the authorization url that the user should be redirected to. ''' redirect = redirect_uri if redirect_uri else self._redirect_uri if not redirect: raise APIError('21305', '...
michaelliao/sinaweibopy
snspy.py
SinaWeiboMixin.parse_signed_request
python
def parse_signed_request(self, signed_request): ''' parse signed request when using in-site app. Returns: dict object like { 'uid': 12345, 'access_token': 'ABC123XYZ', 'expires': unix-timestamp }, or None if parse failed. ''' def _b64_normalize(s): ...
parse signed request when using in-site app. Returns: dict object like { 'uid': 12345, 'access_token': 'ABC123XYZ', 'expires': unix-timestamp }, or None if parse failed.
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L264-L291
[ "def _parse_json(s):\n '''\n Parse json string into JsonDict.\n\n >>> r = _parse_json(r'{\"name\":\"Michael\",\"score\":95}')\n >>> r.name\n u'Michael'\n >>> r['score']\n 95\n '''\n return json.loads(s, object_hook=lambda pairs: JsonDict(pairs.iteritems()))\n", "def _b64_normalize(s):\n...
class SinaWeiboMixin(SNSMixin): def get_authorize_url(self, redirect_uri, **kw): ''' return the authorization url that the user should be redirected to. ''' redirect = redirect_uri if redirect_uri else self._redirect_uri if not redirect: raise APIError('21305', '...
michaelliao/sinaweibopy
snspy.py
QQMixin.request_access_token
python
def request_access_token(self, code, redirect_uri=None): ''' Return access token as a JsonDict: {"access_token":"your-access-token","expires":12345678,"uid":1234}, expires is represented using standard unix-epoch-time ''' redirect = redirect_uri or self._redirect_uri resp_text = ...
Return access token as a JsonDict: {"access_token":"your-access-token","expires":12345678,"uid":1234}, expires is represented using standard unix-epoch-time
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L314-L322
[ "def _http(method, url, headers=None, **kw):\n '''\n Send http request and return response text.\n '''\n params = None\n boundary = None\n if method == 'UPLOAD':\n params, boundary = _encode_multipart(**kw)\n else:\n params = _encode_params(**kw)\n http_url = '%s?%s' % (url, pa...
class QQMixin(SNSMixin): def get_authorize_url(self, redirect_uri='', **kw): ''' return the authorization url that the user should be redirected to. ''' redirect = redirect_uri if redirect_uri else self._redirect_uri if not redirect: raise APIError('21305', 'Para...
michaelliao/sinaweibopy
snspy.py
QQMixin.refresh_access_token
python
def refresh_access_token(self, refresh_token, redirect_uri=None): ''' Refresh access token. ''' redirect = redirect_uri or self._redirect_uri resp_text = _http('POST', 'https://graph.qq.com/oauth2.0/token', refresh_token=refresh_token, ...
Refresh access token.
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L324-L333
[ "def _http(method, url, headers=None, **kw):\n '''\n Send http request and return response text.\n '''\n params = None\n boundary = None\n if method == 'UPLOAD':\n params, boundary = _encode_multipart(**kw)\n else:\n params = _encode_params(**kw)\n http_url = '%s?%s' % (url, pa...
class QQMixin(SNSMixin): def get_authorize_url(self, redirect_uri='', **kw): ''' return the authorization url that the user should be redirected to. ''' redirect = redirect_uri if redirect_uri else self._redirect_uri if not redirect: raise APIError('21305', 'Para...
michaelliao/sinaweibopy
snspy.py
QQMixin._parse_access_token
python
def _parse_access_token(self, resp_text): ' parse access token from urlencoded str like access_token=abcxyz&expires_in=123000&other=true ' r = self._qs2dict(resp_text) access_token = r.pop('access_token') expires = time.time() + float(r.pop('expires_in')) return JsonDict(access_t...
parse access token from urlencoded str like access_token=abcxyz&expires_in=123000&other=true
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L336-L341
[ "def _qs2dict(self, text):\n qs = urlparse.parse_qs(text)\n return dict(((k, v[0]) for k, v in qs.iteritems()))\n" ]
class QQMixin(SNSMixin): def get_authorize_url(self, redirect_uri='', **kw): ''' return the authorization url that the user should be redirected to. ''' redirect = redirect_uri if redirect_uri else self._redirect_uri if not redirect: raise APIError('21305', 'Para...
michaelliao/sinaweibopy
snspy.py
APIClient.get_authorize_url
python
def get_authorize_url(self, redirect_uri='', **kw): ''' return the authorization url that the user should be redirected to. ''' return self._mixin.get_authorize_url(redirect_uri or self._mixin._redirect_uri, **kw)
return the authorization url that the user should be redirected to.
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L366-L370
null
class APIClient(object): ''' API client using synchronized invocation. ''' def __init__(self, mixin, app_key, app_secret, redirect_uri='', access_token='', expires=0.0): self._mixin = mixin(app_key, app_secret, redirect_uri) self._access_token = str(access_token) self._expires = ...
michaelliao/sinaweibopy
snspy.py
APIClient.request_access_token
python
def request_access_token(self, code, redirect_uri=None): ''' Return access token as a JsonDict: { "access_token": "your-access-token", "expires": 12345678, # represented using standard unix-epoch-time "uid": 1234 # other fields } ''' r ...
Return access token as a JsonDict: { "access_token": "your-access-token", "expires": 12345678, # represented using standard unix-epoch-time "uid": 1234 # other fields }
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L372-L383
null
class APIClient(object): ''' API client using synchronized invocation. ''' def __init__(self, mixin, app_key, app_secret, redirect_uri='', access_token='', expires=0.0): self._mixin = mixin(app_key, app_secret, redirect_uri) self._access_token = str(access_token) self._expires = ...
michaelliao/sinaweibopy
weibo.py
_parse_json
python
def _parse_json(s): ' parse str into JsonDict ' def _obj_hook(pairs): ' convert json object to python object ' o = JsonDict() for k, v in pairs.iteritems(): o[str(k)] = v return o return json.loads(s, object_hook=_obj_hook)
parse str into JsonDict
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/weibo.py#L46-L55
null
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = '1.1.4' __author__ = 'Liao Xuefeng (askxuefeng@gmail.com)' ''' Python client SDK for sina weibo API using OAuth 2. ''' try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import time import json import hmac import...
michaelliao/sinaweibopy
weibo.py
_encode_params
python
def _encode_params(**kw): ''' do url-encode parameters >>> _encode_params(a=1, b='R&D') 'a=1&b=R%26D' >>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123]) 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123' ''' args = [] for k, v in kw.iteritems(): if isinstance(v, basestring): ...
do url-encode parameters >>> _encode_params(a=1, b='R&D') 'a=1&b=R%26D' >>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123]) 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123'
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/weibo.py#L71-L92
null
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = '1.1.4' __author__ = 'Liao Xuefeng (askxuefeng@gmail.com)' ''' Python client SDK for sina weibo API using OAuth 2. ''' try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import time import json import hmac import...
michaelliao/sinaweibopy
weibo.py
_http_call
python
def _http_call(the_url, method, authorization, **kw): ''' send an http request and return a json object if no error occurred. ''' params = None boundary = None if method == _HTTP_UPLOAD: # fix sina upload url: the_url = the_url.replace('https://api.', 'https://upload.api.') ...
send an http request and return a json object if no error occurred.
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/weibo.py#L154-L191
[ "def _parse_json(s):\n ' parse str into JsonDict '\n\n def _obj_hook(pairs):\n ' convert json object to python object '\n o = JsonDict()\n for k, v in pairs.iteritems():\n o[str(k)] = v\n return o\n return json.loads(s, object_hook=_obj_hook)\n", "def _encode_params...
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = '1.1.4' __author__ = 'Liao Xuefeng (askxuefeng@gmail.com)' ''' Python client SDK for sina weibo API using OAuth 2. ''' try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import time import json import hmac import...
michaelliao/sinaweibopy
weibo.py
APIClient.get_authorize_url
python
def get_authorize_url(self, redirect_uri=None, **kw): ''' return the authorization url that the user should be redirected to. ''' redirect = redirect_uri if redirect_uri else self.redirect_uri if not redirect: raise APIError('21305', 'Parameter absent: redirect_uri', ...
return the authorization url that the user should be redirected to.
train
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/weibo.py#L259-L270
[ "def _encode_params(**kw):\n '''\n do url-encode parameters\n\n >>> _encode_params(a=1, b='R&D')\n 'a=1&b=R%26D'\n >>> _encode_params(a=u'\\u4e2d\\u6587', b=['A', 'B', 123])\n 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123'\n '''\n args = []\n for k, v in kw.iteritems():\n if isinstance(v, ba...
class APIClient(object): ''' API client using synchronized invocation. ''' def __init__(self, app_key, app_secret, redirect_uri=None, response_type='code', domain='api.weibo.com', version='2'): self.client_id = str(app_key) self.client_secret = str(app_secret) self.redirect_uri =...