code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# Validate the path
if not path:
raise ValueError("Empty path")
elif not is_string(path):
raise ValueError("Path must be a string")
# Validate the visitor
if visitor is None:
raise ValueError("No visitor method given")
# Use ... | def install_visiting(self, path, visitor, prefix=None) | Installs all the modules found in the given path if they are accepted
by the visitor.
The visitor must be a callable accepting 3 parameters:
* fullname: The full name of the module
* is_package: If True, the module is a package
* module_path: The path to the module fil... | 2.83794 | 2.563355 | 1.107119 |
# type: (Bundle, Union[List[Any], type, str], object, dict, bool, bool, bool) -> ServiceRegistration
if bundle is None or service is None or not clazz:
raise BundleException("Invalid registration parameters")
if not isinstance(properties, dict):
# Be sure we hav... | def register_service(
self,
bundle,
clazz,
service,
properties,
send_event,
factory=False,
prototype=False,
) | Registers a service and calls the listeners
:param bundle: The bundle registering the service
:param clazz: Name(s) of the interface(s) implemented by service
:param service: The service to register
:param properties: Service properties
:param send_event: If not, doesn't trigger... | 3.416272 | 3.548625 | 0.962703 |
# type: () -> bool
with self._lock:
if self._state in (Bundle.STARTING, Bundle.ACTIVE):
# Already started framework
return False
# Reset the stop event
self._fw_stop_event.clear()
# Starting...
self._s... | def start(self) | Starts the framework
:return: True if the bundle has been started, False if it was already
running
:raise BundleException: A bundle failed to start | 4.377243 | 4.275373 | 1.023827 |
# type: () -> bool
with self._lock:
if self._state != Bundle.ACTIVE:
# Invalid state
return False
# Hide all services (they will be deleted by bundle.stop())
for bundle in self.__bundles.values():
self._registr... | def stop(self) | Stops the framework
:return: True if the framework stopped, False it wasn't running | 3.69662 | 3.655204 | 1.011331 |
if not force and self._state not in (
Bundle.INSTALLED,
Bundle.RESOLVED,
Bundle.STOPPING,
):
_logger.warning("Trying to delete an active framework")
return False
return FrameworkFactory.delete_framework(self) | def delete(self, force=False) | Deletes the current framework
:param force: If True, stops the framework before deleting it
:return: True if the framework has been delete, False if is couldn't | 7.27061 | 6.244706 | 1.164284 |
# type: (Bundle) -> None
if bundle is None:
# Do nothing
return
with self.__bundles_lock:
# Stop the bundle first
bundle.stop()
bundle_id = bundle.get_bundle_id()
if bundle_id not in self.__bundles:
... | def uninstall_bundle(self, bundle) | Ends the uninstallation of the given bundle (must be called by Bundle)
:param bundle: The bundle to uninstall
:raise BundleException: Invalid bundle | 4.012131 | 4.130126 | 0.971431 |
# type: (ServiceRegistration) -> bool
# Get the Service Reference
reference = registration.get_reference()
# Remove the service from the registry
svc_instance = self._registry.unregister(reference)
# Keep a track of the unregistering reference
self.__un... | def unregister_service(self, registration) | Unregisters the given service
:param registration: A ServiceRegistration to the service to unregister
:raise BundleException: Invalid reference | 4.136935 | 4.335472 | 0.954207 |
with self._lock:
if self._state == Bundle.ACTIVE:
self.stop()
self.start() | def update(self) | Stops and starts the framework, if the framework is active.
:raise BundleException: Something wrong occurred while stopping or
starting the framework. | 8.570922 | 4.768551 | 1.797385 |
# type: (Optional[int]) -> bool
if self._state != Bundle.ACTIVE:
# Inactive framework, ignore the call
return True
self._fw_stop_event.wait(timeout)
with self._lock:
# If the timeout raised, we should be in another state
return s... | def wait_for_stop(self, timeout=None) | Waits for the framework to stop. Does nothing if the framework bundle
is not in ACTIVE state.
Uses a threading.Condition object
:param timeout: The maximum time to wait (in seconds)
:return: True if the framework has stopped, False if the timeout raised | 8.391638 | 7.118028 | 1.178927 |
# type: (Any) -> bool
return self.__registry.unget_service(
self.__bundle, self.__reference, service
) | def unget_service(self, service) | Releases a service object for the associated service.
:param service: An instance of a service returned by ``get_service()``
:return: True if the bundle usage has been removed | 8.43528 | 14.00403 | 0.602347 |
return self.__framework._dispatcher.add_service_listener(
self, listener, specification, ldap_filter
) | def add_service_listener(
self, listener, ldap_filter=None, specification=None
) | Registers a service listener
The service listener must have a method with the following prototype::
def service_changed(self, event):
'''
Called by Pelix when some service properties changes
event: A ServiceEvent object
'''
... | 7.606052 | 13.20085 | 0.576179 |
# type: (Union[Bundle, int]) -> Bundle
if bundle_id is None:
# Current bundle
return self.__bundle
elif isinstance(bundle_id, Bundle):
# Got a bundle (compatibility with older install_bundle())
bundle_id = bundle_id.get_bundle_id()
... | def get_bundle(self, bundle_id=None) | Retrieves the :class:`~pelix.framework.Bundle` object for the bundle
matching the given ID (int). If no ID is given (None), the bundle
associated to this context is returned.
:param bundle_id: A bundle ID (optional)
:return: The requested :class:`~pelix.framework.Bundle` object
... | 4.241686 | 4.933907 | 0.859701 |
# type: (Optional[str], Optional[str]) -> Optional[ServiceReference]
result = self.__framework.find_service_references(
clazz, ldap_filter, True
)
try:
return result[0]
except TypeError:
return None | def get_service_reference(self, clazz, ldap_filter=None) | Returns a ServiceReference object for a service that implements and
was registered under the specified class
:param clazz: The class name with which the service was registered.
:param ldap_filter: A filter on service properties
:return: A service reference, None if not found | 4.205023 | 6.534309 | 0.64353 |
# type: (Optional[str], Optional[str]) -> Optional[List[ServiceReference]]
refs = self.__framework.find_service_references(clazz, ldap_filter)
if refs:
for ref in refs:
if ref.get_bundle() is not self.__bundle:
refs.remove(ref)
re... | def get_service_references(self, clazz, ldap_filter=None) | Returns the service references for services that were registered under
the specified class by this bundle and matching the given filter
:param clazz: The class name with which the service was registered.
:param ldap_filter: A filter on service properties
:return: The list of references ... | 3.198047 | 4.365897 | 0.732506 |
# type: (str, bool) -> tuple
return self.__framework.install_package(path, recursive) | def install_package(self, path, recursive=False) | Installs all the modules found in the given package (directory).
It is a utility method working like
:meth:`~pelix.framework.BundleContext.install_visiting`, with a visitor
accepting every module found.
:param path: Path of the package (folder)
:param recursive: If True, install... | 7.586584 | 21.175686 | 0.358269 |
# type: (Union[List[Any], type, str], object, dict, bool, bool, bool) -> ServiceRegistration
return self.__framework.register_service(
self.__bundle,
clazz,
service,
properties,
send_event,
factory,
prototype,
... | def register_service(
self,
clazz,
service,
properties,
send_event=True,
factory=False,
prototype=False,
) | Registers a service
:param clazz: Class or Classes (list) implemented by this service
:param service: The service instance
:param properties: The services properties (dictionary)
:param send_event: If not, doesn't trigger a service registered event
:param factory: If True, the g... | 3.725395 | 5.576505 | 0.668052 |
# type: (ServiceReference) -> bool
# Lose the dependency
return self.__framework._registry.unget_service(
self.__bundle, reference
) | def unget_service(self, reference) | Disables a reference to the service
:return: True if the bundle was using this reference, else False | 11.608808 | 17.830256 | 0.651074 |
# type: (Optional[dict]) -> Framework
if cls.__singleton is None:
# Normalize sys.path
normalize_path()
cls.__singleton = Framework(properties)
return cls.__singleton | def get_framework(cls, properties=None) | If it doesn't exist yet, creates a framework with the given properties,
else returns the current framework instance.
:return: A Pelix instance | 8.332505 | 12.358466 | 0.674235 |
# type: (Optional[Framework]) -> bool
# pylint: disable=W0212
if framework is None:
framework = cls.__singleton
if framework is cls.__singleton:
# Stop the framework
try:
framework.stop()
except:
_l... | def delete_framework(cls, framework=None) | Removes the framework singleton
:return: True on success, else False | 3.132807 | 3.351407 | 0.934774 |
# type: (List[str], Optional[List[str]]) -> Optional[List[str]]
if object_class is None or exported_intfs is None:
return None
if isinstance(exported_intfs, str) and exported_intfs == "*":
return object_class
# after this exported_intfs will be list
exported_intfs = get_string... | def get_matching_interfaces(object_class, exported_intfs) | Returns the list of interfaces matching the export property
:param object_class: The specifications of the service
:param exported_intfs: The declared exported interfaces
:return: The list of declared exported interfaces | 3.396062 | 3.965549 | 0.856391 |
# type: (str, Dict[str, Any], Any) -> Any
if not props:
return default
try:
return props[name]
except KeyError:
return default | def get_prop_value(name, props, default=None) | Returns the value of a property or the default one
:param name: Name of a property
:param props: Dictionary of properties
:param default: Default value
:return: The value of the property or the default one | 2.49792 | 4.544495 | 0.549659 |
# type: (str, Dict[str, Any], Any) -> None
value = get_prop_value(name, props)
if value is None:
props[name] = if_null | def set_prop_if_null(name, props, if_null) | Updates the value of a property if the previous one was None
:param name: Name of the property
:param props: Dictionary of properties
:param if_null: Value to insert if the previous was None | 2.783698 | 4.86623 | 0.572044 |
# type: (Any) -> Optional[List[str]]
if value:
if isinstance(value, str):
return [value]
if isinstance(value, list):
return value
if isinstance(value, tuple):
return list(value)
return None | def get_string_plus_property_value(value) | Converts a string or list of string into a list of strings
:param value: A string or a list of strings
:return: A list of strings or None | 2.51577 | 3.077253 | 0.817538 |
# type: (str, Dict[str, Any], Optional[Any]) -> Any
val = get_string_plus_property_value(get_prop_value(name, props, default))
return default if val is None else val | def get_string_plus_property(name, props, default=None) | Returns the value of the given property or the default value
:param name: A property name
:param props: A dictionary of properties
:param default: Value to return if the property doesn't exist
:return: The property value or the default one | 3.528529 | 6.555765 | 0.538233 |
# type: (ServiceReference, Optional[Dict[str, Any]]) -> Optional[List[str]]
# first check overriding_props for service.exported.interfaces
exported_intfs = get_prop_value(
SERVICE_EXPORTED_INTERFACES, overriding_props
)
# then check svc_ref property
if not exported_intfs:
ex... | def get_exported_interfaces(svc_ref, overriding_props=None) | Looks for the interfaces exported by a service
:param svc_ref: Service reference
:param overriding_props: Properties overriding service ones
:return: The list of exported interfaces | 2.856621 | 3.555022 | 0.803545 |
# type: (List[str], List[str]) -> bool
if (
not exported_intfs
or not isinstance(exported_intfs, list)
or not exported_intfs
):
return False
else:
for exintf in exported_intfs:
if exintf not in object_class:
return False
return... | def validate_exported_interfaces(object_class, exported_intfs) | Validates that the exported interfaces are all provided by the service
:param object_class: The specifications of a service
:param exported_intfs: The exported specifications
:return: True if the exported specifications are all provided by the service | 2.759139 | 3.407066 | 0.809828 |
# type: (List[str], Dict[str, Any]) -> List[Tuple[str, str]]
result = []
for intf in intfs:
pkg_name = get_package_from_classname(intf)
if pkg_name:
key = ENDPOINT_PACKAGE_VERSION_ + pkg_name
val = props.get(key, None)
if val:
result.a... | def get_package_versions(intfs, props) | Gets the package version of interfaces
:param intfs: A list of interfaces
:param props: A dictionary containing endpoint package versions
:return: A list of tuples (package name, version) | 3.2558 | 3.920547 | 0.830445 |
results = {}
if not object_class:
raise ArgumentError(
"object_class", "object_class must be an [] of Strings"
)
results["objectClass"] = object_class
if not exported_cfgs:
raise ArgumentError(
"exported_cfgs", "exported_cfgs must be an array of Strin... | def get_rsa_props(
object_class,
exported_cfgs,
remote_intents=None,
ep_svc_id=None,
fw_id=None,
pkg_vers=None,
service_intents=None,
) | Constructs a dictionary of RSA properties from the given arguments
:param object_class: Service specifications
:param exported_cfgs: Export configurations
:param remote_intents: Supported remote intents
:param ep_svc_id: Endpoint service ID
:param fw_id: Remote Framework ID
:param pkg_vers: Ver... | 2.794758 | 2.798086 | 0.998811 |
results = {}
if not ep_id:
raise ArgumentError("ep_id", "ep_id must be a valid endpoint id")
results[ECF_ENDPOINT_ID] = ep_id
if not ep_id_ns:
raise ArgumentError("ep_id_ns", "ep_id_ns must be a valid namespace")
results[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = ep_id_ns
if not ... | def get_ecf_props(ep_id, ep_id_ns, rsvc_id=None, ep_ts=None) | Prepares the ECF properties
:param ep_id: Endpoint ID
:param ep_id_ns: Namespace of the Endpoint ID
:param rsvc_id: Remote service ID
:param ep_ts: Timestamp of the endpoint
:return: A dictionary of ECF properties | 2.309189 | 2.29575 | 1.005854 |
# type: (Dict[str, Any]) -> Dict[str, Any]
return {
key: value
for key, value in props.items()
if key not in ECFPROPNAMES
and key not in RSA_PROP_NAMES
and not key.startswith(ENDPOINT_PACKAGE_VERSION_)
} | def get_extra_props(props) | Returns the extra properties, *i.e.* non-ECF, non-RSA properties
:param props: A dictionary of properties
:return: A filtered dictionary | 6.556629 | 5.486412 | 1.195067 |
osgi_props = get_rsa_props(
object_class,
exported_cfgs,
remote_intents,
ep_rsvc_id,
fw_id,
pkg_ver,
service_intents,
)
ecf_props = get_ecf_props(ecf_ep_id, ep_namespace, ep_rsvc_id, ep_ts)
return merge_dicts(osgi_props, ecf_props) | def get_edef_props(
object_class,
exported_cfgs,
ep_namespace,
ep_id,
ecf_ep_id,
ep_rsvc_id,
ep_ts,
remote_intents=None,
fw_id=None,
pkg_ver=None,
service_intents=None,
) | Prepares the EDEF properties of an endpoint, merge of RSA and ECF
properties | 2.330671 | 2.154568 | 1.081735 |
# type: (str, Dict[str, Any], bool) -> Dict[str, Any]
result_props = {}
if props:
dot_keys = [x for x in props.keys() if x.startswith(prefix + ".")]
for dot_key in dot_keys:
if remove_prefix:
new_key = dot_key[len(prefix) + 1 :]
else:
... | def get_dot_properties(prefix, props, remove_prefix) | Gets the properties starting with the given prefix | 1.963666 | 2.018492 | 0.972838 |
# type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any]
target.update(
{
key: value
for key, value in props.items()
if not is_reserved_property(key)
}
)
return target | def copy_non_reserved(props, target) | Copies all properties with non-reserved names from ``props`` to ``target``
:param props: A dictionary of properties
:param target: Another dictionary
:return: The target dictionary | 2.200669 | 3.50281 | 0.628258 |
# type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any]
target.update(
{key: value for key, value in props.items() if key not in ECFPROPNAMES}
)
return target | def copy_non_ecf(props, target) | Copies non-ECF properties from ``props`` to ``target``
:param props: An input dictionary
:param target: The dictionary to copy non-ECF properties to
:return: The ``target`` dictionary | 2.922781 | 4.657447 | 0.62755 |
# type: (set, Any) -> set
if item:
if isinstance(item, (list, tuple)):
input_set.update(item)
else:
input_set.add(item)
return input_set | def set_append(input_set, item) | Appends in-place the given item to the set.
If the item is a list, all elements are added to the set.
:param input_set: An existing set
:param item: The item or list of items to add
:return: The given set | 2.516371 | 3.627055 | 0.693778 |
# type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent
exc = import_reg.get_exception()
if exc:
return RemoteServiceAdminEvent(
RemoteServiceAdminEvent.IMPORT_ERROR,
bundle,
import_reg.get_import_container_id(),
... | def fromimportreg(cls, bundle, import_reg) | Creates a RemoteServiceAdminEvent object from an ImportRegistration | 2.590893 | 2.261446 | 1.14568 |
# type: (Bundle, ExportRegistration) -> RemoteServiceAdminEvent
exc = export_reg.get_exception()
if exc:
return RemoteServiceAdminEvent(
RemoteServiceAdminEvent.EXPORT_ERROR,
bundle,
export_reg.get_export_container_id(),
... | def fromexportreg(cls, bundle, export_reg) | Creates a RemoteServiceAdminEvent object from an ExportRegistration | 2.546676 | 2.202858 | 1.156078 |
# type: (Bundle, ExportRegistration) -> RemoteServiceAdminEvent
exc = export_reg.get_exception()
if exc:
return RemoteServiceAdminEvent(
RemoteServiceAdminEvent.EXPORT_ERROR,
bundle,
export_reg.get_export_container_id(),
... | def fromexportupdate(cls, bundle, export_reg) | Creates a RemoteServiceAdminEvent object from the update of an
ExportRegistration | 2.449213 | 2.149616 | 1.139372 |
# type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent
exc = import_reg.get_exception()
if exc:
return RemoteServiceAdminEvent(
RemoteServiceAdminEvent.IMPORT_ERROR,
bundle,
import_reg.get_import_container_id(),
... | def fromimportupdate(cls, bundle, import_reg) | Creates a RemoteServiceAdminEvent object from the update of an
ImportRegistration | 2.529555 | 2.217298 | 1.140828 |
# type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], ImportReference, Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent
return RemoteServiceAdminEvent(
typ=RemoteServiceAdminEvent.IMPORT_UNREGISTRATION,
bundle=bundle,
c... | def fromimportunreg(
cls, bundle, cid, rsid, import_ref, exception, endpoint
) | Creates a RemoteServiceAdminEvent object from the departure of an
ImportRegistration | 3.35817 | 2.898666 | 1.158522 |
# type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], ExportReference, Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent
return RemoteServiceAdminEvent(
typ=RemoteServiceAdminEvent.EXPORT_UNREGISTRATION,
bundle=bundle,
c... | def fromexportunreg(
cls, bundle, exporterid, rsid, export_ref, exception, endpoint
) | Creates a RemoteServiceAdminEvent object from the departure of an
ExportRegistration | 3.775641 | 3.351076 | 1.126695 |
# type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent
return RemoteServiceAdminEvent(
RemoteServiceAdminEvent.IMPORT_ERROR,
bundle,
importerid,
rsid,
... | def fromimporterror(cls, bundle, importerid, rsid, exception, endpoint) | Creates a RemoteServiceAdminEvent object from an import error | 4.254805 | 3.671416 | 1.1589 |
# type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent
return RemoteServiceAdminEvent(
RemoteServiceAdminEvent.EXPORT_ERROR,
bundle,
exporterid,
rsid,
... | def fromexporterror(cls, bundle, exporterid, rsid, exception, endpoint) | Creates a RemoteServiceAdminEvent object from an export error | 4.385797 | 3.665429 | 1.19653 |
# type: (Any, str, str) -> None
try:
# Get component properties
with self.__lock:
properties = self.__queue[factory][component]
except KeyError:
# Component not in queue
return
else:
try:
... | def _try_instantiate(self, ipopo, factory, component) | Tries to instantiate a component from the queue. Hides all exceptions.
:param ipopo: The iPOPO service
:param factory: Component factory
:param component: Component name | 4.268896 | 4.654321 | 0.91719 |
try:
# Try to register to factory events
with use_ipopo(self.__context) as ipopo:
ipopo.add_listener(self)
except BundleException:
# Service not yet present
pass
# Register the iPOPO service listener
self.__context... | def _start(self) | Starts the instantiation queue (called by its bundle activator) | 9.440373 | 8.525169 | 1.107353 |
# Unregisters the iPOPO service listener
self.__context.remove_service_listener(self)
try:
# Try to register to factory events
with use_ipopo(self.__context) as ipopo:
ipopo.remove_listener(self)
except BundleException:
# Serv... | def _stop(self) | Stops the instantiation queue (called by its bundle activator) | 9.819207 | 8.244326 | 1.191026 |
self.__names.clear()
self.__queue.clear()
self.__context = None | def _clear(self) | Clear all references (called by its bundle activator) | 12.008083 | 9.125 | 1.315954 |
# type: (ServiceEvent) -> None
kind = event.get_kind()
if kind == ServiceEvent.REGISTERED:
# iPOPO service registered: register to factory events
with use_ipopo(self.__context) as ipopo:
ipopo.add_listener(self) | def service_changed(self, event) | Handles an event about the iPOPO service | 7.184907 | 5.960534 | 1.205413 |
# type: (IPopoEvent) -> None
kind = event.get_kind()
if kind == IPopoEvent.REGISTERED:
# A factory has been registered
try:
with use_ipopo(self.__context) as ipopo:
factory = event.get_factory_name()
with s... | def handle_ipopo_event(self, event) | Handles an iPOPO event
:param event: iPOPO event bean | 5.685606 | 6.035426 | 0.942039 |
# type: (str, str, dict) -> None
with self.__lock:
if component in self.__names:
raise ValueError(
"Component name already queued: {0}".format(component)
)
# Normalize properties
if properties is None:
... | def add(self, factory, component, properties=None) | Enqueues the instantiation of the given component
:param factory: Factory name
:param component: Component name
:param properties: Component properties
:raise ValueError: Component name already reserved in the queue
:raise Exception: Error instantiating the component | 5.064974 | 5.06797 | 0.999409 |
# type: (str) -> None
with self.__lock:
# Find its factory
factory = self.__names.pop(component)
components = self.__queue[factory]
# Clear the queue
del components[component]
if not components:
# No more c... | def remove(self, component) | Kills/Removes the component with the given name
:param component: A component name
:raise KeyError: Unknown component | 6.51306 | 6.989153 | 0.931881 |
# Set up the request handler creator
active_flag = SharedBoolean(True)
def request_handler(*rh_args):
return RemoteConsole(shell, active_flag, *rh_args)
# Set up the server
server = ThreadingTCPServerFamily(
(server_address, port),
request_handler,
cer... | def _create_server(
shell,
server_address,
port,
cert_file=None,
key_file=None,
key_password=None,
ca_file=None,
) | Creates the TCP console on the given address and port
:param shell: The remote shell handler
:param server_address: Server bound address
:param port: Server port
:param cert_file: Path to the server certificate
:param key_file: Path to the server private key
:param key_password: Password for th... | 3.572068 | 3.342412 | 1.06871 |
# Script-only imports
import code
try:
import readline
import rlcompleter
readline.set_completer(rlcompleter.Completer(variables).complete)
readline.parse_and_bind("tab: complete")
except ImportError:
# readline is not available: ignore
pass
# ... | def _run_interpreter(variables, banner) | Runs a Python interpreter console and blocks until the user exits it.
:param variables: Interpreters variables (locals)
:param banner: Start-up banners | 3.147543 | 3.049884 | 1.03202 |
if data is not None:
data = data.encode("UTF-8")
try:
self.wfile.write(data)
self.wfile.flush()
return True
except IOError:
# An error occurred, mask it
# -> This allows to handle the command even if the client ha... | def send(self, data) | Tries to send data to the client.
:param data: Data to be sent
:return: True if the data was sent, False on error | 7.199827 | 7.499205 | 0.960079 |
_logger.info(
"RemoteConsole client connected: [%s]:%d",
self.client_address[0],
self.client_address[1],
)
# Prepare the session
session = beans.ShellSession(
beans.IOHandler(self.rfile, self.wfile),
{"remote_client_ip... | def handle(self) | Handles a TCP client | 3.81211 | 3.739875 | 1.019315 |
# Accept the client
client_socket, client_address = self.socket.accept()
if ssl is not None and self.cert_file:
# Setup an SSL context to accept clients with a certificate
# signed by a known chain of authority.
# Other clients will be rejected durin... | def get_request(self) | Accepts a new client. Sets up SSL wrapping if necessary.
:return: A tuple: (client socket, client address tuple) | 3.252142 | 3.075127 | 1.057563 |
thread = threading.Thread(
name="RemoteShell-{0}-Client-{1}".format(
self.server_address[1], client_address[:2]
),
target=self.process_request_thread,
args=(request, client_address),
)
thread.daemon = self.daemon_threads
... | def process_request(self, request, client_address) | Starts a new thread to process the request, adding the client address
in its name. | 3.693217 | 3.403336 | 1.085175 |
# type: (str, ShellSession, BundleContext, List[str], int) -> None
# Prepare a line pattern for each match (-1 for the trailing space)
match_pattern = "{{0: <{}}} from {{1}}".format(longest_match_len - 1)
# Sort matching names
matches = sorted(match for match in matches... | def display_hook(prompt, session, context, matches, longest_match_len) | Displays the available services matches and the service details
:param prompt: Shell prompt string
:param session: Current shell session (for display)
:param context: BundleContext of the shell
:param matches: List of words matching the substitution
:param longest_match_len: Len... | 5.618199 | 5.94315 | 0.945323 |
# type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str]
# Register a method to display helpful completion
self.set_display_hook(self.display_hook, prompt, session, context)
# Return a list of component factories
with use_ipopo(context) as... | def complete(
self, config, prompt, session, context, current_arguments, current
) | Returns the list of services IDs matching the current state
:param config: Configuration of the current completion
:param prompt: Shell prompt (for re-display)
:param session: Shell session (to display in shell)
:param context: Bundle context of the Shell bundle
:param current_a... | 7.337826 | 8.109385 | 0.904856 |
# type: (str, ShellSession, BundleContext, List[str], int) -> None
# Prepare a line pattern for each match (-1 for the trailing space)
match_pattern = "{{0: <{}}} from {{1}}".format(longest_match_len - 1)
# Sort matching names
matches = sorted(match for match in matches... | def display_hook(prompt, session, context, matches, longest_match_len) | Displays the available services matches and the service details
:param prompt: Shell prompt string
:param session: Current shell session (for display)
:param context: BundleContext of the shell
:param matches: List of words matching the substitution
:param longest_match_len: Len... | 6.281421 | 6.811136 | 0.922228 |
# type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str]
# Register a method to display helpful completion
self.set_display_hook(self.display_hook, prompt, session, context)
# Return a list of component factories
with use_ipopo(context) as... | def complete(
self, config, prompt, session, context, current_arguments, current
) | Returns the list of services IDs matching the current state
:param config: Configuration of the current completion
:param prompt: Shell prompt (for re-display)
:param session: Shell session (to display in shell)
:param context: Bundle context of the Shell bundle
:param current_a... | 7.672668 | 8.426725 | 0.910516 |
# type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str]
with use_ipopo(context) as ipopo:
try:
# Find the factory name
for idx, completer_id in enumerate(config.completers):
if completer_id == FACTOR... | def complete(
self, config, prompt, session, context, current_arguments, current
) | Returns the list of services IDs matching the current state
:param config: Configuration of the current completion
:param prompt: Shell prompt (for re-display)
:param session: Shell session (to display in shell)
:param context: Bundle context of the Shell bundle
:param current_a... | 3.714745 | 4.143408 | 0.896543 |
return self._handler.headers.get(name, default) | def get_header(self, name, default=None) | Retrieves the value of a header | 9.505535 | 9.371655 | 1.014286 |
# Send them all at once
for name, value in self._headers.items():
self._handler.send_header(name, value)
self._handler.end_headers() | def end_headers(self) | Ends the headers part | 4.119578 | 4.178271 | 0.985953 |
# pylint: disable=W0221
self._service.log(logging.ERROR, message, *args, **kwargs) | def log_error(self, message, *args, **kwargs) | Log server error | 4.81416 | 4.790237 | 1.004994 |
self._service.log(logging.DEBUG, '"%s" %s', self.requestline, code) | def log_request(self, code="-", size="-") | Logs a request to the server | 10.962089 | 10.422565 | 1.051765 |
# Use the helper to send the error page
response = _HTTPServletResponse(self)
response.send_content(404, self._service.make_not_found_page(self.path)) | def send_no_servlet_response(self) | Default response sent when no servlet is found for the requested path | 10.319681 | 10.097523 | 1.022001 |
# Get a formatted stack trace
stack = traceback.format_exc()
# Log the error
self.log_error(
"Error handling request upon: %s\n%s\n", self.path, stack
)
# Send the page
response.send_content(
500, self._service.make_exception_pag... | def send_exception(self, response) | Sends an exception page with a 500 error code.
Must be called from inside the exception handling block.
:param response: The response handler | 5.546956 | 5.506829 | 1.007287 |
TCPServer.server_bind(self)
host, port = self.socket.getsockname()[:2]
self.server_port = port
try:
self.server_name = socket.getfqdn(host)
except ValueError:
# Use the local host name in case of error, like CPython does
self.server_na... | def server_bind(self) | Override server_bind to store the server name, even in IronPython.
See https://ironpython.codeplex.com/workitem/29477 | 3.369906 | 3.559123 | 0.946836 |
# type: (str, Iterable) -> Dict[str, str]
if not list_:
return {}
return {key: " ".join(str(i) for i in list_)} | def encode_list(key, list_) | Converts a list into a space-separated string and puts it in a dictionary
:param key: Dictionary key to store the list
:param list_: A list of objects
:return: A dictionary key->string or an empty dictionary | 3.557175 | 4.923288 | 0.72252 |
# type: (str) -> str
if not package:
return ""
lastdot = package.rfind(".")
if lastdot == -1:
return package
return package[:lastdot] | def package_name(package) | Returns the package name of the given module name | 3.228674 | 3.347199 | 0.96459 |
# type: (EndpointDescription) -> Dict[str, str]
result_props = {}
intfs = ed.get_interfaces()
result_props[OBJECTCLASS] = " ".join(intfs)
for intf in intfs:
pkg_name = package_name(intf)
ver = ed.get_package_version(pkg_name)
if ver and not ver == (0, 0, 0):
... | def encode_osgi_props(ed) | Prepares a dictionary of OSGi properties for the given EndpointDescription | 2.330689 | 2.329799 | 1.000382 |
# type: (Dict[str, str], str) -> List[str]
val_str = input_props.get(name, None)
if val_str:
return val_str.split(" ")
return [] | def decode_list(input_props, name) | Decodes a space-separated list | 2.953738 | 2.958149 | 0.998509 |
# type: (Dict[str, Any]) -> Dict[str, Any]
result_props = {}
intfs = decode_list(input_props, OBJECTCLASS)
result_props[OBJECTCLASS] = intfs
for intf in intfs:
package_key = ENDPOINT_PACKAGE_VERSION_ + package_name(intf)
intfversionstr = input_props.get(package_key, None)
... | def decode_osgi_props(input_props) | Decodes the OSGi properties of the given endpoint properties | 2.243706 | 2.223402 | 1.009132 |
# type: (Dict) -> Dict[str, Any]
ed_props = decode_osgi_props(input_props)
ed_props[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = input_props[
ECF_ENDPOINT_CONTAINERID_NAMESPACE
]
ed_props[ECF_RSVC_ID] = int(input_props[ECF_RSVC_ID])
ed_props[ECF_ENDPOINT_ID] = input_props[ECF_ENDPOINT_ID]
... | def decode_endpoint_props(input_props) | Decodes the endpoint properties from the given dictionary | 2.086761 | 2.091502 | 0.997733 |
props = encode_osgi_props(ed)
props[ECF_RSVC_ID] = "{0}".format(ed.get_remoteservice_id()[1])
props[ECF_ENDPOINT_ID] = "{0}".format(ed.get_container_id()[1])
props[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = "{0}".format(
ed.get_container_id()[0]
)
props[ECF_ENDPOINT_TIMESTAMP] = "{0}".fo... | def encode_endpoint_props(ed) | Encodes the properties of the given EndpointDescription | 2.608444 | 2.603976 | 1.001716 |
# type: (str) -> Tuple[int, int, int]
name = "{0}{1}".format(ENDPOINT_PACKAGE_VERSION_, package)
try:
# Get the version string
version = self._properties[name]
# Split dots ('.')
return tuple(version.split("."))
except KeyError:
... | def get_package_version(self, package) | Provides the version of the given package name.
:param package: The name of the package
:return: The version of the specified package as a tuple or (0,0,0) | 5.777816 | 6.774357 | 0.852895 |
# type: (EndpointDescription) -> bool
return (
self.get_framework_uuid() == endpoint.get_framework_uuid()
and self.get_service_id() == endpoint.get_service_id()
) | def is_same_service(self, endpoint) | Tests if this endpoint and the given one have the same framework UUID
and service ID
:param endpoint: Another endpoint
:return: True if both endpoints represent the same remote service | 3.484524 | 3.217936 | 1.082845 |
if not prefix:
# Normalize string
prefix = ""
else:
# Truncate long prefixes
prefix = prefix[:8]
# Prepare the missing part
nb_bytes = (23 - len(prefix)) // 2
random_bytes = os.urandom(nb_bytes)
if sys.version_inf... | def generate_id(cls, prefix="pelix-") | Generates a random MQTT client ID
:param prefix: Client ID prefix (truncated to 8 chars)
:return: A client ID of 22 or 23 characters | 3.202429 | 3.113571 | 1.028539 |
self.__mqtt.will_set(topic, payload, qos, retain=retain) | def set_will(self, topic, payload, qos=0, retain=False) | Sets up the will message
:param topic: Topic of the will message
:param payload: Content of the message
:param qos: Quality of Service
:param retain: The message will be retained
:raise ValueError: Invalid topic
:raise TypeError: Invalid payload | 3.993083 | 5.610766 | 0.711682 |
# Disconnect first (it also stops the timer)
self.disconnect()
# Prepare the connection
self.__mqtt.connect(host, port, keepalive)
# Start the MQTT loop
self.__mqtt.loop_start() | def connect(self, host="localhost", port=1883, keepalive=60) | Connects to the MQTT server. The client will automatically try to
reconnect to this server when the connection is lost.
:param host: MQTT server host
:param port: MQTT server port
:param keepalive: Maximum period in seconds between communications with
the broke... | 5.568456 | 5.795924 | 0.960754 |
# Stop the timer
self.__stop_timer()
# Unlock all publishers
for event in self.__in_flight.values():
event.set()
# Disconnect from the server
self.__mqtt.disconnect()
# Stop the MQTT loop thread
# Use a thread to avoid a dead lock i... | def disconnect(self) | Disconnects from the MQTT server | 5.258944 | 4.76182 | 1.104398 |
result = self.__mqtt.publish(topic, payload, qos, retain)
if wait and not result[0]:
# Publish packet sent, wait for it to return
self.__in_flight[result[1]] = threading.Event()
_logger.debug("Waiting for publication of %s", topic)
return result[1] | def publish(self, topic, payload, qos=0, retain=False, wait=False) | Sends a message through the MQTT connection
:param topic: Message topic
:param payload: Message content
:param qos: Quality of Service
:param retain: Retain flag
:param wait: If True, prepares an event to wait for the message to be
published
:return:... | 5.124748 | 5.607149 | 0.913967 |
self.__timer = threading.Timer(delay, self.__reconnect)
self.__timer.daemon = True
self.__timer.start() | def __start_timer(self, delay) | Starts the reconnection timer
:param delay: Delay (in seconds) before calling the reconnection method | 3.097854 | 2.630097 | 1.177848 |
# Cancel the timer, if any
self.__stop_timer()
try:
# Try to reconnect the server
result_code = self.__mqtt.reconnect()
if result_code:
# Something wrong happened
message = "Error connecting the MQTT server: {0} ({1})"... | def __reconnect(self) | Tries to connect to the MQTT server | 4.45035 | 4.277054 | 1.040518 |
# pylint: disable=W0613
if result_code:
# result_code != 0: something wrong happened
_logger.error(
"Error connecting the MQTT server: %s (%d)",
paho.connack_string(result_code),
result_code,
)
else:
... | def __on_connect(self, client, userdata, flags, result_code) | Client connected to the server
:param client: Connected Paho client
:param userdata: User data (unused)
:param flags: Response flags sent by the broker
:param result_code: Connection result code (0: success, others: error) | 3.571366 | 3.719397 | 0.9602 |
# pylint: disable=W0613
if result_code:
# rc != 0: unexpected disconnection
_logger.error(
"Unexpected disconnection from the MQTT server: %s (%d)",
paho.connack_string(result_code),
result_code,
)
... | def __on_disconnect(self, client, userdata, result_code) | Client has been disconnected from the server
:param client: Client that received the message
:param userdata: User data (unused)
:param result_code: Disconnection reason (0: expected, 1: error) | 3.560832 | 3.744399 | 0.950976 |
# pylint: disable=W0613
# Notify the caller, if any
if self.on_message is not None:
try:
self.on_message(self, msg)
except Exception as ex:
_logger.exception("Error notifying MQTT listener: %s", ex) | def __on_message(self, client, userdata, msg) | A message has been received from a server
:param client: Client that received the message
:param userdata: User data (unused)
:param msg: A MQTTMessage bean | 3.517038 | 3.868289 | 0.909197 |
# pylint: disable=W0613
try:
self.__in_flight[mid].set()
except KeyError:
pass | def __on_publish(self, client, userdata, mid) | A message has been published by a server
:param client: Client that received the message
:param userdata: User data (unused)
:param mid: Message ID | 4.377739 | 6.950458 | 0.629849 |
# type: (dict) -> dict
# Copy the given dictionary
props = properties.copy()
# Add the "imported" property
props[pelix.remote.PROP_IMPORTED] = True
# Remote service ID
try:
props[pelix.remote.PROP_ENDPOINT_SERVICE_ID] = props.pop(
pelix.constants.SERVICE_ID
... | def to_import_properties(properties) | Returns a dictionary where export properties have been replaced by import
ones
:param properties: A dictionary of service properties (with export keys)
:return: A dictionary with import properties | 3.144916 | 3.290761 | 0.955681 |
# type: (pelix.framework.ServiceReference) -> List[str]
if svc_ref.get_property(pelix.remote.PROP_EXPORT_NONE):
# The export of this service is explicitly forbidden, stop here
return []
# Service specifications
specs = svc_ref.get_property(pelix.constants.OBJECTCLASS)
# Export... | def compute_exported_specifications(svc_ref) | Computes the list of specifications exported by the given service
:param svc_ref: A ServiceReference
:return: The list of exported specifications (or an empty list) | 2.872245 | 3.017678 | 0.951806 |
# type: (Any[str, List[str]], dict) -> List[str]
all_specs = set(pelix.utilities.to_iterable(specifications))
try:
synonyms = pelix.utilities.to_iterable(
properties[pelix.remote.PROP_SYNONYMS], False
)
all_specs.update(synonyms)
except KeyError:
# No syn... | def extract_specifications(specifications, properties) | Converts "python:/name" specifications to "name". Keeps the other
specifications as is.
:param specifications: The specifications found in a remote registration
:param properties: Service properties
:return: The filtered specifications (as a list) | 4.328602 | 4.358475 | 0.993146 |
# type: (Iterable[str]) -> List[str]
transformed = set()
for original in specifications:
try:
lang, spec = _extract_specification_parts(original)
transformed.add(_format_specification(lang, spec))
except ValueError:
# Ignore invalid specifications
... | def format_specifications(specifications) | Transforms the interfaces names into URI strings, with the interface
implementation language as a scheme.
:param specifications: Specifications to transform
:return: The transformed names | 4.599059 | 5.356467 | 0.858599 |
# type: (str) -> Tuple[str, str]
try:
# Parse the URI-like string
parsed = urlparse(specification)
except:
# Invalid URL
raise ValueError("Invalid specification URL: {0}".format(specification))
# Extract the interface name
interface = parsed.path
# Extract ... | def _extract_specification_parts(specification) | Extract the language and the interface from a "language:/interface"
interface name
:param specification: The formatted interface name
:return: A (language, interface name) tuple
:raise ValueError: Invalid specification content | 5.799042 | 5.336137 | 1.086749 |
# type: () -> dict
# Get service properties
properties = self.__reference.get_properties()
# Merge with local properties
properties.update(self.__properties)
# Some properties can't be merged
for key in pelix.constants.OBJECTCLASS, pelix.constants.SERVI... | def get_properties(self) | Returns merged properties
:return: Endpoint merged properties | 5.395291 | 5.47785 | 0.984929 |
# type: () -> dict
# Convert merged properties
props = to_import_properties(self.get_properties())
# Add the framework UID
props[pelix.remote.PROP_ENDPOINT_FRAMEWORK_UUID] = self.__fw_uid
return props | def make_import_properties(self) | Returns the properties of this endpoint where export properties have
been replaced by import ones
:return: A dictionary with import properties | 14.057942 | 14.825528 | 0.948225 |
# type: (dict) -> None
# Mandatory properties
mandatory = (
pelix.remote.PROP_ENDPOINT_ID,
pelix.remote.PROP_IMPORTED_CONFIGS,
pelix.constants.OBJECTCLASS,
)
for key in mandatory:
if key not in props:
raise ... | def __check_properties(props) | Checks that the given dictionary doesn't have export keys and has
import keys
:param props: Properties to validate
:raise ValueError: Invalid properties | 2.821241 | 2.892669 | 0.975307 |
# type: (str) -> Tuple[int, ...]
name = "{0}{1}".format(
pelix.remote.PROP_ENDPOINT_PACKAGE_VERSION_, package
)
try:
# Get the version string
version = self.__properties[name]
# Split dots ('.')
return tuple(version.sp... | def get_package_version(self, package) | Provides the version of the given package name.
:param package: The name of the package
:return: The version of the specified package as a tuple or (0,0,0) | 6.336111 | 7.524585 | 0.842055 |
# type: (Any[str, pelix.ldapfilter.LDAPFilter]) -> bool
return pelix.ldapfilter.get_ldap_filter(ldap_filter).matches(
self.__properties
) | def matches(self, ldap_filter) | Tests the properties of this EndpointDescription against the given
filter
:param ldap_filter: A filter
:return: True if properties matches the filter | 8.225801 | 11.672511 | 0.704716 |
# type: () -> ImportEndpoint
# Properties
properties = self.get_properties()
# Framework UUID
fw_uid = self.get_framework_uuid()
# Endpoint name
try:
# From Pelix UID
name = properties[pelix.remote.PROP_ENDPOINT_NAME]
exc... | def to_import(self) | Converts an EndpointDescription bean to an ImportEndpoint
:return: An ImportEndpoint bean | 5.912265 | 5.684118 | 1.040138 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.