_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
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 =
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 commas >>> splitem('dogs, cats, or prarie dogs?') ['dogs', 'cats', 'prarie dogs'] Allow choices to be prefixed by some ignored prompt. >>> splitem('stuff: a, b, c')
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)
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 recipient first lead = recipient if not recipient else "%s, " % recipient trail = "" body = random.choice(pmxbot.phrases.adj_intros)
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'] value = yaml.safe_load(res['value']) if op in ('+=', '-='): # list operation op_name = {'+=': 'append', '-=': 'remove'}[op] op_name if key not in pmxbot.config: msg = "{key} not
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:
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:
python
{ "resource": "" }
q9407
LoggingCommandBot._get_wrapper
train
def _get_wrapper(): """ Get a socket wrapper based on SSL config. """ if
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
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():
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['status'].keys()): if self._response['status']['credits'] is not None:
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 ('remaining_credits' in self._response['status'].keys()): if self._response['status']['remaining_credits'] is not None:
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():
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 :class:`forces.Force` object) :type force: str or :class:`forces.Force` :rtype: list :return: A ``list`` of :class:`neighbourhoods.Neighbourhood` objects (one for each Neighbourhood Policing Team in the given force). """ if not isinstance(force, Force):
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 or :class:`forces.Force` object) :type force: str or Force :param str neighbourhood: The ID of the neighbourhood to fetch. :rtype: Neighbourhood
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: float or str :param lng: The longitude of the location. :type lng: float or str :rtype: Neighbourhood or None :return: The Neighbourhood object representing the Neighbourhood Policing Team responsible for the given location.
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/
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 category is valid for (the latest date is used if ``None``). :type date: str or None :return: A crime category with the given ID which is valid for the
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 of the crime to get. :return: The ``Crime`` with the
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. :type lat: float or str :param lng: The longitude of the location. :type lng: float or str :param date: The month in which the crimes were reported in the format ``YYYY-MM`` (the latest date is used if ``None``). :type date: str or None :param category: The category of the crimes to filter by (either by ID or CrimeCategory object) :type category: str or CrimeCategory :return: A ``list`` of crimes which were reported within 1 mile of the specified location, in the given month (optionally filtered by category).
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. :param date: The month in which the crimes were reported in the format ``YYYY-MM`` (the latest date is used if ``None``). :type date: str or None :param category: The category of the crimes to filter by (either
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_id: The ID of the location to get crimes for. :param date: The month in which the crimes were reported in the format ``YYYY-MM`` (the latest date is used if ``None``). :type date: str or None :return: A ``list`` of :class:`Crime` objects which were snapped to the
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: The force to get no-location crimes for. :type force: str or Force :param date: The month in which the crimes were reported in the format ``YYYY-MM`` (the latest date is used if ``None``). :type date: str or None :param category: The category of the crimes to filter by (either by ID or CrimeCategory object) :type category: str or CrimeCategory :return: A ``list`` of :class:`crime.NoLocationCrime` objects which were reported in the given month, by the specified force, but which don't have a location. """ if not isinstance(force, Force):
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 while True: attr, args, kwargs = rx.get() # First, handle special case where the wrapper is asking if attr is callable. # In this case, we actually have RetroWrapper.symbol, attr, and {}. if attr == RetroWrapper.symbol: result = env.__getattribute__(args)
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. """
python
{ "resource": "" }
q9426
RetroWrapper.close
train
def close(self): """ Shutdown the environment. """ if "_tx"
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 """
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:
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 is an error """ self.addParam('src', 'mc-python') params = urlencode(self._params) url = self._url if 'doc' in self._file.keys(): headers = {} if (extraHeaders is not None) and (extraHeaders is dict): headers = headers.update(extraHeaders) result =
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 """ leaves = self._getTreeLeaves() lemmas = {} for leaf in leaves: analyses = [] if 'analysis_list' in leaf.keys():
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 """
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.info("Connected to ZooKeeper") self._queue.enqueue(self.on_first_connection) else: self._logger.warning("Re-connected to ZooKeeper") self._queue.enqueue(self.on_client_reconnection) elif state == KazooState.SUSPENDED:
python
{ "resource": "" }
q9433
ZooKeeperClient.start
train
def start(self): """ Starts the connection """ self.__stop = False
python
{ "resource": "" }
q9434
ZooKeeperClient.stop
train
def stop(self): """ Stops the connection """ self.__stop = True
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
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 """
python
{ "resource": "" }
q9437
ZooKeeperClient.get
train
def get(self, path, watch=None): """ Gets the content of a ZooKeeper node :param path: Z-Path
python
{ "resource": "" }
q9438
ZooKeeperClient.get_children
train
def get_children(self, path, watch=None): """ Gets the list of children of a node
python
{ "resource": "" }
q9439
ZooKeeperClient.set
train
def set(self, path, data): """ Sets the content of a ZooKeeper node :param path: Z-Path
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 service itself, None if not available """ # Look after the service ref = bundle_context.get_service_reference(SERVICE_IPOPO) if ref is None: return None try:
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 service :raise BundleException: Service
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 context :return: The iPOPO waiting list service
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 """
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) """ # None ? if value is None: return None # Map ? elif isinstance(value, dict): if JAVA_CLASS in value or JSON_CLASS in value: if not _is_converted_class(value.get(JAVA_CLASS)): # Bean representation converted_result = {} for key, content in value.items(): converted_result[key] = to_jabsorb(content) try: # Keep the raw jsonrpclib information converted_result[JSON_CLASS] = value[JSON_CLASS] except KeyError: pass else: # We already worked on this value converted_result = value else: # Needs the whole transformation converted_result = {JAVA_CLASS: "java.util.HashMap"} converted_result["map"] = map_pairs = {} for key, content in value.items(): map_pairs[key] = to_jabsorb(content) try: # Keep the raw jsonrpclib information map_pairs[JSON_CLASS] = value[JSON_CLASS] except KeyError: pass # List ? (consider tuples as an array) elif isinstance(value, list): converted_result = { JAVA_CLASS: "java.util.ArrayList", "list": [to_jabsorb(entry) for entry in value], } # Set ? elif isinstance(value, (set, frozenset)): converted_result = { JAVA_CLASS: "java.util.HashSet", "set": [to_jabsorb(entry) for entry in value], } # Tuple ? (used as
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,
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) or isinstance( props_filter, (ldapfilter.LDAPFilter, ldapfilter.LDAPCriteria) ) ):
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 key, value in data.items()} elif isinstance(data, (list, tuple, set, frozenset)): # Copy sequence types
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 factory context and duplicate its values new_context = FactoryContext() for field in self.__slots__: if not field.startswith("_"): setattr( new_context, field, self._deepcopy(getattr(self, field))
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 handler, configuration in self.__inherited_configuration.items(): if handler in excluded_handlers: # Excluded handler continue
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 instance name
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 :return: A 2-tuple containing the callback associated to the given
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 methods """ # Local variable, to avoid messing with "self" stored_instance = self._ipopo_instance # Choose public or hidden properties # and select the method to call to notify about the property update if public_properties: properties = stored_instance.context.properties update_notifier = stored_instance.update_property else: # Copy Hidden properties and remove them from the context properties = stored_instance.context.grab_hidden_properties() update_notifier = stored_instance.update_hidden_property def get_value(_, name): """ Retrieves the property value, from the iPOPO dictionaries :param name: The property name :return: The property value """ return properties.get(name)
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: getter and a setter field names """ if public_properties: prefix = ipopo_constants.IPOPO_PROPERTY_PREFIX else: prefix
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 =
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:
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 :param component_instance: The component instance
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")
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 shell prompt string :param session: Current shell session :param context: Context of the shell UI bundle :param current: Current argument (to be completed) :param arguments: List of all arguments in their current state :return: A list of possible completions """ if not current: # No word yet, so the current position is after the existing ones arg_idx = len(arguments) else: # Find the current word position arg_idx = arguments.index(current) # Find the ID of the next completer completers = config.completers if arg_idx > len(completers) - 1: # Argument is too far to be positional, try if config.multiple: # Multiple calls allowed for the last completer completer_id = completers[-1] else: # Nothing to return return [] else: completer_id =
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:
python
{ "resource": "" }
q9460
InteractiveShell._normal_prompt
train
def _normal_prompt(self): """ Flushes the prompt before requesting the input :return: The command line
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( self.__session, self._context.get_property(PROP_INIT_FILE) ) # Run the script script_file = self._context.get_property(PROP_RUN_FILE) if script_file: self._run_script(self.__session, script_file) else:
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 else self._normal_prompt ) while not self._stop_event.is_set(): # Wait for the shell to be there # Before Python 2.7, wait() doesn't return a result if self._shell_event.wait(.2) or self._shell_event.is_set(): # Shell present if first_prompt: # Show the banner on first prompt sys.stdout.write(self._shell.get_banner()) first_prompt = False
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_matches_hook(None) except AttributeError: pass # Get the full line full_line = readline.get_line_buffer() begin_idx = readline.get_begidx() # Parse arguments as best as we can try: arguments = shlex.split(full_line) except ValueError: arguments = full_line.split() # Extract the command (maybe with its namespace) command = arguments.pop(0) if begin_idx > 0: # We're completing after the command (and maybe some args) try: # Find the command ns, command = self._shell.get_ns_command(command) except ValueError: # Ambiguous command: ignore return None # Use the completer associated to the command, if any try: configuration = self._shell.get_command_completers( ns, command ) if configuration is not None: self._readline_matches = completion_hints( configuration, self.__get_ps1(), self.__session, self._context, text, arguments, ) except KeyError: # Unknown command pass elif "." in command: # Completing the command, and a name space is given namespace, prefix = text.split(".", 2) commands = self._shell.get_commands(namespace) # Filter methods according to the prefix self._readline_matches = [ "{0}.{1}".format(namespace, command) for command in commands if command.startswith(prefix) ] else: # Completing a command or namespace prefix = command # Default commands goes first... possibilities = [ "{0} ".format(command)
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
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 self.set_shell(reference)
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.get_service(self._shell_ref)
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
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
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_data()) # Dispatch result = self._marshaled_dispatch(data, self._simple_dispatch) # Send the result
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 # inside a listener list copy... # or we've been told to ignore this event return # Call sub-methods kind = event.get_kind() svc_ref = event.get_service_reference() if kind == ServiceEvent.REGISTERED: # Service coming
python
{ "resource": "" }
q9471
_RuntimeDependency.start
train
def start(self): """ Starts the dependency manager """ self._context.add_service_listener( self,
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(): try: listener.logged(entry) except Exception as ex: # Create a new log entry, without using logging nor
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 (sys.exc_info()), if any :param reference: The ServiceReference associated to the log """ if not isinstance(reference, pelix.framework.ServiceReference): # Ensure we have a clean Service Reference reference = None if exc_info is not None: # Format the exception to avoid memory leaks
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:
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
python
{ "resource": "" }
q9476
_MqttConnection.publish
train
def publish(self, topic, payload, qos=0, retain=False): """ Publishes an MQTT message """
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:
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_value[key] prop_services.remove(service) # Clean up if not prop_services:
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:
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 matches this export registration """ with self.__lock: our_sr = self.get_reference() if our_sr is None: return
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
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_ref = self.__exportref rsid = self.__exportref.get_remoteservice_id() ed = self.__exportref.get_description() exception = self.__exportref.get_exception() self.__closed = True publish = self.__exportref.close(self)
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 advertise. Must not be None. :return: True
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) """ endpoint_id = updated_ed.get_id() with self._published_endpoints_lock: if self.get_advertised_endpoint(endpoint_id) is None: return False
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 """ Retrieves the controller value, from the iPOPO dictionaries :param name: The property name :return: The property value """ return stored_instance.get_controller_state(name) def set_value(self, name, new_value): # 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 to do return # Update the controller value self.__controller_on
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
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 properties properties = self._ipopo_instance.context.properties.copy() bundle_context = self._ipopo_instance.bundle_context # Register the service self._registration = bundle_context.register_service( self.specifications, self._ipopo_instance.instance,
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 at this level logger = logging.getLogger( "-".join((self._ipopo_instance.name, "ServiceRegistration")) ) logger.error("Error unregistering a service: %s",
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 service to use :return: The requested service
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 True, then the list of locks names will be sorted before locking. :param locks_attr_names: A list of the lock(s) attribute(s) name(s) to be used for synchronization :return: The decorator method, surrounded with the lock """ # Filter the names (remove empty ones) locks_attr_names = [ lock_name for lock_name in locks_attr_names if lock_name ] if not locks_attr_names: raise ValueError("The lock names list can't be empty") if "sorted" not in kwargs or kwargs["sorted"]: # Sort the lock names if requested # (locking always in the same order reduces the risk of dead lock) locks_attr_names = list(locks_attr_names) locks_attr_names.sort() def wrapped(method): """ The wrapping method :param method: The wrapped method :return: The wrapped method :raise AttributeError: The given attribute name doesn't exist """ @functools.wraps(method) def synchronized(self, *args, **kwargs): """ Calls the wrapped method with a lock """ # Raises an AttributeError if needed locks = [getattr(self, attr_name) for attr_name in locks_attr_names] locked = collections.deque() i = 0 try: # Lock for lock in locks:
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
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
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)
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
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 None if value is None, else it returns an empty list :return: A list containing the given string, or the given value """ if value is None: #
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_stack())
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: self.__value -= 1 if self.__value == 0: # All done
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 display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match """ # Prepare a line pattern for each match match_pattern = "{{0: >{}}}: {{1}}".format(longest_match_len) # Sort matching IDs matches = sorted(int(match) for match in
python
{ "resource": "" }