sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def local_ip():
"""Get the local network IP of this machine"""
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith('127.'):
# Check eth0, eth1, eth2, en0, ...
interfaces = [
i + str(n) for i in ("eth", "en", "wlan") for n in xrange(3)
] # :(
for inte... | Get the local network IP of this machine | entailment |
def client_for(service, service_module, thrift_service_name=None):
"""Build a client class for the given Thrift service.
The generated class accepts a TChannel and an optional hostport as
initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registered with
Hyperbahn... | Build a client class for the given Thrift service.
The generated class accepts a TChannel and an optional hostport as
initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registered with
Hyperbahn under the name "comment", here's how this may be used:
.. code-block... | entailment |
def generate_method(service_module, service_name, method_name):
"""Generate a method for the given Thrift service.
:param service_module:
Thrift-generated service module
:param service_name:
Name of the Thrift service
:param method_name:
Method being called
"""
assert se... | Generate a method for the given Thrift service.
:param service_module:
Thrift-generated service module
:param service_name:
Name of the Thrift service
:param method_name:
Method being called | entailment |
def connect(self):
"""Get a connection to this peer.
If an connection to the peer already exists (either incoming or
outgoing), that's returned. Otherwise, a new outgoing connection to
this peer is created.
:return:
A future containing a connection to this host.
... | Get a connection to this peer.
If an connection to the peer already exists (either incoming or
outgoing), that's returned. Otherwise, a new outgoing connection to
this peer is created.
:return:
A future containing a connection to this host. | entailment |
def register_outgoing_conn(self, conn):
"""Add outgoing connection into the heap."""
assert conn, "conn is required"
conn.set_outbound_pending_change_callback(self._on_conn_change)
self.connections.append(conn)
self._set_on_close_cb(conn)
self._on_conn_change() | Add outgoing connection into the heap. | entailment |
def register_incoming_conn(self, conn):
"""Add incoming connection into the heap."""
assert conn, "conn is required"
conn.set_outbound_pending_change_callback(self._on_conn_change)
self.connections.appendleft(conn)
self._set_on_close_cb(conn)
self._on_conn_change() | Add incoming connection into the heap. | entailment |
def outgoing_connections(self):
"""Returns a list of all outgoing connections for this peer."""
# Outgoing connections are on the right
return list(
dropwhile(lambda c: c.direction != OUTGOING, self.connections)
) | Returns a list of all outgoing connections for this peer. | entailment |
def incoming_connections(self):
"""Returns a list of all incoming connections for this peer."""
# Incoming connections are on the left.
return list(
takewhile(lambda c: c.direction == INCOMING, self.connections)
) | Returns a list of all incoming connections for this peer. | entailment |
def _get_peer_connection(self, blacklist=None):
"""Find a peer and connect to it.
Returns a ``(peer, connection)`` tuple.
Raises ``NoAvailablePeerError`` if no healthy peers are found.
:param blacklist:
If given, a set of hostports for peers that we must not try.
"... | Find a peer and connect to it.
Returns a ``(peer, connection)`` tuple.
Raises ``NoAvailablePeerError`` if no healthy peers are found.
:param blacklist:
If given, a set of hostports for peers that we must not try. | entailment |
def send(
self, arg1, arg2, arg3,
headers=None,
retry_limit=None,
ttl=None,
):
"""Make a request to the Peer.
:param arg1:
String or Stream containing the contents of arg1. If None, an empty
stream is used.
:param arg2:
Str... | Make a request to the Peer.
:param arg1:
String or Stream containing the contents of arg1. If None, an empty
stream is used.
:param arg2:
String or Stream containing the contents of arg2. If None, an empty
stream is used.
:param arg3:
... | entailment |
def clear(self):
"""Reset this PeerGroup.
This closes all connections to all known peers and forgets about
these peers.
:returns:
A Future that resolves with a value of None when the operation
has finished
"""
try:
for peer in self._p... | Reset this PeerGroup.
This closes all connections to all known peers and forgets about
these peers.
:returns:
A Future that resolves with a value of None when the operation
has finished | entailment |
def remove(self, hostport):
"""Delete the Peer for the given host port.
Does nothing if a matching Peer does not exist.
:returns: The removed Peer
"""
assert hostport, "hostport is required"
peer = self._peers.pop(hostport, None)
peer_in_heap = peer and peer.ind... | Delete the Peer for the given host port.
Does nothing if a matching Peer does not exist.
:returns: The removed Peer | entailment |
def get(self, hostport):
"""Get a Peer for the given destination.
A new Peer is added to the peer heap and returned if one does
not already exist for the given host-port. Otherwise, the
existing Peer is returned.
"""
assert hostport, "hostport is required"
assert... | Get a Peer for the given destination.
A new Peer is added to the peer heap and returned if one does
not already exist for the given host-port. Otherwise, the
existing Peer is returned. | entailment |
def _add(self, hostport):
"""Creates a peer from the hostport and adds it to the peer heap"""
peer = self.peer_class(
tchannel=self.tchannel,
hostport=hostport,
on_conn_change=self._update_heap,
)
peer.rank = self.rank_calculator.get_rank(peer)
... | Creates a peer from the hostport and adds it to the peer heap | entailment |
def _update_heap(self, peer):
"""Recalculate the peer's rank and update itself in the peer heap."""
rank = self.rank_calculator.get_rank(peer)
if rank == peer.rank:
return
peer.rank = rank
self.peer_heap.update_peer(peer) | Recalculate the peer's rank and update itself in the peer heap. | entailment |
def _get_isolated(self, hostport):
"""Get a Peer for the given destination for a request.
A new Peer is added and returned if one does not already exist for the
given host-port. Otherwise, the existing Peer is returned.
**NOTE** new peers will not be added to the peer heap.
"""... | Get a Peer for the given destination for a request.
A new Peer is added and returned if one does not already exist for the
given host-port. Otherwise, the existing Peer is returned.
**NOTE** new peers will not be added to the peer heap. | entailment |
def request(self, service, hostport=None, **kwargs):
"""Initiate a new request through this PeerGroup.
:param hostport:
If specified, requests will be sent to the specific host.
Otherwise, a known peer will be picked at random.
:param service:
Name of the ser... | Initiate a new request through this PeerGroup.
:param hostport:
If specified, requests will be sent to the specific host.
Otherwise, a known peer will be picked at random.
:param service:
Name of the service being called. Defaults to an empty string. | entailment |
def choose(self, hostport=None, blacklist=None):
"""Choose a Peer that matches the given criteria.
:param hostport:
Specifies that the returned Peer must be for the given host-port.
Without this, all peers managed by this PeerGroup are
candidates.
:param blac... | Choose a Peer that matches the given criteria.
:param hostport:
Specifies that the returned Peer must be for the given host-port.
Without this, all peers managed by this PeerGroup are
candidates.
:param blacklist:
Peers on the blacklist won't be chosen.
... | entailment |
def fail_to(future):
"""A decorator for function callbacks to catch uncaught non-async
exceptions and forward them to the given future.
The primary use for this is to catch exceptions in async callbacks and
propagate them to futures. For example, consider,
.. code-block:: python
answer = ... | A decorator for function callbacks to catch uncaught non-async
exceptions and forward them to the given future.
The primary use for this is to catch exceptions in async callbacks and
propagate them to futures. For example, consider,
.. code-block:: python
answer = Future()
def on_don... | entailment |
def get_arg(context, index):
"""get value from arg stream in async way"""
if index < len(context.argstreams):
arg = ""
chunk = yield context.argstreams[index].read()
while chunk:
arg += chunk
chunk = yield context.argstreams[index].read()
raise tornado.ge... | get value from arg stream in async way | entailment |
def put(self, value):
"""Puts an item into the queue.
Returns a Future that resolves to None once the value has been
accepted by the queue.
"""
io_loop = IOLoop.current()
new_hole = Future()
new_put = Future()
new_put.set_result(new_hole)
with s... | Puts an item into the queue.
Returns a Future that resolves to None once the value has been
accepted by the queue. | entailment |
def get_nowait(self):
"""Returns a value from the queue without waiting.
Raises ``QueueEmpty`` if no values are available right now.
"""
new_get = Future()
with self._lock:
if not self._get.done():
raise QueueEmpty
get, self._get = self._... | Returns a value from the queue without waiting.
Raises ``QueueEmpty`` if no values are available right now. | entailment |
def get(self):
"""Gets the next item from the queue.
Returns a Future that resolves to the next item once it is available.
"""
io_loop = IOLoop.current()
new_get = Future()
with self._lock:
get, self._get = self._get, new_get
answer = Future()
... | Gets the next item from the queue.
Returns a Future that resolves to the next item once it is available. | entailment |
def fragment(self, space_left, fragment_msg):
"""Streaming Message got fragmented based on
payload size. All the data within space_left
will be kept. All the rest will be shifted to
next fragment message.
:param space_left:
space left for current frame
:param... | Streaming Message got fragmented based on
payload size. All the data within space_left
will be kept. All the rest will be shifted to
next fragment message.
:param space_left:
space left for current frame
:param fragment_msg:
the type is either CallRequest... | entailment |
def response_from_mixed(mixed):
"""Create Response from mixed input."""
# if none then give empty Response
if mixed is None:
return Response()
# if not Response, then treat like body
if not isinstance(mixed, Response):
return Response(mixed)
# it's already a Response
retur... | Create Response from mixed input. | entailment |
def register_hook(self, hook, event_type=None):
"""
If ``event_type`` is provided, then ``hook`` will be called whenever
that event is fired.
If no ``event_type`` is specifid, but ``hook`` implements any methods
with names matching an event hook, then those will be registered wi... | If ``event_type`` is provided, then ``hook`` will be called whenever
that event is fired.
If no ``event_type`` is specifid, but ``hook`` implements any methods
with names matching an event hook, then those will be registered with
their corresponding events. This allows for more stateful... | entailment |
def init(h):
"""Initialize existing object into the heap."""
# heapify
n = h.size()
for i in six.moves.range(int(math.floor(n/2)) - 1, -1, -1):
down(h, i, n) | Initialize existing object into the heap. | entailment |
def push(h, x):
"""Push a new value into heap."""
h.push(x)
up(h, h.size()-1) | Push a new value into heap. | entailment |
def pop(h):
"""Pop the heap value from the heap."""
n = h.size() - 1
h.swap(0, n)
down(h, 0, n)
return h.pop() | Pop the heap value from the heap. | entailment |
def remove(h, i):
"""Remove the item at position i of the heap."""
n = h.size() - 1
if n != i:
h.swap(i, n)
down(h, i, n)
up(h, i)
return h.pop() | Remove the item at position i of the heap. | entailment |
def fix(h, i):
"""Rearrange the heap after the item at position i got updated."""
down(h, i, h.size())
up(h, i) | Rearrange the heap after the item at position i got updated. | entailment |
def smallest(heap, predicate):
"""Finds the index of the smallest item in the heap that matches the given
predicate.
:param heap:
Heap on which this search is being performed.
:param predicate:
Function that accepts an item from the heap and returns true or false.
:returns:
... | Finds the index of the smallest item in the heap that matches the given
predicate.
:param heap:
Heap on which this search is being performed.
:param predicate:
Function that accepts an item from the heap and returns true or false.
:returns:
Index of the first item for which ``pr... | entailment |
def span_to_tracing_field(span):
"""
Inject the span into Trace field, if Zipkin format is supported
:param span: OpenTracing Span
"""
if span is None:
return common.random_tracing()
# noinspection PyBroadException
try:
carrier = {}
span.tracer.inject(span, ZIPKIN_SPA... | Inject the span into Trace field, if Zipkin format is supported
:param span: OpenTracing Span | entailment |
def apply_trace_flag(span, trace, default_trace):
"""
If ``trace`` (or ``default_trace``) is False, disables tracing on ``span``.
:param span:
:param trace:
:param default_trace:
:return:
"""
if trace is None:
trace = default_trace
trace = trace() if callable(trace) else trac... | If ``trace`` (or ``default_trace``) is False, disables tracing on ``span``.
:param span:
:param trace:
:param default_trace:
:return: | entailment |
def start_basic_span(self, request):
"""
Start tracing span from the protocol's `tracing` fields.
This will only work if the `tracer` supports Zipkin-style span context.
:param request: inbound request
:type request: tchannel.tornado.request.Request
"""
# noinspe... | Start tracing span from the protocol's `tracing` fields.
This will only work if the `tracer` supports Zipkin-style span context.
:param request: inbound request
:type request: tchannel.tornado.request.Request | entailment |
def start_span(self, request, headers, peer_host, peer_port):
"""
Start a new server-side span. If the span has already been started
by `start_basic_span`, this method only adds baggage from the headers.
:param request: inbound tchannel.tornado.request.Request
:param headers: di... | Start a new server-side span. If the span has already been started
by `start_basic_span`, this method only adds baggage from the headers.
:param request: inbound tchannel.tornado.request.Request
:param headers: dictionary containing parsed application headers
:return: | entailment |
def from_code(cls, code, **kw):
"""Construct a ``TChannelError`` instance from an error code.
This will return the appropriate class type for the given code.
"""
return {
TIMEOUT: TimeoutError,
CANCELED: CanceledError,
BUSY: BusyError,
DEC... | Construct a ``TChannelError`` instance from an error code.
This will return the appropriate class type for the given code. | entailment |
def serve():
"""main entry point"""
logging.getLogger().setLevel(logging.DEBUG)
logging.info('Python Tornado Crossdock Server Starting ...')
tracer = Tracer(
service_name='python',
reporter=NullReporter(),
sampler=ConstSampler(decision=True))
opentracing.tracer = tracer
... | main entry point | entailment |
def register(dispatcher, service_module, handler, method=None, service=None):
"""Registers a Thrift service method with the given RequestDispatcher.
.. code-block:: python
# For,
#
# service HelloWorld { string hello(1: string name); }
import tchannel.thrift
import H... | Registers a Thrift service method with the given RequestDispatcher.
.. code-block:: python
# For,
#
# service HelloWorld { string hello(1: string name); }
import tchannel.thrift
import HelloWorld
def hello(request, response):
name = request.args.name... | entailment |
def write_result(self, result):
"""Send back the result of this call.
Only one of this and `write_exc_info` may be called.
:param result:
Return value of the call
"""
assert not self.finished, "Already sent a response"
if not self.result.thrift_spec:
... | Send back the result of this call.
Only one of this and `write_exc_info` may be called.
:param result:
Return value of the call | entailment |
def write_exc_info(self, exc_info=None):
"""Write exception information to the response.
Only one of this and ``write_result`` may be called.
:param exc_info:
3-tuple of exception information. If omitted, the last exception
will be retrieved using ``sys.exc_info()``.
... | Write exception information to the response.
Only one of this and ``write_result`` may be called.
:param exc_info:
3-tuple of exception information. If omitted, the last exception
will be retrieved using ``sys.exc_info()``. | entailment |
def call(
self,
scheme,
service,
arg1,
arg2=None,
arg3=None,
timeout=None,
retry_on=None,
retry_limit=None,
routing_delegate=None,
hostport=None,
shard_key=None,
tracing_span=None,
trace=None, # to trace or ... | Make low-level requests to TChannel services.
**Note:** Usually you would interact with a higher-level arg scheme
like :py:class:`tchannel.schemes.JsonArgScheme` or
:py:class:`tchannel.schemes.ThriftArgScheme`. | entailment |
def advertise(self, routers=None, name=None, timeout=None,
router_file=None, jitter=None):
"""Advertise with Hyperbahn.
After a successful advertisement, Hyperbahn will establish long-lived
connections with your application. These connections are used to load
balance i... | Advertise with Hyperbahn.
After a successful advertisement, Hyperbahn will establish long-lived
connections with your application. These connections are used to load
balance inbound and outbound requests to other applications on the
Hyperbahn network.
Re-advertisement happens p... | entailment |
def thrift_request_builder(service, thrift_module, hostport=None,
thrift_class_name=None):
"""Provide TChannel compatibility with Thrift-generated modules.
The service this creates is meant to be used with TChannel like so:
.. code-block:: python
from tchannel import TC... | Provide TChannel compatibility with Thrift-generated modules.
The service this creates is meant to be used with TChannel like so:
.. code-block:: python
from tchannel import TChannel, thrift_request_builder
from some_other_service_thrift import some_other_service
tchannel = TChannel(... | entailment |
def read_body(self, body):
"""Handles the response body for this request.
If the response body includes a result, returns the result unwrapped
from the response union. If the response contains an exception, raises
that exception.
"""
result_spec = self.result_type.thrift... | Handles the response body for this request.
If the response body includes a result, returns the result unwrapped
from the response union. If the response contains an exception, raises
that exception. | entailment |
def get_rank(self, peer):
"""Calculate the peer rank based on connections.
If the peer has no incoming connections, it will have largest rank.
In our peer selection strategy, the largest number has least priority
in the heap.
If the peer has incoming connections, we will return... | Calculate the peer rank based on connections.
If the peer has no incoming connections, it will have largest rank.
In our peer selection strategy, the largest number has least priority
in the heap.
If the peer has incoming connections, we will return number of outbound
pending r... | entailment |
def prepare(cls, *args, **kwargs):
"""Set arguments to be used when instantiating a TChannel instance.
Arguments are the same as :py:meth:`tchannel.TChannel.__init__`.
"""
cls.args = args
cls.kwargs = kwargs
cls.prepared = True | Set arguments to be used when instantiating a TChannel instance.
Arguments are the same as :py:meth:`tchannel.TChannel.__init__`. | entailment |
def reset(cls, *args, **kwargs):
"""Undo call to prepare, useful for testing."""
cls.local.tchannel = None
cls.args = None
cls.kwargs = None
cls.prepared = False | Undo call to prepare, useful for testing. | entailment |
def get_instance(cls):
"""Get a configured, thread-safe, singleton TChannel instance.
:returns tchannel.TChannel:
"""
if not cls.prepared:
raise SingletonNotPreparedError(
"prepare must be called before get_instance"
)
if hasattr(cls.loca... | Get a configured, thread-safe, singleton TChannel instance.
:returns tchannel.TChannel: | entailment |
def handle_pre_call(self, message, connection):
"""Handle incoming request message including CallRequestMessage and
CallRequestContinueMessage
This method will build the User friendly request object based on the
incoming messages.
It passes all the messages into the message_fac... | Handle incoming request message including CallRequestMessage and
CallRequestContinueMessage
This method will build the User friendly request object based on the
incoming messages.
It passes all the messages into the message_factory to build the init
request object. Only when it... | entailment |
def register(
self,
rule,
handler,
req_serializer=None,
resp_serializer=None
):
"""Register a new endpoint with the given name.
.. code-block:: python
@dispatcher.register('is_healthy')
def check_health(request, re... | Register a new endpoint with the given name.
.. code-block:: python
@dispatcher.register('is_healthy')
def check_health(request, response):
# ...
:param rule:
Name of the endpoint. Incoming Call Requests must have this as
``arg1`` to dis... | entailment |
def random_tracing():
"""
Create new Tracing() tuple with random IDs.
"""
new_id = _uniq_id()
return Tracing(
span_id=new_id,
parent_id=0,
trace_id=new_id,
traceflags=0) | Create new Tracing() tuple with random IDs. | entailment |
def generate_checksum(message, previous_csum=0):
"""Generate checksum for messages with
CALL_REQ, CALL_REQ_CONTINUE,
CALL_RES,CALL_RES_CONTINUE types.
:param message: outgoing message
:param previous_csum: accumulated checksum value
"""
if message.message_type in CHECKSUM_MSG_TYPES:... | Generate checksum for messages with
CALL_REQ, CALL_REQ_CONTINUE,
CALL_RES,CALL_RES_CONTINUE types.
:param message: outgoing message
:param previous_csum: accumulated checksum value | entailment |
def verify_checksum(message, previous_csum=0):
"""Verify checksum for incoming message.
:param message: incoming message
:param previous_csum: accumulated checksum value
:return return True if message checksum type is None
or checksum is correct
"""
if message.message_type in CHECKSUM_MSG_... | Verify checksum for incoming message.
:param message: incoming message
:param previous_csum: accumulated checksum value
:return return True if message checksum type is None
or checksum is correct | entailment |
def advertise(tchannel, service, routers=None, timeout=None, router_file=None,
jitter=None):
"""Advertise with Hyperbahn.
See :py:class:`tchannel.TChannel.advertise`.
"""
timeout = timeout or FIRST_ADVERTISE_TIME
if routers is not None and router_file is not None:
raise ValueE... | Advertise with Hyperbahn.
See :py:class:`tchannel.TChannel.advertise`. | entailment |
def start(self):
"""Starts the advertise loop.
Returns the result of the first ad request.
"""
if self.running:
raise Exception('Advertiser is already running')
if self.io_loop is None:
self.io_loop = tornado.ioloop.IOLoop.current()
self.running ... | Starts the advertise loop.
Returns the result of the first ad request. | entailment |
def _schedule_ad(self, delay=None, response_future=None):
"""Schedules an ``ad`` request.
:param delay:
Time in seconds to wait before making the ``ad`` request. Defaults
to self.interval_secs. Regardless of value, a jitter of
self.interval_max_jitter_secs is applied... | Schedules an ``ad`` request.
:param delay:
Time in seconds to wait before making the ``ad`` request. Defaults
to self.interval_secs. Regardless of value, a jitter of
self.interval_max_jitter_secs is applied to this.
:param response_future:
If non-None, th... | entailment |
def add(self, id, ttl_secs):
"""Adds a new request to the Cemetery that is known to have timed out.
The request will be forgotten after ``ttl_secs + ttl_offset_secs``
seconds.
:param id:
ID of the request
:param ttl_secs:
TTL of the request (in seconds)
... | Adds a new request to the Cemetery that is known to have timed out.
The request will be forgotten after ``ttl_secs + ttl_offset_secs``
seconds.
:param id:
ID of the request
:param ttl_secs:
TTL of the request (in seconds) | entailment |
def clear(self):
"""Forget about all requests."""
io_loop = IOLoop.current()
while self._tombstones:
_, req_timeout = self._tombstones.popitem()
io_loop.remove_timeout(req_timeout) | Forget about all requests. | entailment |
def get_header(self):
"""Get the header value from the response.
:return: a future contains the deserialized value of header
"""
raw_header = yield get_arg(self, 1)
if not self.serializer:
raise tornado.gen.Return(raw_header)
else:
header = self.s... | Get the header value from the response.
:return: a future contains the deserialized value of header | entailment |
def get_body(self):
"""Get the body value from the response.
:return: a future contains the deserialized value of body
"""
raw_body = yield get_arg(self, 2)
if not self.serializer:
raise tornado.gen.Return(raw_body)
else:
body = self.serializer.d... | Get the body value from the response.
:return: a future contains the deserialized value of body | entailment |
def set_body_s(self, stream):
"""Set customized body stream.
Note: the body stream can only be changed before the stream
is consumed.
:param stream: InMemStream/PipeStream for body
:except TChannelError:
Raise TChannelError if the stream is being sent when you try
... | Set customized body stream.
Note: the body stream can only be changed before the stream
is consumed.
:param stream: InMemStream/PipeStream for body
:except TChannelError:
Raise TChannelError if the stream is being sent when you try
to change the stream. | entailment |
def set_header_s(self, stream):
"""Set customized header stream.
Note: the header stream can only be changed before the stream
is consumed.
:param stream: InMemStream/PipeStream for header
:except TChannelError:
Raise TChannelError if the stream is being sent when ... | Set customized header stream.
Note: the header stream can only be changed before the stream
is consumed.
:param stream: InMemStream/PipeStream for header
:except TChannelError:
Raise TChannelError if the stream is being sent when you try
to change the stream. | entailment |
def write_header(self, chunk):
"""Write to header.
Note: the header stream is only available to write before write body.
:param chunk: content to write to header
:except TChannelError:
Raise TChannelError if the response's flush() has been called
"""
if se... | Write to header.
Note: the header stream is only available to write before write body.
:param chunk: content to write to header
:except TChannelError:
Raise TChannelError if the response's flush() has been called | entailment |
def write_body(self, chunk):
"""Write to header.
Note: whenever write_body is called, the header stream will be closed.
write_header method is unavailable.
:param chunk: content to write to body
:except TChannelError:
Raise TChannelError if the response's flush() h... | Write to header.
Note: whenever write_body is called, the header stream will be closed.
write_header method is unavailable.
:param chunk: content to write to body
:except TChannelError:
Raise TChannelError if the response's flush() has been called | entailment |
def read_message(stream):
"""Reads a message from the given IOStream.
:param IOStream stream:
IOStream to read from.
"""
answer = tornado.gen.Future()
io_loop = IOLoop.current()
def on_error(future):
log.info('Failed to read data: %s', future.exception())
return answer.... | Reads a message from the given IOStream.
:param IOStream stream:
IOStream to read from. | entailment |
def set_close_callback(self, cb):
"""Specify a function to be called when this connection is closed.
:param cb:
A callable that takes no arguments. This callable will be called
when this connection is closed.
"""
assert self._close_cb is None, (
'A cl... | Specify a function to be called when this connection is closed.
:param cb:
A callable that takes no arguments. This callable will be called
when this connection is closed. | entailment |
def send(self, message):
"""Send the given message up the wire.
Use this for messages which have a response message.
:param message:
Message to send
:returns:
A Future containing the response for the message
"""
assert self._handshake_performed, "... | Send the given message up the wire.
Use this for messages which have a response message.
:param message:
Message to send
:returns:
A Future containing the response for the message | entailment |
def write(self, message):
"""Writes the given message up the wire.
Does not expect a response back for the message.
:param message:
Message to write.
"""
message.id = message.id or self.writer.next_message_id()
if message.message_type in self.CALL_REQ_TYPES... | Writes the given message up the wire.
Does not expect a response back for the message.
:param message:
Message to write. | entailment |
def _write_fragments(self, fragments):
"""
:param fragments:
A generator of messages
"""
answer = tornado.gen.Future()
if not fragments:
answer.set_result(None)
return answer
io_loop = IOLoop.current()
def _write_fragment(fut... | :param fragments:
A generator of messages | entailment |
def initiate_handshake(self, headers, timeout=None):
"""Initiate a handshake with the remote host.
:param headers:
A dictionary of headers to send.
:returns:
A future that resolves (with a value of None) when the handshake
is complete.
"""
io_... | Initiate a handshake with the remote host.
:param headers:
A dictionary of headers to send.
:returns:
A future that resolves (with a value of None) when the handshake
is complete. | entailment |
def expect_handshake(self, headers):
"""Expect a handshake from the remote host.
:param headers:
Headers to respond with
:returns:
A future that resolves (with a value of None) when the handshake
is complete.
"""
init_req = yield self.reader.g... | Expect a handshake from the remote host.
:param headers:
Headers to respond with
:returns:
A future that resolves (with a value of None) when the handshake
is complete. | entailment |
def outgoing(cls, hostport, process_name=None, serve_hostport=None,
handler=None, tchannel=None):
"""Initiate a new connection to the given host.
:param hostport:
String in the form ``$host:$port`` specifying the target host
:param process_name:
Process ... | Initiate a new connection to the given host.
:param hostport:
String in the form ``$host:$port`` specifying the target host
:param process_name:
Process name of the entity making the connection.
:param serve_hostport:
String in the form ``$host:$port`` specif... | entailment |
def serve(self, handler):
"""Serve calls over this connection using the given RequestHandler.
:param handler:
RequestHandler to process the requests through
:return:
A Future that resolves (to None) once the loop is done running --
which happens once this con... | Serve calls over this connection using the given RequestHandler.
:param handler:
RequestHandler to process the requests through
:return:
A Future that resolves (to None) once the loop is done running --
which happens once this connection is closed. | entailment |
def send_error(self, error):
"""Convenience method for writing Error frames up the wire.
:param error:
TChannel Error. :py:class`tchannel.errors.TChannelError`.
:returns:
A future that resolves when the write finishes.
"""
error_message = build_raw_error... | Convenience method for writing Error frames up the wire.
:param error:
TChannel Error. :py:class`tchannel.errors.TChannelError`.
:returns:
A future that resolves when the write finishes. | entailment |
def _stream(self, context, message_factory):
"""write request/response into frames
Transform request/response into protocol level message objects based on
types and argstreams.
Assumption: the chunk data read from stream can fit into memory.
If arg stream is at init or streami... | write request/response into frames
Transform request/response into protocol level message objects based on
types and argstreams.
Assumption: the chunk data read from stream can fit into memory.
If arg stream is at init or streaming state, build the message based on
current chu... | entailment |
def stream_request(self, request, out_future):
"""send the given request and response is not required"""
request.close_argstreams()
def on_done(future):
if future.exception() and out_future.running():
out_future.set_exc_info(future.exc_info())
request.clo... | send the given request and response is not required | entailment |
def send_request(self, request):
"""Send the given request and response is required.
Use this for messages which have a response message.
:param request:
request to send
:returns:
A Future containing the response for the request
"""
assert self._... | Send the given request and response is required.
Use this for messages which have a response message.
:param request:
request to send
:returns:
A Future containing the response for the request | entailment |
def _add_timeout(self, request, future):
"""Adds a timeout for the given request to the given future."""
io_loop = IOLoop.current()
t = io_loop.call_later(
request.ttl,
self._request_timed_out,
request.id,
request.service,
request.ttl,
... | Adds a timeout for the given request to the given future. | entailment |
def get(self):
"""Receive the next message off the wire.
:returns:
A Future that resolves to the next message off the wire.
"""
if not self.filling:
self.fill()
answer = tornado.gen.Future()
def _on_result(future):
if future.exceptio... | Receive the next message off the wire.
:returns:
A Future that resolves to the next message off the wire. | entailment |
def put(self, message):
"""Enqueues the given message for writing to the wire.
The message must be small enough to fit in a single frame.
"""
if self.draining is False:
self.drain()
return self._enqueue(message) | Enqueues the given message for writing to the wire.
The message must be small enough to fit in a single frame. | entailment |
def advertise(
self,
routers=None,
name=None,
timeout=None,
router_file=None,
jitter=None,
):
"""Make a service available on the Hyperbahn routing mesh.
This will make contact with a Hyperbahn host from a list of known
Hyperbahn routers. Addit... | Make a service available on the Hyperbahn routing mesh.
This will make contact with a Hyperbahn host from a list of known
Hyperbahn routers. Additional Hyperbahn connections will be established
once contact has been made with the network.
:param router:
A seed list of addre... | entailment |
def request(self,
hostport=None,
service=None,
arg_scheme=None,
retry=None,
**kwargs):
"""Initiate a new request through this TChannel.
:param hostport:
Host to which the request will be made. If unspecified, a ... | Initiate a new request through this TChannel.
:param hostport:
Host to which the request will be made. If unspecified, a random
known peer will be picked. This is not necessary if using
Hyperbahn.
:param service:
The name of a service available on Hyperb... | entailment |
def listen(self, port=None):
"""Start listening for incoming connections.
A request handler must have already been specified with
``TChannel.host``.
:param port:
An explicit port to listen on. This is unnecessary when advertising
on Hyperbahn.
:returns:... | Start listening for incoming connections.
A request handler must have already been specified with
``TChannel.host``.
:param port:
An explicit port to listen on. This is unnecessary when advertising
on Hyperbahn.
:returns:
Returns immediately.
... | entailment |
def _register_simple(self, endpoint, scheme, f):
"""Register a simple endpoint with this TChannel.
:param endpoint:
Name of the endpoint being registered.
:param scheme:
Name of the arg scheme under which the endpoint will be
registered.
:param f:
... | Register a simple endpoint with this TChannel.
:param endpoint:
Name of the endpoint being registered.
:param scheme:
Name of the arg scheme under which the endpoint will be
registered.
:param f:
Callable handler for the endpoint. | entailment |
def _register_thrift(self, service_module, handler, **kwargs):
"""Register a Thrift endpoint on this TChannel.
:param service_module:
Reference to the Thrift-generated module for the service being
registered.
:param handler:
Handler for the endpoint
:... | Register a Thrift endpoint on this TChannel.
:param service_module:
Reference to the Thrift-generated module for the service being
registered.
:param handler:
Handler for the endpoint
:param method:
Name of the Thrift method being registered. If o... | entailment |
def register(self, endpoint, scheme=None, handler=None, **kwargs):
"""Register a handler with this TChannel.
This may be used as a decorator:
.. code-block:: python
app = TChannel(name='bar')
@app.register("hello", "json")
def hello_handler(request, respon... | Register a handler with this TChannel.
This may be used as a decorator:
.. code-block:: python
app = TChannel(name='bar')
@app.register("hello", "json")
def hello_handler(request, response):
params = yield request.get_body()
Or as a functi... | entailment |
def lt(self, i, j):
"""Compare the priority of two peers.
Primary comparator will be the rank of each peer. If the ``rank`` is
same then compare the ``order``. The ``order`` attribute of the peer
tracks the heap push order of the peer. This help solve the imbalance
problem cause... | Compare the priority of two peers.
Primary comparator will be the rank of each peer. If the ``rank`` is
same then compare the ``order``. The ``order`` attribute of the peer
tracks the heap push order of the peer. This help solve the imbalance
problem caused by randomization when deal wi... | entailment |
def push_peer(self, peer):
"""Push a new peer into the heap"""
self.order += 1
peer.order = self.order + random.randint(0, self.size())
heap.push(self, peer) | Push a new peer into the heap | entailment |
def add_and_shuffle(self, peer):
"""Push a new peer into the heap and shuffle the heap"""
self.push_peer(peer)
r = random.randint(0, self.size() - 1)
self.swap_order(peer.index, r) | Push a new peer into the heap and shuffle the heap | entailment |
def remove_peer(self, peer):
"""Remove the peer from the heap.
Return: removed peer if peer exists. If peer's index is out of range,
raise IndexError.
"""
if peer.index < 0 or peer.index >= self.size():
raise IndexError('Peer index is out of range')
assert p... | Remove the peer from the heap.
Return: removed peer if peer exists. If peer's index is out of range,
raise IndexError. | entailment |
def token_request(self, authorization_code):
"""
Makes a token request. If the 'token_endpoint' is not configured in the provider metadata, no request will
be made.
Args:
authorization_code (str): authorization code issued to client after user authorization
Returns... | Makes a token request. If the 'token_endpoint' is not configured in the provider metadata, no request will
be made.
Args:
authorization_code (str): authorization code issued to client after user authorization
Returns:
Union[AccessTokenResponse, TokenErrorResponse, None... | entailment |
def userinfo_request(self, access_token):
"""
Args:
access_token (str): Bearer access token to use when fetching userinfo
Returns:
oic.oic.message.OpenIDSchema: UserInfo Response
"""
http_method = self._provider_configuration.userinfo_endpoint_method
... | Args:
access_token (str): Bearer access token to use when fetching userinfo
Returns:
oic.oic.message.OpenIDSchema: UserInfo Response | entailment |
def update(self, access_token=None, id_token=None, id_token_jwt=None, userinfo=None):
"""
Args:
access_token (str)
id_token (Mapping[str, str])
id_token_jwt (str)
userinfo (Mapping[str, str])
"""
def set_if_defined(session_key, value):
... | Args:
access_token (str)
id_token (Mapping[str, str])
id_token_jwt (str)
userinfo (Mapping[str, str]) | entailment |
def log_background_messages(self, name=None):
"""Forwards messages logged on background to Robot Framework log.
By default forwards all messages logged by all threads, but can be
limited to a certain thread by passing thread's name as an argument.
Logged messages are removed from the m... | Forwards messages logged on background to Robot Framework log.
By default forwards all messages logged by all threads, but can be
limited to a certain thread by passing thread's name as an argument.
Logged messages are removed from the message storage. | entailment |
def decorate(func, caller):
"""
decorate(func, caller) decorates a function using a caller.
"""
evaldict = func.__globals__.copy()
evaldict['_call_'] = caller
evaldict['_func_'] = func
fun = FunctionMaker.create(
func, "return _call_(_func_, %(shortsignature)s)",
evaldict, __... | decorate(func, caller) decorates a function using a caller. | entailment |
def decorator(caller, _func=None):
"""decorator(caller) converts a caller function into a decorator"""
if _func is not None: # return a decorated function
# this is obsolete behavior; you should use decorate instead
return decorate(_func, caller)
# else return a decorator function
if in... | decorator(caller) converts a caller function into a decorator | entailment |
def set_client_handler(self, handler_func, name=None, header_filter=None, interval=0.5):
"""Sets an automatic handler for the type of message template currently loaded.
This feature allows users to set a python handler function which is called
automatically by the Rammbock message queue when me... | Sets an automatic handler for the type of message template currently loaded.
This feature allows users to set a python handler function which is called
automatically by the Rammbock message queue when message matches the expected
template. The optional name argument defines the client node to w... | entailment |
def set_server_handler(self, handler_func, name=None, header_filter=None, alias=None, interval=0.5):
"""Sets an automatic handler for the type of message template currently loaded.
This feature allows users to set a python handler function which is called
automatically by the Rammbock message q... | Sets an automatic handler for the type of message template currently loaded.
This feature allows users to set a python handler function which is called
automatically by the Rammbock message queue when message matches the expected
template. The optional name argument defines the server node to w... | entailment |
def reset_rammbock(self):
"""Closes all connections, deletes all servers, clients, and protocols.
You should call this method before exiting your test run. This will
close all the connections and the ports will therefore be available for
reuse faster.
"""
for client in s... | Closes all connections, deletes all servers, clients, and protocols.
You should call this method before exiting your test run. This will
close all the connections and the ports will therefore be available for
reuse faster. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.