repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
aaugustin/websockets | src/websockets/extensions/permessage_deflate.py | ClientPerMessageDeflateFactory.process_response_params | def process_response_params(
self,
params: Sequence[ExtensionParameter],
accepted_extensions: Sequence["Extension"],
) -> PerMessageDeflate:
"""
Process response parameters.
Return an extension instance.
"""
if any(other.name == self.name for other in accepted_extensions):
raise NegotiationError(f"Received duplicate {self.name}")
# Request parameters are available in instance variables.
# Load response parameters in local variables.
(
server_no_context_takeover,
client_no_context_takeover,
server_max_window_bits,
client_max_window_bits,
) = _extract_parameters(params, is_server=False)
# After comparing the request and the response, the final
# configuration must be available in the local variables.
# server_no_context_takeover
#
# Req. Resp. Result
# ------ ------ --------------------------------------------------
# False False False
# False True True
# True False Error!
# True True True
if self.server_no_context_takeover:
if not server_no_context_takeover:
raise NegotiationError("Expected server_no_context_takeover")
# client_no_context_takeover
#
# Req. Resp. Result
# ------ ------ --------------------------------------------------
# False False False
# False True True
# True False True - must change value
# True True True
if self.client_no_context_takeover:
if not client_no_context_takeover:
client_no_context_takeover = True
# server_max_window_bits
# Req. Resp. Result
# ------ ------ --------------------------------------------------
# None None None
# None 8≤M≤15 M
# 8≤N≤15 None Error!
# 8≤N≤15 8≤M≤N M
# 8≤N≤15 N<M≤15 Error!
if self.server_max_window_bits is None:
pass
else:
if server_max_window_bits is None:
raise NegotiationError("Expected server_max_window_bits")
elif server_max_window_bits > self.server_max_window_bits:
raise NegotiationError("Unsupported server_max_window_bits")
# client_max_window_bits
# Req. Resp. Result
# ------ ------ --------------------------------------------------
# None None None
# None 8≤M≤15 Error!
# True None None
# True 8≤M≤15 M
# 8≤N≤15 None N - must change value
# 8≤N≤15 8≤M≤N M
# 8≤N≤15 N<M≤15 Error!
if self.client_max_window_bits is None:
if client_max_window_bits is not None:
raise NegotiationError("Unexpected client_max_window_bits")
elif self.client_max_window_bits is True:
pass
else:
if client_max_window_bits is None:
client_max_window_bits = self.client_max_window_bits
elif client_max_window_bits > self.client_max_window_bits:
raise NegotiationError("Unsupported client_max_window_bits")
return PerMessageDeflate(
server_no_context_takeover, # remote_no_context_takeover
client_no_context_takeover, # local_no_context_takeover
server_max_window_bits or 15, # remote_max_window_bits
client_max_window_bits or 15, # local_max_window_bits
self.compress_settings,
) | python | def process_response_params(
self,
params: Sequence[ExtensionParameter],
accepted_extensions: Sequence["Extension"],
) -> PerMessageDeflate:
"""
Process response parameters.
Return an extension instance.
"""
if any(other.name == self.name for other in accepted_extensions):
raise NegotiationError(f"Received duplicate {self.name}")
# Request parameters are available in instance variables.
# Load response parameters in local variables.
(
server_no_context_takeover,
client_no_context_takeover,
server_max_window_bits,
client_max_window_bits,
) = _extract_parameters(params, is_server=False)
# After comparing the request and the response, the final
# configuration must be available in the local variables.
# server_no_context_takeover
#
# Req. Resp. Result
# ------ ------ --------------------------------------------------
# False False False
# False True True
# True False Error!
# True True True
if self.server_no_context_takeover:
if not server_no_context_takeover:
raise NegotiationError("Expected server_no_context_takeover")
# client_no_context_takeover
#
# Req. Resp. Result
# ------ ------ --------------------------------------------------
# False False False
# False True True
# True False True - must change value
# True True True
if self.client_no_context_takeover:
if not client_no_context_takeover:
client_no_context_takeover = True
# server_max_window_bits
# Req. Resp. Result
# ------ ------ --------------------------------------------------
# None None None
# None 8≤M≤15 M
# 8≤N≤15 None Error!
# 8≤N≤15 8≤M≤N M
# 8≤N≤15 N<M≤15 Error!
if self.server_max_window_bits is None:
pass
else:
if server_max_window_bits is None:
raise NegotiationError("Expected server_max_window_bits")
elif server_max_window_bits > self.server_max_window_bits:
raise NegotiationError("Unsupported server_max_window_bits")
# client_max_window_bits
# Req. Resp. Result
# ------ ------ --------------------------------------------------
# None None None
# None 8≤M≤15 Error!
# True None None
# True 8≤M≤15 M
# 8≤N≤15 None N - must change value
# 8≤N≤15 8≤M≤N M
# 8≤N≤15 N<M≤15 Error!
if self.client_max_window_bits is None:
if client_max_window_bits is not None:
raise NegotiationError("Unexpected client_max_window_bits")
elif self.client_max_window_bits is True:
pass
else:
if client_max_window_bits is None:
client_max_window_bits = self.client_max_window_bits
elif client_max_window_bits > self.client_max_window_bits:
raise NegotiationError("Unsupported client_max_window_bits")
return PerMessageDeflate(
server_no_context_takeover, # remote_no_context_takeover
client_no_context_takeover, # local_no_context_takeover
server_max_window_bits or 15, # remote_max_window_bits
client_max_window_bits or 15, # local_max_window_bits
self.compress_settings,
) | [
"def",
"process_response_params",
"(",
"self",
",",
"params",
":",
"Sequence",
"[",
"ExtensionParameter",
"]",
",",
"accepted_extensions",
":",
"Sequence",
"[",
"\"Extension\"",
"]",
",",
")",
"->",
"PerMessageDeflate",
":",
"if",
"any",
"(",
"other",
".",
"na... | Process response parameters.
Return an extension instance. | [
"Process",
"response",
"parameters",
"."
] | 17b3f47549b6f752a1be07fa1ba3037cb59c7d56 | https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L325-L428 | train | 214,200 |
aaugustin/websockets | src/websockets/extensions/permessage_deflate.py | ServerPerMessageDeflateFactory.process_request_params | def process_request_params(
self,
params: Sequence[ExtensionParameter],
accepted_extensions: Sequence["Extension"],
) -> Tuple[List[ExtensionParameter], PerMessageDeflate]:
"""
Process request parameters.
Return response params and an extension instance.
"""
if any(other.name == self.name for other in accepted_extensions):
raise NegotiationError(f"Skipped duplicate {self.name}")
# Load request parameters in local variables.
(
server_no_context_takeover,
client_no_context_takeover,
server_max_window_bits,
client_max_window_bits,
) = _extract_parameters(params, is_server=True)
# Configuration parameters are available in instance variables.
# After comparing the request and the configuration, the response must
# be available in the local variables.
# server_no_context_takeover
#
# Config Req. Resp.
# ------ ------ --------------------------------------------------
# False False False
# False True True
# True False True - must change value to True
# True True True
if self.server_no_context_takeover:
if not server_no_context_takeover:
server_no_context_takeover = True
# client_no_context_takeover
#
# Config Req. Resp.
# ------ ------ --------------------------------------------------
# False False False
# False True True (or False)
# True False True - must change value to True
# True True True (or False)
if self.client_no_context_takeover:
if not client_no_context_takeover:
client_no_context_takeover = True
# server_max_window_bits
# Config Req. Resp.
# ------ ------ --------------------------------------------------
# None None None
# None 8≤M≤15 M
# 8≤N≤15 None N - must change value
# 8≤N≤15 8≤M≤N M
# 8≤N≤15 N<M≤15 N - must change value
if self.server_max_window_bits is None:
pass
else:
if server_max_window_bits is None:
server_max_window_bits = self.server_max_window_bits
elif server_max_window_bits > self.server_max_window_bits:
server_max_window_bits = self.server_max_window_bits
# client_max_window_bits
# Config Req. Resp.
# ------ ------ --------------------------------------------------
# None None None
# None True None - must change value
# None 8≤M≤15 M (or None)
# 8≤N≤15 None Error!
# 8≤N≤15 True N - must change value
# 8≤N≤15 8≤M≤N M (or None)
# 8≤N≤15 N<M≤15 N
if self.client_max_window_bits is None:
if client_max_window_bits is True:
client_max_window_bits = self.client_max_window_bits
else:
if client_max_window_bits is None:
raise NegotiationError("Required client_max_window_bits")
elif client_max_window_bits is True:
client_max_window_bits = self.client_max_window_bits
elif self.client_max_window_bits < client_max_window_bits:
client_max_window_bits = self.client_max_window_bits
return (
_build_parameters(
server_no_context_takeover,
client_no_context_takeover,
server_max_window_bits,
client_max_window_bits,
),
PerMessageDeflate(
client_no_context_takeover, # remote_no_context_takeover
server_no_context_takeover, # local_no_context_takeover
client_max_window_bits or 15, # remote_max_window_bits
server_max_window_bits or 15, # local_max_window_bits
self.compress_settings,
),
) | python | def process_request_params(
self,
params: Sequence[ExtensionParameter],
accepted_extensions: Sequence["Extension"],
) -> Tuple[List[ExtensionParameter], PerMessageDeflate]:
"""
Process request parameters.
Return response params and an extension instance.
"""
if any(other.name == self.name for other in accepted_extensions):
raise NegotiationError(f"Skipped duplicate {self.name}")
# Load request parameters in local variables.
(
server_no_context_takeover,
client_no_context_takeover,
server_max_window_bits,
client_max_window_bits,
) = _extract_parameters(params, is_server=True)
# Configuration parameters are available in instance variables.
# After comparing the request and the configuration, the response must
# be available in the local variables.
# server_no_context_takeover
#
# Config Req. Resp.
# ------ ------ --------------------------------------------------
# False False False
# False True True
# True False True - must change value to True
# True True True
if self.server_no_context_takeover:
if not server_no_context_takeover:
server_no_context_takeover = True
# client_no_context_takeover
#
# Config Req. Resp.
# ------ ------ --------------------------------------------------
# False False False
# False True True (or False)
# True False True - must change value to True
# True True True (or False)
if self.client_no_context_takeover:
if not client_no_context_takeover:
client_no_context_takeover = True
# server_max_window_bits
# Config Req. Resp.
# ------ ------ --------------------------------------------------
# None None None
# None 8≤M≤15 M
# 8≤N≤15 None N - must change value
# 8≤N≤15 8≤M≤N M
# 8≤N≤15 N<M≤15 N - must change value
if self.server_max_window_bits is None:
pass
else:
if server_max_window_bits is None:
server_max_window_bits = self.server_max_window_bits
elif server_max_window_bits > self.server_max_window_bits:
server_max_window_bits = self.server_max_window_bits
# client_max_window_bits
# Config Req. Resp.
# ------ ------ --------------------------------------------------
# None None None
# None True None - must change value
# None 8≤M≤15 M (or None)
# 8≤N≤15 None Error!
# 8≤N≤15 True N - must change value
# 8≤N≤15 8≤M≤N M (or None)
# 8≤N≤15 N<M≤15 N
if self.client_max_window_bits is None:
if client_max_window_bits is True:
client_max_window_bits = self.client_max_window_bits
else:
if client_max_window_bits is None:
raise NegotiationError("Required client_max_window_bits")
elif client_max_window_bits is True:
client_max_window_bits = self.client_max_window_bits
elif self.client_max_window_bits < client_max_window_bits:
client_max_window_bits = self.client_max_window_bits
return (
_build_parameters(
server_no_context_takeover,
client_no_context_takeover,
server_max_window_bits,
client_max_window_bits,
),
PerMessageDeflate(
client_no_context_takeover, # remote_no_context_takeover
server_no_context_takeover, # local_no_context_takeover
client_max_window_bits or 15, # remote_max_window_bits
server_max_window_bits or 15, # local_max_window_bits
self.compress_settings,
),
) | [
"def",
"process_request_params",
"(",
"self",
",",
"params",
":",
"Sequence",
"[",
"ExtensionParameter",
"]",
",",
"accepted_extensions",
":",
"Sequence",
"[",
"\"Extension\"",
"]",
",",
")",
"->",
"Tuple",
"[",
"List",
"[",
"ExtensionParameter",
"]",
",",
"Pe... | Process request parameters.
Return response params and an extension instance. | [
"Process",
"request",
"parameters",
"."
] | 17b3f47549b6f752a1be07fa1ba3037cb59c7d56 | https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L482-L592 | train | 214,201 |
aaugustin/websockets | src/websockets/utils.py | apply_mask | def apply_mask(data: bytes, mask: bytes) -> bytes:
"""
Apply masking to the data of a WebSocket message.
``data`` and ``mask`` are bytes-like objects.
Return :class:`bytes`.
"""
if len(mask) != 4:
raise ValueError("mask must contain 4 bytes")
return bytes(b ^ m for b, m in zip(data, itertools.cycle(mask))) | python | def apply_mask(data: bytes, mask: bytes) -> bytes:
"""
Apply masking to the data of a WebSocket message.
``data`` and ``mask`` are bytes-like objects.
Return :class:`bytes`.
"""
if len(mask) != 4:
raise ValueError("mask must contain 4 bytes")
return bytes(b ^ m for b, m in zip(data, itertools.cycle(mask))) | [
"def",
"apply_mask",
"(",
"data",
":",
"bytes",
",",
"mask",
":",
"bytes",
")",
"->",
"bytes",
":",
"if",
"len",
"(",
"mask",
")",
"!=",
"4",
":",
"raise",
"ValueError",
"(",
"\"mask must contain 4 bytes\"",
")",
"return",
"bytes",
"(",
"b",
"^",
"m",
... | Apply masking to the data of a WebSocket message.
``data`` and ``mask`` are bytes-like objects.
Return :class:`bytes`. | [
"Apply",
"masking",
"to",
"the",
"data",
"of",
"a",
"WebSocket",
"message",
"."
] | 17b3f47549b6f752a1be07fa1ba3037cb59c7d56 | https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/utils.py#L7-L19 | train | 214,202 |
aaugustin/websockets | src/websockets/exceptions.py | format_close | def format_close(code: int, reason: str) -> str:
"""
Display a human-readable version of the close code and reason.
"""
if 3000 <= code < 4000:
explanation = "registered"
elif 4000 <= code < 5000:
explanation = "private use"
else:
explanation = CLOSE_CODES.get(code, "unknown")
result = f"code = {code} ({explanation}), "
if reason:
result += f"reason = {reason}"
else:
result += "no reason"
return result | python | def format_close(code: int, reason: str) -> str:
"""
Display a human-readable version of the close code and reason.
"""
if 3000 <= code < 4000:
explanation = "registered"
elif 4000 <= code < 5000:
explanation = "private use"
else:
explanation = CLOSE_CODES.get(code, "unknown")
result = f"code = {code} ({explanation}), "
if reason:
result += f"reason = {reason}"
else:
result += "no reason"
return result | [
"def",
"format_close",
"(",
"code",
":",
"int",
",",
"reason",
":",
"str",
")",
"->",
"str",
":",
"if",
"3000",
"<=",
"code",
"<",
"4000",
":",
"explanation",
"=",
"\"registered\"",
"elif",
"4000",
"<=",
"code",
"<",
"5000",
":",
"explanation",
"=",
... | Display a human-readable version of the close code and reason. | [
"Display",
"a",
"human",
"-",
"readable",
"version",
"of",
"the",
"close",
"code",
"and",
"reason",
"."
] | 17b3f47549b6f752a1be07fa1ba3037cb59c7d56 | https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/exceptions.py#L202-L221 | train | 214,203 |
nameko/nameko | nameko/runners.py | ServiceRunner.start | def start(self):
""" Start all the registered services.
A new container is created for each service using the container
class provided in the __init__ method.
All containers are started concurrently and the method will block
until all have completed their startup routine.
"""
service_names = ', '.join(self.service_names)
_log.info('starting services: %s', service_names)
SpawningProxy(self.containers).start()
_log.debug('services started: %s', service_names) | python | def start(self):
""" Start all the registered services.
A new container is created for each service using the container
class provided in the __init__ method.
All containers are started concurrently and the method will block
until all have completed their startup routine.
"""
service_names = ', '.join(self.service_names)
_log.info('starting services: %s', service_names)
SpawningProxy(self.containers).start()
_log.debug('services started: %s', service_names) | [
"def",
"start",
"(",
"self",
")",
":",
"service_names",
"=",
"', '",
".",
"join",
"(",
"self",
".",
"service_names",
")",
"_log",
".",
"info",
"(",
"'starting services: %s'",
",",
"service_names",
")",
"SpawningProxy",
"(",
"self",
".",
"containers",
")",
... | Start all the registered services.
A new container is created for each service using the container
class provided in the __init__ method.
All containers are started concurrently and the method will block
until all have completed their startup routine. | [
"Start",
"all",
"the",
"registered",
"services",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/runners.py#L54-L68 | train | 214,204 |
nameko/nameko | nameko/runners.py | ServiceRunner.wait | def wait(self):
""" Wait for all running containers to stop.
"""
try:
SpawningProxy(self.containers, abort_on_error=True).wait()
except Exception:
# If a single container failed, stop its peers and re-raise the
# exception
self.stop()
raise | python | def wait(self):
""" Wait for all running containers to stop.
"""
try:
SpawningProxy(self.containers, abort_on_error=True).wait()
except Exception:
# If a single container failed, stop its peers and re-raise the
# exception
self.stop()
raise | [
"def",
"wait",
"(",
"self",
")",
":",
"try",
":",
"SpawningProxy",
"(",
"self",
".",
"containers",
",",
"abort_on_error",
"=",
"True",
")",
".",
"wait",
"(",
")",
"except",
"Exception",
":",
"# If a single container failed, stop its peers and re-raise the",
"# exc... | Wait for all running containers to stop. | [
"Wait",
"for",
"all",
"running",
"containers",
"to",
"stop",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/runners.py#L92-L101 | train | 214,205 |
nameko/nameko | nameko/amqp/publish.py | Publisher.publish | def publish(self, payload, **kwargs):
""" Publish a message.
"""
publish_kwargs = self.publish_kwargs.copy()
# merge headers from when the publisher was instantiated
# with any provided now; "extra" headers always win
headers = publish_kwargs.pop('headers', {}).copy()
headers.update(kwargs.pop('headers', {}))
headers.update(kwargs.pop('extra_headers', {}))
use_confirms = kwargs.pop('use_confirms', self.use_confirms)
transport_options = kwargs.pop('transport_options',
self.transport_options
)
transport_options['confirm_publish'] = use_confirms
delivery_mode = kwargs.pop('delivery_mode', self.delivery_mode)
mandatory = kwargs.pop('mandatory', self.mandatory)
priority = kwargs.pop('priority', self.priority)
expiration = kwargs.pop('expiration', self.expiration)
serializer = kwargs.pop('serializer', self.serializer)
compression = kwargs.pop('compression', self.compression)
retry = kwargs.pop('retry', self.retry)
retry_policy = kwargs.pop('retry_policy', self.retry_policy)
declare = self.declare[:]
declare.extend(kwargs.pop('declare', ()))
publish_kwargs.update(kwargs) # remaining publish-time kwargs win
with get_producer(self.amqp_uri,
use_confirms,
self.ssl,
transport_options,
) as producer:
try:
producer.publish(
payload,
headers=headers,
delivery_mode=delivery_mode,
mandatory=mandatory,
priority=priority,
expiration=expiration,
compression=compression,
declare=declare,
retry=retry,
retry_policy=retry_policy,
serializer=serializer,
**publish_kwargs
)
except ChannelError as exc:
if "NO_ROUTE" in str(exc):
raise UndeliverableMessage()
raise
if mandatory:
if not use_confirms:
warnings.warn(
"Mandatory delivery was requested, but "
"unroutable messages cannot be detected without "
"publish confirms enabled."
) | python | def publish(self, payload, **kwargs):
""" Publish a message.
"""
publish_kwargs = self.publish_kwargs.copy()
# merge headers from when the publisher was instantiated
# with any provided now; "extra" headers always win
headers = publish_kwargs.pop('headers', {}).copy()
headers.update(kwargs.pop('headers', {}))
headers.update(kwargs.pop('extra_headers', {}))
use_confirms = kwargs.pop('use_confirms', self.use_confirms)
transport_options = kwargs.pop('transport_options',
self.transport_options
)
transport_options['confirm_publish'] = use_confirms
delivery_mode = kwargs.pop('delivery_mode', self.delivery_mode)
mandatory = kwargs.pop('mandatory', self.mandatory)
priority = kwargs.pop('priority', self.priority)
expiration = kwargs.pop('expiration', self.expiration)
serializer = kwargs.pop('serializer', self.serializer)
compression = kwargs.pop('compression', self.compression)
retry = kwargs.pop('retry', self.retry)
retry_policy = kwargs.pop('retry_policy', self.retry_policy)
declare = self.declare[:]
declare.extend(kwargs.pop('declare', ()))
publish_kwargs.update(kwargs) # remaining publish-time kwargs win
with get_producer(self.amqp_uri,
use_confirms,
self.ssl,
transport_options,
) as producer:
try:
producer.publish(
payload,
headers=headers,
delivery_mode=delivery_mode,
mandatory=mandatory,
priority=priority,
expiration=expiration,
compression=compression,
declare=declare,
retry=retry,
retry_policy=retry_policy,
serializer=serializer,
**publish_kwargs
)
except ChannelError as exc:
if "NO_ROUTE" in str(exc):
raise UndeliverableMessage()
raise
if mandatory:
if not use_confirms:
warnings.warn(
"Mandatory delivery was requested, but "
"unroutable messages cannot be detected without "
"publish confirms enabled."
) | [
"def",
"publish",
"(",
"self",
",",
"payload",
",",
"*",
"*",
"kwargs",
")",
":",
"publish_kwargs",
"=",
"self",
".",
"publish_kwargs",
".",
"copy",
"(",
")",
"# merge headers from when the publisher was instantiated",
"# with any provided now; \"extra\" headers always wi... | Publish a message. | [
"Publish",
"a",
"message",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/amqp/publish.py#L161-L223 | train | 214,206 |
nameko/nameko | nameko/rpc.py | RpcConsumer.stop | def stop(self):
""" Stop the RpcConsumer.
The RpcConsumer ordinary unregisters from the QueueConsumer when the
last Rpc subclass unregisters from it. If no providers were registered,
we should unregister from the QueueConsumer as soon as we're asked
to stop.
"""
if not self._providers_registered:
self.queue_consumer.unregister_provider(self)
self._unregistered_from_queue_consumer.send(True) | python | def stop(self):
""" Stop the RpcConsumer.
The RpcConsumer ordinary unregisters from the QueueConsumer when the
last Rpc subclass unregisters from it. If no providers were registered,
we should unregister from the QueueConsumer as soon as we're asked
to stop.
"""
if not self._providers_registered:
self.queue_consumer.unregister_provider(self)
self._unregistered_from_queue_consumer.send(True) | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_providers_registered",
":",
"self",
".",
"queue_consumer",
".",
"unregister_provider",
"(",
"self",
")",
"self",
".",
"_unregistered_from_queue_consumer",
".",
"send",
"(",
"True",
")"
] | Stop the RpcConsumer.
The RpcConsumer ordinary unregisters from the QueueConsumer when the
last Rpc subclass unregisters from it. If no providers were registered,
we should unregister from the QueueConsumer as soon as we're asked
to stop. | [
"Stop",
"the",
"RpcConsumer",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/rpc.py#L70-L80 | train | 214,207 |
nameko/nameko | nameko/rpc.py | RpcConsumer.unregister_provider | def unregister_provider(self, provider):
""" Unregister a provider.
Blocks until this RpcConsumer is unregistered from its QueueConsumer,
which only happens when all providers have asked to unregister.
"""
self._unregistering_providers.add(provider)
remaining_providers = self._providers - self._unregistering_providers
if not remaining_providers:
_log.debug('unregistering from queueconsumer %s', self)
self.queue_consumer.unregister_provider(self)
_log.debug('unregistered from queueconsumer %s', self)
self._unregistered_from_queue_consumer.send(True)
_log.debug('waiting for unregister from queue consumer %s', self)
self._unregistered_from_queue_consumer.wait()
super(RpcConsumer, self).unregister_provider(provider) | python | def unregister_provider(self, provider):
""" Unregister a provider.
Blocks until this RpcConsumer is unregistered from its QueueConsumer,
which only happens when all providers have asked to unregister.
"""
self._unregistering_providers.add(provider)
remaining_providers = self._providers - self._unregistering_providers
if not remaining_providers:
_log.debug('unregistering from queueconsumer %s', self)
self.queue_consumer.unregister_provider(self)
_log.debug('unregistered from queueconsumer %s', self)
self._unregistered_from_queue_consumer.send(True)
_log.debug('waiting for unregister from queue consumer %s', self)
self._unregistered_from_queue_consumer.wait()
super(RpcConsumer, self).unregister_provider(provider) | [
"def",
"unregister_provider",
"(",
"self",
",",
"provider",
")",
":",
"self",
".",
"_unregistering_providers",
".",
"add",
"(",
"provider",
")",
"remaining_providers",
"=",
"self",
".",
"_providers",
"-",
"self",
".",
"_unregistering_providers",
"if",
"not",
"re... | Unregister a provider.
Blocks until this RpcConsumer is unregistered from its QueueConsumer,
which only happens when all providers have asked to unregister. | [
"Unregister",
"a",
"provider",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/rpc.py#L82-L98 | train | 214,208 |
nameko/nameko | nameko/events.py | EventDispatcher.get_dependency | def get_dependency(self, worker_ctx):
""" Inject a dispatch method onto the service instance
"""
extra_headers = self.get_message_headers(worker_ctx)
def dispatch(event_type, event_data):
self.publisher.publish(
event_data,
exchange=self.exchange,
routing_key=event_type,
extra_headers=extra_headers
)
return dispatch | python | def get_dependency(self, worker_ctx):
""" Inject a dispatch method onto the service instance
"""
extra_headers = self.get_message_headers(worker_ctx)
def dispatch(event_type, event_data):
self.publisher.publish(
event_data,
exchange=self.exchange,
routing_key=event_type,
extra_headers=extra_headers
)
return dispatch | [
"def",
"get_dependency",
"(",
"self",
",",
"worker_ctx",
")",
":",
"extra_headers",
"=",
"self",
".",
"get_message_headers",
"(",
"worker_ctx",
")",
"def",
"dispatch",
"(",
"event_type",
",",
"event_data",
")",
":",
"self",
".",
"publisher",
".",
"publish",
... | Inject a dispatch method onto the service instance | [
"Inject",
"a",
"dispatch",
"method",
"onto",
"the",
"service",
"instance"
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/events.py#L86-L99 | train | 214,209 |
nameko/nameko | nameko/events.py | EventHandler.broadcast_identifier | def broadcast_identifier(self):
""" A unique string to identify a service instance for `BROADCAST`
type handlers.
The `broadcast_identifier` is appended to the queue name when the
`BROADCAST` handler type is used. It must uniquely identify service
instances that receive broadcasts.
The default `broadcast_identifier` is a uuid that is set when the
service starts. It will change when the service restarts, meaning
that any unconsumed messages that were broadcast to the 'old' service
instance will not be received by the 'new' one. ::
@property
def broadcast_identifier(self):
# use a uuid as the identifier.
# the identifier will change when the service restarts and
# any unconsumed messages will be lost
return uuid.uuid4().hex
The default behaviour is therefore incompatible with reliable delivery.
An alternative `broadcast_identifier` that would survive service
restarts is ::
@property
def broadcast_identifier(self):
# use the machine hostname as the identifier.
# this assumes that only one instance of a service runs on
# any given machine
return socket.gethostname()
If neither of these approaches are appropriate, you could read the
value out of a configuration file ::
@property
def broadcast_identifier(self):
return self.config['SERVICE_IDENTIFIER'] # or similar
Broadcast queues are exclusive to ensure that `broadcast_identifier`
values are unique.
Because this method is a descriptor, it will be called during
container creation, regardless of the configured `handler_type`.
See :class:`nameko.extensions.Extension` for more details.
"""
if self.handler_type is not BROADCAST:
return None
if self.reliable_delivery:
raise EventHandlerConfigurationError(
"You are using the default broadcast identifier "
"which is not compatible with reliable delivery. See "
":meth:`nameko.events.EventHandler.broadcast_identifier` "
"for details.")
return uuid.uuid4().hex | python | def broadcast_identifier(self):
""" A unique string to identify a service instance for `BROADCAST`
type handlers.
The `broadcast_identifier` is appended to the queue name when the
`BROADCAST` handler type is used. It must uniquely identify service
instances that receive broadcasts.
The default `broadcast_identifier` is a uuid that is set when the
service starts. It will change when the service restarts, meaning
that any unconsumed messages that were broadcast to the 'old' service
instance will not be received by the 'new' one. ::
@property
def broadcast_identifier(self):
# use a uuid as the identifier.
# the identifier will change when the service restarts and
# any unconsumed messages will be lost
return uuid.uuid4().hex
The default behaviour is therefore incompatible with reliable delivery.
An alternative `broadcast_identifier` that would survive service
restarts is ::
@property
def broadcast_identifier(self):
# use the machine hostname as the identifier.
# this assumes that only one instance of a service runs on
# any given machine
return socket.gethostname()
If neither of these approaches are appropriate, you could read the
value out of a configuration file ::
@property
def broadcast_identifier(self):
return self.config['SERVICE_IDENTIFIER'] # or similar
Broadcast queues are exclusive to ensure that `broadcast_identifier`
values are unique.
Because this method is a descriptor, it will be called during
container creation, regardless of the configured `handler_type`.
See :class:`nameko.extensions.Extension` for more details.
"""
if self.handler_type is not BROADCAST:
return None
if self.reliable_delivery:
raise EventHandlerConfigurationError(
"You are using the default broadcast identifier "
"which is not compatible with reliable delivery. See "
":meth:`nameko.events.EventHandler.broadcast_identifier` "
"for details.")
return uuid.uuid4().hex | [
"def",
"broadcast_identifier",
"(",
"self",
")",
":",
"if",
"self",
".",
"handler_type",
"is",
"not",
"BROADCAST",
":",
"return",
"None",
"if",
"self",
".",
"reliable_delivery",
":",
"raise",
"EventHandlerConfigurationError",
"(",
"\"You are using the default broadcas... | A unique string to identify a service instance for `BROADCAST`
type handlers.
The `broadcast_identifier` is appended to the queue name when the
`BROADCAST` handler type is used. It must uniquely identify service
instances that receive broadcasts.
The default `broadcast_identifier` is a uuid that is set when the
service starts. It will change when the service restarts, meaning
that any unconsumed messages that were broadcast to the 'old' service
instance will not be received by the 'new' one. ::
@property
def broadcast_identifier(self):
# use a uuid as the identifier.
# the identifier will change when the service restarts and
# any unconsumed messages will be lost
return uuid.uuid4().hex
The default behaviour is therefore incompatible with reliable delivery.
An alternative `broadcast_identifier` that would survive service
restarts is ::
@property
def broadcast_identifier(self):
# use the machine hostname as the identifier.
# this assumes that only one instance of a service runs on
# any given machine
return socket.gethostname()
If neither of these approaches are appropriate, you could read the
value out of a configuration file ::
@property
def broadcast_identifier(self):
return self.config['SERVICE_IDENTIFIER'] # or similar
Broadcast queues are exclusive to ensure that `broadcast_identifier`
values are unique.
Because this method is a descriptor, it will be called during
container creation, regardless of the configured `handler_type`.
See :class:`nameko.extensions.Extension` for more details. | [
"A",
"unique",
"string",
"to",
"identify",
"a",
"service",
"instance",
"for",
"BROADCAST",
"type",
"handlers",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/events.py#L166-L222 | train | 214,210 |
nameko/nameko | nameko/exceptions.py | get_module_path | def get_module_path(exc_type):
""" Return the dotted module path of `exc_type`, including the class name.
e.g.::
>>> get_module_path(MethodNotFound)
>>> "nameko.exceptions.MethodNotFound"
"""
module = inspect.getmodule(exc_type)
return "{}.{}".format(module.__name__, exc_type.__name__) | python | def get_module_path(exc_type):
""" Return the dotted module path of `exc_type`, including the class name.
e.g.::
>>> get_module_path(MethodNotFound)
>>> "nameko.exceptions.MethodNotFound"
"""
module = inspect.getmodule(exc_type)
return "{}.{}".format(module.__name__, exc_type.__name__) | [
"def",
"get_module_path",
"(",
"exc_type",
")",
":",
"module",
"=",
"inspect",
".",
"getmodule",
"(",
"exc_type",
")",
"return",
"\"{}.{}\"",
".",
"format",
"(",
"module",
".",
"__name__",
",",
"exc_type",
".",
"__name__",
")"
] | Return the dotted module path of `exc_type`, including the class name.
e.g.::
>>> get_module_path(MethodNotFound)
>>> "nameko.exceptions.MethodNotFound" | [
"Return",
"the",
"dotted",
"module",
"path",
"of",
"exc_type",
"including",
"the",
"class",
"name",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/exceptions.py#L38-L48 | train | 214,211 |
nameko/nameko | nameko/exceptions.py | safe_for_serialization | def safe_for_serialization(value):
""" Transform a value in preparation for serializing as json
no-op for strings, mappings and iterables have their entries made safe,
and all other values are stringified, with a fallback value if that fails
"""
if isinstance(value, six.string_types):
return value
if isinstance(value, dict):
return {
safe_for_serialization(key): safe_for_serialization(val)
for key, val in six.iteritems(value)
}
if isinstance(value, collections.Iterable):
return list(map(safe_for_serialization, value))
try:
return six.text_type(value)
except Exception:
return '[__unicode__ failed]' | python | def safe_for_serialization(value):
""" Transform a value in preparation for serializing as json
no-op for strings, mappings and iterables have their entries made safe,
and all other values are stringified, with a fallback value if that fails
"""
if isinstance(value, six.string_types):
return value
if isinstance(value, dict):
return {
safe_for_serialization(key): safe_for_serialization(val)
for key, val in six.iteritems(value)
}
if isinstance(value, collections.Iterable):
return list(map(safe_for_serialization, value))
try:
return six.text_type(value)
except Exception:
return '[__unicode__ failed]' | [
"def",
"safe_for_serialization",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"return",
"value",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"{",
"safe_for_serialization",
"(",
... | Transform a value in preparation for serializing as json
no-op for strings, mappings and iterables have their entries made safe,
and all other values are stringified, with a fallback value if that fails | [
"Transform",
"a",
"value",
"in",
"preparation",
"for",
"serializing",
"as",
"json"
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/exceptions.py#L62-L82 | train | 214,212 |
nameko/nameko | nameko/exceptions.py | serialize | def serialize(exc):
""" Serialize `self.exc` into a data dictionary representing it.
"""
return {
'exc_type': type(exc).__name__,
'exc_path': get_module_path(type(exc)),
'exc_args': list(map(safe_for_serialization, exc.args)),
'value': safe_for_serialization(exc),
} | python | def serialize(exc):
""" Serialize `self.exc` into a data dictionary representing it.
"""
return {
'exc_type': type(exc).__name__,
'exc_path': get_module_path(type(exc)),
'exc_args': list(map(safe_for_serialization, exc.args)),
'value': safe_for_serialization(exc),
} | [
"def",
"serialize",
"(",
"exc",
")",
":",
"return",
"{",
"'exc_type'",
":",
"type",
"(",
"exc",
")",
".",
"__name__",
",",
"'exc_path'",
":",
"get_module_path",
"(",
"type",
"(",
"exc",
")",
")",
",",
"'exc_args'",
":",
"list",
"(",
"map",
"(",
"safe... | Serialize `self.exc` into a data dictionary representing it. | [
"Serialize",
"self",
".",
"exc",
"into",
"a",
"data",
"dictionary",
"representing",
"it",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/exceptions.py#L85-L94 | train | 214,213 |
nameko/nameko | nameko/exceptions.py | deserialize | def deserialize(data):
""" Deserialize `data` to an exception instance.
If the `exc_path` value matches an exception registered as
``deserializable``, return an instance of that exception type.
Otherwise, return a `RemoteError` instance describing the exception
that occurred.
"""
key = data.get('exc_path')
if key in registry:
exc_args = data.get('exc_args', ())
return registry[key](*exc_args)
exc_type = data.get('exc_type')
value = data.get('value')
return RemoteError(exc_type=exc_type, value=value) | python | def deserialize(data):
""" Deserialize `data` to an exception instance.
If the `exc_path` value matches an exception registered as
``deserializable``, return an instance of that exception type.
Otherwise, return a `RemoteError` instance describing the exception
that occurred.
"""
key = data.get('exc_path')
if key in registry:
exc_args = data.get('exc_args', ())
return registry[key](*exc_args)
exc_type = data.get('exc_type')
value = data.get('value')
return RemoteError(exc_type=exc_type, value=value) | [
"def",
"deserialize",
"(",
"data",
")",
":",
"key",
"=",
"data",
".",
"get",
"(",
"'exc_path'",
")",
"if",
"key",
"in",
"registry",
":",
"exc_args",
"=",
"data",
".",
"get",
"(",
"'exc_args'",
",",
"(",
")",
")",
"return",
"registry",
"[",
"key",
"... | Deserialize `data` to an exception instance.
If the `exc_path` value matches an exception registered as
``deserializable``, return an instance of that exception type.
Otherwise, return a `RemoteError` instance describing the exception
that occurred. | [
"Deserialize",
"data",
"to",
"an",
"exception",
"instance",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/exceptions.py#L97-L112 | train | 214,214 |
nameko/nameko | nameko/utils/__init__.py | import_from_path | def import_from_path(path):
""" Import and return the object at `path` if it exists.
Raises an :exc:`ImportError` if the object is not found.
"""
if path is None:
return
obj = locate(path)
if obj is None:
raise ImportError(
"`{}` could not be imported".format(path)
)
return obj | python | def import_from_path(path):
""" Import and return the object at `path` if it exists.
Raises an :exc:`ImportError` if the object is not found.
"""
if path is None:
return
obj = locate(path)
if obj is None:
raise ImportError(
"`{}` could not be imported".format(path)
)
return obj | [
"def",
"import_from_path",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"obj",
"=",
"locate",
"(",
"path",
")",
"if",
"obj",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"\"`{}` could not be imported\"",
".",
"format",
"(",
"path",
... | Import and return the object at `path` if it exists.
Raises an :exc:`ImportError` if the object is not found. | [
"Import",
"and",
"return",
"the",
"object",
"at",
"path",
"if",
"it",
"exists",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/utils/__init__.py#L110-L124 | train | 214,215 |
nameko/nameko | nameko/utils/__init__.py | sanitize_url | def sanitize_url(url):
"""Redact password in urls."""
parts = urlparse(url)
if parts.password is None:
return url
host_info = parts.netloc.rsplit('@', 1)[-1]
parts = parts._replace(netloc='{}:{}@{}'.format(
parts.username, REDACTED, host_info))
return parts.geturl() | python | def sanitize_url(url):
"""Redact password in urls."""
parts = urlparse(url)
if parts.password is None:
return url
host_info = parts.netloc.rsplit('@', 1)[-1]
parts = parts._replace(netloc='{}:{}@{}'.format(
parts.username, REDACTED, host_info))
return parts.geturl() | [
"def",
"sanitize_url",
"(",
"url",
")",
":",
"parts",
"=",
"urlparse",
"(",
"url",
")",
"if",
"parts",
".",
"password",
"is",
"None",
":",
"return",
"url",
"host_info",
"=",
"parts",
".",
"netloc",
".",
"rsplit",
"(",
"'@'",
",",
"1",
")",
"[",
"-"... | Redact password in urls. | [
"Redact",
"password",
"in",
"urls",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/utils/__init__.py#L127-L135 | train | 214,216 |
nameko/nameko | nameko/web/websocket.py | WebSocketHub.get_subscriptions | def get_subscriptions(self, socket_id):
"""Returns a list of all the subscriptions of a socket."""
con = self._get_connection(socket_id, create=False)
if con is None:
return []
return sorted(con.subscriptions) | python | def get_subscriptions(self, socket_id):
"""Returns a list of all the subscriptions of a socket."""
con = self._get_connection(socket_id, create=False)
if con is None:
return []
return sorted(con.subscriptions) | [
"def",
"get_subscriptions",
"(",
"self",
",",
"socket_id",
")",
":",
"con",
"=",
"self",
".",
"_get_connection",
"(",
"socket_id",
",",
"create",
"=",
"False",
")",
"if",
"con",
"is",
"None",
":",
"return",
"[",
"]",
"return",
"sorted",
"(",
"con",
"."... | Returns a list of all the subscriptions of a socket. | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"subscriptions",
"of",
"a",
"socket",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L189-L194 | train | 214,217 |
nameko/nameko | nameko/web/websocket.py | WebSocketHub.subscribe | def subscribe(self, socket_id, channel):
"""Subscribes a socket to a channel."""
con = self._get_connection(socket_id)
self.subscriptions.setdefault(channel, set()).add(socket_id)
con.subscriptions.add(channel) | python | def subscribe(self, socket_id, channel):
"""Subscribes a socket to a channel."""
con = self._get_connection(socket_id)
self.subscriptions.setdefault(channel, set()).add(socket_id)
con.subscriptions.add(channel) | [
"def",
"subscribe",
"(",
"self",
",",
"socket_id",
",",
"channel",
")",
":",
"con",
"=",
"self",
".",
"_get_connection",
"(",
"socket_id",
")",
"self",
".",
"subscriptions",
".",
"setdefault",
"(",
"channel",
",",
"set",
"(",
")",
")",
".",
"add",
"(",... | Subscribes a socket to a channel. | [
"Subscribes",
"a",
"socket",
"to",
"a",
"channel",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L196-L200 | train | 214,218 |
nameko/nameko | nameko/web/websocket.py | WebSocketHub.unsubscribe | def unsubscribe(self, socket_id, channel):
"""Unsubscribes a socket from a channel."""
con = self._get_connection(socket_id, create=False)
if con is not None:
con.subscriptions.discard(channel)
try:
self.subscriptions[channel].discard(socket_id)
except KeyError:
pass | python | def unsubscribe(self, socket_id, channel):
"""Unsubscribes a socket from a channel."""
con = self._get_connection(socket_id, create=False)
if con is not None:
con.subscriptions.discard(channel)
try:
self.subscriptions[channel].discard(socket_id)
except KeyError:
pass | [
"def",
"unsubscribe",
"(",
"self",
",",
"socket_id",
",",
"channel",
")",
":",
"con",
"=",
"self",
".",
"_get_connection",
"(",
"socket_id",
",",
"create",
"=",
"False",
")",
"if",
"con",
"is",
"not",
"None",
":",
"con",
".",
"subscriptions",
".",
"dis... | Unsubscribes a socket from a channel. | [
"Unsubscribes",
"a",
"socket",
"from",
"a",
"channel",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L202-L210 | train | 214,219 |
nameko/nameko | nameko/web/websocket.py | WebSocketHub.broadcast | def broadcast(self, channel, event, data):
"""Broadcasts an event to all sockets listening on a channel."""
payload = self._server.serialize_event(event, data)
for socket_id in self.subscriptions.get(channel, ()):
rv = self._server.sockets.get(socket_id)
if rv is not None:
rv.socket.send(payload) | python | def broadcast(self, channel, event, data):
"""Broadcasts an event to all sockets listening on a channel."""
payload = self._server.serialize_event(event, data)
for socket_id in self.subscriptions.get(channel, ()):
rv = self._server.sockets.get(socket_id)
if rv is not None:
rv.socket.send(payload) | [
"def",
"broadcast",
"(",
"self",
",",
"channel",
",",
"event",
",",
"data",
")",
":",
"payload",
"=",
"self",
".",
"_server",
".",
"serialize_event",
"(",
"event",
",",
"data",
")",
"for",
"socket_id",
"in",
"self",
".",
"subscriptions",
".",
"get",
"(... | Broadcasts an event to all sockets listening on a channel. | [
"Broadcasts",
"an",
"event",
"to",
"all",
"sockets",
"listening",
"on",
"a",
"channel",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L212-L218 | train | 214,220 |
nameko/nameko | nameko/web/websocket.py | WebSocketHub.unicast | def unicast(self, socket_id, event, data):
"""Sends an event to a single socket. Returns `True` if that
worked or `False` if not.
"""
payload = self._server.serialize_event(event, data)
rv = self._server.sockets.get(socket_id)
if rv is not None:
rv.socket.send(payload)
return True
return False | python | def unicast(self, socket_id, event, data):
"""Sends an event to a single socket. Returns `True` if that
worked or `False` if not.
"""
payload = self._server.serialize_event(event, data)
rv = self._server.sockets.get(socket_id)
if rv is not None:
rv.socket.send(payload)
return True
return False | [
"def",
"unicast",
"(",
"self",
",",
"socket_id",
",",
"event",
",",
"data",
")",
":",
"payload",
"=",
"self",
".",
"_server",
".",
"serialize_event",
"(",
"event",
",",
"data",
")",
"rv",
"=",
"self",
".",
"_server",
".",
"sockets",
".",
"get",
"(",
... | Sends an event to a single socket. Returns `True` if that
worked or `False` if not. | [
"Sends",
"an",
"event",
"to",
"a",
"single",
"socket",
".",
"Returns",
"True",
"if",
"that",
"worked",
"or",
"False",
"if",
"not",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L220-L229 | train | 214,221 |
nameko/nameko | nameko/log_helpers.py | make_timing_logger | def make_timing_logger(logger, precision=3, level=logging.DEBUG):
""" Return a timing logger.
Usage::
>>> logger = logging.getLogger('foobar')
>>> log_time = make_timing_logger(
... logger, level=logging.INFO, precision=2)
>>>
>>> with log_time("hello %s", "world"):
... time.sleep(1)
INFO:foobar:hello world in 1.00s
"""
@contextmanager
def log_time(msg, *args):
""" Log `msg` and `*args` with (naive wallclock) timing information
when the context block exits.
"""
start_time = time.time()
try:
yield
finally:
message = "{} in %0.{}fs".format(msg, precision)
duration = time.time() - start_time
args = args + (duration,)
logger.log(level, message, *args)
return log_time | python | def make_timing_logger(logger, precision=3, level=logging.DEBUG):
""" Return a timing logger.
Usage::
>>> logger = logging.getLogger('foobar')
>>> log_time = make_timing_logger(
... logger, level=logging.INFO, precision=2)
>>>
>>> with log_time("hello %s", "world"):
... time.sleep(1)
INFO:foobar:hello world in 1.00s
"""
@contextmanager
def log_time(msg, *args):
""" Log `msg` and `*args` with (naive wallclock) timing information
when the context block exits.
"""
start_time = time.time()
try:
yield
finally:
message = "{} in %0.{}fs".format(msg, precision)
duration = time.time() - start_time
args = args + (duration,)
logger.log(level, message, *args)
return log_time | [
"def",
"make_timing_logger",
"(",
"logger",
",",
"precision",
"=",
"3",
",",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"@",
"contextmanager",
"def",
"log_time",
"(",
"msg",
",",
"*",
"args",
")",
":",
"\"\"\" Log `msg` and `*args` with (naive wallclock) t... | Return a timing logger.
Usage::
>>> logger = logging.getLogger('foobar')
>>> log_time = make_timing_logger(
... logger, level=logging.INFO, precision=2)
>>>
>>> with log_time("hello %s", "world"):
... time.sleep(1)
INFO:foobar:hello world in 1.00s | [
"Return",
"a",
"timing",
"logger",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/log_helpers.py#L8-L36 | train | 214,222 |
nameko/nameko | nameko/web/server.py | WebServer.get_wsgi_server | def get_wsgi_server(
self, sock, wsgi_app, protocol=HttpOnlyProtocol, debug=False
):
"""Get the WSGI server used to process requests."""
return wsgi.Server(
sock,
sock.getsockname(),
wsgi_app,
protocol=protocol,
debug=debug,
log=getLogger(__name__)
) | python | def get_wsgi_server(
self, sock, wsgi_app, protocol=HttpOnlyProtocol, debug=False
):
"""Get the WSGI server used to process requests."""
return wsgi.Server(
sock,
sock.getsockname(),
wsgi_app,
protocol=protocol,
debug=debug,
log=getLogger(__name__)
) | [
"def",
"get_wsgi_server",
"(",
"self",
",",
"sock",
",",
"wsgi_app",
",",
"protocol",
"=",
"HttpOnlyProtocol",
",",
"debug",
"=",
"False",
")",
":",
"return",
"wsgi",
".",
"Server",
"(",
"sock",
",",
"sock",
".",
"getsockname",
"(",
")",
",",
"wsgi_app",... | Get the WSGI server used to process requests. | [
"Get",
"the",
"WSGI",
"server",
"used",
"to",
"process",
"requests",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/server.py#L125-L136 | train | 214,223 |
nameko/nameko | nameko/standalone/events.py | get_event_exchange | def get_event_exchange(service_name):
""" Get an exchange for ``service_name`` events.
"""
exchange_name = "{}.events".format(service_name)
exchange = Exchange(
exchange_name, type='topic', durable=True, delivery_mode=PERSISTENT
)
return exchange | python | def get_event_exchange(service_name):
""" Get an exchange for ``service_name`` events.
"""
exchange_name = "{}.events".format(service_name)
exchange = Exchange(
exchange_name, type='topic', durable=True, delivery_mode=PERSISTENT
)
return exchange | [
"def",
"get_event_exchange",
"(",
"service_name",
")",
":",
"exchange_name",
"=",
"\"{}.events\"",
".",
"format",
"(",
"service_name",
")",
"exchange",
"=",
"Exchange",
"(",
"exchange_name",
",",
"type",
"=",
"'topic'",
",",
"durable",
"=",
"True",
",",
"deliv... | Get an exchange for ``service_name`` events. | [
"Get",
"an",
"exchange",
"for",
"service_name",
"events",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/standalone/events.py#L10-L18 | train | 214,224 |
nameko/nameko | nameko/standalone/events.py | event_dispatcher | def event_dispatcher(nameko_config, **kwargs):
""" Return a function that dispatches nameko events.
"""
amqp_uri = nameko_config[AMQP_URI_CONFIG_KEY]
serializer, _ = serialization.setup(nameko_config)
serializer = kwargs.pop('serializer', serializer)
ssl = nameko_config.get(AMQP_SSL_CONFIG_KEY)
# TODO: standalone event dispatcher should accept context event_data
# and insert a call id
publisher = Publisher(amqp_uri, serializer=serializer, ssl=ssl, **kwargs)
def dispatch(service_name, event_type, event_data):
""" Dispatch an event claiming to originate from `service_name` with
the given `event_type` and `event_data`.
"""
exchange = get_event_exchange(service_name)
publisher.publish(
event_data,
exchange=exchange,
routing_key=event_type
)
return dispatch | python | def event_dispatcher(nameko_config, **kwargs):
""" Return a function that dispatches nameko events.
"""
amqp_uri = nameko_config[AMQP_URI_CONFIG_KEY]
serializer, _ = serialization.setup(nameko_config)
serializer = kwargs.pop('serializer', serializer)
ssl = nameko_config.get(AMQP_SSL_CONFIG_KEY)
# TODO: standalone event dispatcher should accept context event_data
# and insert a call id
publisher = Publisher(amqp_uri, serializer=serializer, ssl=ssl, **kwargs)
def dispatch(service_name, event_type, event_data):
""" Dispatch an event claiming to originate from `service_name` with
the given `event_type` and `event_data`.
"""
exchange = get_event_exchange(service_name)
publisher.publish(
event_data,
exchange=exchange,
routing_key=event_type
)
return dispatch | [
"def",
"event_dispatcher",
"(",
"nameko_config",
",",
"*",
"*",
"kwargs",
")",
":",
"amqp_uri",
"=",
"nameko_config",
"[",
"AMQP_URI_CONFIG_KEY",
"]",
"serializer",
",",
"_",
"=",
"serialization",
".",
"setup",
"(",
"nameko_config",
")",
"serializer",
"=",
"kw... | Return a function that dispatches nameko events. | [
"Return",
"a",
"function",
"that",
"dispatches",
"nameko",
"events",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/standalone/events.py#L21-L48 | train | 214,225 |
nameko/nameko | nameko/timer.py | Timer._run | def _run(self):
""" Runs the interval loop. """
def get_next_interval():
start_time = time.time()
start = 0 if self.eager else 1
for count in itertools.count(start=start):
yield max(start_time + count * self.interval - time.time(), 0)
interval = get_next_interval()
sleep_time = next(interval)
while True:
# sleep for `sleep_time`, unless `should_stop` fires, in which
# case we leave the while loop and stop entirely
with Timeout(sleep_time, exception=False):
self.should_stop.wait()
break
self.handle_timer_tick()
self.worker_complete.wait()
self.worker_complete.reset()
sleep_time = next(interval) | python | def _run(self):
""" Runs the interval loop. """
def get_next_interval():
start_time = time.time()
start = 0 if self.eager else 1
for count in itertools.count(start=start):
yield max(start_time + count * self.interval - time.time(), 0)
interval = get_next_interval()
sleep_time = next(interval)
while True:
# sleep for `sleep_time`, unless `should_stop` fires, in which
# case we leave the while loop and stop entirely
with Timeout(sleep_time, exception=False):
self.should_stop.wait()
break
self.handle_timer_tick()
self.worker_complete.wait()
self.worker_complete.reset()
sleep_time = next(interval) | [
"def",
"_run",
"(",
"self",
")",
":",
"def",
"get_next_interval",
"(",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"start",
"=",
"0",
"if",
"self",
".",
"eager",
"else",
"1",
"for",
"count",
"in",
"itertools",
".",
"count",
"(",
"st... | Runs the interval loop. | [
"Runs",
"the",
"interval",
"loop",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/timer.py#L58-L80 | train | 214,226 |
nameko/nameko | nameko/messaging.py | QueueConsumer.stop | def stop(self):
""" Stop the queue-consumer gracefully.
Wait until the last provider has been unregistered and for
the ConsumerMixin's greenthread to exit (i.e. until all pending
messages have been acked or requeued and all consumers stopped).
"""
if not self._consumers_ready.ready():
_log.debug('stopping while consumer is starting %s', self)
stop_exc = QueueConsumerStopped()
# stopping before we have started successfully by brutally
# killing the consumer thread as we don't have a way to hook
# into the pre-consumption startup process
self._gt.kill(stop_exc)
self.wait_for_providers()
try:
_log.debug('waiting for consumer death %s', self)
self._gt.wait()
except QueueConsumerStopped:
pass
super(QueueConsumer, self).stop()
_log.debug('stopped %s', self) | python | def stop(self):
""" Stop the queue-consumer gracefully.
Wait until the last provider has been unregistered and for
the ConsumerMixin's greenthread to exit (i.e. until all pending
messages have been acked or requeued and all consumers stopped).
"""
if not self._consumers_ready.ready():
_log.debug('stopping while consumer is starting %s', self)
stop_exc = QueueConsumerStopped()
# stopping before we have started successfully by brutally
# killing the consumer thread as we don't have a way to hook
# into the pre-consumption startup process
self._gt.kill(stop_exc)
self.wait_for_providers()
try:
_log.debug('waiting for consumer death %s', self)
self._gt.wait()
except QueueConsumerStopped:
pass
super(QueueConsumer, self).stop()
_log.debug('stopped %s', self) | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_consumers_ready",
".",
"ready",
"(",
")",
":",
"_log",
".",
"debug",
"(",
"'stopping while consumer is starting %s'",
",",
"self",
")",
"stop_exc",
"=",
"QueueConsumerStopped",
"(",
")",
"# st... | Stop the queue-consumer gracefully.
Wait until the last provider has been unregistered and for
the ConsumerMixin's greenthread to exit (i.e. until all pending
messages have been acked or requeued and all consumers stopped). | [
"Stop",
"the",
"queue",
"-",
"consumer",
"gracefully",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L240-L266 | train | 214,227 |
nameko/nameko | nameko/messaging.py | QueueConsumer.kill | def kill(self):
""" Kill the queue-consumer.
Unlike `stop()` any pending message ack or requeue-requests,
requests to remove providers, etc are lost and the consume thread is
asked to terminate as soon as possible.
"""
# greenlet has a magic attribute ``dead`` - pylint: disable=E1101
if self._gt is not None and not self._gt.dead:
# we can't just kill the thread because we have to give
# ConsumerMixin a chance to close the sockets properly.
self._providers = set()
self._pending_remove_providers = {}
self.should_stop = True
try:
self._gt.wait()
except Exception as exc:
# discard the exception since we're already being killed
_log.warn(
'QueueConsumer %s raised `%s` during kill', self, exc)
super(QueueConsumer, self).kill()
_log.debug('killed %s', self) | python | def kill(self):
""" Kill the queue-consumer.
Unlike `stop()` any pending message ack or requeue-requests,
requests to remove providers, etc are lost and the consume thread is
asked to terminate as soon as possible.
"""
# greenlet has a magic attribute ``dead`` - pylint: disable=E1101
if self._gt is not None and not self._gt.dead:
# we can't just kill the thread because we have to give
# ConsumerMixin a chance to close the sockets properly.
self._providers = set()
self._pending_remove_providers = {}
self.should_stop = True
try:
self._gt.wait()
except Exception as exc:
# discard the exception since we're already being killed
_log.warn(
'QueueConsumer %s raised `%s` during kill', self, exc)
super(QueueConsumer, self).kill()
_log.debug('killed %s', self) | [
"def",
"kill",
"(",
"self",
")",
":",
"# greenlet has a magic attribute ``dead`` - pylint: disable=E1101",
"if",
"self",
".",
"_gt",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"_gt",
".",
"dead",
":",
"# we can't just kill the thread because we have to give",
"# Co... | Kill the queue-consumer.
Unlike `stop()` any pending message ack or requeue-requests,
requests to remove providers, etc are lost and the consume thread is
asked to terminate as soon as possible. | [
"Kill",
"the",
"queue",
"-",
"consumer",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L268-L290 | train | 214,228 |
nameko/nameko | nameko/messaging.py | QueueConsumer.connection | def connection(self):
""" Provide the connection parameters for kombu's ConsumerMixin.
The `Connection` object is a declaration of connection parameters
that is lazily evaluated. It doesn't represent an established
connection to the broker at this point.
"""
heartbeat = self.container.config.get(
HEARTBEAT_CONFIG_KEY, DEFAULT_HEARTBEAT
)
transport_options = self.container.config.get(
TRANSPORT_OPTIONS_CONFIG_KEY, DEFAULT_TRANSPORT_OPTIONS
)
ssl = self.container.config.get(AMQP_SSL_CONFIG_KEY)
conn = Connection(self.amqp_uri,
transport_options=transport_options,
heartbeat=heartbeat,
ssl=ssl
)
return conn | python | def connection(self):
""" Provide the connection parameters for kombu's ConsumerMixin.
The `Connection` object is a declaration of connection parameters
that is lazily evaluated. It doesn't represent an established
connection to the broker at this point.
"""
heartbeat = self.container.config.get(
HEARTBEAT_CONFIG_KEY, DEFAULT_HEARTBEAT
)
transport_options = self.container.config.get(
TRANSPORT_OPTIONS_CONFIG_KEY, DEFAULT_TRANSPORT_OPTIONS
)
ssl = self.container.config.get(AMQP_SSL_CONFIG_KEY)
conn = Connection(self.amqp_uri,
transport_options=transport_options,
heartbeat=heartbeat,
ssl=ssl
)
return conn | [
"def",
"connection",
"(",
"self",
")",
":",
"heartbeat",
"=",
"self",
".",
"container",
".",
"config",
".",
"get",
"(",
"HEARTBEAT_CONFIG_KEY",
",",
"DEFAULT_HEARTBEAT",
")",
"transport_options",
"=",
"self",
".",
"container",
".",
"config",
".",
"get",
"(",... | Provide the connection parameters for kombu's ConsumerMixin.
The `Connection` object is a declaration of connection parameters
that is lazily evaluated. It doesn't represent an established
connection to the broker at this point. | [
"Provide",
"the",
"connection",
"parameters",
"for",
"kombu",
"s",
"ConsumerMixin",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L339-L359 | train | 214,229 |
nameko/nameko | nameko/messaging.py | QueueConsumer.get_consumers | def get_consumers(self, consumer_cls, channel):
""" Kombu callback to set up consumers.
Called after any (re)connection to the broker.
"""
_log.debug('setting up consumers %s', self)
for provider in self._providers:
callbacks = [partial(self.handle_message, provider)]
consumer = consumer_cls(
queues=[provider.queue],
callbacks=callbacks,
accept=self.accept
)
consumer.qos(prefetch_count=self.prefetch_count)
self._consumers[provider] = consumer
return self._consumers.values() | python | def get_consumers(self, consumer_cls, channel):
""" Kombu callback to set up consumers.
Called after any (re)connection to the broker.
"""
_log.debug('setting up consumers %s', self)
for provider in self._providers:
callbacks = [partial(self.handle_message, provider)]
consumer = consumer_cls(
queues=[provider.queue],
callbacks=callbacks,
accept=self.accept
)
consumer.qos(prefetch_count=self.prefetch_count)
self._consumers[provider] = consumer
return self._consumers.values() | [
"def",
"get_consumers",
"(",
"self",
",",
"consumer_cls",
",",
"channel",
")",
":",
"_log",
".",
"debug",
"(",
"'setting up consumers %s'",
",",
"self",
")",
"for",
"provider",
"in",
"self",
".",
"_providers",
":",
"callbacks",
"=",
"[",
"partial",
"(",
"s... | Kombu callback to set up consumers.
Called after any (re)connection to the broker. | [
"Kombu",
"callback",
"to",
"set",
"up",
"consumers",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L369-L388 | train | 214,230 |
nameko/nameko | nameko/messaging.py | QueueConsumer.on_iteration | def on_iteration(self):
""" Kombu callback for each `drain_events` loop iteration."""
self._cancel_consumers_if_requested()
if len(self._consumers) == 0:
_log.debug('requesting stop after iteration')
self.should_stop = True | python | def on_iteration(self):
""" Kombu callback for each `drain_events` loop iteration."""
self._cancel_consumers_if_requested()
if len(self._consumers) == 0:
_log.debug('requesting stop after iteration')
self.should_stop = True | [
"def",
"on_iteration",
"(",
"self",
")",
":",
"self",
".",
"_cancel_consumers_if_requested",
"(",
")",
"if",
"len",
"(",
"self",
".",
"_consumers",
")",
"==",
"0",
":",
"_log",
".",
"debug",
"(",
"'requesting stop after iteration'",
")",
"self",
".",
"should... | Kombu callback for each `drain_events` loop iteration. | [
"Kombu",
"callback",
"for",
"each",
"drain_events",
"loop",
"iteration",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L390-L396 | train | 214,231 |
nameko/nameko | nameko/messaging.py | QueueConsumer.on_consume_ready | def on_consume_ready(self, connection, channel, consumers, **kwargs):
""" Kombu callback when consumers are ready to accept messages.
Called after any (re)connection to the broker.
"""
if not self._consumers_ready.ready():
_log.debug('consumer started %s', self)
self._consumers_ready.send(None) | python | def on_consume_ready(self, connection, channel, consumers, **kwargs):
""" Kombu callback when consumers are ready to accept messages.
Called after any (re)connection to the broker.
"""
if not self._consumers_ready.ready():
_log.debug('consumer started %s', self)
self._consumers_ready.send(None) | [
"def",
"on_consume_ready",
"(",
"self",
",",
"connection",
",",
"channel",
",",
"consumers",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_consumers_ready",
".",
"ready",
"(",
")",
":",
"_log",
".",
"debug",
"(",
"'consumer started %s'",
... | Kombu callback when consumers are ready to accept messages.
Called after any (re)connection to the broker. | [
"Kombu",
"callback",
"when",
"consumers",
"are",
"ready",
"to",
"accept",
"messages",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L404-L411 | train | 214,232 |
nameko/nameko | nameko/cli/shell.py | make_nameko_helper | def make_nameko_helper(config):
"""Create a fake module that provides some convenient access to nameko
standalone functionality for interactive shell usage.
"""
module = ModuleType('nameko')
module.__doc__ = """Nameko shell helper for making rpc calls and dispatching
events.
Usage:
>>> n.rpc.service.method()
"reply"
>>> n.dispatch_event('service', 'event_type', 'event_data')
"""
proxy = ClusterRpcProxy(config)
module.rpc = proxy.start()
module.dispatch_event = event_dispatcher(config)
module.config = config
module.disconnect = proxy.stop
return module | python | def make_nameko_helper(config):
"""Create a fake module that provides some convenient access to nameko
standalone functionality for interactive shell usage.
"""
module = ModuleType('nameko')
module.__doc__ = """Nameko shell helper for making rpc calls and dispatching
events.
Usage:
>>> n.rpc.service.method()
"reply"
>>> n.dispatch_event('service', 'event_type', 'event_data')
"""
proxy = ClusterRpcProxy(config)
module.rpc = proxy.start()
module.dispatch_event = event_dispatcher(config)
module.config = config
module.disconnect = proxy.stop
return module | [
"def",
"make_nameko_helper",
"(",
"config",
")",
":",
"module",
"=",
"ModuleType",
"(",
"'nameko'",
")",
"module",
".",
"__doc__",
"=",
"\"\"\"Nameko shell helper for making rpc calls and dispatching\nevents.\n\nUsage:\n >>> n.rpc.service.method()\n \"reply\"\n\n >>> n.dispa... | Create a fake module that provides some convenient access to nameko
standalone functionality for interactive shell usage. | [
"Create",
"a",
"fake",
"module",
"that",
"provides",
"some",
"convenient",
"access",
"to",
"nameko",
"standalone",
"functionality",
"for",
"interactive",
"shell",
"usage",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/cli/shell.py#L58-L77 | train | 214,233 |
nameko/nameko | nameko/extensions.py | iter_extensions | def iter_extensions(extension):
""" Depth-first iterator over sub-extensions on `extension`.
"""
for _, ext in inspect.getmembers(extension, is_extension):
for item in iter_extensions(ext):
yield item
yield ext | python | def iter_extensions(extension):
""" Depth-first iterator over sub-extensions on `extension`.
"""
for _, ext in inspect.getmembers(extension, is_extension):
for item in iter_extensions(ext):
yield item
yield ext | [
"def",
"iter_extensions",
"(",
"extension",
")",
":",
"for",
"_",
",",
"ext",
"in",
"inspect",
".",
"getmembers",
"(",
"extension",
",",
"is_extension",
")",
":",
"for",
"item",
"in",
"iter_extensions",
"(",
"ext",
")",
":",
"yield",
"item",
"yield",
"ex... | Depth-first iterator over sub-extensions on `extension`. | [
"Depth",
"-",
"first",
"iterator",
"over",
"sub",
"-",
"extensions",
"on",
"extension",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L354-L360 | train | 214,234 |
nameko/nameko | nameko/extensions.py | Extension.bind | def bind(self, container):
""" Get an instance of this Extension to bind to `container`.
"""
def clone(prototype):
if prototype.is_bound():
raise RuntimeError('Cannot `bind` a bound extension.')
cls = type(prototype)
args, kwargs = prototype.__params
instance = cls(*args, **kwargs)
# instance.container must be a weakref to avoid a strong reference
# from value to key in the `shared_extensions` weakkey dict
# see test_extension_sharing.py: test_weakref
instance.container = weakref.proxy(container)
return instance
instance = clone(self)
# recurse over sub-extensions
for name, ext in inspect.getmembers(self, is_extension):
setattr(instance, name, ext.bind(container))
return instance | python | def bind(self, container):
""" Get an instance of this Extension to bind to `container`.
"""
def clone(prototype):
if prototype.is_bound():
raise RuntimeError('Cannot `bind` a bound extension.')
cls = type(prototype)
args, kwargs = prototype.__params
instance = cls(*args, **kwargs)
# instance.container must be a weakref to avoid a strong reference
# from value to key in the `shared_extensions` weakkey dict
# see test_extension_sharing.py: test_weakref
instance.container = weakref.proxy(container)
return instance
instance = clone(self)
# recurse over sub-extensions
for name, ext in inspect.getmembers(self, is_extension):
setattr(instance, name, ext.bind(container))
return instance | [
"def",
"bind",
"(",
"self",
",",
"container",
")",
":",
"def",
"clone",
"(",
"prototype",
")",
":",
"if",
"prototype",
".",
"is_bound",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'Cannot `bind` a bound extension.'",
")",
"cls",
"=",
"type",
"(",
"protot... | Get an instance of this Extension to bind to `container`. | [
"Get",
"an",
"instance",
"of",
"this",
"Extension",
"to",
"bind",
"to",
"container",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L81-L103 | train | 214,235 |
nameko/nameko | nameko/extensions.py | SharedExtension.bind | def bind(self, container):
""" Bind implementation that supports sharing.
"""
# if there's already a matching bound instance, return that
shared = container.shared_extensions.get(self.sharing_key)
if shared:
return shared
instance = super(SharedExtension, self).bind(container)
# save the new instance
container.shared_extensions[self.sharing_key] = instance
return instance | python | def bind(self, container):
""" Bind implementation that supports sharing.
"""
# if there's already a matching bound instance, return that
shared = container.shared_extensions.get(self.sharing_key)
if shared:
return shared
instance = super(SharedExtension, self).bind(container)
# save the new instance
container.shared_extensions[self.sharing_key] = instance
return instance | [
"def",
"bind",
"(",
"self",
",",
"container",
")",
":",
"# if there's already a matching bound instance, return that",
"shared",
"=",
"container",
".",
"shared_extensions",
".",
"get",
"(",
"self",
".",
"sharing_key",
")",
"if",
"shared",
":",
"return",
"shared",
... | Bind implementation that supports sharing. | [
"Bind",
"implementation",
"that",
"supports",
"sharing",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L123-L136 | train | 214,236 |
nameko/nameko | nameko/extensions.py | DependencyProvider.bind | def bind(self, container, attr_name):
""" Get an instance of this Dependency to bind to `container` with
`attr_name`.
"""
instance = super(DependencyProvider, self).bind(container)
instance.attr_name = attr_name
self.attr_name = attr_name
return instance | python | def bind(self, container, attr_name):
""" Get an instance of this Dependency to bind to `container` with
`attr_name`.
"""
instance = super(DependencyProvider, self).bind(container)
instance.attr_name = attr_name
self.attr_name = attr_name
return instance | [
"def",
"bind",
"(",
"self",
",",
"container",
",",
"attr_name",
")",
":",
"instance",
"=",
"super",
"(",
"DependencyProvider",
",",
"self",
")",
".",
"bind",
"(",
"container",
")",
"instance",
".",
"attr_name",
"=",
"attr_name",
"self",
".",
"attr_name",
... | Get an instance of this Dependency to bind to `container` with
`attr_name`. | [
"Get",
"an",
"instance",
"of",
"this",
"Dependency",
"to",
"bind",
"to",
"container",
"with",
"attr_name",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L143-L150 | train | 214,237 |
nameko/nameko | nameko/extensions.py | ProviderCollector.wait_for_providers | def wait_for_providers(self):
""" Wait for any providers registered with the collector to have
unregistered.
Returns immediately if no providers were ever registered.
"""
if self._providers_registered:
_log.debug('waiting for providers to unregister %s', self)
self._last_provider_unregistered.wait()
_log.debug('all providers unregistered %s', self) | python | def wait_for_providers(self):
""" Wait for any providers registered with the collector to have
unregistered.
Returns immediately if no providers were ever registered.
"""
if self._providers_registered:
_log.debug('waiting for providers to unregister %s', self)
self._last_provider_unregistered.wait()
_log.debug('all providers unregistered %s', self) | [
"def",
"wait_for_providers",
"(",
"self",
")",
":",
"if",
"self",
".",
"_providers_registered",
":",
"_log",
".",
"debug",
"(",
"'waiting for providers to unregister %s'",
",",
"self",
")",
"self",
".",
"_last_provider_unregistered",
".",
"wait",
"(",
")",
"_log",... | Wait for any providers registered with the collector to have
unregistered.
Returns immediately if no providers were ever registered. | [
"Wait",
"for",
"any",
"providers",
"registered",
"with",
"the",
"collector",
"to",
"have",
"unregistered",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L231-L240 | train | 214,238 |
nameko/nameko | nameko/extensions.py | Entrypoint.bind | def bind(self, container, method_name):
""" Get an instance of this Entrypoint to bind to `container` with
`method_name`.
"""
instance = super(Entrypoint, self).bind(container)
instance.method_name = method_name
return instance | python | def bind(self, container, method_name):
""" Get an instance of this Entrypoint to bind to `container` with
`method_name`.
"""
instance = super(Entrypoint, self).bind(container)
instance.method_name = method_name
return instance | [
"def",
"bind",
"(",
"self",
",",
"container",
",",
"method_name",
")",
":",
"instance",
"=",
"super",
"(",
"Entrypoint",
",",
"self",
")",
".",
"bind",
"(",
"container",
")",
"instance",
".",
"method_name",
"=",
"method_name",
"return",
"instance"
] | Get an instance of this Entrypoint to bind to `container` with
`method_name`. | [
"Get",
"an",
"instance",
"of",
"this",
"Entrypoint",
"to",
"bind",
"to",
"container",
"with",
"method_name",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L294-L300 | train | 214,239 |
nameko/nameko | nameko/containers.py | ServiceContainer.start | def start(self):
""" Start a container by starting all of its extensions.
"""
_log.debug('starting %s', self)
self.started = True
with _log_time('started %s', self):
self.extensions.all.setup()
self.extensions.all.start() | python | def start(self):
""" Start a container by starting all of its extensions.
"""
_log.debug('starting %s', self)
self.started = True
with _log_time('started %s', self):
self.extensions.all.setup()
self.extensions.all.start() | [
"def",
"start",
"(",
"self",
")",
":",
"_log",
".",
"debug",
"(",
"'starting %s'",
",",
"self",
")",
"self",
".",
"started",
"=",
"True",
"with",
"_log_time",
"(",
"'started %s'",
",",
"self",
")",
":",
"self",
".",
"extensions",
".",
"all",
".",
"se... | Start a container by starting all of its extensions. | [
"Start",
"a",
"container",
"by",
"starting",
"all",
"of",
"its",
"extensions",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L182-L190 | train | 214,240 |
nameko/nameko | nameko/containers.py | ServiceContainer.stop | def stop(self):
""" Stop the container gracefully.
First all entrypoints are asked to ``stop()``.
This ensures that no new worker threads are started.
It is the extensions' responsibility to gracefully shut down when
``stop()`` is called on them and only return when they have stopped.
After all entrypoints have stopped the container waits for any
active workers to complete.
After all active workers have stopped the container stops all
dependency providers.
At this point there should be no more managed threads. In case there
are any managed threads, they are killed by the container.
"""
if self._died.ready():
_log.debug('already stopped %s', self)
return
if self._being_killed:
# this race condition can happen when a container is hosted by a
# runner and yields during its kill method; if it's unlucky in
# scheduling the runner will try to stop() it before self._died
# has a result
_log.debug('already being killed %s', self)
try:
self._died.wait()
except:
pass # don't re-raise if we died with an exception
return
_log.debug('stopping %s', self)
with _log_time('stopped %s', self):
# entrypoint have to be stopped before dependencies to ensure
# that running workers can successfully complete
self.entrypoints.all.stop()
# there might still be some running workers, which we have to
# wait for to complete before we can stop dependencies
self._worker_pool.waitall()
# it should be safe now to stop any dependency as there is no
# active worker which could be using it
self.dependencies.all.stop()
# finally, stop remaining extensions
self.subextensions.all.stop()
# any any managed threads they spawned
self._kill_managed_threads()
self.started = False
# if `kill` is called after `stop`, they race to send this
if not self._died.ready():
self._died.send(None) | python | def stop(self):
""" Stop the container gracefully.
First all entrypoints are asked to ``stop()``.
This ensures that no new worker threads are started.
It is the extensions' responsibility to gracefully shut down when
``stop()`` is called on them and only return when they have stopped.
After all entrypoints have stopped the container waits for any
active workers to complete.
After all active workers have stopped the container stops all
dependency providers.
At this point there should be no more managed threads. In case there
are any managed threads, they are killed by the container.
"""
if self._died.ready():
_log.debug('already stopped %s', self)
return
if self._being_killed:
# this race condition can happen when a container is hosted by a
# runner and yields during its kill method; if it's unlucky in
# scheduling the runner will try to stop() it before self._died
# has a result
_log.debug('already being killed %s', self)
try:
self._died.wait()
except:
pass # don't re-raise if we died with an exception
return
_log.debug('stopping %s', self)
with _log_time('stopped %s', self):
# entrypoint have to be stopped before dependencies to ensure
# that running workers can successfully complete
self.entrypoints.all.stop()
# there might still be some running workers, which we have to
# wait for to complete before we can stop dependencies
self._worker_pool.waitall()
# it should be safe now to stop any dependency as there is no
# active worker which could be using it
self.dependencies.all.stop()
# finally, stop remaining extensions
self.subextensions.all.stop()
# any any managed threads they spawned
self._kill_managed_threads()
self.started = False
# if `kill` is called after `stop`, they race to send this
if not self._died.ready():
self._died.send(None) | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_died",
".",
"ready",
"(",
")",
":",
"_log",
".",
"debug",
"(",
"'already stopped %s'",
",",
"self",
")",
"return",
"if",
"self",
".",
"_being_killed",
":",
"# this race condition can happen when a co... | Stop the container gracefully.
First all entrypoints are asked to ``stop()``.
This ensures that no new worker threads are started.
It is the extensions' responsibility to gracefully shut down when
``stop()`` is called on them and only return when they have stopped.
After all entrypoints have stopped the container waits for any
active workers to complete.
After all active workers have stopped the container stops all
dependency providers.
At this point there should be no more managed threads. In case there
are any managed threads, they are killed by the container. | [
"Stop",
"the",
"container",
"gracefully",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L192-L252 | train | 214,241 |
nameko/nameko | nameko/containers.py | ServiceContainer.kill | def kill(self, exc_info=None):
""" Kill the container in a semi-graceful way.
Entrypoints are killed, followed by any active worker threads.
Next, dependencies are killed. Finally, any remaining managed threads
are killed.
If ``exc_info`` is provided, the exception will be raised by
:meth:`~wait``.
"""
if self._being_killed:
# this happens if a managed thread exits with an exception
# while the container is being killed or if multiple errors
# happen simultaneously
_log.debug('already killing %s ... waiting for death', self)
try:
self._died.wait()
except:
pass # don't re-raise if we died with an exception
return
self._being_killed = True
if self._died.ready():
_log.debug('already stopped %s', self)
return
if exc_info is not None:
_log.info('killing %s due to %s', self, exc_info[1])
else:
_log.info('killing %s', self)
# protect against extensions that throw during kill; the container
# is already dying with an exception, so ignore anything else
def safely_kill_extensions(ext_set):
try:
ext_set.kill()
except Exception as exc:
_log.warning('Extension raised `%s` during kill', exc)
safely_kill_extensions(self.entrypoints.all)
self._kill_worker_threads()
safely_kill_extensions(self.extensions.all)
self._kill_managed_threads()
self.started = False
# if `kill` is called after `stop`, they race to send this
if not self._died.ready():
self._died.send(None, exc_info) | python | def kill(self, exc_info=None):
""" Kill the container in a semi-graceful way.
Entrypoints are killed, followed by any active worker threads.
Next, dependencies are killed. Finally, any remaining managed threads
are killed.
If ``exc_info`` is provided, the exception will be raised by
:meth:`~wait``.
"""
if self._being_killed:
# this happens if a managed thread exits with an exception
# while the container is being killed or if multiple errors
# happen simultaneously
_log.debug('already killing %s ... waiting for death', self)
try:
self._died.wait()
except:
pass # don't re-raise if we died with an exception
return
self._being_killed = True
if self._died.ready():
_log.debug('already stopped %s', self)
return
if exc_info is not None:
_log.info('killing %s due to %s', self, exc_info[1])
else:
_log.info('killing %s', self)
# protect against extensions that throw during kill; the container
# is already dying with an exception, so ignore anything else
def safely_kill_extensions(ext_set):
try:
ext_set.kill()
except Exception as exc:
_log.warning('Extension raised `%s` during kill', exc)
safely_kill_extensions(self.entrypoints.all)
self._kill_worker_threads()
safely_kill_extensions(self.extensions.all)
self._kill_managed_threads()
self.started = False
# if `kill` is called after `stop`, they race to send this
if not self._died.ready():
self._died.send(None, exc_info) | [
"def",
"kill",
"(",
"self",
",",
"exc_info",
"=",
"None",
")",
":",
"if",
"self",
".",
"_being_killed",
":",
"# this happens if a managed thread exits with an exception",
"# while the container is being killed or if multiple errors",
"# happen simultaneously",
"_log",
".",
"d... | Kill the container in a semi-graceful way.
Entrypoints are killed, followed by any active worker threads.
Next, dependencies are killed. Finally, any remaining managed threads
are killed.
If ``exc_info`` is provided, the exception will be raised by
:meth:`~wait``. | [
"Kill",
"the",
"container",
"in",
"a",
"semi",
"-",
"graceful",
"way",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L254-L303 | train | 214,242 |
nameko/nameko | nameko/containers.py | ServiceContainer.spawn_worker | def spawn_worker(self, entrypoint, args, kwargs,
context_data=None, handle_result=None):
""" Spawn a worker thread for running the service method decorated
by `entrypoint`.
``args`` and ``kwargs`` are used as parameters for the service method.
``context_data`` is used to initialize a ``WorkerContext``.
``handle_result`` is an optional function which may be passed
in by the entrypoint. It is called with the result returned
or error raised by the service method. If provided it must return a
value for ``result`` and ``exc_info`` to propagate to dependencies;
these may be different to those returned by the service method.
"""
if self._being_killed:
_log.info("Worker spawn prevented due to being killed")
raise ContainerBeingKilled()
service = self.service_cls()
worker_ctx = WorkerContext(
self, service, entrypoint, args, kwargs, data=context_data
)
_log.debug('spawning %s', worker_ctx)
gt = self._worker_pool.spawn(
self._run_worker, worker_ctx, handle_result
)
gt.link(self._handle_worker_thread_exited, worker_ctx)
self._worker_threads[worker_ctx] = gt
return worker_ctx | python | def spawn_worker(self, entrypoint, args, kwargs,
context_data=None, handle_result=None):
""" Spawn a worker thread for running the service method decorated
by `entrypoint`.
``args`` and ``kwargs`` are used as parameters for the service method.
``context_data`` is used to initialize a ``WorkerContext``.
``handle_result`` is an optional function which may be passed
in by the entrypoint. It is called with the result returned
or error raised by the service method. If provided it must return a
value for ``result`` and ``exc_info`` to propagate to dependencies;
these may be different to those returned by the service method.
"""
if self._being_killed:
_log.info("Worker spawn prevented due to being killed")
raise ContainerBeingKilled()
service = self.service_cls()
worker_ctx = WorkerContext(
self, service, entrypoint, args, kwargs, data=context_data
)
_log.debug('spawning %s', worker_ctx)
gt = self._worker_pool.spawn(
self._run_worker, worker_ctx, handle_result
)
gt.link(self._handle_worker_thread_exited, worker_ctx)
self._worker_threads[worker_ctx] = gt
return worker_ctx | [
"def",
"spawn_worker",
"(",
"self",
",",
"entrypoint",
",",
"args",
",",
"kwargs",
",",
"context_data",
"=",
"None",
",",
"handle_result",
"=",
"None",
")",
":",
"if",
"self",
".",
"_being_killed",
":",
"_log",
".",
"info",
"(",
"\"Worker spawn prevented due... | Spawn a worker thread for running the service method decorated
by `entrypoint`.
``args`` and ``kwargs`` are used as parameters for the service method.
``context_data`` is used to initialize a ``WorkerContext``.
``handle_result`` is an optional function which may be passed
in by the entrypoint. It is called with the result returned
or error raised by the service method. If provided it must return a
value for ``result`` and ``exc_info`` to propagate to dependencies;
these may be different to those returned by the service method. | [
"Spawn",
"a",
"worker",
"thread",
"for",
"running",
"the",
"service",
"method",
"decorated",
"by",
"entrypoint",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L318-L350 | train | 214,243 |
nameko/nameko | nameko/containers.py | ServiceContainer._kill_worker_threads | def _kill_worker_threads(self):
""" Kill any currently executing worker threads.
See :meth:`ServiceContainer.spawn_worker`
"""
num_workers = len(self._worker_threads)
if num_workers:
_log.warning('killing %s active workers(s)', num_workers)
for worker_ctx, gt in list(self._worker_threads.items()):
_log.warning('killing active worker for %s', worker_ctx)
gt.kill() | python | def _kill_worker_threads(self):
""" Kill any currently executing worker threads.
See :meth:`ServiceContainer.spawn_worker`
"""
num_workers = len(self._worker_threads)
if num_workers:
_log.warning('killing %s active workers(s)', num_workers)
for worker_ctx, gt in list(self._worker_threads.items()):
_log.warning('killing active worker for %s', worker_ctx)
gt.kill() | [
"def",
"_kill_worker_threads",
"(",
"self",
")",
":",
"num_workers",
"=",
"len",
"(",
"self",
".",
"_worker_threads",
")",
"if",
"num_workers",
":",
"_log",
".",
"warning",
"(",
"'killing %s active workers(s)'",
",",
"num_workers",
")",
"for",
"worker_ctx",
",",... | Kill any currently executing worker threads.
See :meth:`ServiceContainer.spawn_worker` | [
"Kill",
"any",
"currently",
"executing",
"worker",
"threads",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L439-L450 | train | 214,244 |
nameko/nameko | nameko/containers.py | ServiceContainer._kill_managed_threads | def _kill_managed_threads(self):
""" Kill any currently executing managed threads.
See :meth:`ServiceContainer.spawn_managed_thread`
"""
num_threads = len(self._managed_threads)
if num_threads:
_log.warning('killing %s managed thread(s)', num_threads)
for gt, identifier in list(self._managed_threads.items()):
_log.warning('killing managed thread `%s`', identifier)
gt.kill() | python | def _kill_managed_threads(self):
""" Kill any currently executing managed threads.
See :meth:`ServiceContainer.spawn_managed_thread`
"""
num_threads = len(self._managed_threads)
if num_threads:
_log.warning('killing %s managed thread(s)', num_threads)
for gt, identifier in list(self._managed_threads.items()):
_log.warning('killing managed thread `%s`', identifier)
gt.kill() | [
"def",
"_kill_managed_threads",
"(",
"self",
")",
":",
"num_threads",
"=",
"len",
"(",
"self",
".",
"_managed_threads",
")",
"if",
"num_threads",
":",
"_log",
".",
"warning",
"(",
"'killing %s managed thread(s)'",
",",
"num_threads",
")",
"for",
"gt",
",",
"id... | Kill any currently executing managed threads.
See :meth:`ServiceContainer.spawn_managed_thread` | [
"Kill",
"any",
"currently",
"executing",
"managed",
"threads",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L452-L463 | train | 214,245 |
nameko/nameko | nameko/standalone/rpc.py | ConsumeEvent.wait | def wait(self):
""" Makes a blocking call to its queue_consumer until the message
with the given correlation_id has been processed.
By the time the blocking call exits, self.send() will have been called
with the body of the received message
(see :meth:`~nameko.rpc.ReplyListener.handle_message`).
Exceptions are raised directly.
"""
# disconnected before starting to wait
if self.exception:
raise self.exception
if self.queue_consumer.stopped:
raise RuntimeError(
"This consumer has been stopped, and can no longer be used"
)
if self.queue_consumer.connection.connected is False:
# we can't just reconnect here. the consumer (and its exclusive,
# auto-delete reply queue) must be re-established _before_ sending
# any request, otherwise the reply queue may not exist when the
# response is published.
raise RuntimeError(
"This consumer has been disconnected, and can no longer "
"be used"
)
try:
self.queue_consumer.get_message(self.correlation_id)
except socket.error as exc:
self.exception = exc
# disconnected while waiting
if self.exception:
raise self.exception
return self.body | python | def wait(self):
""" Makes a blocking call to its queue_consumer until the message
with the given correlation_id has been processed.
By the time the blocking call exits, self.send() will have been called
with the body of the received message
(see :meth:`~nameko.rpc.ReplyListener.handle_message`).
Exceptions are raised directly.
"""
# disconnected before starting to wait
if self.exception:
raise self.exception
if self.queue_consumer.stopped:
raise RuntimeError(
"This consumer has been stopped, and can no longer be used"
)
if self.queue_consumer.connection.connected is False:
# we can't just reconnect here. the consumer (and its exclusive,
# auto-delete reply queue) must be re-established _before_ sending
# any request, otherwise the reply queue may not exist when the
# response is published.
raise RuntimeError(
"This consumer has been disconnected, and can no longer "
"be used"
)
try:
self.queue_consumer.get_message(self.correlation_id)
except socket.error as exc:
self.exception = exc
# disconnected while waiting
if self.exception:
raise self.exception
return self.body | [
"def",
"wait",
"(",
"self",
")",
":",
"# disconnected before starting to wait",
"if",
"self",
".",
"exception",
":",
"raise",
"self",
".",
"exception",
"if",
"self",
".",
"queue_consumer",
".",
"stopped",
":",
"raise",
"RuntimeError",
"(",
"\"This consumer has bee... | Makes a blocking call to its queue_consumer until the message
with the given correlation_id has been processed.
By the time the blocking call exits, self.send() will have been called
with the body of the received message
(see :meth:`~nameko.rpc.ReplyListener.handle_message`).
Exceptions are raised directly. | [
"Makes",
"a",
"blocking",
"call",
"to",
"its",
"queue_consumer",
"until",
"the",
"message",
"with",
"the",
"given",
"correlation_id",
"has",
"been",
"processed",
"."
] | 88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/standalone/rpc.py#L37-L73 | train | 214,246 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | StatefulBrowser.select_form | def select_form(self, selector="form", nr=0):
"""Select a form in the current page.
:param selector: CSS selector or a bs4.element.Tag object to identify
the form to select.
If not specified, ``selector`` defaults to "form", which is
useful if, e.g., there is only one form on the page.
For ``selector`` syntax, see the `.select() method in BeautifulSoup
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors>`__.
:param nr: A zero-based index specifying which form among those that
match ``selector`` will be selected. Useful when one or more forms
have the same attributes as the form you want to select, and its
position on the page is the only way to uniquely identify it.
Default is the first matching form (``nr=0``).
:return: The selected form as a soup object. It can also be
retrieved later with :func:`get_current_form`.
"""
if isinstance(selector, bs4.element.Tag):
if selector.name != "form":
raise LinkNotFoundError
self.__state.form = Form(selector)
else:
# nr is a 0-based index for consistency with mechanize
found_forms = self.get_current_page().select(selector,
limit=nr + 1)
if len(found_forms) != nr + 1:
if self.__debug:
print('select_form failed for', selector)
self.launch_browser()
raise LinkNotFoundError()
self.__state.form = Form(found_forms[-1])
return self.get_current_form() | python | def select_form(self, selector="form", nr=0):
"""Select a form in the current page.
:param selector: CSS selector or a bs4.element.Tag object to identify
the form to select.
If not specified, ``selector`` defaults to "form", which is
useful if, e.g., there is only one form on the page.
For ``selector`` syntax, see the `.select() method in BeautifulSoup
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors>`__.
:param nr: A zero-based index specifying which form among those that
match ``selector`` will be selected. Useful when one or more forms
have the same attributes as the form you want to select, and its
position on the page is the only way to uniquely identify it.
Default is the first matching form (``nr=0``).
:return: The selected form as a soup object. It can also be
retrieved later with :func:`get_current_form`.
"""
if isinstance(selector, bs4.element.Tag):
if selector.name != "form":
raise LinkNotFoundError
self.__state.form = Form(selector)
else:
# nr is a 0-based index for consistency with mechanize
found_forms = self.get_current_page().select(selector,
limit=nr + 1)
if len(found_forms) != nr + 1:
if self.__debug:
print('select_form failed for', selector)
self.launch_browser()
raise LinkNotFoundError()
self.__state.form = Form(found_forms[-1])
return self.get_current_form() | [
"def",
"select_form",
"(",
"self",
",",
"selector",
"=",
"\"form\"",
",",
"nr",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"selector",
",",
"bs4",
".",
"element",
".",
"Tag",
")",
":",
"if",
"selector",
".",
"name",
"!=",
"\"form\"",
":",
"raise",
... | Select a form in the current page.
:param selector: CSS selector or a bs4.element.Tag object to identify
the form to select.
If not specified, ``selector`` defaults to "form", which is
useful if, e.g., there is only one form on the page.
For ``selector`` syntax, see the `.select() method in BeautifulSoup
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors>`__.
:param nr: A zero-based index specifying which form among those that
match ``selector`` will be selected. Useful when one or more forms
have the same attributes as the form you want to select, and its
position on the page is the only way to uniquely identify it.
Default is the first matching form (``nr=0``).
:return: The selected form as a soup object. It can also be
retrieved later with :func:`get_current_form`. | [
"Select",
"a",
"form",
"in",
"the",
"current",
"page",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/stateful_browser.py#L177-L210 | train | 214,247 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | StatefulBrowser.links | def links(self, url_regex=None, link_text=None, *args, **kwargs):
"""Return links in the page, as a list of bs4.element.Tag objects.
To return links matching specific criteria, specify ``url_regex``
to match the *href*-attribute, or ``link_text`` to match the
*text*-attribute of the Tag. All other arguments are forwarded to
the `.find_all() method in BeautifulSoup
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all>`__.
"""
all_links = self.get_current_page().find_all(
'a', href=True, *args, **kwargs)
if url_regex is not None:
all_links = [a for a in all_links
if re.search(url_regex, a['href'])]
if link_text is not None:
all_links = [a for a in all_links
if a.text == link_text]
return all_links | python | def links(self, url_regex=None, link_text=None, *args, **kwargs):
"""Return links in the page, as a list of bs4.element.Tag objects.
To return links matching specific criteria, specify ``url_regex``
to match the *href*-attribute, or ``link_text`` to match the
*text*-attribute of the Tag. All other arguments are forwarded to
the `.find_all() method in BeautifulSoup
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all>`__.
"""
all_links = self.get_current_page().find_all(
'a', href=True, *args, **kwargs)
if url_regex is not None:
all_links = [a for a in all_links
if re.search(url_regex, a['href'])]
if link_text is not None:
all_links = [a for a in all_links
if a.text == link_text]
return all_links | [
"def",
"links",
"(",
"self",
",",
"url_regex",
"=",
"None",
",",
"link_text",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"all_links",
"=",
"self",
".",
"get_current_page",
"(",
")",
".",
"find_all",
"(",
"'a'",
",",
"href",
"... | Return links in the page, as a list of bs4.element.Tag objects.
To return links matching specific criteria, specify ``url_regex``
to match the *href*-attribute, or ``link_text`` to match the
*text*-attribute of the Tag. All other arguments are forwarded to
the `.find_all() method in BeautifulSoup
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all>`__. | [
"Return",
"links",
"in",
"the",
"page",
"as",
"a",
"list",
"of",
"bs4",
".",
"element",
".",
"Tag",
"objects",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/stateful_browser.py#L249-L266 | train | 214,248 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | StatefulBrowser.find_link | def find_link(self, *args, **kwargs):
"""Find and return a link, as a bs4.element.Tag object.
The search can be refined by specifying any argument that is accepted
by :func:`links`. If several links match, return the first one found.
If no link is found, raise :class:`LinkNotFoundError`.
"""
links = self.links(*args, **kwargs)
if len(links) == 0:
raise LinkNotFoundError()
else:
return links[0] | python | def find_link(self, *args, **kwargs):
"""Find and return a link, as a bs4.element.Tag object.
The search can be refined by specifying any argument that is accepted
by :func:`links`. If several links match, return the first one found.
If no link is found, raise :class:`LinkNotFoundError`.
"""
links = self.links(*args, **kwargs)
if len(links) == 0:
raise LinkNotFoundError()
else:
return links[0] | [
"def",
"find_link",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"links",
"=",
"self",
".",
"links",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"links",
")",
"==",
"0",
":",
"raise",
"LinkNotFoundError"... | Find and return a link, as a bs4.element.Tag object.
The search can be refined by specifying any argument that is accepted
by :func:`links`. If several links match, return the first one found.
If no link is found, raise :class:`LinkNotFoundError`. | [
"Find",
"and",
"return",
"a",
"link",
"as",
"a",
"bs4",
".",
"element",
".",
"Tag",
"object",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/stateful_browser.py#L268-L280 | train | 214,249 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | StatefulBrowser.follow_link | def follow_link(self, link=None, *args, **kwargs):
"""Follow a link.
If ``link`` is a bs4.element.Tag (i.e. from a previous call to
:func:`links` or :func:`find_link`), then follow the link.
If ``link`` doesn't have a *href*-attribute or is None, treat
``link`` as a url_regex and look it up with :func:`find_link`.
Any additional arguments specified are forwarded to this function.
If the link is not found, raise :class:`LinkNotFoundError`.
Before raising, if debug is activated, list available links in the
page and launch a browser.
:return: Forwarded from :func:`open_relative`.
"""
link = self._find_link_internal(link, args, kwargs)
referer = self.get_url()
headers = {'Referer': referer} if referer else None
return self.open_relative(link['href'], headers=headers) | python | def follow_link(self, link=None, *args, **kwargs):
"""Follow a link.
If ``link`` is a bs4.element.Tag (i.e. from a previous call to
:func:`links` or :func:`find_link`), then follow the link.
If ``link`` doesn't have a *href*-attribute or is None, treat
``link`` as a url_regex and look it up with :func:`find_link`.
Any additional arguments specified are forwarded to this function.
If the link is not found, raise :class:`LinkNotFoundError`.
Before raising, if debug is activated, list available links in the
page and launch a browser.
:return: Forwarded from :func:`open_relative`.
"""
link = self._find_link_internal(link, args, kwargs)
referer = self.get_url()
headers = {'Referer': referer} if referer else None
return self.open_relative(link['href'], headers=headers) | [
"def",
"follow_link",
"(",
"self",
",",
"link",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"link",
"=",
"self",
".",
"_find_link_internal",
"(",
"link",
",",
"args",
",",
"kwargs",
")",
"referer",
"=",
"self",
".",
"get_url",
... | Follow a link.
If ``link`` is a bs4.element.Tag (i.e. from a previous call to
:func:`links` or :func:`find_link`), then follow the link.
If ``link`` doesn't have a *href*-attribute or is None, treat
``link`` as a url_regex and look it up with :func:`find_link`.
Any additional arguments specified are forwarded to this function.
If the link is not found, raise :class:`LinkNotFoundError`.
Before raising, if debug is activated, list available links in the
page and launch a browser.
:return: Forwarded from :func:`open_relative`. | [
"Follow",
"a",
"link",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/stateful_browser.py#L312-L333 | train | 214,250 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/form.py | Form.set_input | def set_input(self, data):
"""Fill-in a set of fields in a form.
Example: filling-in a login/password form
.. code-block:: python
form.set_input({"login": username, "password": password})
This will find the input element named "login" and give it the
value ``username``, and the input element named "password" and
give it the value ``password``.
"""
for (name, value) in data.items():
i = self.form.find("input", {"name": name})
if not i:
raise InvalidFormMethod("No input field named " + name)
i["value"] = value | python | def set_input(self, data):
"""Fill-in a set of fields in a form.
Example: filling-in a login/password form
.. code-block:: python
form.set_input({"login": username, "password": password})
This will find the input element named "login" and give it the
value ``username``, and the input element named "password" and
give it the value ``password``.
"""
for (name, value) in data.items():
i = self.form.find("input", {"name": name})
if not i:
raise InvalidFormMethod("No input field named " + name)
i["value"] = value | [
"def",
"set_input",
"(",
"self",
",",
"data",
")",
":",
"for",
"(",
"name",
",",
"value",
")",
"in",
"data",
".",
"items",
"(",
")",
":",
"i",
"=",
"self",
".",
"form",
".",
"find",
"(",
"\"input\"",
",",
"{",
"\"name\"",
":",
"name",
"}",
")",... | Fill-in a set of fields in a form.
Example: filling-in a login/password form
.. code-block:: python
form.set_input({"login": username, "password": password})
This will find the input element named "login" and give it the
value ``username``, and the input element named "password" and
give it the value ``password``. | [
"Fill",
"-",
"in",
"a",
"set",
"of",
"fields",
"in",
"a",
"form",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/form.py#L52-L70 | train | 214,251 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/form.py | Form.new_control | def new_control(self, type, name, value, **kwargs):
"""Add a new input element to the form.
The arguments set the attributes of the new element.
"""
old_input = self.form.find_all('input', {'name': name})
for old in old_input:
old.decompose()
old_textarea = self.form.find_all('textarea', {'name': name})
for old in old_textarea:
old.decompose()
# We don't have access to the original soup object (just the
# Tag), so we instantiate a new BeautifulSoup() to call
# new_tag(). We're only building the soup object, not parsing
# anything, so the parser doesn't matter. Specify the one
# included in Python to avoid having dependency issue.
control = BeautifulSoup("", "html.parser").new_tag('input')
control['type'] = type
control['name'] = name
control['value'] = value
for k, v in kwargs.items():
control[k] = v
self.form.append(control)
return control | python | def new_control(self, type, name, value, **kwargs):
"""Add a new input element to the form.
The arguments set the attributes of the new element.
"""
old_input = self.form.find_all('input', {'name': name})
for old in old_input:
old.decompose()
old_textarea = self.form.find_all('textarea', {'name': name})
for old in old_textarea:
old.decompose()
# We don't have access to the original soup object (just the
# Tag), so we instantiate a new BeautifulSoup() to call
# new_tag(). We're only building the soup object, not parsing
# anything, so the parser doesn't matter. Specify the one
# included in Python to avoid having dependency issue.
control = BeautifulSoup("", "html.parser").new_tag('input')
control['type'] = type
control['name'] = name
control['value'] = value
for k, v in kwargs.items():
control[k] = v
self.form.append(control)
return control | [
"def",
"new_control",
"(",
"self",
",",
"type",
",",
"name",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"old_input",
"=",
"self",
".",
"form",
".",
"find_all",
"(",
"'input'",
",",
"{",
"'name'",
":",
"name",
"}",
")",
"for",
"old",
"in",
"... | Add a new input element to the form.
The arguments set the attributes of the new element. | [
"Add",
"a",
"new",
"input",
"element",
"to",
"the",
"form",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/form.py#L280-L303 | train | 214,252 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/form.py | Form.print_summary | def print_summary(self):
"""Print a summary of the form.
May help finding which fields need to be filled-in.
"""
for input in self.form.find_all(
("input", "textarea", "select", "button")):
input_copy = copy.copy(input)
# Text between the opening tag and the closing tag often
# contains a lot of spaces that we don't want here.
for subtag in input_copy.find_all() + [input_copy]:
if subtag.string:
subtag.string = subtag.string.strip()
print(input_copy) | python | def print_summary(self):
"""Print a summary of the form.
May help finding which fields need to be filled-in.
"""
for input in self.form.find_all(
("input", "textarea", "select", "button")):
input_copy = copy.copy(input)
# Text between the opening tag and the closing tag often
# contains a lot of spaces that we don't want here.
for subtag in input_copy.find_all() + [input_copy]:
if subtag.string:
subtag.string = subtag.string.strip()
print(input_copy) | [
"def",
"print_summary",
"(",
"self",
")",
":",
"for",
"input",
"in",
"self",
".",
"form",
".",
"find_all",
"(",
"(",
"\"input\"",
",",
"\"textarea\"",
",",
"\"select\"",
",",
"\"button\"",
")",
")",
":",
"input_copy",
"=",
"copy",
".",
"copy",
"(",
"in... | Print a summary of the form.
May help finding which fields need to be filled-in. | [
"Print",
"a",
"summary",
"of",
"the",
"form",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/form.py#L370-L383 | train | 214,253 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/browser.py | Browser.__looks_like_html | def __looks_like_html(response):
"""Guesses entity type when Content-Type header is missing.
Since Content-Type is not strictly required, some servers leave it out.
"""
text = response.text.lstrip().lower()
return text.startswith('<html') or text.startswith('<!doctype') | python | def __looks_like_html(response):
"""Guesses entity type when Content-Type header is missing.
Since Content-Type is not strictly required, some servers leave it out.
"""
text = response.text.lstrip().lower()
return text.startswith('<html') or text.startswith('<!doctype') | [
"def",
"__looks_like_html",
"(",
"response",
")",
":",
"text",
"=",
"response",
".",
"text",
".",
"lstrip",
"(",
")",
".",
"lower",
"(",
")",
"return",
"text",
".",
"startswith",
"(",
"'<html'",
")",
"or",
"text",
".",
"startswith",
"(",
"'<!doctype'",
... | Guesses entity type when Content-Type header is missing.
Since Content-Type is not strictly required, some servers leave it out. | [
"Guesses",
"entity",
"type",
"when",
"Content",
"-",
"Type",
"header",
"is",
"missing",
".",
"Since",
"Content",
"-",
"Type",
"is",
"not",
"strictly",
"required",
"some",
"servers",
"leave",
"it",
"out",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L58-L63 | train | 214,254 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/browser.py | Browser.add_soup | def add_soup(response, soup_config):
"""Attaches a soup object to a requests response."""
if ("text/html" in response.headers.get("Content-Type", "") or
Browser.__looks_like_html(response)):
response.soup = bs4.BeautifulSoup(response.content, **soup_config)
else:
response.soup = None | python | def add_soup(response, soup_config):
"""Attaches a soup object to a requests response."""
if ("text/html" in response.headers.get("Content-Type", "") or
Browser.__looks_like_html(response)):
response.soup = bs4.BeautifulSoup(response.content, **soup_config)
else:
response.soup = None | [
"def",
"add_soup",
"(",
"response",
",",
"soup_config",
")",
":",
"if",
"(",
"\"text/html\"",
"in",
"response",
".",
"headers",
".",
"get",
"(",
"\"Content-Type\"",
",",
"\"\"",
")",
"or",
"Browser",
".",
"__looks_like_html",
"(",
"response",
")",
")",
":"... | Attaches a soup object to a requests response. | [
"Attaches",
"a",
"soup",
"object",
"to",
"a",
"requests",
"response",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L66-L72 | train | 214,255 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/browser.py | Browser.set_user_agent | def set_user_agent(self, user_agent):
"""Replaces the current user agent in the requests session headers."""
# set a default user_agent if not specified
if user_agent is None:
requests_ua = requests.utils.default_user_agent()
user_agent = '%s (%s/%s)' % (requests_ua, __title__, __version__)
# the requests module uses a case-insensitive dict for session headers
self.session.headers['User-agent'] = user_agent | python | def set_user_agent(self, user_agent):
"""Replaces the current user agent in the requests session headers."""
# set a default user_agent if not specified
if user_agent is None:
requests_ua = requests.utils.default_user_agent()
user_agent = '%s (%s/%s)' % (requests_ua, __title__, __version__)
# the requests module uses a case-insensitive dict for session headers
self.session.headers['User-agent'] = user_agent | [
"def",
"set_user_agent",
"(",
"self",
",",
"user_agent",
")",
":",
"# set a default user_agent if not specified",
"if",
"user_agent",
"is",
"None",
":",
"requests_ua",
"=",
"requests",
".",
"utils",
".",
"default_user_agent",
"(",
")",
"user_agent",
"=",
"'%s (%s/%s... | Replaces the current user agent in the requests session headers. | [
"Replaces",
"the",
"current",
"user",
"agent",
"in",
"the",
"requests",
"session",
"headers",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L89-L97 | train | 214,256 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/browser.py | Browser._request | def _request(self, form, url=None, **kwargs):
"""Extract input data from the form to pass to a Requests session."""
method = str(form.get("method", "get"))
action = form.get("action")
url = urllib.parse.urljoin(url, action)
if url is None: # This happens when both `action` and `url` are None.
raise ValueError('no URL to submit to')
# read https://www.w3.org/TR/html52/sec-forms.html
data = kwargs.pop("data", dict())
files = kwargs.pop("files", dict())
# Use a list of 2-tuples to better reflect the behavior of browser QSL.
# Requests also retains order when encoding form data in 2-tuple lists.
data = [(k, v) for k, v in data.items()]
# Process form tags in the order that they appear on the page,
# skipping those tags that do not have a name-attribute.
selector = ",".join("{}[name]".format(i) for i in
("input", "button", "textarea", "select"))
for tag in form.select(selector):
name = tag.get("name") # name-attribute of tag
# Skip disabled elements, since they should not be submitted.
if tag.has_attr('disabled'):
continue
if tag.name == "input":
if tag.get("type", "").lower() in ("radio", "checkbox"):
if "checked" not in tag.attrs:
continue
value = tag.get("value", "on")
else:
# browsers use empty string for inputs with missing values
value = tag.get("value", "")
if tag.get("type", "").lower() == "file":
# read http://www.cs.tut.fi/~jkorpela/forms/file.html
# in browsers, file upload only happens if the form
# (or submit button) enctype attribute is set to
# "multipart/form-data". We don't care, simplify.
filename = value
if filename != "" and isinstance(filename, string_types):
content = open(filename, "rb")
else:
content = ""
# If value is the empty string, we still pass it for
# consistency with browsers (see #250).
files[name] = (filename, content)
else:
data.append((name, value))
elif tag.name == "button":
if tag.get("type", "").lower() in ("button", "reset"):
continue
else:
data.append((name, tag.get("value", "")))
elif tag.name == "textarea":
data.append((name, tag.text))
elif tag.name == "select":
# If the value attribute is not specified, the content will
# be passed as a value instead.
options = tag.select("option")
selected_values = [i.get("value", i.text) for i in options
if "selected" in i.attrs]
if "multiple" in tag.attrs:
for value in selected_values:
data.append((name, value))
elif selected_values:
# A standard select element only allows one option to be
# selected, but browsers pick last if somehow multiple.
data.append((name, selected_values[-1]))
elif options:
# Selects the first option if none are selected
first_value = options[0].get("value", options[0].text)
data.append((name, first_value))
if method.lower() == "get":
kwargs["params"] = data
else:
kwargs["data"] = data
return self.session.request(method, url, files=files, **kwargs) | python | def _request(self, form, url=None, **kwargs):
"""Extract input data from the form to pass to a Requests session."""
method = str(form.get("method", "get"))
action = form.get("action")
url = urllib.parse.urljoin(url, action)
if url is None: # This happens when both `action` and `url` are None.
raise ValueError('no URL to submit to')
# read https://www.w3.org/TR/html52/sec-forms.html
data = kwargs.pop("data", dict())
files = kwargs.pop("files", dict())
# Use a list of 2-tuples to better reflect the behavior of browser QSL.
# Requests also retains order when encoding form data in 2-tuple lists.
data = [(k, v) for k, v in data.items()]
# Process form tags in the order that they appear on the page,
# skipping those tags that do not have a name-attribute.
selector = ",".join("{}[name]".format(i) for i in
("input", "button", "textarea", "select"))
for tag in form.select(selector):
name = tag.get("name") # name-attribute of tag
# Skip disabled elements, since they should not be submitted.
if tag.has_attr('disabled'):
continue
if tag.name == "input":
if tag.get("type", "").lower() in ("radio", "checkbox"):
if "checked" not in tag.attrs:
continue
value = tag.get("value", "on")
else:
# browsers use empty string for inputs with missing values
value = tag.get("value", "")
if tag.get("type", "").lower() == "file":
# read http://www.cs.tut.fi/~jkorpela/forms/file.html
# in browsers, file upload only happens if the form
# (or submit button) enctype attribute is set to
# "multipart/form-data". We don't care, simplify.
filename = value
if filename != "" and isinstance(filename, string_types):
content = open(filename, "rb")
else:
content = ""
# If value is the empty string, we still pass it for
# consistency with browsers (see #250).
files[name] = (filename, content)
else:
data.append((name, value))
elif tag.name == "button":
if tag.get("type", "").lower() in ("button", "reset"):
continue
else:
data.append((name, tag.get("value", "")))
elif tag.name == "textarea":
data.append((name, tag.text))
elif tag.name == "select":
# If the value attribute is not specified, the content will
# be passed as a value instead.
options = tag.select("option")
selected_values = [i.get("value", i.text) for i in options
if "selected" in i.attrs]
if "multiple" in tag.attrs:
for value in selected_values:
data.append((name, value))
elif selected_values:
# A standard select element only allows one option to be
# selected, but browsers pick last if somehow multiple.
data.append((name, selected_values[-1]))
elif options:
# Selects the first option if none are selected
first_value = options[0].get("value", options[0].text)
data.append((name, first_value))
if method.lower() == "get":
kwargs["params"] = data
else:
kwargs["data"] = data
return self.session.request(method, url, files=files, **kwargs) | [
"def",
"_request",
"(",
"self",
",",
"form",
",",
"url",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"method",
"=",
"str",
"(",
"form",
".",
"get",
"(",
"\"method\"",
",",
"\"get\"",
")",
")",
"action",
"=",
"form",
".",
"get",
"(",
"\"action... | Extract input data from the form to pass to a Requests session. | [
"Extract",
"input",
"data",
"from",
"the",
"form",
"to",
"pass",
"to",
"a",
"Requests",
"session",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L142-L226 | train | 214,257 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/browser.py | Browser.submit | def submit(self, form, url=None, **kwargs):
"""Prepares and sends a form request.
NOTE: To submit a form with a :class:`StatefulBrowser` instance, it is
recommended to use :func:`StatefulBrowser.submit_selected` instead of
this method so that the browser state is correctly updated.
:param form: The filled-out form.
:param url: URL of the page the form is on. If the form action is a
relative path, then this must be specified.
:param \\*\\*kwargs: Arguments forwarded to `requests.Session.request
<http://docs.python-requests.org/en/master/api/#requests.Session.request>`__.
:return: `requests.Response
<http://docs.python-requests.org/en/master/api/#requests.Response>`__
object with a *soup*-attribute added by :func:`add_soup`.
"""
if isinstance(form, Form):
form = form.form
response = self._request(form, url, **kwargs)
Browser.add_soup(response, self.soup_config)
return response | python | def submit(self, form, url=None, **kwargs):
"""Prepares and sends a form request.
NOTE: To submit a form with a :class:`StatefulBrowser` instance, it is
recommended to use :func:`StatefulBrowser.submit_selected` instead of
this method so that the browser state is correctly updated.
:param form: The filled-out form.
:param url: URL of the page the form is on. If the form action is a
relative path, then this must be specified.
:param \\*\\*kwargs: Arguments forwarded to `requests.Session.request
<http://docs.python-requests.org/en/master/api/#requests.Session.request>`__.
:return: `requests.Response
<http://docs.python-requests.org/en/master/api/#requests.Response>`__
object with a *soup*-attribute added by :func:`add_soup`.
"""
if isinstance(form, Form):
form = form.form
response = self._request(form, url, **kwargs)
Browser.add_soup(response, self.soup_config)
return response | [
"def",
"submit",
"(",
"self",
",",
"form",
",",
"url",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"form",
",",
"Form",
")",
":",
"form",
"=",
"form",
".",
"form",
"response",
"=",
"self",
".",
"_request",
"(",
"form"... | Prepares and sends a form request.
NOTE: To submit a form with a :class:`StatefulBrowser` instance, it is
recommended to use :func:`StatefulBrowser.submit_selected` instead of
this method so that the browser state is correctly updated.
:param form: The filled-out form.
:param url: URL of the page the form is on. If the form action is a
relative path, then this must be specified.
:param \\*\\*kwargs: Arguments forwarded to `requests.Session.request
<http://docs.python-requests.org/en/master/api/#requests.Session.request>`__.
:return: `requests.Response
<http://docs.python-requests.org/en/master/api/#requests.Response>`__
object with a *soup*-attribute added by :func:`add_soup`. | [
"Prepares",
"and",
"sends",
"a",
"form",
"request",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L228-L249 | train | 214,258 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/browser.py | Browser.close | def close(self):
"""Close the current session, if still open."""
if self.session is not None:
self.session.cookies.clear()
self.session.close()
self.session = None | python | def close(self):
"""Close the current session, if still open."""
if self.session is not None:
self.session.cookies.clear()
self.session.close()
self.session = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"session",
"is",
"not",
"None",
":",
"self",
".",
"session",
".",
"cookies",
".",
"clear",
"(",
")",
"self",
".",
"session",
".",
"close",
"(",
")",
"self",
".",
"session",
"=",
"None"
] | Close the current session, if still open. | [
"Close",
"the",
"current",
"session",
"if",
"still",
"open",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L260-L265 | train | 214,259 |
MechanicalSoup/MechanicalSoup | setup.py | requirements_from_file | def requirements_from_file(filename):
"""Parses a pip requirements file into a list."""
return [line.strip() for line in open(filename, 'r')
if line.strip() and not line.strip().startswith('--')] | python | def requirements_from_file(filename):
"""Parses a pip requirements file into a list."""
return [line.strip() for line in open(filename, 'r')
if line.strip() and not line.strip().startswith('--')] | [
"def",
"requirements_from_file",
"(",
"filename",
")",
":",
"return",
"[",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"open",
"(",
"filename",
",",
"'r'",
")",
"if",
"line",
".",
"strip",
"(",
")",
"and",
"not",
"line",
".",
"strip",
"(",
... | Parses a pip requirements file into a list. | [
"Parses",
"a",
"pip",
"requirements",
"file",
"into",
"a",
"list",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/setup.py#L9-L12 | train | 214,260 |
MechanicalSoup/MechanicalSoup | setup.py | read | def read(fname, URL, URLImage):
"""Read the content of a file."""
readme = open(path.join(path.dirname(__file__), fname)).read()
if hasattr(readme, 'decode'):
# In Python 3, turn bytes into str.
readme = readme.decode('utf8')
# turn relative links into absolute ones
readme = re.sub(r'`<([^>]*)>`__',
r'`\1 <' + URL + r"/blob/master/\1>`__",
readme)
readme = re.sub(r"\.\. image:: /", ".. image:: " + URLImage + "/", readme)
return readme | python | def read(fname, URL, URLImage):
"""Read the content of a file."""
readme = open(path.join(path.dirname(__file__), fname)).read()
if hasattr(readme, 'decode'):
# In Python 3, turn bytes into str.
readme = readme.decode('utf8')
# turn relative links into absolute ones
readme = re.sub(r'`<([^>]*)>`__',
r'`\1 <' + URL + r"/blob/master/\1>`__",
readme)
readme = re.sub(r"\.\. image:: /", ".. image:: " + URLImage + "/", readme)
return readme | [
"def",
"read",
"(",
"fname",
",",
"URL",
",",
"URLImage",
")",
":",
"readme",
"=",
"open",
"(",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"fname",
")",
")",
".",
"read",
"(",
")",
"if",
"hasattr",
"(",
"readme",... | Read the content of a file. | [
"Read",
"the",
"content",
"of",
"a",
"file",
"."
] | 027a270febf5bcda6a75db60ea9838d631370f4b | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/setup.py#L15-L27 | train | 214,261 |
DmitryUlyanov/Multicore-TSNE | tsne-embedding.py | imscatter | def imscatter(images, positions):
'''
Creates a scatter plot, where each plot is shown by corresponding image
'''
positions = np.array(positions)
bottoms = positions[:, 1] - np.array([im.shape[1] / 2.0 for im in images])
tops = bottoms + np.array([im.shape[1] for im in images])
lefts = positions[:, 0] - np.array([im.shape[0] / 2.0 for im in images])
rigths = lefts + np.array([im.shape[0] for im in images])
most_bottom = int(np.floor(bottoms.min()))
most_top = int(np.ceil(tops.max()))
most_left = int(np.floor(lefts.min()))
most_right = int(np.ceil(rigths.max()))
scatter_image = np.zeros(
[most_right - most_left, most_top - most_bottom, 3], dtype=imgs[0].dtype)
# shift, now all from zero
positions -= [most_left, most_bottom]
for im, pos in zip(images, positions):
xl = int(pos[0] - im.shape[0] / 2)
xr = xl + im.shape[0]
yb = int(pos[1] - im.shape[1] / 2)
yt = yb + im.shape[1]
scatter_image[xl:xr, yb:yt, :] = im
return scatter_image | python | def imscatter(images, positions):
'''
Creates a scatter plot, where each plot is shown by corresponding image
'''
positions = np.array(positions)
bottoms = positions[:, 1] - np.array([im.shape[1] / 2.0 for im in images])
tops = bottoms + np.array([im.shape[1] for im in images])
lefts = positions[:, 0] - np.array([im.shape[0] / 2.0 for im in images])
rigths = lefts + np.array([im.shape[0] for im in images])
most_bottom = int(np.floor(bottoms.min()))
most_top = int(np.ceil(tops.max()))
most_left = int(np.floor(lefts.min()))
most_right = int(np.ceil(rigths.max()))
scatter_image = np.zeros(
[most_right - most_left, most_top - most_bottom, 3], dtype=imgs[0].dtype)
# shift, now all from zero
positions -= [most_left, most_bottom]
for im, pos in zip(images, positions):
xl = int(pos[0] - im.shape[0] / 2)
xr = xl + im.shape[0]
yb = int(pos[1] - im.shape[1] / 2)
yt = yb + im.shape[1]
scatter_image[xl:xr, yb:yt, :] = im
return scatter_image | [
"def",
"imscatter",
"(",
"images",
",",
"positions",
")",
":",
"positions",
"=",
"np",
".",
"array",
"(",
"positions",
")",
"bottoms",
"=",
"positions",
"[",
":",
",",
"1",
"]",
"-",
"np",
".",
"array",
"(",
"[",
"im",
".",
"shape",
"[",
"1",
"]"... | Creates a scatter plot, where each plot is shown by corresponding image | [
"Creates",
"a",
"scatter",
"plot",
"where",
"each",
"plot",
"is",
"shown",
"by",
"corresponding",
"image"
] | 62dedde52469f3a0aeb22fdd7bce2538f17f77ef | https://github.com/DmitryUlyanov/Multicore-TSNE/blob/62dedde52469f3a0aeb22fdd7bce2538f17f77ef/tsne-embedding.py#L9-L42 | train | 214,262 |
Blueqat/Blueqat | blueqat/opt.py | pauli | def pauli(qubo):
"""
Convert to pauli operators of universal gate model.
Requires blueqat.
"""
from blueqat.pauli import qubo_bit
h = 0.0
assert all(len(q) == len(qubo) for q in qubo)
for i in range(len(qubo)):
h += qubo_bit(i) * qubo[i][i]
for j in range(i + 1, len(qubo)):
h += qubo_bit(i)*qubo_bit(j) * (qubo[i][j] + qubo[j][i])
return h | python | def pauli(qubo):
"""
Convert to pauli operators of universal gate model.
Requires blueqat.
"""
from blueqat.pauli import qubo_bit
h = 0.0
assert all(len(q) == len(qubo) for q in qubo)
for i in range(len(qubo)):
h += qubo_bit(i) * qubo[i][i]
for j in range(i + 1, len(qubo)):
h += qubo_bit(i)*qubo_bit(j) * (qubo[i][j] + qubo[j][i])
return h | [
"def",
"pauli",
"(",
"qubo",
")",
":",
"from",
"blueqat",
".",
"pauli",
"import",
"qubo_bit",
"h",
"=",
"0.0",
"assert",
"all",
"(",
"len",
"(",
"q",
")",
"==",
"len",
"(",
"qubo",
")",
"for",
"q",
"in",
"qubo",
")",
"for",
"i",
"in",
"range",
... | Convert to pauli operators of universal gate model.
Requires blueqat. | [
"Convert",
"to",
"pauli",
"operators",
"of",
"universal",
"gate",
"model",
".",
"Requires",
"blueqat",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/opt.py#L18-L30 | train | 214,263 |
Blueqat/Blueqat | blueqat/opt.py | opt.plot | def plot(self):
"""
Draws energy chart using matplotlib.
"""
import matplotlib.pyplot as plt
plt.plot(self.E)
plt.show() | python | def plot(self):
"""
Draws energy chart using matplotlib.
"""
import matplotlib.pyplot as plt
plt.plot(self.E)
plt.show() | [
"def",
"plot",
"(",
"self",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"plt",
".",
"plot",
"(",
"self",
".",
"E",
")",
"plt",
".",
"show",
"(",
")"
] | Draws energy chart using matplotlib. | [
"Draws",
"energy",
"chart",
"using",
"matplotlib",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/opt.py#L366-L372 | train | 214,264 |
Blueqat/Blueqat | blueqat/opt.py | Opt.run | def run(self,shots=1,targetT=0.02,verbose=False):
"""
Run SA with provided QUBO.
Set qubo attribute in advance of calling this method.
"""
if self.qubo != []:
self.qi()
J = self.reJ()
N = len(J)
itetemp = 100
Rtemp = 0.75
self.E = []
qq = []
for i in range(shots):
T = self.Ts
q = np.random.choice([-1,1],N)
EE = []
EE.append(Ei(q,self.J)+self.ep)
while T>targetT:
x_list = np.random.randint(0, N, itetemp)
for x in x_list:
q2 = np.ones(N)*q[x]
q2[x] = 1
dE = -2*sum(q*q2*J[:,x])
if dE < 0 or np.exp(-dE/T) > np.random.random_sample():
q[x] *= -1
EE.append(Ei(q,self.J)+self.ep)
T *= Rtemp
self.E.append(EE)
qtemp = (np.asarray(q,int)+1)/2
qq.append([int(s) for s in qtemp])
if verbose == True:
print(i,':',[int(s) for s in qtemp])
if shots == 1:
qq = qq[0]
if shots == 1:
self.E = self.E[0]
return qq | python | def run(self,shots=1,targetT=0.02,verbose=False):
"""
Run SA with provided QUBO.
Set qubo attribute in advance of calling this method.
"""
if self.qubo != []:
self.qi()
J = self.reJ()
N = len(J)
itetemp = 100
Rtemp = 0.75
self.E = []
qq = []
for i in range(shots):
T = self.Ts
q = np.random.choice([-1,1],N)
EE = []
EE.append(Ei(q,self.J)+self.ep)
while T>targetT:
x_list = np.random.randint(0, N, itetemp)
for x in x_list:
q2 = np.ones(N)*q[x]
q2[x] = 1
dE = -2*sum(q*q2*J[:,x])
if dE < 0 or np.exp(-dE/T) > np.random.random_sample():
q[x] *= -1
EE.append(Ei(q,self.J)+self.ep)
T *= Rtemp
self.E.append(EE)
qtemp = (np.asarray(q,int)+1)/2
qq.append([int(s) for s in qtemp])
if verbose == True:
print(i,':',[int(s) for s in qtemp])
if shots == 1:
qq = qq[0]
if shots == 1:
self.E = self.E[0]
return qq | [
"def",
"run",
"(",
"self",
",",
"shots",
"=",
"1",
",",
"targetT",
"=",
"0.02",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"self",
".",
"qubo",
"!=",
"[",
"]",
":",
"self",
".",
"qi",
"(",
")",
"J",
"=",
"self",
".",
"reJ",
"(",
")",
"N"... | Run SA with provided QUBO.
Set qubo attribute in advance of calling this method. | [
"Run",
"SA",
"with",
"provided",
"QUBO",
".",
"Set",
"qubo",
"attribute",
"in",
"advance",
"of",
"calling",
"this",
"method",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/opt.py#L554-L594 | train | 214,265 |
Blueqat/Blueqat | blueqat/gate.py | Gate._str_targets | def _str_targets(self):
"""Returns printable string of targets."""
def _slice_to_str(obj):
if isinstance(obj, slice):
start = "" if obj.start is None else str(obj.start.__index__())
stop = "" if obj.stop is None else str(obj.stop.__index__())
if obj.step is None:
return f"{start}:{stop}"
else:
step = str(obj.step.__index__())
return f"{start}:{stop}:{step}"
else:
return obj.__index__()
if isinstance(self.targets, tuple):
return f"[{', '.join(_slice_to_str(idx for idx in self.targets))}]"
else:
return f"[{_slice_to_str(self.targets)}]" | python | def _str_targets(self):
"""Returns printable string of targets."""
def _slice_to_str(obj):
if isinstance(obj, slice):
start = "" if obj.start is None else str(obj.start.__index__())
stop = "" if obj.stop is None else str(obj.stop.__index__())
if obj.step is None:
return f"{start}:{stop}"
else:
step = str(obj.step.__index__())
return f"{start}:{stop}:{step}"
else:
return obj.__index__()
if isinstance(self.targets, tuple):
return f"[{', '.join(_slice_to_str(idx for idx in self.targets))}]"
else:
return f"[{_slice_to_str(self.targets)}]" | [
"def",
"_str_targets",
"(",
"self",
")",
":",
"def",
"_slice_to_str",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"slice",
")",
":",
"start",
"=",
"\"\"",
"if",
"obj",
".",
"start",
"is",
"None",
"else",
"str",
"(",
"obj",
".",
"star... | Returns printable string of targets. | [
"Returns",
"printable",
"string",
"of",
"targets",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/gate.py#L36-L53 | train | 214,266 |
Blueqat/Blueqat | blueqat/vqe.py | get_scipy_minimizer | def get_scipy_minimizer(**kwargs):
"""Get minimizer which uses `scipy.optimize.minimize`"""
def minimizer(objective, n_params):
params = [random.random() for _ in range(n_params)]
result = scipy_minimizer(objective, params, **kwargs)
return result.x
return minimizer | python | def get_scipy_minimizer(**kwargs):
"""Get minimizer which uses `scipy.optimize.minimize`"""
def minimizer(objective, n_params):
params = [random.random() for _ in range(n_params)]
result = scipy_minimizer(objective, params, **kwargs)
return result.x
return minimizer | [
"def",
"get_scipy_minimizer",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"minimizer",
"(",
"objective",
",",
"n_params",
")",
":",
"params",
"=",
"[",
"random",
".",
"random",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"n_params",
")",
"]",
"result",
"... | Get minimizer which uses `scipy.optimize.minimize` | [
"Get",
"minimizer",
"which",
"uses",
"scipy",
".",
"optimize",
".",
"minimize"
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L158-L164 | train | 214,267 |
Blueqat/Blueqat | blueqat/vqe.py | expect | def expect(qubits, meas):
"For the VQE simulation without sampling."
result = {}
i = np.arange(len(qubits))
meas = tuple(meas)
def to_mask(n):
return reduce(lambda acc, im: acc | (n & (1 << im[0])) << (im[1] - im[0]), enumerate(meas), 0)
def to_key(k):
return tuple(1 if k & (1 << i) else 0 for i in meas)
mask = reduce(lambda acc, v: acc | (1 << v), meas, 0)
cnt = defaultdict(float)
for i, v in enumerate(qubits):
p = v.real ** 2 + v.imag ** 2
if p != 0.0:
cnt[i & mask] += p
return {to_key(k): v for k, v in cnt.items()} | python | def expect(qubits, meas):
"For the VQE simulation without sampling."
result = {}
i = np.arange(len(qubits))
meas = tuple(meas)
def to_mask(n):
return reduce(lambda acc, im: acc | (n & (1 << im[0])) << (im[1] - im[0]), enumerate(meas), 0)
def to_key(k):
return tuple(1 if k & (1 << i) else 0 for i in meas)
mask = reduce(lambda acc, v: acc | (1 << v), meas, 0)
cnt = defaultdict(float)
for i, v in enumerate(qubits):
p = v.real ** 2 + v.imag ** 2
if p != 0.0:
cnt[i & mask] += p
return {to_key(k): v for k, v in cnt.items()} | [
"def",
"expect",
"(",
"qubits",
",",
"meas",
")",
":",
"result",
"=",
"{",
"}",
"i",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"qubits",
")",
")",
"meas",
"=",
"tuple",
"(",
"meas",
")",
"def",
"to_mask",
"(",
"n",
")",
":",
"return",
"reduce"... | For the VQE simulation without sampling. | [
"For",
"the",
"VQE",
"simulation",
"without",
"sampling",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L166-L185 | train | 214,268 |
Blueqat/Blueqat | blueqat/vqe.py | non_sampling_sampler | def non_sampling_sampler(circuit, meas):
"""Calculate the expectations without sampling."""
meas = tuple(meas)
n_qubits = circuit.n_qubits
return expect(circuit.run(returns="statevector"), meas) | python | def non_sampling_sampler(circuit, meas):
"""Calculate the expectations without sampling."""
meas = tuple(meas)
n_qubits = circuit.n_qubits
return expect(circuit.run(returns="statevector"), meas) | [
"def",
"non_sampling_sampler",
"(",
"circuit",
",",
"meas",
")",
":",
"meas",
"=",
"tuple",
"(",
"meas",
")",
"n_qubits",
"=",
"circuit",
".",
"n_qubits",
"return",
"expect",
"(",
"circuit",
".",
"run",
"(",
"returns",
"=",
"\"statevector\"",
")",
",",
"... | Calculate the expectations without sampling. | [
"Calculate",
"the",
"expectations",
"without",
"sampling",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L187-L191 | train | 214,269 |
Blueqat/Blueqat | blueqat/vqe.py | get_measurement_sampler | def get_measurement_sampler(n_sample, run_options=None):
"""Returns a function which get the expectations by sampling the measured circuit"""
if run_options is None:
run_options = {}
def sampling_by_measurement(circuit, meas):
def reduce_bits(bits, meas):
bits = [int(x) for x in bits[::-1]]
return tuple(bits[m] for m in meas)
meas = tuple(meas)
circuit.measure[meas]
counter = circuit.run(shots=n_sample, returns="shots", **run_options)
counts = Counter({reduce_bits(bits, meas): val for bits, val in counter.items()})
return {k: v / n_sample for k, v in counts.items()}
return sampling_by_measurement | python | def get_measurement_sampler(n_sample, run_options=None):
"""Returns a function which get the expectations by sampling the measured circuit"""
if run_options is None:
run_options = {}
def sampling_by_measurement(circuit, meas):
def reduce_bits(bits, meas):
bits = [int(x) for x in bits[::-1]]
return tuple(bits[m] for m in meas)
meas = tuple(meas)
circuit.measure[meas]
counter = circuit.run(shots=n_sample, returns="shots", **run_options)
counts = Counter({reduce_bits(bits, meas): val for bits, val in counter.items()})
return {k: v / n_sample for k, v in counts.items()}
return sampling_by_measurement | [
"def",
"get_measurement_sampler",
"(",
"n_sample",
",",
"run_options",
"=",
"None",
")",
":",
"if",
"run_options",
"is",
"None",
":",
"run_options",
"=",
"{",
"}",
"def",
"sampling_by_measurement",
"(",
"circuit",
",",
"meas",
")",
":",
"def",
"reduce_bits",
... | Returns a function which get the expectations by sampling the measured circuit | [
"Returns",
"a",
"function",
"which",
"get",
"the",
"expectations",
"by",
"sampling",
"the",
"measured",
"circuit"
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L193-L209 | train | 214,270 |
Blueqat/Blueqat | blueqat/vqe.py | get_state_vector_sampler | def get_state_vector_sampler(n_sample):
"""Returns a function which get the expectations by sampling the state vector"""
def sampling_by_measurement(circuit, meas):
val = 0.0
e = expect(circuit.run(returns="statevector"), meas)
bits, probs = zip(*e.items())
dists = np.random.multinomial(n_sample, probs) / n_sample
return dict(zip(tuple(bits), dists))
return sampling_by_measurement | python | def get_state_vector_sampler(n_sample):
"""Returns a function which get the expectations by sampling the state vector"""
def sampling_by_measurement(circuit, meas):
val = 0.0
e = expect(circuit.run(returns="statevector"), meas)
bits, probs = zip(*e.items())
dists = np.random.multinomial(n_sample, probs) / n_sample
return dict(zip(tuple(bits), dists))
return sampling_by_measurement | [
"def",
"get_state_vector_sampler",
"(",
"n_sample",
")",
":",
"def",
"sampling_by_measurement",
"(",
"circuit",
",",
"meas",
")",
":",
"val",
"=",
"0.0",
"e",
"=",
"expect",
"(",
"circuit",
".",
"run",
"(",
"returns",
"=",
"\"statevector\"",
")",
",",
"mea... | Returns a function which get the expectations by sampling the state vector | [
"Returns",
"a",
"function",
"which",
"get",
"the",
"expectations",
"by",
"sampling",
"the",
"state",
"vector"
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L211-L219 | train | 214,271 |
Blueqat/Blueqat | blueqat/vqe.py | get_qiskit_sampler | def get_qiskit_sampler(backend, **execute_kwargs):
"""Returns a function which get the expectation by sampling via Qiskit.
This function requires `qiskit` module.
"""
try:
import qiskit
except ImportError:
raise ImportError("blueqat.vqe.get_qiskit_sampler() requires qiskit. Please install before call this function.")
try:
shots = execute_kwargs['shots']
except KeyError:
execute_kwargs['shots'] = shots = 1024
def reduce_bits(bits, meas):
# In Qiskit 0.6.1, For example
# Aer backend returns bit string and IBMQ backend returns hex string.
# Sample code:
"""
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
IBMQ.load_accounts()
q, c = QuantumRegister(4, 'q'), ClassicalRegister(4, 'c')
circ = QuantumCircuit(q, c)
circ.x(q[1])
for i in range(4):
circ.measure(q[i], c[i])
print("Aer qasm_simulator_py")
print(execute(circ, Aer.get_backend('qasm_simulator_py')).result().get_counts())
print("IBMQ ibmq_qasm_simulator")
print(execute(circ, IBMQ.get_backend('ibmq_qasm_simulator')).result().get_counts())
"""
# The result is,
# Aer: {'0010': 1024}
# IBMQ: {'0x2': 1024}
# This is workaround for this IBM's specifications.
if bits.startswith("0x"):
bits = int(bits, base=16)
bits = "0"*100 + format(bits, "b")
bits = [int(x) for x in bits[::-1]]
return tuple(bits[m] for m in meas)
def sampling(circuit, meas):
meas = tuple(meas)
if not meas:
return {}
circuit.measure[meas]
qasm = circuit.to_qasm()
qk_circuit = qiskit.load_qasm_string(qasm)
result = qiskit.execute(qk_circuit, backend, **execute_kwargs).result()
counts = Counter({reduce_bits(bits, meas): val for bits, val in result.get_counts().items()})
return {k: v / shots for k, v in counts.items()}
return sampling | python | def get_qiskit_sampler(backend, **execute_kwargs):
"""Returns a function which get the expectation by sampling via Qiskit.
This function requires `qiskit` module.
"""
try:
import qiskit
except ImportError:
raise ImportError("blueqat.vqe.get_qiskit_sampler() requires qiskit. Please install before call this function.")
try:
shots = execute_kwargs['shots']
except KeyError:
execute_kwargs['shots'] = shots = 1024
def reduce_bits(bits, meas):
# In Qiskit 0.6.1, For example
# Aer backend returns bit string and IBMQ backend returns hex string.
# Sample code:
"""
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
IBMQ.load_accounts()
q, c = QuantumRegister(4, 'q'), ClassicalRegister(4, 'c')
circ = QuantumCircuit(q, c)
circ.x(q[1])
for i in range(4):
circ.measure(q[i], c[i])
print("Aer qasm_simulator_py")
print(execute(circ, Aer.get_backend('qasm_simulator_py')).result().get_counts())
print("IBMQ ibmq_qasm_simulator")
print(execute(circ, IBMQ.get_backend('ibmq_qasm_simulator')).result().get_counts())
"""
# The result is,
# Aer: {'0010': 1024}
# IBMQ: {'0x2': 1024}
# This is workaround for this IBM's specifications.
if bits.startswith("0x"):
bits = int(bits, base=16)
bits = "0"*100 + format(bits, "b")
bits = [int(x) for x in bits[::-1]]
return tuple(bits[m] for m in meas)
def sampling(circuit, meas):
meas = tuple(meas)
if not meas:
return {}
circuit.measure[meas]
qasm = circuit.to_qasm()
qk_circuit = qiskit.load_qasm_string(qasm)
result = qiskit.execute(qk_circuit, backend, **execute_kwargs).result()
counts = Counter({reduce_bits(bits, meas): val for bits, val in result.get_counts().items()})
return {k: v / shots for k, v in counts.items()}
return sampling | [
"def",
"get_qiskit_sampler",
"(",
"backend",
",",
"*",
"*",
"execute_kwargs",
")",
":",
"try",
":",
"import",
"qiskit",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"blueqat.vqe.get_qiskit_sampler() requires qiskit. Please install before call this function.\""... | Returns a function which get the expectation by sampling via Qiskit.
This function requires `qiskit` module. | [
"Returns",
"a",
"function",
"which",
"get",
"the",
"expectation",
"by",
"sampling",
"via",
"Qiskit",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L221-L273 | train | 214,272 |
Blueqat/Blueqat | blueqat/vqe.py | AnsatzBase.get_energy | def get_energy(self, circuit, sampler):
"""Calculate energy from circuit and sampler."""
val = 0.0
for meas in self.hamiltonian:
c = circuit.copy()
for op in meas.ops:
if op.op == "X":
c.h[op.n]
elif op.op == "Y":
c.rx(-np.pi / 2)[op.n]
measured = sampler(c, meas.n_iter())
for bits, prob in measured.items():
if sum(bits) % 2:
val -= prob * meas.coeff
else:
val += prob * meas.coeff
return val.real | python | def get_energy(self, circuit, sampler):
"""Calculate energy from circuit and sampler."""
val = 0.0
for meas in self.hamiltonian:
c = circuit.copy()
for op in meas.ops:
if op.op == "X":
c.h[op.n]
elif op.op == "Y":
c.rx(-np.pi / 2)[op.n]
measured = sampler(c, meas.n_iter())
for bits, prob in measured.items():
if sum(bits) % 2:
val -= prob * meas.coeff
else:
val += prob * meas.coeff
return val.real | [
"def",
"get_energy",
"(",
"self",
",",
"circuit",
",",
"sampler",
")",
":",
"val",
"=",
"0.0",
"for",
"meas",
"in",
"self",
".",
"hamiltonian",
":",
"c",
"=",
"circuit",
".",
"copy",
"(",
")",
"for",
"op",
"in",
"meas",
".",
"ops",
":",
"if",
"op... | Calculate energy from circuit and sampler. | [
"Calculate",
"energy",
"from",
"circuit",
"and",
"sampler",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L36-L52 | train | 214,273 |
Blueqat/Blueqat | blueqat/vqe.py | AnsatzBase.get_objective | def get_objective(self, sampler):
"""Get an objective function to be optimized."""
def objective(params):
circuit = self.get_circuit(params)
circuit.make_cache()
return self.get_energy(circuit, sampler)
return objective | python | def get_objective(self, sampler):
"""Get an objective function to be optimized."""
def objective(params):
circuit = self.get_circuit(params)
circuit.make_cache()
return self.get_energy(circuit, sampler)
return objective | [
"def",
"get_objective",
"(",
"self",
",",
"sampler",
")",
":",
"def",
"objective",
"(",
"params",
")",
":",
"circuit",
"=",
"self",
".",
"get_circuit",
"(",
"params",
")",
"circuit",
".",
"make_cache",
"(",
")",
"return",
"self",
".",
"get_energy",
"(",
... | Get an objective function to be optimized. | [
"Get",
"an",
"objective",
"function",
"to",
"be",
"optimized",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L54-L60 | train | 214,274 |
Blueqat/Blueqat | blueqat/vqe.py | VqeResult.get_probs | def get_probs(self, sampler=None, rerun=None, store=True):
"""Get probabilities."""
if rerun is None:
rerun = sampler is not None
if self._probs is not None and not rerun:
return self._probs
if sampler is None:
sampler = self.vqe.sampler
probs = sampler(self.circuit, range(self.circuit.n_qubits))
if store:
self._probs = probs
return probs | python | def get_probs(self, sampler=None, rerun=None, store=True):
"""Get probabilities."""
if rerun is None:
rerun = sampler is not None
if self._probs is not None and not rerun:
return self._probs
if sampler is None:
sampler = self.vqe.sampler
probs = sampler(self.circuit, range(self.circuit.n_qubits))
if store:
self._probs = probs
return probs | [
"def",
"get_probs",
"(",
"self",
",",
"sampler",
"=",
"None",
",",
"rerun",
"=",
"None",
",",
"store",
"=",
"True",
")",
":",
"if",
"rerun",
"is",
"None",
":",
"rerun",
"=",
"sampler",
"is",
"not",
"None",
"if",
"self",
".",
"_probs",
"is",
"not",
... | Get probabilities. | [
"Get",
"probabilities",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L113-L124 | train | 214,275 |
Blueqat/Blueqat | blueqat/backends/backendbase.py | Backend._run_gates | def _run_gates(self, gates, n_qubits, ctx):
"""Iterate gates and call backend's action for each gates"""
for gate in gates:
action = self._get_action(gate)
if action is not None:
ctx = action(gate, ctx)
else:
ctx = self._run_gates(gate.fallback(n_qubits), n_qubits, ctx)
return ctx | python | def _run_gates(self, gates, n_qubits, ctx):
"""Iterate gates and call backend's action for each gates"""
for gate in gates:
action = self._get_action(gate)
if action is not None:
ctx = action(gate, ctx)
else:
ctx = self._run_gates(gate.fallback(n_qubits), n_qubits, ctx)
return ctx | [
"def",
"_run_gates",
"(",
"self",
",",
"gates",
",",
"n_qubits",
",",
"ctx",
")",
":",
"for",
"gate",
"in",
"gates",
":",
"action",
"=",
"self",
".",
"_get_action",
"(",
"gate",
")",
"if",
"action",
"is",
"not",
"None",
":",
"ctx",
"=",
"action",
"... | Iterate gates and call backend's action for each gates | [
"Iterate",
"gates",
"and",
"call",
"backend",
"s",
"action",
"for",
"each",
"gates"
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/backendbase.py#L45-L53 | train | 214,276 |
Blueqat/Blueqat | blueqat/backends/backendbase.py | Backend._run | def _run(self, gates, n_qubits, args, kwargs):
"""Default implementation of `Backend.run`.
Backend developer shouldn't override this function, but override `run` instead of this.
The default flow of running is:
1. preprocessing
2. call the gate action which defined in backend
3. postprocessing
Backend developer can:
1. Define preprocessing process. Override `_preprocess_run`
2. Define the gate action. Define methods `gate_{gate.lowername}`,
for example, `gate_x` for X gate, `gate_cx` for CX gate.
3. Define postprocessing process (and make return value). Override `_postprocess_run`
Otherwise, the developer can override `run` method if they want to change the flow of run.
"""
gates, ctx = self._preprocess_run(gates, n_qubits, args, kwargs)
self._run_gates(gates, n_qubits, ctx)
return self._postprocess_run(ctx) | python | def _run(self, gates, n_qubits, args, kwargs):
"""Default implementation of `Backend.run`.
Backend developer shouldn't override this function, but override `run` instead of this.
The default flow of running is:
1. preprocessing
2. call the gate action which defined in backend
3. postprocessing
Backend developer can:
1. Define preprocessing process. Override `_preprocess_run`
2. Define the gate action. Define methods `gate_{gate.lowername}`,
for example, `gate_x` for X gate, `gate_cx` for CX gate.
3. Define postprocessing process (and make return value). Override `_postprocess_run`
Otherwise, the developer can override `run` method if they want to change the flow of run.
"""
gates, ctx = self._preprocess_run(gates, n_qubits, args, kwargs)
self._run_gates(gates, n_qubits, ctx)
return self._postprocess_run(ctx) | [
"def",
"_run",
"(",
"self",
",",
"gates",
",",
"n_qubits",
",",
"args",
",",
"kwargs",
")",
":",
"gates",
",",
"ctx",
"=",
"self",
".",
"_preprocess_run",
"(",
"gates",
",",
"n_qubits",
",",
"args",
",",
"kwargs",
")",
"self",
".",
"_run_gates",
"(",... | Default implementation of `Backend.run`.
Backend developer shouldn't override this function, but override `run` instead of this.
The default flow of running is:
1. preprocessing
2. call the gate action which defined in backend
3. postprocessing
Backend developer can:
1. Define preprocessing process. Override `_preprocess_run`
2. Define the gate action. Define methods `gate_{gate.lowername}`,
for example, `gate_x` for X gate, `gate_cx` for CX gate.
3. Define postprocessing process (and make return value). Override `_postprocess_run`
Otherwise, the developer can override `run` method if they want to change the flow of run. | [
"Default",
"implementation",
"of",
"Backend",
".",
"run",
".",
"Backend",
"developer",
"shouldn",
"t",
"override",
"this",
"function",
"but",
"override",
"run",
"instead",
"of",
"this",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/backendbase.py#L55-L73 | train | 214,277 |
Blueqat/Blueqat | blueqat/backends/backendbase.py | Backend.run | def run(self, gates, n_qubits, *args, **kwargs):
"""Run the backend."""
return self._run(gates, n_qubits, args, kwargs) | python | def run(self, gates, n_qubits, *args, **kwargs):
"""Run the backend."""
return self._run(gates, n_qubits, args, kwargs) | [
"def",
"run",
"(",
"self",
",",
"gates",
",",
"n_qubits",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_run",
"(",
"gates",
",",
"n_qubits",
",",
"args",
",",
"kwargs",
")"
] | Run the backend. | [
"Run",
"the",
"backend",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/backendbase.py#L82-L84 | train | 214,278 |
Blueqat/Blueqat | blueqat/backends/backendbase.py | Backend._resolve_fallback | def _resolve_fallback(self, gates, n_qubits):
"""Resolve fallbacks and flatten gates."""
flattened = []
for g in gates:
if self._has_action(g):
flattened.append(g)
else:
flattened += self._resolve_fallback(g.fallback(n_qubits), n_qubits)
return flattened | python | def _resolve_fallback(self, gates, n_qubits):
"""Resolve fallbacks and flatten gates."""
flattened = []
for g in gates:
if self._has_action(g):
flattened.append(g)
else:
flattened += self._resolve_fallback(g.fallback(n_qubits), n_qubits)
return flattened | [
"def",
"_resolve_fallback",
"(",
"self",
",",
"gates",
",",
"n_qubits",
")",
":",
"flattened",
"=",
"[",
"]",
"for",
"g",
"in",
"gates",
":",
"if",
"self",
".",
"_has_action",
"(",
"g",
")",
":",
"flattened",
".",
"append",
"(",
"g",
")",
"else",
"... | Resolve fallbacks and flatten gates. | [
"Resolve",
"fallbacks",
"and",
"flatten",
"gates",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/backendbase.py#L95-L103 | train | 214,279 |
Blueqat/Blueqat | blueqat/backends/numpy_backend.py | _NumPyBackendContext.prepare | def prepare(self, cache):
"""Prepare to run next shot."""
if cache is not None:
np.copyto(self.qubits, cache)
else:
self.qubits.fill(0.0)
self.qubits[0] = 1.0
self.cregs = [0] * self.n_qubits | python | def prepare(self, cache):
"""Prepare to run next shot."""
if cache is not None:
np.copyto(self.qubits, cache)
else:
self.qubits.fill(0.0)
self.qubits[0] = 1.0
self.cregs = [0] * self.n_qubits | [
"def",
"prepare",
"(",
"self",
",",
"cache",
")",
":",
"if",
"cache",
"is",
"not",
"None",
":",
"np",
".",
"copyto",
"(",
"self",
".",
"qubits",
",",
"cache",
")",
"else",
":",
"self",
".",
"qubits",
".",
"fill",
"(",
"0.0",
")",
"self",
".",
"... | Prepare to run next shot. | [
"Prepare",
"to",
"run",
"next",
"shot",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/numpy_backend.py#L38-L45 | train | 214,280 |
Blueqat/Blueqat | blueqat/backends/numpy_backend.py | _NumPyBackendContext.store_shot | def store_shot(self):
"""Store current cregs to shots_result"""
def to_str(cregs):
return ''.join(str(b) for b in cregs)
key = to_str(self.cregs)
self.shots_result[key] = self.shots_result.get(key, 0) + 1 | python | def store_shot(self):
"""Store current cregs to shots_result"""
def to_str(cregs):
return ''.join(str(b) for b in cregs)
key = to_str(self.cregs)
self.shots_result[key] = self.shots_result.get(key, 0) + 1 | [
"def",
"store_shot",
"(",
"self",
")",
":",
"def",
"to_str",
"(",
"cregs",
")",
":",
"return",
"''",
".",
"join",
"(",
"str",
"(",
"b",
")",
"for",
"b",
"in",
"cregs",
")",
"key",
"=",
"to_str",
"(",
"self",
".",
"cregs",
")",
"self",
".",
"sho... | Store current cregs to shots_result | [
"Store",
"current",
"cregs",
"to",
"shots_result"
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/numpy_backend.py#L47-L52 | train | 214,281 |
Blueqat/Blueqat | blueqat/circuit.py | Circuit.copy | def copy(self, copy_backends=True, copy_default_backend=True,
copy_cache=None, copy_history=None):
"""Copy the circuit.
:params
copy_backends :bool copy backends if True.
copy_default_backend :bool copy default_backend if True.
"""
copied = Circuit(self.n_qubits, self.ops.copy())
if copy_backends:
copied._backends = {k: v.copy() for k, v in self._backends.items()}
if copy_default_backend:
copied._default_backend = self._default_backend
# Warn for deprecated options
if copy_cache is not None:
warnings.warn("copy_cache is deprecated. Use copy_backends instead.",
DeprecationWarning)
if copy_history is not None:
warnings.warn("copy_history is deprecated.", DeprecationWarning)
return copied | python | def copy(self, copy_backends=True, copy_default_backend=True,
copy_cache=None, copy_history=None):
"""Copy the circuit.
:params
copy_backends :bool copy backends if True.
copy_default_backend :bool copy default_backend if True.
"""
copied = Circuit(self.n_qubits, self.ops.copy())
if copy_backends:
copied._backends = {k: v.copy() for k, v in self._backends.items()}
if copy_default_backend:
copied._default_backend = self._default_backend
# Warn for deprecated options
if copy_cache is not None:
warnings.warn("copy_cache is deprecated. Use copy_backends instead.",
DeprecationWarning)
if copy_history is not None:
warnings.warn("copy_history is deprecated.", DeprecationWarning)
return copied | [
"def",
"copy",
"(",
"self",
",",
"copy_backends",
"=",
"True",
",",
"copy_default_backend",
"=",
"True",
",",
"copy_cache",
"=",
"None",
",",
"copy_history",
"=",
"None",
")",
":",
"copied",
"=",
"Circuit",
"(",
"self",
".",
"n_qubits",
",",
"self",
".",... | Copy the circuit.
:params
copy_backends :bool copy backends if True.
copy_default_backend :bool copy default_backend if True. | [
"Copy",
"the",
"circuit",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L127-L148 | train | 214,282 |
Blueqat/Blueqat | blueqat/circuit.py | Circuit.run | def run(self, *args, backend=None, **kwargs):
"""Run the circuit.
`Circuit` have several backends. When `backend` parameter is specified,
use specified backend, and otherwise, default backend is used.
Other parameters are passed to the backend.
The meaning of parameters are depends on the backend specifications.
However, following parameters are commonly used.
Commonly used args (Depends on backend):
shots (int, optional): The number of sampling the circuit.
returns (str, optional): The category of returns value.
e.g. "statevector" returns the state vector after run the circuit.
"shots" returns the counter of measured value.
token, url (str, optional): The token and URL for cloud resource.
Returns:
Depends on backend.
Raises:
Depends on backend.
"""
if backend is None:
if self._default_backend is None:
backend = self.__get_backend(DEFAULT_BACKEND_NAME)
else:
backend = self.__get_backend(self._default_backend)
elif isinstance(backend, str):
backend = self.__get_backend(backend)
return backend.run(self.ops, self.n_qubits, *args, **kwargs) | python | def run(self, *args, backend=None, **kwargs):
"""Run the circuit.
`Circuit` have several backends. When `backend` parameter is specified,
use specified backend, and otherwise, default backend is used.
Other parameters are passed to the backend.
The meaning of parameters are depends on the backend specifications.
However, following parameters are commonly used.
Commonly used args (Depends on backend):
shots (int, optional): The number of sampling the circuit.
returns (str, optional): The category of returns value.
e.g. "statevector" returns the state vector after run the circuit.
"shots" returns the counter of measured value.
token, url (str, optional): The token and URL for cloud resource.
Returns:
Depends on backend.
Raises:
Depends on backend.
"""
if backend is None:
if self._default_backend is None:
backend = self.__get_backend(DEFAULT_BACKEND_NAME)
else:
backend = self.__get_backend(self._default_backend)
elif isinstance(backend, str):
backend = self.__get_backend(backend)
return backend.run(self.ops, self.n_qubits, *args, **kwargs) | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
",",
"backend",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"backend",
"is",
"None",
":",
"if",
"self",
".",
"_default_backend",
"is",
"None",
":",
"backend",
"=",
"self",
".",
"__get_backend",
... | Run the circuit.
`Circuit` have several backends. When `backend` parameter is specified,
use specified backend, and otherwise, default backend is used.
Other parameters are passed to the backend.
The meaning of parameters are depends on the backend specifications.
However, following parameters are commonly used.
Commonly used args (Depends on backend):
shots (int, optional): The number of sampling the circuit.
returns (str, optional): The category of returns value.
e.g. "statevector" returns the state vector after run the circuit.
"shots" returns the counter of measured value.
token, url (str, optional): The token and URL for cloud resource.
Returns:
Depends on backend.
Raises:
Depends on backend. | [
"Run",
"the",
"circuit",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L150-L180 | train | 214,283 |
Blueqat/Blueqat | blueqat/circuit.py | Circuit.make_cache | def make_cache(self, backend=None):
"""Make a cache to reduce the time of run. Some backends may implemented it.
This is temporary API. It may changed or deprecated."""
if backend is None:
if self._default_backend is None:
backend = DEFAULT_BACKEND_NAME
else:
backend = self._default_backend
return self.__get_backend(backend).make_cache(self.ops, self.n_qubits) | python | def make_cache(self, backend=None):
"""Make a cache to reduce the time of run. Some backends may implemented it.
This is temporary API. It may changed or deprecated."""
if backend is None:
if self._default_backend is None:
backend = DEFAULT_BACKEND_NAME
else:
backend = self._default_backend
return self.__get_backend(backend).make_cache(self.ops, self.n_qubits) | [
"def",
"make_cache",
"(",
"self",
",",
"backend",
"=",
"None",
")",
":",
"if",
"backend",
"is",
"None",
":",
"if",
"self",
".",
"_default_backend",
"is",
"None",
":",
"backend",
"=",
"DEFAULT_BACKEND_NAME",
"else",
":",
"backend",
"=",
"self",
".",
"_def... | Make a cache to reduce the time of run. Some backends may implemented it.
This is temporary API. It may changed or deprecated. | [
"Make",
"a",
"cache",
"to",
"reduce",
"the",
"time",
"of",
"run",
".",
"Some",
"backends",
"may",
"implemented",
"it",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L182-L191 | train | 214,284 |
Blueqat/Blueqat | blueqat/circuit.py | Circuit.set_default_backend | def set_default_backend(self, backend_name):
"""Set the default backend of this circuit.
This setting is only applied for this circuit.
If you want to change the default backend of all gates,
use `BlueqatGlobalSetting.set_default_backend()`.
After set the default backend by this method,
global setting is ignored even if `BlueqatGlobalSetting.set_default_backend()` is called.
If you want to use global default setting, call this method with backend_name=None.
Args:
backend_name (str or None): new default backend name.
If None is given, global setting is applied.
Raises:
ValueError: If `backend_name` is not registered backend.
"""
if backend_name not in BACKENDS:
raise ValueError(f"Unknown backend '{backend_name}'.")
self._default_backend = backend_name | python | def set_default_backend(self, backend_name):
"""Set the default backend of this circuit.
This setting is only applied for this circuit.
If you want to change the default backend of all gates,
use `BlueqatGlobalSetting.set_default_backend()`.
After set the default backend by this method,
global setting is ignored even if `BlueqatGlobalSetting.set_default_backend()` is called.
If you want to use global default setting, call this method with backend_name=None.
Args:
backend_name (str or None): new default backend name.
If None is given, global setting is applied.
Raises:
ValueError: If `backend_name` is not registered backend.
"""
if backend_name not in BACKENDS:
raise ValueError(f"Unknown backend '{backend_name}'.")
self._default_backend = backend_name | [
"def",
"set_default_backend",
"(",
"self",
",",
"backend_name",
")",
":",
"if",
"backend_name",
"not",
"in",
"BACKENDS",
":",
"raise",
"ValueError",
"(",
"f\"Unknown backend '{backend_name}'.\"",
")",
"self",
".",
"_default_backend",
"=",
"backend_name"
] | Set the default backend of this circuit.
This setting is only applied for this circuit.
If you want to change the default backend of all gates,
use `BlueqatGlobalSetting.set_default_backend()`.
After set the default backend by this method,
global setting is ignored even if `BlueqatGlobalSetting.set_default_backend()` is called.
If you want to use global default setting, call this method with backend_name=None.
Args:
backend_name (str or None): new default backend name.
If None is given, global setting is applied.
Raises:
ValueError: If `backend_name` is not registered backend. | [
"Set",
"the",
"default",
"backend",
"of",
"this",
"circuit",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L201-L221 | train | 214,285 |
Blueqat/Blueqat | blueqat/circuit.py | BlueqatGlobalSetting.register_macro | def register_macro(name: str, func: Callable, allow_overwrite: bool = False) -> None:
"""Register new macro to Circuit.
Args:
name (str): The name of macro.
func (callable): The function to be called.
allow_overwrite (bool, optional): If True, allow to overwrite the existing macro.
Otherwise, raise the ValueError.
Raises:
ValueError: The name is duplicated with existing macro, gate or method.
When `allow_overwrite=True`, this error is not raised.
"""
if hasattr(Circuit, name):
if allow_overwrite:
warnings.warn(f"Circuit has attribute `{name}`.")
else:
raise ValueError(f"Circuit has attribute `{name}`.")
if name.startswith("run_with_"):
if allow_overwrite:
warnings.warn(f"Gate name `{name}` may conflict with run of backend.")
else:
raise ValueError(f"Gate name `{name}` shall not start with 'run_with_'.")
if not allow_overwrite:
if name in GATE_SET:
raise ValueError(f"Gate '{name}' is already exists in gate set.")
if name in GLOBAL_MACROS:
raise ValueError(f"Macro '{name}' is already exists.")
GLOBAL_MACROS[name] = func | python | def register_macro(name: str, func: Callable, allow_overwrite: bool = False) -> None:
"""Register new macro to Circuit.
Args:
name (str): The name of macro.
func (callable): The function to be called.
allow_overwrite (bool, optional): If True, allow to overwrite the existing macro.
Otherwise, raise the ValueError.
Raises:
ValueError: The name is duplicated with existing macro, gate or method.
When `allow_overwrite=True`, this error is not raised.
"""
if hasattr(Circuit, name):
if allow_overwrite:
warnings.warn(f"Circuit has attribute `{name}`.")
else:
raise ValueError(f"Circuit has attribute `{name}`.")
if name.startswith("run_with_"):
if allow_overwrite:
warnings.warn(f"Gate name `{name}` may conflict with run of backend.")
else:
raise ValueError(f"Gate name `{name}` shall not start with 'run_with_'.")
if not allow_overwrite:
if name in GATE_SET:
raise ValueError(f"Gate '{name}' is already exists in gate set.")
if name in GLOBAL_MACROS:
raise ValueError(f"Macro '{name}' is already exists.")
GLOBAL_MACROS[name] = func | [
"def",
"register_macro",
"(",
"name",
":",
"str",
",",
"func",
":",
"Callable",
",",
"allow_overwrite",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"if",
"hasattr",
"(",
"Circuit",
",",
"name",
")",
":",
"if",
"allow_overwrite",
":",
"warnings",
... | Register new macro to Circuit.
Args:
name (str): The name of macro.
func (callable): The function to be called.
allow_overwrite (bool, optional): If True, allow to overwrite the existing macro.
Otherwise, raise the ValueError.
Raises:
ValueError: The name is duplicated with existing macro, gate or method.
When `allow_overwrite=True`, this error is not raised. | [
"Register",
"new",
"macro",
"to",
"Circuit",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L267-L295 | train | 214,286 |
Blueqat/Blueqat | blueqat/circuit.py | BlueqatGlobalSetting.register_gate | def register_gate(name, gateclass, allow_overwrite=False):
"""Register new gate to gate set.
Args:
name (str): The name of gate.
gateclass (type): The type object of gate.
allow_overwrite (bool, optional): If True, allow to overwrite the existing gate.
Otherwise, raise the ValueError.
Raises:
ValueError: The name is duplicated with existing gate.
When `allow_overwrite=True`, this error is not raised.
"""
if hasattr(Circuit, name):
if allow_overwrite:
warnings.warn(f"Circuit has attribute `{name}`.")
else:
raise ValueError(f"Circuit has attribute `{name}`.")
if name.startswith("run_with_"):
if allow_overwrite:
warnings.warn(f"Gate name `{name}` may conflict with run of backend.")
else:
raise ValueError(f"Gate name `{name}` shall not start with 'run_with_'.")
if not allow_overwrite:
if name in GATE_SET:
raise ValueError(f"Gate '{name}' is already exists in gate set.")
if name in GLOBAL_MACROS:
raise ValueError(f"Macro '{name}' is already exists.")
GATE_SET[name] = gateclass | python | def register_gate(name, gateclass, allow_overwrite=False):
"""Register new gate to gate set.
Args:
name (str): The name of gate.
gateclass (type): The type object of gate.
allow_overwrite (bool, optional): If True, allow to overwrite the existing gate.
Otherwise, raise the ValueError.
Raises:
ValueError: The name is duplicated with existing gate.
When `allow_overwrite=True`, this error is not raised.
"""
if hasattr(Circuit, name):
if allow_overwrite:
warnings.warn(f"Circuit has attribute `{name}`.")
else:
raise ValueError(f"Circuit has attribute `{name}`.")
if name.startswith("run_with_"):
if allow_overwrite:
warnings.warn(f"Gate name `{name}` may conflict with run of backend.")
else:
raise ValueError(f"Gate name `{name}` shall not start with 'run_with_'.")
if not allow_overwrite:
if name in GATE_SET:
raise ValueError(f"Gate '{name}' is already exists in gate set.")
if name in GLOBAL_MACROS:
raise ValueError(f"Macro '{name}' is already exists.")
GATE_SET[name] = gateclass | [
"def",
"register_gate",
"(",
"name",
",",
"gateclass",
",",
"allow_overwrite",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"Circuit",
",",
"name",
")",
":",
"if",
"allow_overwrite",
":",
"warnings",
".",
"warn",
"(",
"f\"Circuit has attribute `{name}`.\"",
"... | Register new gate to gate set.
Args:
name (str): The name of gate.
gateclass (type): The type object of gate.
allow_overwrite (bool, optional): If True, allow to overwrite the existing gate.
Otherwise, raise the ValueError.
Raises:
ValueError: The name is duplicated with existing gate.
When `allow_overwrite=True`, this error is not raised. | [
"Register",
"new",
"gate",
"to",
"gate",
"set",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L312-L340 | train | 214,287 |
Blueqat/Blueqat | blueqat/circuit.py | BlueqatGlobalSetting.register_backend | def register_backend(name, backend, allow_overwrite=False):
"""Register new backend.
Args:
name (str): The name of backend.
gateclass (type): The type object of backend
allow_overwrite (bool, optional): If True, allow to overwrite the existing backend.
Otherwise, raise the ValueError.
Raises:
ValueError: The name is duplicated with existing backend.
When `allow_overwrite=True`, this error is not raised.
"""
if hasattr(Circuit, "run_with_" + name):
if allow_overwrite:
warnings.warn(f"Circuit has attribute `run_with_{name}`.")
else:
raise ValueError(f"Circuit has attribute `run_with_{name}`.")
if not allow_overwrite:
if name in BACKENDS:
raise ValueError(f"Backend '{name}' is already registered as backend.")
BACKENDS[name] = backend | python | def register_backend(name, backend, allow_overwrite=False):
"""Register new backend.
Args:
name (str): The name of backend.
gateclass (type): The type object of backend
allow_overwrite (bool, optional): If True, allow to overwrite the existing backend.
Otherwise, raise the ValueError.
Raises:
ValueError: The name is duplicated with existing backend.
When `allow_overwrite=True`, this error is not raised.
"""
if hasattr(Circuit, "run_with_" + name):
if allow_overwrite:
warnings.warn(f"Circuit has attribute `run_with_{name}`.")
else:
raise ValueError(f"Circuit has attribute `run_with_{name}`.")
if not allow_overwrite:
if name in BACKENDS:
raise ValueError(f"Backend '{name}' is already registered as backend.")
BACKENDS[name] = backend | [
"def",
"register_backend",
"(",
"name",
",",
"backend",
",",
"allow_overwrite",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"Circuit",
",",
"\"run_with_\"",
"+",
"name",
")",
":",
"if",
"allow_overwrite",
":",
"warnings",
".",
"warn",
"(",
"f\"Circuit has ... | Register new backend.
Args:
name (str): The name of backend.
gateclass (type): The type object of backend
allow_overwrite (bool, optional): If True, allow to overwrite the existing backend.
Otherwise, raise the ValueError.
Raises:
ValueError: The name is duplicated with existing backend.
When `allow_overwrite=True`, this error is not raised. | [
"Register",
"new",
"backend",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L357-L378 | train | 214,288 |
Blueqat/Blueqat | examples/maxcut_qaoa.py | maxcut_qaoa | def maxcut_qaoa(n_step, edges, minimizer=None, sampler=None, verbose=True):
"""Setup QAOA.
:param n_step: The number of step of QAOA
:param n_sample: The number of sampling time of each measurement in VQE.
If None, use calculated ideal value.
:param edges: The edges list of the graph.
:returns Vqe object
"""
sampler = sampler or vqe.non_sampling_sampler
minimizer = minimizer or vqe.get_scipy_minimizer(
method="Powell",
options={"ftol": 5.0e-2, "xtol": 5.0e-2, "maxiter": 1000, "disp": True}
)
hamiltonian = pauli.I() * 0
for i, j in edges:
hamiltonian += pauli.Z(i) * pauli.Z(j)
return vqe.Vqe(vqe.QaoaAnsatz(hamiltonian, n_step), minimizer, sampler) | python | def maxcut_qaoa(n_step, edges, minimizer=None, sampler=None, verbose=True):
"""Setup QAOA.
:param n_step: The number of step of QAOA
:param n_sample: The number of sampling time of each measurement in VQE.
If None, use calculated ideal value.
:param edges: The edges list of the graph.
:returns Vqe object
"""
sampler = sampler or vqe.non_sampling_sampler
minimizer = minimizer or vqe.get_scipy_minimizer(
method="Powell",
options={"ftol": 5.0e-2, "xtol": 5.0e-2, "maxiter": 1000, "disp": True}
)
hamiltonian = pauli.I() * 0
for i, j in edges:
hamiltonian += pauli.Z(i) * pauli.Z(j)
return vqe.Vqe(vqe.QaoaAnsatz(hamiltonian, n_step), minimizer, sampler) | [
"def",
"maxcut_qaoa",
"(",
"n_step",
",",
"edges",
",",
"minimizer",
"=",
"None",
",",
"sampler",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"sampler",
"=",
"sampler",
"or",
"vqe",
".",
"non_sampling_sampler",
"minimizer",
"=",
"minimizer",
"or",
... | Setup QAOA.
:param n_step: The number of step of QAOA
:param n_sample: The number of sampling time of each measurement in VQE.
If None, use calculated ideal value.
:param edges: The edges list of the graph.
:returns Vqe object | [
"Setup",
"QAOA",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/examples/maxcut_qaoa.py#L3-L22 | train | 214,289 |
Blueqat/Blueqat | blueqat/pauli.py | pauli_from_char | def pauli_from_char(ch, n=0):
"""Make Pauli matrix from an character.
Args:
ch (str): "X" or "Y" or "Z" or "I".
n (int, optional): Make Pauli matrix as n-th qubits.
Returns:
If ch is "X" => X, "Y" => Y, "Z" => Z, "I" => I
Raises:
ValueError: When ch is not "X", "Y", "Z" nor "I".
"""
ch = ch.upper()
if ch == "I":
return I
if ch == "X":
return X(n)
if ch == "Y":
return Y(n)
if ch == "Z":
return Z(n)
raise ValueError("ch shall be X, Y, Z or I") | python | def pauli_from_char(ch, n=0):
"""Make Pauli matrix from an character.
Args:
ch (str): "X" or "Y" or "Z" or "I".
n (int, optional): Make Pauli matrix as n-th qubits.
Returns:
If ch is "X" => X, "Y" => Y, "Z" => Z, "I" => I
Raises:
ValueError: When ch is not "X", "Y", "Z" nor "I".
"""
ch = ch.upper()
if ch == "I":
return I
if ch == "X":
return X(n)
if ch == "Y":
return Y(n)
if ch == "Z":
return Z(n)
raise ValueError("ch shall be X, Y, Z or I") | [
"def",
"pauli_from_char",
"(",
"ch",
",",
"n",
"=",
"0",
")",
":",
"ch",
"=",
"ch",
".",
"upper",
"(",
")",
"if",
"ch",
"==",
"\"I\"",
":",
"return",
"I",
"if",
"ch",
"==",
"\"X\"",
":",
"return",
"X",
"(",
"n",
")",
"if",
"ch",
"==",
"\"Y\""... | Make Pauli matrix from an character.
Args:
ch (str): "X" or "Y" or "Z" or "I".
n (int, optional): Make Pauli matrix as n-th qubits.
Returns:
If ch is "X" => X, "Y" => Y, "Z" => Z, "I" => I
Raises:
ValueError: When ch is not "X", "Y", "Z" nor "I". | [
"Make",
"Pauli",
"matrix",
"from",
"an",
"character",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L28-L50 | train | 214,290 |
Blueqat/Blueqat | blueqat/pauli.py | is_commutable | def is_commutable(expr1, expr2, eps=0.00000001):
"""Test whether expr1 and expr2 are commutable.
Args:
expr1 (Expr, Term or Pauli operator): Pauli's expression.
expr2 (Expr, Term or Pauli operator): Pauli's expression.
eps (float, optional): Machine epsilon.
If |[expr1, expr2]| < eps, consider it is commutable.
Returns:
bool: if expr1 and expr2 are commutable, returns True, otherwise False.
"""
return sum((x * x.conjugate()).real for x in commutator(expr1, expr2).coeffs()) < eps | python | def is_commutable(expr1, expr2, eps=0.00000001):
"""Test whether expr1 and expr2 are commutable.
Args:
expr1 (Expr, Term or Pauli operator): Pauli's expression.
expr2 (Expr, Term or Pauli operator): Pauli's expression.
eps (float, optional): Machine epsilon.
If |[expr1, expr2]| < eps, consider it is commutable.
Returns:
bool: if expr1 and expr2 are commutable, returns True, otherwise False.
"""
return sum((x * x.conjugate()).real for x in commutator(expr1, expr2).coeffs()) < eps | [
"def",
"is_commutable",
"(",
"expr1",
",",
"expr2",
",",
"eps",
"=",
"0.00000001",
")",
":",
"return",
"sum",
"(",
"(",
"x",
"*",
"x",
".",
"conjugate",
"(",
")",
")",
".",
"real",
"for",
"x",
"in",
"commutator",
"(",
"expr1",
",",
"expr2",
")",
... | Test whether expr1 and expr2 are commutable.
Args:
expr1 (Expr, Term or Pauli operator): Pauli's expression.
expr2 (Expr, Term or Pauli operator): Pauli's expression.
eps (float, optional): Machine epsilon.
If |[expr1, expr2]| < eps, consider it is commutable.
Returns:
bool: if expr1 and expr2 are commutable, returns True, otherwise False. | [
"Test",
"whether",
"expr1",
"and",
"expr2",
"are",
"commutable",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L103-L115 | train | 214,291 |
Blueqat/Blueqat | blueqat/pauli.py | Term.from_pauli | def from_pauli(pauli, coeff=1.0):
"""Make new Term from an Pauli operator"""
if pauli.is_identity or coeff == 0:
return Term((), coeff)
return Term((pauli,), coeff) | python | def from_pauli(pauli, coeff=1.0):
"""Make new Term from an Pauli operator"""
if pauli.is_identity or coeff == 0:
return Term((), coeff)
return Term((pauli,), coeff) | [
"def",
"from_pauli",
"(",
"pauli",
",",
"coeff",
"=",
"1.0",
")",
":",
"if",
"pauli",
".",
"is_identity",
"or",
"coeff",
"==",
"0",
":",
"return",
"Term",
"(",
"(",
")",
",",
"coeff",
")",
"return",
"Term",
"(",
"(",
"pauli",
",",
")",
",",
"coef... | Make new Term from an Pauli operator | [
"Make",
"new",
"Term",
"from",
"an",
"Pauli",
"operator"
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L281-L285 | train | 214,292 |
Blueqat/Blueqat | blueqat/pauli.py | Term.simplify | def simplify(self):
"""Simplify the Term."""
def mul(op1, op2):
if op1 == "I":
return 1.0, op2
if op2 == "I":
return 1.0, op1
if op1 == op2:
return 1.0, "I"
if op1 == "X":
return (-1j, "Z") if op2 == "Y" else (1j, "Y")
if op1 == "Y":
return (-1j, "X") if op2 == "Z" else (1j, "Z")
if op1 == "Z":
return (-1j, "Y") if op2 == "X" else (1j, "X")
before = defaultdict(list)
for op in self.ops:
if op.op == "I":
continue
before[op.n].append(op.op)
new_coeff = self.coeff
new_ops = []
for n in sorted(before.keys()):
ops = before[n]
assert ops
k = 1.0
op = ops[0]
for _op in ops[1:]:
_k, op = mul(op, _op)
k *= _k
new_coeff *= k
if new_coeff.imag == 0:
# cast to float
new_coeff = new_coeff.real
if op != "I":
new_ops.append(pauli_from_char(op, n))
return Term(tuple(new_ops), new_coeff) | python | def simplify(self):
"""Simplify the Term."""
def mul(op1, op2):
if op1 == "I":
return 1.0, op2
if op2 == "I":
return 1.0, op1
if op1 == op2:
return 1.0, "I"
if op1 == "X":
return (-1j, "Z") if op2 == "Y" else (1j, "Y")
if op1 == "Y":
return (-1j, "X") if op2 == "Z" else (1j, "Z")
if op1 == "Z":
return (-1j, "Y") if op2 == "X" else (1j, "X")
before = defaultdict(list)
for op in self.ops:
if op.op == "I":
continue
before[op.n].append(op.op)
new_coeff = self.coeff
new_ops = []
for n in sorted(before.keys()):
ops = before[n]
assert ops
k = 1.0
op = ops[0]
for _op in ops[1:]:
_k, op = mul(op, _op)
k *= _k
new_coeff *= k
if new_coeff.imag == 0:
# cast to float
new_coeff = new_coeff.real
if op != "I":
new_ops.append(pauli_from_char(op, n))
return Term(tuple(new_ops), new_coeff) | [
"def",
"simplify",
"(",
"self",
")",
":",
"def",
"mul",
"(",
"op1",
",",
"op2",
")",
":",
"if",
"op1",
"==",
"\"I\"",
":",
"return",
"1.0",
",",
"op2",
"if",
"op2",
"==",
"\"I\"",
":",
"return",
"1.0",
",",
"op1",
"if",
"op1",
"==",
"op2",
":",... | Simplify the Term. | [
"Simplify",
"the",
"Term",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L423-L460 | train | 214,293 |
Blueqat/Blueqat | blueqat/pauli.py | Term.append_to_circuit | def append_to_circuit(self, circuit, simplify=True):
"""Append Pauli gates to `Circuit`."""
if simplify:
term = self.simplify()
else:
term = self
for op in term.ops[::-1]:
gate = op.op.lower()
if gate != "i":
getattr(circuit, gate)[op.n] | python | def append_to_circuit(self, circuit, simplify=True):
"""Append Pauli gates to `Circuit`."""
if simplify:
term = self.simplify()
else:
term = self
for op in term.ops[::-1]:
gate = op.op.lower()
if gate != "i":
getattr(circuit, gate)[op.n] | [
"def",
"append_to_circuit",
"(",
"self",
",",
"circuit",
",",
"simplify",
"=",
"True",
")",
":",
"if",
"simplify",
":",
"term",
"=",
"self",
".",
"simplify",
"(",
")",
"else",
":",
"term",
"=",
"self",
"for",
"op",
"in",
"term",
".",
"ops",
"[",
":... | Append Pauli gates to `Circuit`. | [
"Append",
"Pauli",
"gates",
"to",
"Circuit",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L470-L479 | train | 214,294 |
Blueqat/Blueqat | blueqat/pauli.py | Term.get_time_evolution | def get_time_evolution(self):
"""Get the function to append the time evolution of this term.
Returns:
function(circuit: Circuit, t: float):
Add gates for time evolution to `circuit` with time `t`
"""
term = self.simplify()
coeff = term.coeff
if coeff.imag:
raise ValueError("Not a real coefficient.")
ops = term.ops
def append_to_circuit(circuit, t):
if not ops:
return
for op in ops:
n = op.n
if op.op == "X":
circuit.h[n]
elif op.op == "Y":
circuit.rx(-half_pi)[n]
for i in range(1, len(ops)):
circuit.cx[ops[i-1].n, ops[i].n]
circuit.rz(-2 * coeff * t)[ops[-1].n]
for i in range(len(ops)-1, 0, -1):
circuit.cx[ops[i-1].n, ops[i].n]
for op in ops:
n = op.n
if op.op == "X":
circuit.h[n]
elif op.op == "Y":
circuit.rx(half_pi)[n]
return append_to_circuit | python | def get_time_evolution(self):
"""Get the function to append the time evolution of this term.
Returns:
function(circuit: Circuit, t: float):
Add gates for time evolution to `circuit` with time `t`
"""
term = self.simplify()
coeff = term.coeff
if coeff.imag:
raise ValueError("Not a real coefficient.")
ops = term.ops
def append_to_circuit(circuit, t):
if not ops:
return
for op in ops:
n = op.n
if op.op == "X":
circuit.h[n]
elif op.op == "Y":
circuit.rx(-half_pi)[n]
for i in range(1, len(ops)):
circuit.cx[ops[i-1].n, ops[i].n]
circuit.rz(-2 * coeff * t)[ops[-1].n]
for i in range(len(ops)-1, 0, -1):
circuit.cx[ops[i-1].n, ops[i].n]
for op in ops:
n = op.n
if op.op == "X":
circuit.h[n]
elif op.op == "Y":
circuit.rx(half_pi)[n]
return append_to_circuit | [
"def",
"get_time_evolution",
"(",
"self",
")",
":",
"term",
"=",
"self",
".",
"simplify",
"(",
")",
"coeff",
"=",
"term",
".",
"coeff",
"if",
"coeff",
".",
"imag",
":",
"raise",
"ValueError",
"(",
"\"Not a real coefficient.\"",
")",
"ops",
"=",
"term",
"... | Get the function to append the time evolution of this term.
Returns:
function(circuit: Circuit, t: float):
Add gates for time evolution to `circuit` with time `t` | [
"Get",
"the",
"function",
"to",
"append",
"the",
"time",
"evolution",
"of",
"this",
"term",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L481-L513 | train | 214,295 |
Blueqat/Blueqat | blueqat/pauli.py | Expr.is_identity | def is_identity(self):
"""If `self` is I, returns True, otherwise False."""
if not self.terms:
return True
return len(self.terms) == 1 and not self.terms[0].ops and self.terms[0].coeff == 1.0 | python | def is_identity(self):
"""If `self` is I, returns True, otherwise False."""
if not self.terms:
return True
return len(self.terms) == 1 and not self.terms[0].ops and self.terms[0].coeff == 1.0 | [
"def",
"is_identity",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"terms",
":",
"return",
"True",
"return",
"len",
"(",
"self",
".",
"terms",
")",
"==",
"1",
"and",
"not",
"self",
".",
"terms",
"[",
"0",
"]",
".",
"ops",
"and",
"self",
".",
... | If `self` is I, returns True, otherwise False. | [
"If",
"self",
"is",
"I",
"returns",
"True",
"otherwise",
"False",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L565-L569 | train | 214,296 |
Blueqat/Blueqat | blueqat/pauli.py | Expr.max_n | def max_n(self):
"""Returns the maximum index of Pauli matrices in the Term."""
return max(term.max_n() for term in self.terms if term.ops) | python | def max_n(self):
"""Returns the maximum index of Pauli matrices in the Term."""
return max(term.max_n() for term in self.terms if term.ops) | [
"def",
"max_n",
"(",
"self",
")",
":",
"return",
"max",
"(",
"term",
".",
"max_n",
"(",
")",
"for",
"term",
"in",
"self",
".",
"terms",
"if",
"term",
".",
"ops",
")"
] | Returns the maximum index of Pauli matrices in the Term. | [
"Returns",
"the",
"maximum",
"index",
"of",
"Pauli",
"matrices",
"in",
"the",
"Term",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L707-L709 | train | 214,297 |
Blueqat/Blueqat | blueqat/pauli.py | Expr.is_all_terms_commutable | def is_all_terms_commutable(self):
"""Test whether all terms are commutable. This function may very slow."""
return all(is_commutable(a, b) for a, b in combinations(self.terms, 2)) | python | def is_all_terms_commutable(self):
"""Test whether all terms are commutable. This function may very slow."""
return all(is_commutable(a, b) for a, b in combinations(self.terms, 2)) | [
"def",
"is_all_terms_commutable",
"(",
"self",
")",
":",
"return",
"all",
"(",
"is_commutable",
"(",
"a",
",",
"b",
")",
"for",
"a",
",",
"b",
"in",
"combinations",
"(",
"self",
".",
"terms",
",",
"2",
")",
")"
] | Test whether all terms are commutable. This function may very slow. | [
"Test",
"whether",
"all",
"terms",
"are",
"commutable",
".",
"This",
"function",
"may",
"very",
"slow",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L724-L726 | train | 214,298 |
Blueqat/Blueqat | blueqat/pauli.py | Expr.simplify | def simplify(self):
"""Simplify the Expr."""
d = defaultdict(float)
for term in self.terms:
term = term.simplify()
d[term.ops] += term.coeff
return Expr.from_terms_iter(
Term.from_ops_iter(k, d[k]) for k in sorted(d, key=repr) if d[k]) | python | def simplify(self):
"""Simplify the Expr."""
d = defaultdict(float)
for term in self.terms:
term = term.simplify()
d[term.ops] += term.coeff
return Expr.from_terms_iter(
Term.from_ops_iter(k, d[k]) for k in sorted(d, key=repr) if d[k]) | [
"def",
"simplify",
"(",
"self",
")",
":",
"d",
"=",
"defaultdict",
"(",
"float",
")",
"for",
"term",
"in",
"self",
".",
"terms",
":",
"term",
"=",
"term",
".",
"simplify",
"(",
")",
"d",
"[",
"term",
".",
"ops",
"]",
"+=",
"term",
".",
"coeff",
... | Simplify the Expr. | [
"Simplify",
"the",
"Expr",
"."
] | 2ac8592c79e7acf4f385d982af82fbd68dafa5cc | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L728-L735 | train | 214,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.