_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9400 | Bot.transmit | train | def transmit(self, channel, message):
"""
Send the message to Slack.
:param channel: channel or user to whom the message should be sent.
If a ``thread`` attribute is present, that thread ID is used.
:param str message: message to send.
"""
target = (
self.slack.server.channels.find(channel)
or sel... | python | {
"resource": ""
} |
q9401 | splitem | train | def splitem(query):
"""
Split a query into choices
>>> splitem('dog, cat')
['dog', 'cat']
Disregards trailing punctuation.
>>> splitem('dogs, cats???')
['dogs', 'cats']
>>> splitem('cats!!!')
['cats']
Allow or
>>> splitem('dogs, cats or prarie dogs?')
['dogs', 'cats', 'prarie dogs']
Honors serial comm... | python | {
"resource": ""
} |
q9402 | urban_lookup | train | def urban_lookup(word):
'''
Return a Urban Dictionary definition for a word or None if no result was
found.
'''
url = "http://api.urbandictionary.com/v0/define"
params = dict(term=word)
resp = requests.get(url, params=params)
resp.raise_for_status()
res = resp.json()
if not res['list']:
return
return res['... | python | {
"resource": ""
} |
q9403 | passagg | train | def passagg(recipient, sender):
"""
Generate a passive-aggressive statement to recipient from sender.
"""
adj = random.choice(pmxbot.phrases.adjs)
if random.choice([False, True]):
# address the recipient last
lead = ""
trail = recipient if not recipient else ", %s" % recipient
else:
# address the recipien... | python | {
"resource": ""
} |
q9404 | config | train | def config(client, event, channel, nick, rest):
"Change the running config, something like a=b or a+=b or a-=b"
pattern = re.compile(r'(?P<key>\w+)\s*(?P<op>[+-]?=)\s*(?P<value>.*)$')
match = pattern.match(rest)
if not match:
return "Command not recognized"
res = match.groupdict()
key = res['key']
op = res['op... | python | {
"resource": ""
} |
q9405 | trap_exceptions | train | def trap_exceptions(results, handler, exceptions=Exception):
"""
Iterate through the results, but if an exception occurs, stop
processing the results and instead replace
the results with the output from the exception handler.
"""
try:
for result in results:
yield result
except exceptions as exc:
for resul... | python | {
"resource": ""
} |
q9406 | MongoDBQuotes.delete | train | def delete(self, lookup):
"""
If exactly one quote matches, delete it. Otherwise,
raise a ValueError.
"""
lookup, num = self.split_num(lookup)
if num:
result = self.find_matches(lookup)[num - 1]
else:
result, = self.find_matches(lookup)
self.db.delete_one(result) | python | {
"resource": ""
} |
q9407 | LoggingCommandBot._get_wrapper | train | def _get_wrapper():
"""
Get a socket wrapper based on SSL config.
"""
if not pmxbot.config.get('use_ssl', False):
return lambda x: x
return importlib.import_module('ssl').wrap_socket | python | {
"resource": ""
} |
q9408 | Response.getStatusCode | train | def getStatusCode(self):
"""
Returns the code of the status or None if it does not exist
:return:
Status code of the response
"""
if 'status' in self._response.keys():
if (self._response['status'] is not None) and ('code' in self._response['status'].keys... | python | {
"resource": ""
} |
q9409 | Response.getStatusMsg | train | def getStatusMsg(self):
"""
Returns the message of the status or an empty string if it does not exist
:return:
Status message of the response
"""
if 'status' in self._response.keys():
if (self._response['status'] is not None) and ('msg' in self._response... | python | {
"resource": ""
} |
q9410 | Response.getConsumedCredits | train | def getConsumedCredits(self):
"""
Returns the credit consumed by the request made
:return:
String with the number of credits consumed
"""
if 'status' in self._response.keys():
if (self._response['status'] is not None) and ('credits' in self._response['st... | python | {
"resource": ""
} |
q9411 | Response.getRemainingCredits | train | def getRemainingCredits(self):
"""
Returns the remaining credits for the license key used after the request was made
:return:
String with remaining credits
"""
if 'status' in self._response.keys():
if (self._response['status'] is not None) and ('remainin... | python | {
"resource": ""
} |
q9412 | Response.getResults | train | def getResults(self):
"""
Returns the results from the API without the status of the request
:return:
Dictionary with the results
"""
results = self._response.copy()
if 'status' in self._response.keys():
if results['status'] is not None:
... | python | {
"resource": ""
} |
q9413 | PoliceAPI.get_forces | train | def get_forces(self):
"""
Get a list of all police forces. Uses the forces_ API call.
.. _forces: https://data.police.uk/docs/method/forces/
:rtype: list
:return: A list of :class:`forces.Force` objects (one for each police
force represented in the API)
... | python | {
"resource": ""
} |
q9414 | PoliceAPI.get_neighbourhoods | train | def get_neighbourhoods(self, force):
"""
Get a list of all neighbourhoods for a force. Uses the neighbourhoods_
API call.
.. _neighbourhoods: https://data.police.uk/docs/method/neighbourhoods/
:param force: The force to get neighbourhoods for (either by ID or
... | python | {
"resource": ""
} |
q9415 | PoliceAPI.get_neighbourhood | train | def get_neighbourhood(self, force, id, **attrs):
"""
Get a specific neighbourhood. Uses the neighbourhood_ API call.
.. _neighbourhood: https://data.police.uk/docs/method/neighbourhood/
:param force: The force within which the neighbourhood resides (either
by ID o... | python | {
"resource": ""
} |
q9416 | PoliceAPI.locate_neighbourhood | train | def locate_neighbourhood(self, lat, lng):
"""
Find a neighbourhood by location. Uses the locate-neighbourhood_ API
call.
.. _locate-neighbourhood:
https://data.police.uk/docs/method/neighbourhood-locate/
:param lat: The latitude of the location.
:type lat: f... | python | {
"resource": ""
} |
q9417 | PoliceAPI.get_crime_categories | train | def get_crime_categories(self, date=None):
"""
Get a list of crime categories, valid for a particular date. Uses the
crime-categories_ API call.
.. _crime-categories:
https://data.police.uk/docs/method/crime-categories/
:rtype: list
:param date: The date of ... | python | {
"resource": ""
} |
q9418 | PoliceAPI.get_crime_category | train | def get_crime_category(self, id, date=None):
"""
Get a particular crime category by ID, valid at a particular date. Uses
the crime-categories_ API call.
:rtype: CrimeCategory
:param str id: The ID of the crime category to get.
:param date: The date that the given crime c... | python | {
"resource": ""
} |
q9419 | PoliceAPI.get_crime | train | def get_crime(self, persistent_id):
"""
Get a particular crime by persistent ID. Uses the outcomes-for-crime_
API call.
.. _outcomes-for-crime:
https://data.police.uk/docs/method/outcomes-for-crime/
:rtype: Crime
:param str persistent_id: The persistent ID o... | python | {
"resource": ""
} |
q9420 | PoliceAPI.get_crimes_point | train | def get_crimes_point(self, lat, lng, date=None, category=None):
"""
Get crimes within a 1-mile radius of a location. Uses the crime-street_
API call.
.. _crime-street: https//data.police.uk/docs/method/crime-street/
:rtype: list
:param lat: The latitude of the location.... | python | {
"resource": ""
} |
q9421 | PoliceAPI.get_crimes_area | train | def get_crimes_area(self, points, date=None, category=None):
"""
Get crimes within a custom area. Uses the crime-street_ API call.
.. _crime-street: https//data.police.uk/docs/method/crime-street/
:rtype: list
:param list points: A ``list`` of ``(lat, lng)`` tuples.
:pa... | python | {
"resource": ""
} |
q9422 | PoliceAPI.get_crimes_location | train | def get_crimes_location(self, location_id, date=None):
"""
Get crimes at a particular snap-point location. Uses the
crimes-at-location_ API call.
.. _crimes-at-location:
https://data.police.uk/docs/method/crimes-at-location/
:rtype: list
:param int location_... | python | {
"resource": ""
} |
q9423 | PoliceAPI.get_crimes_no_location | train | def get_crimes_no_location(self, force, date=None, category=None):
"""
Get crimes with no location for a force. Uses the crimes-no-location_
API call.
.. _crimes-no-location:
https://data.police.uk/docs/method/crimes-no-location/
:rtype: list
:param force: T... | python | {
"resource": ""
} |
q9424 | _retrocom | train | def _retrocom(rx, tx, game, kwargs):
"""
This function is the target for RetroWrapper's internal
process and does all the work of communicating with the
environment.
"""
env = RetroWrapper.retro_make_func(game, **kwargs)
# Sit around on the queue, waiting for calls from RetroWrapper
whi... | python | {
"resource": ""
} |
q9425 | RetroWrapper._ask_if_attr_is_callable | train | def _ask_if_attr_is_callable(self, attr):
"""
Returns whether or not the attribute is a callable.
"""
self._tx.put((RetroWrapper.symbol, attr, {}))
return self._rx.get() | python | {
"resource": ""
} |
q9426 | RetroWrapper.close | train | def close(self):
"""
Shutdown the environment.
"""
if "_tx" in self.__dict__ and "_proc" in self.__dict__:
self._tx.put(("close", (), {}))
self._proc.join() | python | {
"resource": ""
} |
q9427 | Request.addParam | train | def addParam(self, paramName, paramValue):
"""
Add a parameter to the request
:param paramName:
Name of the parameter
:param paramValue:
Value of the parameter
"""
if not paramName:
raise ValueError('paramName cannot be empty')
... | python | {
"resource": ""
} |
q9428 | Request.setContent | train | def setContent(self, type_, value):
"""
Sets the content that's going to be sent to analyze according to its type
:param type_:
Type of the content (text, file or url)
:param value:
Value of the content
"""
if type_ in [self.CONTENT_TYPE_TXT, sel... | python | {
"resource": ""
} |
q9429 | Request.sendRequest | train | def sendRequest(self, extraHeaders=""):
"""
Sends a request to the URL specified and returns a response only if the HTTP code returned is OK
:param extraHeaders:
Allows to configure additional headers in the request
:return:
Response object set to None if there ... | python | {
"resource": ""
} |
q9430 | ParserResponse.getLemmatization | train | def getLemmatization(self, fullPOSTag=False):
"""
This function obtains the lemmas and PoS for the text sent
:param fullPOSTag:
Set to true to obtain the complete PoS tag
:return:
Dictionary of tokens from the syntactic tree with their lemmas and PoS
"""
... | python | {
"resource": ""
} |
q9431 | TopicsResponse.getTypeLastNode | train | def getTypeLastNode(self, type_):
"""
Obtains the last node or leaf of the type specified
:param type_:
Type we want to analize (sementity, semtheme)
:return:
Last node of the type
"""
lastNode = ""
if type_ and (type(type_) is not list) ... | python | {
"resource": ""
} |
q9432 | ZooKeeperClient.__conn_listener | train | def __conn_listener(self, state):
"""
Connection event listener
:param state: The new connection state
"""
if state == KazooState.CONNECTED:
self.__online = True
if not self.__connected:
self.__connected = True
self._logger... | python | {
"resource": ""
} |
q9433 | ZooKeeperClient.start | train | def start(self):
"""
Starts the connection
"""
self.__stop = False
self._queue.start()
self._zk.start() | python | {
"resource": ""
} |
q9434 | ZooKeeperClient.stop | train | def stop(self):
"""
Stops the connection
"""
self.__stop = True
self._queue.stop()
self._zk.stop() | python | {
"resource": ""
} |
q9435 | ZooKeeperClient.__path | train | def __path(self, path):
"""
Adds the prefix to the given path
:param path: Z-Path
:return: Prefixed Z-Path
"""
if path.startswith(self.__prefix):
return path
return "{}{}".format(self.__prefix, path) | python | {
"resource": ""
} |
q9436 | ZooKeeperClient.create | train | def create(self, path, data, ephemeral=False, sequence=False):
"""
Creates a ZooKeeper node
:param path: Z-Path
:param data: Node Content
:param ephemeral: Ephemeral flag
:param sequence: Sequential flag
"""
return self._zk.create(
self.__path... | python | {
"resource": ""
} |
q9437 | ZooKeeperClient.get | train | def get(self, path, watch=None):
"""
Gets the content of a ZooKeeper node
:param path: Z-Path
:param watch: Watch method
"""
return self._zk.get(self.__path(path), watch=watch) | python | {
"resource": ""
} |
q9438 | ZooKeeperClient.get_children | train | def get_children(self, path, watch=None):
"""
Gets the list of children of a node
:param path: Z-Path
:param watch: Watch method
"""
return self._zk.get_children(self.__path(path), watch=watch) | python | {
"resource": ""
} |
q9439 | ZooKeeperClient.set | train | def set(self, path, data):
"""
Sets the content of a ZooKeeper node
:param path: Z-Path
:param data: New content
"""
return self._zk.set(self.__path(path), data) | python | {
"resource": ""
} |
q9440 | get_ipopo_svc_ref | train | def get_ipopo_svc_ref(bundle_context):
# type: (BundleContext) -> Optional[Tuple[ServiceReference, Any]]
"""
Retrieves a tuple containing the service reference to iPOPO and the service
itself
:param bundle_context: The calling bundle context
:return: The reference to the iPOPO service and the s... | python | {
"resource": ""
} |
q9441 | use_ipopo | train | def use_ipopo(bundle_context):
# type: (BundleContext) -> Any
"""
Utility context to use the iPOPO service safely in a "with" block.
It looks after the the iPOPO service and releases its reference when
exiting the context.
:param bundle_context: The calling bundle context
:return: The iPOPO... | python | {
"resource": ""
} |
q9442 | use_waiting_list | train | def use_waiting_list(bundle_context):
# type: (BundleContext) -> Any
"""
Utility context to use the iPOPO waiting list safely in a "with" block.
It looks after the the iPOPO waiting list service and releases its
reference when exiting the context.
:param bundle_context: The calling bundle conte... | python | {
"resource": ""
} |
q9443 | _is_builtin | train | def _is_builtin(obj):
"""
Checks if the type of the given object is a built-in one or not
:param obj: An object
:return: True if the object is of a built-in type
"""
module_ = inspect.getmodule(obj)
if module_ in (None, builtins):
return True
return module_.__name__ in ("", "__... | python | {
"resource": ""
} |
q9444 | to_jabsorb | train | def to_jabsorb(value):
"""
Adds information for Jabsorb, if needed.
Converts maps and lists to a jabsorb form.
Keeps tuples as is, to let them be considered as arrays.
:param value: A Python result to send to Jabsorb
:return: The result in a Jabsorb map format (not a JSON object)
"""
#... | python | {
"resource": ""
} |
q9445 | Requirement.copy | train | def copy(self):
# type: () -> Requirement
"""
Returns a copy of this instance
:return: A copy of this instance
"""
return Requirement(
self.specification,
self.aggregate,
self.optional,
self.__original_filter,
s... | python | {
"resource": ""
} |
q9446 | Requirement.set_filter | train | def set_filter(self, props_filter):
"""
Changes the current filter for the given one
:param props_filter: The new requirement filter on service properties
:raise TypeError: Unknown filter type
"""
if props_filter is not None and not (
is_string(props_filter)
... | python | {
"resource": ""
} |
q9447 | FactoryContext._deepcopy | train | def _deepcopy(self, data):
"""
Deep copies the given object
:param data: Data to copy
:return: A copy of the data, if supported, else the data itself
"""
if isinstance(data, dict):
# Copy dictionary values
return {key: self._deepcopy(value) for ke... | python | {
"resource": ""
} |
q9448 | FactoryContext.copy | train | def copy(self, inheritance=False):
# type: (bool) -> FactoryContext
"""
Returns a deep copy of the current FactoryContext instance
:param inheritance: If True, current handlers configurations are stored
as inherited ones
"""
# Create a new fac... | python | {
"resource": ""
} |
q9449 | FactoryContext.inherit_handlers | train | def inherit_handlers(self, excluded_handlers):
# type: (Iterable[str]) -> None
"""
Merges the inherited configuration with the current ones
:param excluded_handlers: Excluded handlers
"""
if not excluded_handlers:
excluded_handlers = tuple()
for hand... | python | {
"resource": ""
} |
q9450 | FactoryContext.add_instance | train | def add_instance(self, name, properties):
# type: (str, dict) -> None
"""
Stores the description of a component instance. The given properties
are stored as is.
:param name: Instance name
:param properties: Instance properties
:raise NameError: Already known inst... | python | {
"resource": ""
} |
q9451 | ComponentContext.get_field_callback | train | def get_field_callback(self, field, event):
# type: (str, str) -> Optional[Tuple[Callable, bool]]
"""
Retrieves the registered method for the given event. Returns None if
not found
:param field: Name of the dependency field
:param event: A component life cycle event
... | python | {
"resource": ""
} |
q9452 | PropertiesHandler._field_property_generator | train | def _field_property_generator(self, public_properties):
"""
Generates the methods called by the injected class properties
:param public_properties: If True, create a public property accessor,
else an hidden property accessor
:return: getter and setter m... | python | {
"resource": ""
} |
q9453 | PropertiesHandler.get_methods_names | train | def get_methods_names(public_properties):
"""
Generates the names of the fields where to inject the getter and setter
methods
:param public_properties: If True, returns the names of public property
accessors, else of hidden property ones
:return... | python | {
"resource": ""
} |
q9454 | _full_class_name | train | def _full_class_name(obj):
"""
Returns the full name of the class of the given object
:param obj: Any Python object
:return: The full name of the class of the object (if possible)
"""
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
return o... | python | {
"resource": ""
} |
q9455 | IOHandler._prompt | train | def _prompt(self, prompt=None):
"""
Reads a line written by the user
:param prompt: An optional prompt message
:return: The read line, after a conversion to str
"""
if prompt:
# Print the prompt
self.write(prompt)
self.output.flush()
... | python | {
"resource": ""
} |
q9456 | _LoggerHandler.manipulate | train | def manipulate(self, stored_instance, component_instance):
"""
Called by iPOPO right after the instantiation of the component.
This is the last chance to manipulate the component before the other
handlers start.
:param stored_instance: The iPOPO component StoredInstance
... | python | {
"resource": ""
} |
q9457 | _LoggerHandler.clear | train | def clear(self):
"""
Cleans up the handler. The handler can't be used after this method has
been called
"""
self._logger.debug("Component handlers are cleared")
# Clean up everything to avoid stale references, ...
self._field = None
self._name = None
... | python | {
"resource": ""
} |
q9458 | completion_hints | train | def completion_hints(config, prompt, session, context, current, arguments):
# type: (CompletionInfo, str, ShellSession, BundleContext, str, List[str]) -> List[str]
"""
Returns the possible completions of the current argument
:param config: Configuration of the current completion
:param prompt: The ... | python | {
"resource": ""
} |
q9459 | _resolve_file | train | def _resolve_file(file_name):
"""
Checks if the file exists.
If the file exists, the method returns its absolute path.
Else, it returns None
:param file_name: The name of the file to check
:return: An absolute path, or None
"""
if not file_name:
return None
path = os.path.... | python | {
"resource": ""
} |
q9460 | InteractiveShell._normal_prompt | train | def _normal_prompt(self):
"""
Flushes the prompt before requesting the input
:return: The command line
"""
sys.stdout.write(self.__get_ps1())
sys.stdout.flush()
return safe_input() | python | {
"resource": ""
} |
q9461 | InteractiveShell.loop_input | train | def loop_input(self, on_quit=None):
"""
Reads the standard input until the shell session is stopped
:param on_quit: A call back method, called without argument when the
shell session has ended
"""
# Start the init script
self._run_script(
... | python | {
"resource": ""
} |
q9462 | InteractiveShell._run_loop | train | def _run_loop(self, session):
"""
Runs the main input loop
:param session: Current shell session
"""
try:
first_prompt = True
# Set up the prompt
prompt = (
self._readline_prompt
if readline is not None
... | python | {
"resource": ""
} |
q9463 | InteractiveShell.readline_completer | train | def readline_completer(self, text, state):
"""
A completer for the readline library
"""
if state == 0:
# New completion, reset the list of matches and the display hook
self._readline_matches = []
try:
readline.set_completion_display_mat... | python | {
"resource": ""
} |
q9464 | InteractiveShell.search_shell | train | def search_shell(self):
"""
Looks for a shell service
"""
with self._lock:
if self._shell is not None:
# A shell is already there
return
reference = self._context.get_service_reference(SERVICE_SHELL)
if reference is not... | python | {
"resource": ""
} |
q9465 | InteractiveShell.service_changed | train | def service_changed(self, event):
"""
Called by Pelix when an events changes
"""
kind = event.get_kind()
reference = event.get_service_reference()
if kind in (pelix.ServiceEvent.REGISTERED, pelix.ServiceEvent.MODIFIED):
# A service matches our filter
... | python | {
"resource": ""
} |
q9466 | InteractiveShell.set_shell | train | def set_shell(self, svc_ref):
"""
Binds the given shell service.
:param svc_ref: A service reference
"""
if svc_ref is None:
return
with self._lock:
# Get the service
self._shell_ref = svc_ref
self._shell = self._context.g... | python | {
"resource": ""
} |
q9467 | InteractiveShell.clear_shell | train | def clear_shell(self):
"""
Unbinds the active shell service
"""
with self._lock:
# Clear the flag
self._shell_event.clear()
# Clear the readline completer
if readline is not None:
readline.set_completer(None)
... | python | {
"resource": ""
} |
q9468 | InteractiveShell.stop | train | def stop(self):
"""
Clears all members
"""
# Exit the loop
with self._lock:
self._stop_event.set()
self._shell_event.clear()
if self._context is not None:
# Unregister from events
self._context.remove_service_listener(self)... | python | {
"resource": ""
} |
q9469 | _JsonRpcServlet.do_POST | train | def do_POST(self, request, response):
# pylint: disable=C0103
"""
Handles a HTTP POST request
:param request: The HTTP request bean
:param response: The HTTP response handler
"""
try:
# Get the request content
data = to_str(request.read_da... | python | {
"resource": ""
} |
q9470 | _RuntimeDependency.service_changed | train | def service_changed(self, event):
"""
Called by the framework when a service event occurs
"""
if (
self._ipopo_instance is None
or not self._ipopo_instance.check_event(event)
):
# stop() and clean() may have been called after we have been put
... | python | {
"resource": ""
} |
q9471 | _RuntimeDependency.start | train | def start(self):
"""
Starts the dependency manager
"""
self._context.add_service_listener(
self, self.requirement.filter, self.requirement.specification
) | python | {
"resource": ""
} |
q9472 | LogReaderService._store_entry | train | def _store_entry(self, entry):
"""
Stores a new log entry and notifies listeners
:param entry: A LogEntry object
"""
# Get the logger and log the message
self.__logs.append(entry)
# Notify listeners
for listener in self.__listeners.copy():
tr... | python | {
"resource": ""
} |
q9473 | LogServiceInstance.log | train | def log(self, level, message, exc_info=None, reference=None):
# pylint: disable=W0212
"""
Logs a message, possibly with an exception
:param level: Severity of the message (Python logging level)
:param message: Human readable message
:param exc_info: The exception context... | python | {
"resource": ""
} |
q9474 | LogServiceFactory._bundle_from_module | train | def _bundle_from_module(self, module_object):
"""
Find the bundle associated to a module
:param module_object: A Python module object
:return: The Bundle object associated to the module, or None
"""
try:
# Get the module name
module_object = modul... | python | {
"resource": ""
} |
q9475 | LogServiceFactory.emit | train | def emit(self, record):
# pylint: disable=W0212
"""
Handle a message logged with the logger
:param record: A log record
"""
# Get the bundle
bundle = self._bundle_from_module(record.module)
# Convert to a LogEntry
entry = LogEntry(
re... | python | {
"resource": ""
} |
q9476 | _MqttConnection.publish | train | def publish(self, topic, payload, qos=0, retain=False):
"""
Publishes an MQTT message
"""
# TODO: check (full transmission) success
return self._client.publish(topic, payload, qos, retain) | python | {
"resource": ""
} |
q9477 | AggregateDependency.__store_service | train | def __store_service(self, key, service):
"""
Stores the given service in the dictionary
:param key: Dictionary key
:param service: Service to add to the dictionary
"""
self._future_value.setdefault(key, []).append(service) | python | {
"resource": ""
} |
q9478 | AggregateDependency.__remove_service | train | def __remove_service(self, key, service):
"""
Removes the given service from the future dictionary
:param key: Dictionary key
:param service: Service to remove from the dictionary
"""
try:
# Remove the injected service
prop_services = self._future... | python | {
"resource": ""
} |
q9479 | AggregateDependency.get_value | train | def get_value(self):
"""
Retrieves the value to inject in the component
:return: The value to inject
"""
with self._lock:
# The value field must be a deep copy of our dictionary
if self._future_value is not None:
return {
... | python | {
"resource": ""
} |
q9480 | ExportRegistrationImpl.match_sr | train | def match_sr(self, svc_ref, cid=None):
# type: (ServiceReference, Optional[Tuple[str, str]] ) -> bool
"""
Checks if this export registration matches the given service reference
:param svc_ref: A service reference
:param cid: A container ID
:return: True if the service ma... | python | {
"resource": ""
} |
q9481 | ExportRegistrationImpl.get_exception | train | def get_exception(self):
# type: () -> Optional[Tuple[Any, Any, Any]]
"""
Returns the exception associated to the export
:return: An exception tuple, if any
"""
with self.__lock:
return (
self.__updateexception
if self.__update... | python | {
"resource": ""
} |
q9482 | ExportRegistrationImpl.close | train | def close(self):
"""
Cleans up the export endpoint
"""
publish = False
exporterid = rsid = exception = export_ref = ed = None
with self.__lock:
if not self.__closed:
exporterid = self.__exportref.get_export_container_id()
export... | python | {
"resource": ""
} |
q9483 | EndpointAdvertiser.advertise_endpoint | train | def advertise_endpoint(self, endpoint_description):
"""
Advertise and endpoint_description for remote discovery.
If it hasn't already been a endpoint_description will be advertised via
a some protocol.
:param endpoint_description: an instance of EndpointDescription to
ad... | python | {
"resource": ""
} |
q9484 | EndpointAdvertiser.update_endpoint | train | def update_endpoint(self, updated_ed):
"""
Update a previously advertised endpoint_description.
:param endpoint_description: an instance of EndpointDescription to
update. Must not be None.
:return: True if advertised, False if not
(e.g. it's already been advertised)
... | python | {
"resource": ""
} |
q9485 | ServiceRegistrationHandler._field_controller_generator | train | def _field_controller_generator(self):
"""
Generates the methods called by the injected controller
"""
# Local variable, to avoid messing with "self"
stored_instance = self._ipopo_instance
def get_value(self, name):
# pylint: disable=W0613
"""
... | python | {
"resource": ""
} |
q9486 | ServiceRegistrationHandler.on_controller_change | train | def on_controller_change(self, name, value):
"""
Called by the instance manager when a controller value has been
modified
:param name: The name of the controller
:param value: The new value of the controller
"""
if self.__controller != name:
# Nothing... | python | {
"resource": ""
} |
q9487 | ServiceRegistrationHandler.on_property_change | train | def on_property_change(self, name, old_value, new_value):
"""
Called by the instance manager when a component property is modified
:param name: The changed property name
:param old_value: The previous property value
:param new_value: The new property value
"""
if... | python | {
"resource": ""
} |
q9488 | ServiceRegistrationHandler._register_service | train | def _register_service(self):
"""
Registers the provided service, if possible
"""
if (
self._registration is None
and self.specifications
and self.__validated
and self.__controller_on
):
# Use a copy of component properti... | python | {
"resource": ""
} |
q9489 | ServiceRegistrationHandler._unregister_service | train | def _unregister_service(self):
"""
Unregisters the provided service, if needed
"""
if self._registration is not None:
# Ignore error
try:
self._registration.unregister()
except BundleException as ex:
# Only log the error... | python | {
"resource": ""
} |
q9490 | use_service | train | def use_service(bundle_context, svc_reference):
"""
Utility context to safely use a service in a "with" block.
It looks after the the given service and releases its reference when
exiting the context.
:param bundle_context: The calling bundle context
:param svc_reference: The reference of the s... | python | {
"resource": ""
} |
q9491 | SynchronizedClassMethod | train | def SynchronizedClassMethod(*locks_attr_names, **kwargs):
# pylint: disable=C1801
"""
A synchronizer decorator for class methods. An AttributeError can be raised
at runtime if the given lock attribute doesn't exist or if it is None.
If a parameter ``sorted`` is found in ``kwargs`` and its value is ... | python | {
"resource": ""
} |
q9492 | is_lock | train | def is_lock(lock):
"""
Tests if the given lock is an instance of a lock class
"""
if lock is None:
# Don't do useless tests
return False
for attr in "acquire", "release", "__enter__", "__exit__":
if not hasattr(lock, attr):
# Missing something
return ... | python | {
"resource": ""
} |
q9493 | remove_duplicates | train | def remove_duplicates(items):
"""
Returns a list without duplicates, keeping elements order
:param items: A list of items
:return: The list without duplicates, in the same order
"""
if items is None:
return items
new_list = []
for item in items:
if item not in new_list:... | python | {
"resource": ""
} |
q9494 | add_listener | train | def add_listener(registry, listener):
"""
Adds a listener in the registry, if it is not yet in
:param registry: A registry (a list)
:param listener: The listener to register
:return: True if the listener has been added
"""
if listener is None or listener in registry:
return False
... | python | {
"resource": ""
} |
q9495 | remove_listener | train | def remove_listener(registry, listener):
"""
Removes a listener from the registry
:param registry: A registry (a list)
:param listener: The listener to remove
:return: True if the listener was in the list
"""
if listener is not None and listener in registry:
registry.remove(listener... | python | {
"resource": ""
} |
q9496 | to_iterable | train | def to_iterable(value, allow_none=True):
"""
Tries to convert the given value to an iterable, if necessary.
If the given value is a list, a list is returned; if it is a string, a list
containing one string is returned, ...
:param value: Any object
:param allow_none: If True, the method returns ... | python | {
"resource": ""
} |
q9497 | Deprecated.__log | train | def __log(self, method_name):
"""
Logs the deprecation message on first call, does nothing after
:param method_name: Name of the deprecated method
"""
if not self.__already_logged:
# Print only if not already done
stack = "\n\t".join(traceback.format_stac... | python | {
"resource": ""
} |
q9498 | CountdownEvent.step | train | def step(self):
# type: () -> bool
"""
Decreases the internal counter. Raises an error if the counter goes
below 0
:return: True if this step was the final one, else False
:raise ValueError: The counter has gone below 0
"""
with self.__lock:
s... | python | {
"resource": ""
} |
q9499 | BundleCompleter.display_hook | train | def display_hook(prompt, session, context, matches, longest_match_len):
# type: (str, ShellSession, BundleContext, List[str], int) -> None
"""
Displays the available bundle matches and the bundle name
:param prompt: Shell prompt string
:param session: Current shell session (for ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.