code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
result = []
frames = sorted(self.items)
for idx, frame in enumerate(frames[:-1]):
next_frame = frames[idx + 1]
if next_frame - frame != 1:
r = xrange(frame + 1, next_frame)
# Check if the next update to the result set
... | def invertedFrameRange(self, zfill=0) | Return the inverse of the :class:`FrameSet` 's frame range, padded if
desired.
The inverse is every frame within the full extent of the range.
Examples:
>>> FrameSet('1-100x2').invertedFrameRange()
'2-98x2'
>>> FrameSet('1-100x2').invertedFrameRange(5)
... | 6.484597 | 6.716742 | 0.965438 |
return FrameSet(FrameSet.framesToFrameRange(
self.items, sort=True, compress=False)) | def normalize(self) | Returns a new normalized (sorted and compacted) :class:`FrameSet`.
Returns:
:class:`FrameSet`: | 34.449371 | 25.591785 | 1.346111 |
other = self._cast_to_frameset(other)
if other is NotImplemented:
return NotImplemented
return self.items.isdisjoint(other.items) | def isdisjoint(self, other) | Check if the contents of :class:self has no common intersection with the
contents of :class:other.
Args:
other (:class:`FrameSet`):
Returns:
bool:
:class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` | 5.333252 | 4.68183 | 1.139138 |
other = self._cast_to_frameset(other)
if other is NotImplemented:
return NotImplemented
return self.items <= other.items | def issubset(self, other) | Check if the contents of `self` is a subset of the contents of
`other.`
Args:
other (:class:`FrameSet`):
Returns:
bool:
:class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` | 7.335958 | 5.88939 | 1.245623 |
other = self._cast_to_frameset(other)
if other is NotImplemented:
return NotImplemented
return self.items >= other.items | def issuperset(self, other) | Check if the contents of `self` is a superset of the contents of
`other.`
Args:
other (:class:`FrameSet`):
Returns:
bool:
:class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` | 7.446269 | 6.271289 | 1.187359 |
from_frozenset = self.items.difference(*map(set, other))
return self.from_iterable(from_frozenset, sort=True) | def difference(self, *other) | Returns a new :class:`FrameSet` with elements in `self` but not in
`other`.
Args:
other (:class:`FrameSet`): or objects that can cast to :class:`FrameSet`
Returns:
:class:`FrameSet`: | 9.49687 | 12.594979 | 0.75402 |
other = self._cast_to_frameset(other)
if other is NotImplemented:
return NotImplemented
from_frozenset = self.items.symmetric_difference(other.items)
return self.from_iterable(from_frozenset, sort=True) | def symmetric_difference(self, other) | Returns a new :class:`FrameSet` that contains all the elements in either
`self` or `other`, but not both.
Args:
other (:class:`FrameSet`):
Returns:
:class:`FrameSet`: | 5.825325 | 6.482547 | 0.898617 |
fail = False
size = 0
if isinstance(obj, numbers.Number):
if obj > constants.MAX_FRAME_SIZE:
fail = True
size = obj
elif hasattr(obj, '__len__'):
size = len(obj)
fail = size > constants.MAX_FRAME_SIZE
... | def _maxSizeCheck(cls, obj) | Raise a MaxSizeException if ``obj`` exceeds MAX_FRAME_SIZE
Args:
obj (numbers.Number or collection):
Raises:
:class:`fileseq.exceptions.MaxSizeException`: | 3.087346 | 2.536744 | 1.217051 |
# we're willing to trim padding characters from consideration
# this translation is orders of magnitude faster than prior method
frange = str(frange).translate(None, ''.join(PAD_MAP.keys()))
if not frange:
return True
for part in frange.split(','):
... | def isFrameRange(frange) | Return True if the given string is a frame range. Any padding
characters, such as '#' and '@' are ignored.
Args:
frange (str): a frame range to test
Returns:
bool: | 8.245572 | 7.980755 | 1.033182 |
def _do_pad(match):
result = list(match.groups())
result[1] = pad(result[1], zfill)
if result[4]:
result[4] = pad(result[4], zfill)
return ''.join((i for i in result if i))
return PAD_RE.sub(_do_pad, frange) | def padFrameRange(frange, zfill) | Return the zero-padded version of the frame range string.
Args:
frange (str): a frame range to test
zfill (int):
Returns:
str: | 3.854896 | 4.372808 | 0.881561 |
match = FRANGE_RE.match(frange)
if not match:
msg = 'Could not parse "{0}": did not match {1}'
raise ParseException(msg.format(frange, FRANGE_RE.pattern))
start, end, modifier, chunk = match.groups()
start = int(start)
end = int(end) if end is not... | def _parse_frange_part(frange) | Internal method: parse a discrete frame range part.
Args:
frange (str): single part of a frame range as a string
(ie "1-100x5")
Returns:
tuple: (start, end, modifier, chunk)
Raises:
:class:`.ParseException`: if the frame range can
... | 2.75964 | 2.492279 | 1.107275 |
if stop is None:
return ''
pad_start = pad(start, zfill)
pad_stop = pad(stop, zfill)
if stride is None or start == stop:
return '{0}'.format(pad_start)
elif abs(stride) == 1:
return '{0}-{1}'.format(pad_start, pad_stop)
else:
... | def _build_frange_part(start, stop, stride, zfill=0) | Private method: builds a proper and padded
frame range string.
Args:
start (int): first frame
stop (int or None): last frame
stride (int or None): increment
zfill (int): width for zero padding
Returns:
str: | 2.294744 | 2.323005 | 0.987834 |
_build = FrameSet._build_frange_part
curr_start = None
curr_stride = None
curr_frame = None
last_frame = None
curr_count = 0
for curr_frame in frames:
if curr_start is None:
curr_start = curr_frame
last_frame = ... | def framesToFrameRanges(frames, zfill=0) | Converts a sequence of frames to a series of padded
frame range strings.
Args:
frames (collections.Iterable): sequence of frames to process
zfill (int): width for zero padding
Yields:
str: | 2.064047 | 2.156772 | 0.957008 |
if compress:
frames = unique(set(), frames)
frames = list(frames)
if not frames:
return ''
if len(frames) == 1:
return pad(frames[0], zfill)
if sort:
frames.sort()
return ','.join(FrameSet.framesToFrameRanges(frames... | def framesToFrameRange(frames, sort=True, zfill=0, compress=False) | Converts an iterator of frames into a
frame range string.
Args:
frames (collections.Iterable): sequence of frames to process
sort (bool): sort the sequence before processing
zfill (int): width for zero padding
compress (bool): remove any duplicates before... | 3.748139 | 4.254684 | 0.880944 |
'''
A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects OAuth 1.0/a parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url: The resource to be requested.
:type url: str
... | def request(self,
method,
url,
header_auth=False,
realm='',
**req_kwargs) | A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects OAuth 1.0/a parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url: The resource to be requested.
:type url: str
:param header_auth:... | 2.730322 | 2.176476 | 1.254469 |
'''
Parses and sets optional OAuth parameters on a request.
:param oauth_param: The OAuth parameter to parse.
:type oauth_param: str
:param req_kwargs: The keyworded arguments passed to the request
method.
:type req_kwargs: dict
'''
params = r... | def _parse_optional_params(self, oauth_params, req_kwargs) | Parses and sets optional OAuth parameters on a request.
:param oauth_param: The OAuth parameter to parse.
:type oauth_param: str
:param req_kwargs: The keyworded arguments passed to the request
method.
:type req_kwargs: dict | 2.392434 | 1.728172 | 1.384373 |
'''Prepares OAuth params for signing.'''
oauth_params = {}
oauth_params['oauth_consumer_key'] = self.consumer_key
oauth_params['oauth_nonce'] = sha1(
str(random()).encode('ascii')).hexdigest()
oauth_params['oauth_signature_method'] = self.signature.NAME
oauth... | def _get_oauth_params(self, req_kwargs) | Prepares OAuth params for signing. | 2.36685 | 2.229189 | 1.061754 |
'''
A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects OAuth 2.0 parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url: The resource to be requested.
:type url: str
:... | def request(self, method, url, bearer_auth=True, **req_kwargs) | A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects OAuth 2.0 parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url: The resource to be requested.
:type url: str
:param bearer_auth: W... | 2.729393 | 1.782732 | 1.531017 |
'''
A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects Ofly parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url: The resource to be requested.
:type url: str
:param... | def request(self,
method,
url,
user_id=None,
hash_meth='sha1',
**req_kwargs) | A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects Ofly parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url: The resource to be requested.
:type url: str
:param hash_meth: The hash... | 3.035129 | 1.961114 | 1.547656 |
'''
A signature method which generates the necessary Ofly parameters.
:param app_id: The oFlyAppId, i.e. "application ID".
:type app_id: str
:param app_secret: The oFlyAppSecret, i.e. "shared secret".
:type app_secret: str
:param hash_meth: The hash method to use... | def sign(url, app_id, app_secret, hash_meth='sha1', **params) | A signature method which generates the necessary Ofly parameters.
:param app_id: The oFlyAppId, i.e. "application ID".
:type app_id: str
:param app_secret: The oFlyAppSecret, i.e. "shared secret".
:type app_secret: str
:param hash_meth: The hash method to use for signing, defaul... | 2.716516 | 1.948139 | 1.394415 |
''' Constructs and returns an authentication header. '''
realm = 'realm="{realm}"'.format(realm=self.realm)
params = ['{k}="{v}"'.format(k=k, v=quote(str(v), safe=''))
for k, v in self.oauth_params.items()]
return 'OAuth ' + ','.join([realm] + params) | def _get_auth_header(self) | Constructs and returns an authentication header. | 3.8901 | 3.445399 | 1.129071 |
'''
Removes a query string from a URL before signing.
:param url: The URL to strip.
:type url: str
'''
scheme, netloc, path, query, fragment = urlsplit(url)
return urlunsplit((scheme, netloc, path, '', fragment)) | def _remove_qs(self, url) | Removes a query string from a URL before signing.
:param url: The URL to strip.
:type url: str | 3.709028 | 2.280698 | 1.626269 |
'''
This process normalizes the request parameters as detailed in the OAuth
1.0 spec.
Additionally we apply a `Content-Type` header to the request of the
`FORM_URLENCODE` type if the `Content-Type` was previously set, i.e. if
this is a `POST` or `PUT` request. This ensur... | def _normalize_request_parameters(self, oauth_params, req_kwargs) | This process normalizes the request parameters as detailed in the OAuth
1.0 spec.
Additionally we apply a `Content-Type` header to the request of the
`FORM_URLENCODE` type if the `Content-Type` was previously set, i.e. if
this is a `POST` or `PUT` request. This ensures the correct heade... | 3.549323 | 2.049065 | 1.732167 |
'''Sign request parameters.
:param consumer_secret: Consumer secret.
:type consumer_secret: str
:param access_token_secret: Access token secret.
:type access_token_secret: str
:param method: The method of this particular request.
:type method: str
:param ... | def sign(self,
consumer_secret,
access_token_secret,
method,
url,
oauth_params,
req_kwargs) | Sign request parameters.
:param consumer_secret: Consumer secret.
:type consumer_secret: str
:param access_token_secret: Access token secret.
:type access_token_secret: str
:param method: The method of this particular request.
:type method: str
:param url: The UR... | 2.469459 | 2.068271 | 1.193972 |
'''Sign request parameters.
:param consumer_secret: RSA private key.
:type consumer_secret: str or RSA._RSAobj
:param access_token_secret: Unused.
:type access_token_secret: str
:param method: The method of this particular request.
:type method: str
:para... | def sign(self,
consumer_secret,
access_token_secret,
method,
url,
oauth_params,
req_kwargs) | Sign request parameters.
:param consumer_secret: RSA private key.
:type consumer_secret: str or RSA._RSAobj
:param access_token_secret: Unused.
:type access_token_secret: str
:param method: The method of this particular request.
:type method: str
:param url: The ... | 3.026238 | 2.321617 | 1.303504 |
'''Sign request using PLAINTEXT method.
:param consumer_secret: Consumer secret.
:type consumer_secret: str
:param access_token_secret: Access token secret (optional).
:type access_token_secret: str
:param method: Unused
:type method: str
:param url: Unus... | def sign(self, consumer_secret, access_token_secret, method, url,
oauth_params, req_kwargs) | Sign request using PLAINTEXT method.
:param consumer_secret: Consumer secret.
:type consumer_secret: str
:param access_token_secret: Access token secret (optional).
:type access_token_secret: str
:param method: Unused
:type method: str
:param url: Unused
... | 2.24709 | 1.725574 | 1.302227 |
'''
If provided a `token` parameter, tries to retrieve a stored
`rauth.OAuth1Session` instance. Otherwise generates a new session
instance with the :class:`rauth.OAuth1Service.consumer_key` and
:class:`rauth.OAuth1Service.consumer_secret` stored on the
`rauth.OAuth1Servic... | def get_session(self, token=None, signature=None) | If provided a `token` parameter, tries to retrieve a stored
`rauth.OAuth1Session` instance. Otherwise generates a new session
instance with the :class:`rauth.OAuth1Service.consumer_key` and
:class:`rauth.OAuth1Service.consumer_secret` stored on the
`rauth.OAuth1Service` instance.
... | 3.544944 | 1.708161 | 2.075299 |
'''
Returns a Requests' response over the
:attr:`rauth.OAuth1Service.request_token_url`.
Use this if your endpoint if you need the full `Response` object.
:param method: A string representation of the HTTP method to be used,
defaults to `GET`.
:type method: ... | def get_raw_request_token(self, method='GET', **kwargs) | Returns a Requests' response over the
:attr:`rauth.OAuth1Service.request_token_url`.
Use this if your endpoint if you need the full `Response` object.
:param method: A string representation of the HTTP method to be used,
defaults to `GET`.
:type method: str
:param \... | 4.616173 | 1.837699 | 2.511931 |
'''
Return a request token pair.
:param method: A string representation of the HTTP method to be used,
defaults to `GET`.
:type method: str
:param decoder: A function used to parse the Response content. Should
return a dictionary.
:type decoder: f... | def get_request_token(self,
method='GET',
decoder=parse_utf8_qsl,
key_token='oauth_token',
key_token_secret='oauth_token_secret',
**kwargs) | Return a request token pair.
:param method: A string representation of the HTTP method to be used,
defaults to `GET`.
:type method: str
:param decoder: A function used to parse the Response content. Should
return a dictionary.
:type decoder: func
:param k... | 2.871777 | 1.434468 | 2.00198 |
'''
Returns a formatted authorize URL.
:param request_token: The request token as returned by
:class:`get_request_token`.
:type request_token: str
:param \*\*params: Additional keyworded arguments to be added to the
request querystring.
:type \*\*... | def get_authorize_url(self, request_token, **params) | Returns a formatted authorize URL.
:param request_token: The request token as returned by
:class:`get_request_token`.
:type request_token: str
:param \*\*params: Additional keyworded arguments to be added to the
request querystring.
:type \*\*params: dict | 3.374844 | 1.711362 | 1.972023 |
'''
Returns a Requests' response over the
:attr:`rauth.OAuth1Service.access_token_url`.
Use this if your endpoint if you need the full `Response` object.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: s... | def get_raw_access_token(self,
request_token,
request_token_secret,
method='GET',
**kwargs) | Returns a Requests' response over the
:attr:`rauth.OAuth1Service.access_token_url`.
Use this if your endpoint if you need the full `Response` object.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: str
:param re... | 3.210386 | 1.590304 | 2.018725 |
'''
Returns an access token pair.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: str
:param request_token_secret: The request token secret as returned by
:meth:`get_request_token`.
:type requ... | def get_access_token(self,
request_token,
request_token_secret,
method='GET',
decoder=parse_utf8_qsl,
key_token='oauth_token',
key_token_secret='oauth_token_secret',
... | Returns an access token pair.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: str
:param request_token_secret: The request token secret as returned by
:meth:`get_request_token`.
:type request_token_secret: st... | 2.328166 | 1.344435 | 1.731707 |
'''
Gets an access token, intializes a new authenticated session with the
access token. Returns an instance of :attr:`session_obj`.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: str
:param request_token... | def get_auth_session(self,
request_token,
request_token_secret,
method='GET',
**kwargs) | Gets an access token, intializes a new authenticated session with the
access token. Returns an instance of :attr:`session_obj`.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: str
:param request_token_secret: The request... | 2.475256 | 1.402964 | 1.764305 |
'''
If provided, the `token` parameter is used to initialize an
authenticated session, otherwise an unauthenticated session object is
generated. Returns an instance of :attr:`session_obj`..
:param token: A token with which to initilize the session.
:type token: str
... | def get_session(self, token=None) | If provided, the `token` parameter is used to initialize an
authenticated session, otherwise an unauthenticated session object is
generated. Returns an instance of :attr:`session_obj`..
:param token: A token with which to initilize the session.
:type token: str | 3.706223 | 1.788521 | 2.072228 |
'''
Returns a formatted authorize URL.
:param \*\*params: Additional keyworded arguments to be added to the
URL querystring.
:type \*\*params: dict
'''
params.update({'client_id': self.client_id})
return self.authorize_url + '?' + urlencode(params) | def get_authorize_url(self, **params) | Returns a formatted authorize URL.
:param \*\*params: Additional keyworded arguments to be added to the
URL querystring.
:type \*\*params: dict | 4.150437 | 2.197922 | 1.888346 |
'''
Returns a Requests' response over the
:attr:`OAuth2Service.access_token_url`.
Use this if your endpoint if you need the full `Response` object.
:param method: A string representation of the HTTP method to be used,
defaults to `POST`.
:type method: str
... | def get_raw_access_token(self, method='POST', **kwargs) | Returns a Requests' response over the
:attr:`OAuth2Service.access_token_url`.
Use this if your endpoint if you need the full `Response` object.
:param method: A string representation of the HTTP method to be used,
defaults to `POST`.
:type method: str
:param \*\*kwa... | 3.989425 | 1.845562 | 2.161632 |
'''
Returns an access token.
:param method: A string representation of the HTTP method to be used,
defaults to `POST`.
:type method: str
:param decoder: A function used to parse the Response content. Should
return a dictionary.
:type decoder: func... | def get_access_token(self,
method='POST',
decoder=parse_utf8_qsl,
key='access_token',
**kwargs) | Returns an access token.
:param method: A string representation of the HTTP method to be used,
defaults to `POST`.
:type method: str
:param decoder: A function used to parse the Response content. Should
return a dictionary.
:type decoder: func
:param key:... | 4.037211 | 1.760128 | 2.293703 |
'''
Gets an access token, intializes a new authenticated session with the
access token. Returns an instance of :attr:`session_obj`.
:param method: A string representation of the HTTP method to be used,
defaults to `POST`.
:type method: str
:param \*\*kwargs: ... | def get_auth_session(self, method='POST', **kwargs) | Gets an access token, intializes a new authenticated session with the
access token. Returns an instance of :attr:`session_obj`.
:param method: A string representation of the HTTP method to be used,
defaults to `POST`.
:type method: str
:param \*\*kwargs: Optional arguments. ... | 4.605535 | 1.844827 | 2.496459 |
'''
The token parameter should be `oFlyUserid`. This is used to initialize
an authenticated session instance. Returns an instance of
:attr:`session_obj`.
:param token: A token with which to initialize the session with, e.g.
:attr:`OflyService.user_id`.
:type ... | def get_session(self, token) | The token parameter should be `oFlyUserid`. This is used to initialize
an authenticated session instance. Returns an instance of
:attr:`session_obj`.
:param token: A token with which to initialize the session with, e.g.
:attr:`OflyService.user_id`.
:type token: str | 9.216191 | 1.859965 | 4.955035 |
'''
Returns a formatted authorize URL.
:param \*\*params: Additional keyworded arguments to be added to the
request querystring.
:type \*\*params: dict
'''
params = self.session_obj.sign(self.authorize_url,
self.app_id,
... | def get_authorize_url(self, **params) | Returns a formatted authorize URL.
:param \*\*params: Additional keyworded arguments to be added to the
request querystring.
:type \*\*params: dict | 4.931492 | 2.809498 | 1.755293 |
self._channel.queue_declare(
queue=queue_name,
auto_delete=True,
durable=True,
)
self._channel.exchange_declare(
exchange=exchange_name,
exchange_type='topic',
auto_delete=True,
)
self._channel.queue... | def bind_topic_exchange(self, exchange_name, routing_key, queue_name) | 绑定主题交换机和队列
:param exchange_name: 需要绑定的交换机名
:param routing_key:
:param queue_name: 需要绑定的交换机队列名
:return: | 1.616771 | 1.705039 | 0.948231 |
result = self._channel.queue_declare(
queue=queue_name,
passive=passive,
durable=durable,
exclusive=exclusive,
auto_delete=auto_delete,
arguments=arguments
)
return result.method.queue | def declare_queue(self, queue_name='', passive=False, durable=False,
exclusive=False, auto_delete=False, arguments=None) | 声明一个队列
:param queue_name: 队列名
:param passive:
:param durable:
:param exclusive:
:param auto_delete:
:param arguments:
:return: pika 框架生成的随机回调队列名 | 1.699114 | 1.866514 | 0.910314 |
self.bind_topic_exchange(exchange_name, routing_key, queue_name)
self.basic_consuming(
queue_name=queue_name,
callback=callback
) | def declare_consuming(self, exchange_name, routing_key, queue_name, callback) | 声明一个主题交换机队列,并且将队列和交换机进行绑定,同时监听这个队列
:param exchange_name:
:param routing_key:
:param queue_name:
:param callback:
:return: | 3.354526 | 3.305346 | 1.014879 |
self._channel.exchange_declare(exchange=exchange_name,
exchange_type=type)
self._channel.queue_bind(queue=queue,
exchange=exchange_name,
routing_key=routing_key) | def exchange_bind_to_queue(self, type, exchange_name, routing_key, queue) | Declare exchange and bind queue to exchange
:param type: The type of exchange
:param exchange_name: The name of exchange
:param routing_key: The key of exchange bind to queue
:param queue: queue name | 1.930129 | 1.903876 | 1.013789 |
self.data[key]['isAccept'] = True # 设置为已经接受到服务端返回的消息
self.data[key]['result'] = str(result)
self._channel.queue_delete(self.data[key]['reply_queue_name']) | def accept(self, key, result) | 同步接受确认消息
:param key: correlation_id
:param result 服务端返回的消息 | 6.446749 | 5.289946 | 1.21868 |
logger.info("on response => {}".format(body))
corr_id = props.correlation_id # 从props得到服务端返回的客户端传入的corr_id值
self.accept(corr_id, body) | def on_response(self, ch, method, props, body) | All RPC response will call this method, so change the isAccept to True in this method
所有的RPC请求回调都会调用该方法,在该方法内修改对应corr_id已经接受消息的isAccept值和返回结果 | 9.763563 | 7.153625 | 1.364841 |
result = self.declare_queue(
queue_name=queue_name,passive=passive,
durable=durable,exclusive=exclusive,
auto_delete=auto_delete,arguments=arguments
)
self.declare_basic_consuming(
queue_name=queue_name,
callback=callback
... | def declare_default_consuming(self, queue_name, callback, passive=False,
durable=False,exclusive=False, auto_delete=False,
arguments=None) | 声明一个默认的交换机的队列,并且监听这个队列
:param queue_name:
:param callback:
:return: | 2.209286 | 2.39344 | 0.923059 |
self.bind_topic_exchange(exchange_name, routing_key, queue_name)
self.declare_basic_consuming(
queue_name=queue_name,
callback=callback
) | def declare_consuming(self, exchange_name, routing_key, queue_name, callback) | 声明一个主题交换机队列,并且将队列和交换机进行绑定,同时监听这个队列
:param exchange_name:
:param routing_key:
:param queue_name:
:param callback:
:return: | 3.469295 | 3.72574 | 0.93117 |
callback_queue = self.declare_queue(exclusive=True,
auto_delete=True) # 得到随机回调队列名
self._channel.basic_consume(self.on_response, # 客户端消费回调队列
no_ack=True,
queue=callback_queue)
... | def send_sync(self, body, exchange, key) | 发送并同步接受回复消息
:return: | 3.046007 | 3.017227 | 1.009538 |
username = user.get('username')
password = user.get('password')
the_username = os.environ.get(
'SIMPLELOGIN_USERNAME',
current_app.config.get('SIMPLELOGIN_USERNAME', 'admin')
)
the_password = os.environ.get(
'SIMPLELOGIN_PASSWORD',
current_app.config.get('SIMPLEL... | def default_login_checker(user) | user must be a dictionary here default is
checking username/password
if login is ok returns True else False
:param user: dict {'username':'', 'password': ''} | 2.180242 | 2.115706 | 1.030503 |
if username:
if not isinstance(username, (list, tuple)):
username = [username]
return 'simple_logged_in' in session and get_username() in username
return 'simple_logged_in' in session | def is_logged_in(username=None) | Checks if user is logged in if `username`
is passed check if specified user is logged in
username can be a list | 3.813661 | 4.143824 | 0.920324 |
if function and not callable(function):
raise ValueError(
'Decorator receives only named arguments, '
'try login_required(username="foo")'
)
def check(validators):
if validators is None:
return
if not isinstance(validators, (lis... | def login_required(function=None, username=None, basic=False, must=None) | Decorate views to require login
@login_required
@login_required()
@login_required(username='admin')
@login_required(username=['admin', 'jon'])
@login_required(basic=True)
@login_required(must=[function, another_function]) | 2.797428 | 2.792772 | 1.001667 |
msg = current_app.extensions['simplelogin'].messages.get(message)
if msg and (args or kwargs):
return msg.format(*args, **kwargs)
return msg | def get_message(message, *args, **kwargs) | Helper to get internal messages outside this instance | 4.761154 | 4.260412 | 1.117534 |
auth = request.authorization
if auth and self._login_checker({'username': auth.username,
'password': auth.password}):
session['simple_logged_in'] = True
session['simple_basic_auth'] = True
session['simple_username'] = ... | def basic_auth(self, response=None) | Support basic_auth via /login or login_required(basic=True) | 3.450826 | 3.224799 | 1.07009 |
user_data = my_users.get(user['username'])
if not user_data:
return False # <--- invalid credentials
elif user_data.get('password') == user['password']:
return True # <--- user is logged in!
return False | def check_my_users(user) | Check if user exists and its credentials.
Take a look at encrypt_app.py and encrypt_cli.py
to see how to encrypt passwords | 4.442823 | 4.399422 | 1.009865 |
if 'username' not in data or 'password' not in data:
raise ValueError('username and password are required.')
# Hash the user password
data['password'] = generate_password_hash(
data.pop('password'),
method='pbkdf2:sha256'
)
# Here you insert the `data` in your users da... | def create_user(**data) | Creates user with encrypted password | 3.734946 | 3.60616 | 1.035713 |
@wraps(f)
def decorator(*args, **kwargs):
app = create_app()
configure_extensions(app)
configure_views(app)
return f(app=app, *args, **kwargs)
return decorator | def with_app(f) | Calls function passing app as first argument | 2.624754 | 2.81672 | 0.931848 |
with app.app_context():
create_user(username=username, password=password)
click.echo('user created!') | def adduser(app, username, password) | Add new user with admin access | 4.199896 | 4.216334 | 0.996101 |
debug = debug or app.config.get('DEBUG', False)
reloader = reloader or app.config.get('RELOADER', False)
host = host or app.config.get('HOST', '127.0.0.1')
port = port or app.config.get('PORT', 5000)
app.run(
use_reloader=reloader,
debug=debug,
host=host,
port=po... | def runserver(app=None, reloader=None, debug=None, host=None, port=None) | Run the Flask development server i.e. app.run() | 1.483035 | 1.486651 | 0.997568 |
if self._i2c_expander == 'PCF8574':
self.bus.write_byte(self._address, ((value & ~PCF8574_E) | self._backlight))
c.usleep(1)
self.bus.write_byte(self._address, value | PCF8574_E | self._backlight)
c.usleep(1)
self.bus.write_byte(self._address,... | def _pulse_data(self, value) | Pulse the `enable` flag to process value. | 1.929672 | 1.895497 | 1.01803 |
# Wait, if compatibility mode is enabled
if self.compat_mode:
self._wait()
# Choose instruction or data mode
GPIO.output(self.pins.rs, mode)
# If the RW pin is used, set it to low in order to write.
if self.pins.rw is not None:
GPIO.outp... | def _send(self, value, mode) | Send the specified value to the display with automatic 4bit / 8bit
selection. The rs_mode is either ``RS_DATA`` or ``RS_INSTRUCTION``. | 5.787616 | 5.126752 | 1.128905 |
for i in range(4):
bit = (value >> i) & 0x01
GPIO.output(self.pins[i + 7], bit)
self._pulse_enable() | def _write4bits(self, value) | Write 4 bits of data into the data bus. | 3.992152 | 3.91735 | 1.019095 |
GPIO.output(self.pins.e, 0)
c.usleep(1)
GPIO.output(self.pins.e, 1)
c.usleep(1)
GPIO.output(self.pins.e, 0)
c.usleep(100) | def _pulse_enable(self) | Pulse the `enable` flag to process data. | 2.762142 | 2.76135 | 1.000287 |
encoded = self.codec.encode(value) # type: List[int]
ignored = False
for [char, lookahead] in c.sliding_window(encoded, lookahead=1):
# If the previous character has been ignored, skip this one too.
if ignored is True:
ignored = False
... | def write_string(self, value) | Write the specified unicode string to the display.
To control multiline behavior, use newline (``\\n``) and carriage
return (``\\r``) characters.
Lines that are too long automatically continue on next line, as long as
``auto_linebreaks`` has not been disabled.
Make sure that y... | 3.936735 | 4.105632 | 0.958862 |
self.command(c.LCD_CLEARDISPLAY)
self._cursor_pos = (0, 0)
self._content = [[0x20] * self.lcd.cols for _ in range(self.lcd.rows)]
c.msleep(2) | def clear(self) | Overwrite display with blank characters and reset cursor position. | 5.855906 | 5.520256 | 1.060803 |
self.command(c.LCD_RETURNHOME)
self._cursor_pos = (0, 0)
c.msleep(2) | def home(self) | Set cursor to initial position and reset any shifting. | 11.788068 | 8.210873 | 1.435666 |
if amount == 0:
return
direction = c.LCD_MOVERIGHT if amount > 0 else c.LCD_MOVELEFT
for i in range(abs(amount)):
self.command(c.LCD_CURSORSHIFT | c.LCD_DISPLAYMOVE | direction)
c.usleep(50) | def shift_display(self, amount) | Shift the display. Use negative amounts to shift left and positive
amounts to shift right. | 3.444001 | 3.266842 | 1.05423 |
assert 0 <= location <= 7, 'Only locations 0-7 are valid.'
assert len(bitmap) == 8, 'Bitmap should have exactly 8 rows.'
# Store previous position
pos = self.cursor_pos
# Write character to CGRAM
self.command(c.LCD_SETCGRAMADDR | location << 3)
for row ... | def create_char(self, location, bitmap) | Create a new character.
The HD44780 supports up to 8 custom characters (location 0-7).
:param location: The place in memory where the character is stored.
Values need to be integers between 0 and 7.
:type location: int
:param bitmap: The bitmap containing the character. Thi... | 5.001634 | 4.790182 | 1.044143 |
if self._content[row][col] != value:
self._send_data(value)
self._content[row][col] = value # Update content cache
unchanged = False
else:
unchanged = True
except IndexError as e:
# Position out of range
... | def write(self, value): # type: (int) -> None
# Get current position
row, col = self._cursor_pos
# Write byte if changed
try | Write a raw byte to the LCD. | 2.166433 | 2.08942 | 1.036859 |
warnings.warn('The `cursor` context manager is deprecated', DeprecationWarning)
lcd.cursor_pos = (row, col)
yield | def cursor(lcd, row, col) | Context manager to control cursor position. DEPRECATED. | 6.146165 | 4.156987 | 1.478514 |
it = itertools.chain(iter(seq), ' ' * lookahead) # Padded iterator
window_size = lookahead + 1
result = tuple(itertools.islice(it, window_size))
if len(result) == window_size:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result | def sliding_window(seq, lookahead) | Create a sliding window with the specified number of lookahead characters. | 2.810539 | 2.728564 | 1.030043 |
# Assemble the parameters sent to the pigpio script
params = [mode]
params.extend([(value >> i) & 0x01 for i in range(8)])
# Switch off pigpio's exceptions, so that we get the return codes
pigpio.exceptions = False
while True:
ret = self.pi.run_scrip... | def _send(self, value, mode) | Send the specified value to the display with automatic 4bit / 8bit
selection. The rs_mode is either ``RS_DATA`` or ``RS_INSTRUCTION``. | 5.408223 | 5.285299 | 1.023258 |
parser = argparse.ArgumentParser()
parser.add_argument("--connect-timeout",
type=float,
default=10.0,
help="ZK connect timeout")
parser.add_argument("--run-once",
type=str,
default=""... | def get_params() | get the cmdline params | 2.431401 | 2.380575 | 1.02135 |
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = Unbuffered(sys.s... | def set_unbuffered_mode() | make output unbuffered | 1.470603 | 1.381965 | 1.064139 |
try:
scheme, rest = acl.split(":", 1)
credential = ":".join(rest.split(":")[0:-1])
cdrwa = rest.split(":")[-1]
except ValueError:
raise cls.BadACL("Bad ACL: %s. Format is scheme:id:perms" % (acl))
if scheme not in cls.valid_schemes:
... | def extract_acl(cls, acl) | parse an individual ACL (i.e.: world:anyone:cdrwa) | 2.366831 | 2.197365 | 1.077122 |
return {
"perms": acl.perms,
"id": {
"scheme": acl.id.scheme,
"id": acl.id.id
}
} | def to_dict(cls, acl) | transform an ACL to a dict | 3.880218 | 3.368897 | 1.151777 |
perms = acl_dict.get("perms", Permissions.ALL)
id_dict = acl_dict.get("id", {})
id_scheme = id_dict.get("scheme", "world")
id_id = id_dict.get("id", "anyone")
return ACL(perms, Id(id_scheme, id_id)) | def from_dict(cls, acl_dict) | ACL from dict | 3.522723 | 3.298056 | 1.068121 |
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if not self.connected:
self.show_output("Not connected.")
else:
try:
return func(*args, **kwargs)
except APIError:
self.show_output("ZooKeeper internal error... | def connected(func) | check connected, fails otherwise | 2.368949 | 2.330699 | 1.016411 |
@wraps(func)
def wrapper(*args):
self = args[0]
params = args[1]
if not self.in_transaction:
for name in path_params:
value = getattr(params, name)
paths = value if type(value) == list else [value]
resolved = []
... | def check_path_exists_foreach(path_params, func) | check that paths exist (unless we are in a transaction) | 2.67218 | 2.356742 | 1.133845 |
@wraps(func)
def wrapper(*args):
self = args[0]
params = args[1]
orig_path = params.path
sequence = getattr(params, 'sequence', False)
params.path = self.resolve_path(params.path)
if self.in_transaction or sequence or not self.client.exists(params.path):
... | def check_path_absent(func) | check path doesn't exist (unless we are in a txn or it's sequential)
note: when creating sequential znodes, a trailing slash means no prefix, i.e.:
create(/some/path/, sequence=True) -> /some/path/0000001
for all other cases, it's dropped. | 3.666348 | 3.314633 | 1.10611 |
if full_cmd.endswith(" "):
cmd_param, path = " ", " "
else:
pieces = shlex.split(full_cmd)
if len(pieces) > 1:
cmd_param = pieces[-1]
else:
cmd_param = cmd_param_text
path = cmd_param.rstrip("/") if cmd_... | def _complete_path(self, cmd_param_text, full_cmd, *_) | completes paths | 2.980738 | 2.912539 | 1.023415 |
self._zk.add_auth(params.scheme, params.credential) | def do_add_auth(self, params) | \x1b[1mNAME\x1b[0m
add_auth - Authenticates the session
\x1b[1mSYNOPSIS\x1b[0m
add_auth <scheme> <credential>
\x1b[1mEXAMPLES\x1b[0m
> add_auth digest super:s3cr3t | 11.091653 | 11.168815 | 0.993091 |
try:
acls = ACLReader.extract(shlex.split(params.acls))
except ACLReader.BadACL as ex:
self.show_output("Failed to set ACLs: %s.", ex)
return
def set_acls(path):
try:
self._zk.set_acls(path, acls)
except (NoNod... | def do_set_acls(self, params) | \x1b[1mNAME\x1b[0m
set_acls - Sets ACLs for a given path
\x1b[1mSYNOPSIS\x1b[0m
set_acls <path> <acls> [recursive]
\x1b[1mOPTIONS\x1b[0m
* recursive: recursively set the acls on the children
\x1b[1mEXAMPLES\x1b[0m
> set_acls /some/path 'world:anyone:r digest:user:aRxISyaKnTP2+OZ9OmQLk... | 3.386688 | 3.641564 | 0.930009 |
possible_acl = [
"digest:",
"username_password:",
"world:anyone:c",
"world:anyone:cd",
"world:anyone:cdr",
"world:anyone:cdrw",
"world:anyone:cdrwa",
]
complete_acl = partial(complete_values, possible_ac... | def complete_set_acls(self, cmd_param_text, full_cmd, *rest) | FIXME: complete inside a quoted param is broken | 5.032146 | 4.670736 | 1.077378 |
def replace(plist, oldv, newv):
try:
plist.remove(oldv)
plist.insert(0, newv)
except ValueError:
pass
for path, acls in self._zk.get_acls_recursive(params.path, params.depth, params.ephemerals):
replace(acls, R... | def do_get_acls(self, params) | \x1b[1mNAME\x1b[0m
get_acls - Gets ACLs for a given path
\x1b[1mSYNOPSIS\x1b[0m
get_acls <path> [depth] [ephemerals]
\x1b[1mOPTIONS\x1b[0m
* depth: -1 is no recursion, 0 is infinite recursion, N > 0 is up to N levels (default: 0)
* ephemerals: include ephemerals (default: false)
\x1b[... | 4.774691 | 3.92399 | 1.216795 |
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
znodes = self._zk.get_children(params.path, **kwargs)
self.show_output(params.sep.join(sorted(znodes))) | def do_ls(self, params) | \x1b[1mNAME\x1b[0m
ls - Lists the znodes for the given <path>
\x1b[1mSYNOPSIS\x1b[0m
ls <path> [watch] [sep]
\x1b[1mOPTIONS\x1b[0m
* watch: set a (child) watch on the path (default: false)
* sep: separator to be used (default: '\\n')
\x1b[1mEXAMPLES\x1b[0m
> ls /
confi... | 6.053167 | 4.692601 | 1.289939 |
wm = get_watch_manager(self._zk)
if params.command == "start":
debug = to_bool(params.debug)
children = to_int(params.sleep, -1)
wm.add(params.path, debug, children)
elif params.command == "stop":
wm.remove(params.path)
elif params... | def do_watch(self, params) | \x1b[1mNAME\x1b[0m
watch - Recursively watch for all changes under a path.
\x1b[1mSYNOPSIS\x1b[0m
watch <start|stop|stats> <path> [options]
\x1b[1mDESCRIPTION\x1b[0m
watch start <path> [debug] [depth]
with debug=true, print watches as they fire. depth is
the level for recursiv... | 3.139927 | 2.87053 | 1.093849 |
try:
self.copy(params, params.recursive, params.overwrite, params.max_items, False)
except AuthFailedError:
self.show_output("Authentication failed.") | def do_cp(self, params) | \x1b[1mNAME\x1b[0m
cp - Copy from/to local/remote or remote/remote paths
\x1b[1mSYNOPSIS\x1b[0m
cp <src> <dst> [recursive] [overwrite] [asynchronous] [verbose] [max_items]
\x1b[1mDESCRIPTION\x1b[0m
src and dst can be:
/some/path (in the connected server)
zk://[scheme:use... | 11.310551 | 8.997893 | 1.257022 |
question = "Are you sure you want to replace %s with %s?" % (params.dst, params.src)
if params.skip_prompt or self.prompt_yes_no(question):
self.copy(params, True, True, 0, True) | def do_mirror(self, params) | \x1b[1mNAME\x1b[0m
mirror - Mirrors from/to local/remote or remote/remote paths
\x1b[1mSYNOPSIS\x1b[0m
mirror <src> <dst> [async] [verbose] [skip_prompt]
\x1b[1mDESCRIPTION\x1b[0m
src and dst can be:
/some/path (in the connected server)
zk://[user:passwd@]host/<path>
... | 5.237584 | 5.125145 | 1.021939 |
self.show_output(".")
for child, level in self._zk.tree(params.path, params.max_depth):
self.show_output(u"%s├── %s", u"│ " * level, child) | def do_tree(self, params) | \x1b[1mNAME\x1b[0m
tree - Print the tree under a given path
\x1b[1mSYNOPSIS\x1b[0m
tree [path] [max_depth]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* max_depth: max recursion limit (0 is no limit) (default: 0)
\x1b[1mEXAMPLES\x1b[0m
> tree
.
├── zo... | 8.255768 | 9.987736 | 0.826591 |
for child, level in self._zk.tree(params.path, params.depth, full_path=True):
self.show_output("%s: %d", child, self._zk.child_count(child)) | def do_child_count(self, params) | \x1b[1mNAME\x1b[0m
child_count - Prints the child count for paths
\x1b[1mSYNOPSIS\x1b[0m
child_count [path] [depth]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* max_depth: max recursion limit (0 is no limit) (default: 1)
\x1b[1mEXAMPLES\x1b[0m
> child-count /
... | 8.301545 | 8.07756 | 1.027729 |
self.show_output(pretty_bytes(self._zk.du(params.path))) | def do_du(self, params) | \x1b[1mNAME\x1b[0m
du - Total number of bytes under a path
\x1b[1mSYNOPSIS\x1b[0m
du [path]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
\x1b[1mEXAMPLES\x1b[0m
> du /
90 | 21.25708 | 31.2407 | 0.680429 |
for path in self._zk.find(params.path, params.match, 0):
self.show_output(path) | def do_find(self, params) | \x1b[1mNAME\x1b[0m
find - Find znodes whose path matches a given text
\x1b[1mSYNOPSIS\x1b[0m
find [path] [match]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* match: the string to match in the paths (default: '')
\x1b[1mEXAMPLES\x1b[0m
> find / foo
/foo2
... | 10.583858 | 12.491617 | 0.847277 |
seen = set()
# we don't want to recurse once there's a child matching, hence exclude_recurse=
for path in self._zk.fast_tree(params.path, exclude_recurse=params.pattern):
parent, child = split(path)
if parent in seen:
continue
match... | def do_child_matches(self, params) | \x1b[1mNAME\x1b[0m
child_matches - Prints paths that have at least 1 child that matches <pattern>
\x1b[1mSYNOPSIS\x1b[0m
child_matches <path> <pattern> [inverse]
\x1b[1mOPTIONS\x1b[0m
* inverse: display paths which don't match (default: false)
\x1b[1mEXAMPLES\x1b[0m
> child_matches /s... | 5.882597 | 5.296146 | 1.110732 |
self.show_output("%s%s%s%s",
"Created".ljust(32),
"Last modified".ljust(32),
"Owner".ljust(23),
"Name")
results = sorted(self._zk.stat_map(params.path))
# what slice do we want?
... | def do_summary(self, params) | \x1b[1mNAME\x1b[0m
summary - Prints summarized details of a path's children
\x1b[1mSYNOPSIS\x1b[0m
summary [path] [top]
\x1b[1mDESCRIPTION\x1b[0m
The results are sorted by name.
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* top: number of results to be displayed (0 i... | 3.121185 | 2.689975 | 1.160303 |
for path in self._zk.find(params.path, params.match, re.IGNORECASE):
self.show_output(path) | def do_ifind(self, params) | \x1b[1mNAME\x1b[0m
ifind - Find znodes whose path (insensitively) matches a given text
\x1b[1mSYNOPSIS\x1b[0m
ifind [path] [match]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* match: the string to match in the paths (default: '')
\x1b[1mEXAMPLES\x1b[0m
> ifind / fOO... | 10.449045 | 10.657477 | 0.980443 |
self.grep(params.path, params.content, 0, params.show_matches) | def do_grep(self, params) | \x1b[1mNAME\x1b[0m
grep - Prints znodes with a value matching the given text
\x1b[1mSYNOPSIS\x1b[0m
grep [path] <content> [show_matches]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* show_matches: show the content that matched (default: false)
\x1b[1mEXAMPLES\x1b[0m
... | 11.284811 | 6.970368 | 1.618969 |
self.grep(params.path, params.content, re.IGNORECASE, params.show_matches) | def do_igrep(self, params) | \x1b[1mNAME\x1b[0m
igrep - Prints znodes with a value matching the given text (ignoring case)
\x1b[1mSYNOPSIS\x1b[0m
igrep [path] <content> [show_matches]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* show_matches: show the content that matched (default: false)
\x1b[1mEXAMPL... | 9.7123 | 5.599004 | 1.734648 |
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
value, _ = self._zk.get(params.path, **kwargs)
# maybe it's compressed?
if value is not None:
try:
value = zlib.decompress(value)
... | def do_get(self, params) | \x1b[1mNAME\x1b[0m
get - Gets the znode's value
\x1b[1mSYNOPSIS\x1b[0m
get <path> [watch]
\x1b[1mOPTIONS\x1b[0m
* watch: set a (data) watch on the path (default: false)
\x1b[1mEXAMPLES\x1b[0m
> get /foo
bar
# sets a watch
> get /foo true
bar
#... | 5.06896 | 4.821737 | 1.051272 |
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
pretty = params.pretty_date
path = self.resolve_path(params.path)
stat = self._zk.exists(path, **kwargs)
if stat:
session = stat.ephemeralOwner if sta... | def do_exists(self, params) | \x1b[1mNAME\x1b[0m
exists - Gets the znode's stat information
\x1b[1mSYNOPSIS\x1b[0m
exists <path> [watch] [pretty_date]
\x1b[1mOPTIONS\x1b[0m
* watch: set a (data) watch on the path (default: false)
\x1b[1mEXAMPLES\x1b[0m
exists /foo
Stat(
czxid=101,
mzxid... | 2.138582 | 1.846613 | 1.158111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.