_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q34700 | GcpHubClient._GetDebuggee | train | def _GetDebuggee(self):
"""Builds the debuggee structure."""
major_version = 'v' + version.__version__.split('.')[0]
python_version = ''.join(platform.python_version().split('.')[:2])
agent_version = ('google.com/python%s-gcp/%s' % (python_version,
ma... | python | {
"resource": ""
} |
q34701 | GcpHubClient._GetDebuggeeDescription | train | def _GetDebuggeeDescription(self):
"""Formats debuggee description based on debuggee labels."""
return '-'.join(self._debuggee_labels[label]
for label in _DESCRIPTION_LABELS
if label in self._debuggee_labels) | python | {
"resource": ""
} |
q34702 | GcpHubClient._ComputeUniquifier | train | def _ComputeUniquifier(self, debuggee):
"""Computes debuggee uniquifier.
The debuggee uniquifier has to be identical on all instances. Therefore the
uniquifier should not include any random numbers and should only be based
on inputs that are guaranteed to be the same on all instances.
Args:
... | python | {
"resource": ""
} |
q34703 | GcpHubClient._ReadAppJsonFile | train | def _ReadAppJsonFile(self, relative_path):
"""Reads JSON file from an application directory.
Args:
relative_path: file name relative to application root directory.
Returns:
Parsed JSON data or None if the file does not exist, can't be read or
not a valid JSON file.
"""
try:
... | python | {
"resource": ""
} |
q34704 | NormalizePath | train | def NormalizePath(path):
"""Removes any Python system path prefix from the given path.
Python keeps almost all paths absolute. This is not what we actually
want to return. This loops through system paths (directories in which
Python will load modules). If "path" is relative to one of them, the
directory pref... | python | {
"resource": ""
} |
q34705 | DetermineType | train | def DetermineType(value):
"""Determines the type of val, returning a "full path" string.
For example:
DetermineType(5) -> __builtin__.int
DetermineType(Foo()) -> com.google.bar.Foo
Args:
value: Any value, the value is irrelevant as only the type metadata
is checked
Returns:
Type path stri... | python | {
"resource": ""
} |
q34706 | GetLoggingLocation | train | def GetLoggingLocation():
"""Search for and return the file and line number from the log collector.
Returns:
(pathname, lineno, func_name) The full path, line number, and function name
for the logpoint location.
"""
frame = inspect.currentframe()
this_file = frame.f_code.co_filename
frame = frame.f... | python | {
"resource": ""
} |
q34707 | SetLogger | train | def SetLogger(logger):
"""Sets the logger object to use for all 'LOG' breakpoint actions."""
global log_info_message
global log_warning_message
global log_error_message
log_info_message = logger.info
log_warning_message = logger.warning
log_error_message = logger.error
logger.addFilter(LineNoFilter()) | python | {
"resource": ""
} |
q34708 | _EvaluateExpression | train | def _EvaluateExpression(frame, expression):
"""Compiles and evaluates watched expression.
Args:
frame: evaluation context.
expression: watched expression to compile and evaluate.
Returns:
(False, status) on error or (True, value) on success.
"""
try:
code = compile(expression, '<watched_expr... | python | {
"resource": ""
} |
q34709 | _GetFrameCodeObjectName | train | def _GetFrameCodeObjectName(frame):
"""Gets the code object name for the frame.
Args:
frame: the frame to get the name from
Returns:
The function name if the code is a static function or the class name with
the method name if it is an member function.
"""
# This functions under the assumption th... | python | {
"resource": ""
} |
q34710 | CaptureCollector.Collect | train | def Collect(self, top_frame):
"""Collects call stack, local variables and objects.
Starts collection from the specified frame. We don't start from the top
frame to exclude the frames due to debugger. Updates the content of
self.breakpoint.
Args:
top_frame: top frame to start data collection.... | python | {
"resource": ""
} |
q34711 | CaptureCollector.CaptureFrameLocals | train | def CaptureFrameLocals(self, frame):
"""Captures local variables and arguments of the specified frame.
Args:
frame: frame to capture locals and arguments.
Returns:
(arguments, locals) tuple.
"""
# Capture all local variables (including method arguments).
variables = {n: self.Captur... | python | {
"resource": ""
} |
q34712 | CaptureCollector.CaptureNamedVariable | train | def CaptureNamedVariable(self, name, value, depth, limits):
"""Appends name to the product of CaptureVariable.
Args:
name: name of the variable.
value: data to capture
depth: nested depth of dictionaries and vectors so far.
limits: Per-object limits for capturing variable data.
Ret... | python | {
"resource": ""
} |
q34713 | CaptureCollector.CheckDataVisiblity | train | def CheckDataVisiblity(self, value):
"""Returns a status object if the given name is not visible.
Args:
value: The value to check. The actual value here is not important but the
value's metadata (e.g. package and type) will be checked.
Returns:
None if the value is visible. A variable ... | python | {
"resource": ""
} |
q34714 | CaptureCollector.CaptureVariablesList | train | def CaptureVariablesList(self, items, depth, empty_message, limits):
"""Captures list of named items.
Args:
items: iterable of (name, value) tuples.
depth: nested depth of dictionaries and vectors for items.
empty_message: info status message to set if items is empty.
limits: Per-object... | python | {
"resource": ""
} |
q34715 | CaptureCollector.CaptureVariable | train | def CaptureVariable(self, value, depth, limits, can_enqueue=True):
"""Try-Except wrapped version of CaptureVariableInternal."""
try:
return self.CaptureVariableInternal(value, depth, limits, can_enqueue)
except BaseException as e: # pylint: disable=broad-except
return {
'status': {
... | python | {
"resource": ""
} |
q34716 | CaptureCollector._CaptureExpression | train | def _CaptureExpression(self, frame, expression):
"""Evalutes the expression and captures it into a Variable object.
Args:
frame: evaluation context.
expression: watched expression to compile and evaluate.
Returns:
Variable object (which will have error status if the expression fails
... | python | {
"resource": ""
} |
q34717 | CaptureCollector.TrimVariableTable | train | def TrimVariableTable(self, new_size):
"""Trims the variable table in the formatted breakpoint message.
Removes trailing entries in variables table. Then scans the entire
breakpoint message and replaces references to the trimmed variables to
point to var_index of 0 ("buffer full").
Args:
new... | python | {
"resource": ""
} |
q34718 | CaptureCollector._CaptureEnvironmentLabels | train | def _CaptureEnvironmentLabels(self):
"""Captures information about the environment, if possible."""
if 'labels' not in self.breakpoint:
self.breakpoint['labels'] = {}
if callable(breakpoint_labels_collector):
for (key, value) in six.iteritems(breakpoint_labels_collector()):
self.breakpo... | python | {
"resource": ""
} |
q34719 | CaptureCollector._CaptureRequestLogId | train | def _CaptureRequestLogId(self):
"""Captures the request log id if possible.
The request log id is stored inside the breakpoint labels.
"""
# pylint: disable=not-callable
if callable(request_log_id_collector):
request_log_id = request_log_id_collector()
if request_log_id:
# We ha... | python | {
"resource": ""
} |
q34720 | CaptureCollector._CaptureUserId | train | def _CaptureUserId(self):
"""Captures the user id of the end user, if possible."""
user_kind, user_id = user_id_collector()
if user_kind and user_id:
self.breakpoint['evaluatedUserId'] = {'kind': user_kind, 'id': user_id} | python | {
"resource": ""
} |
q34721 | LogCollector.Log | train | def Log(self, frame):
"""Captures the minimal application states, formats it and logs the message.
Args:
frame: Python stack frame of breakpoint hit.
Returns:
None on success or status message on error.
"""
# Return error if log methods were not configured globally.
if not self._lo... | python | {
"resource": ""
} |
q34722 | LogCollector._EvaluateExpressions | train | def _EvaluateExpressions(self, frame):
"""Evaluates watched expressions into a string form.
If expression evaluation fails, the error message is used as evaluated
expression string.
Args:
frame: Python stack frame of breakpoint hit.
Returns:
Array of strings where each string correspo... | python | {
"resource": ""
} |
q34723 | LogCollector._FormatExpression | train | def _FormatExpression(self, frame, expression):
"""Evaluates a single watched expression and formats it into a string form.
If expression evaluation fails, returns error message string.
Args:
frame: Python stack frame in which the expression is evaluated.
expression: string expression to evalu... | python | {
"resource": ""
} |
q34724 | LogCollector._FormatValue | train | def _FormatValue(self, value, level=0):
"""Pretty-prints an object for a logger.
This function is very similar to the standard pprint. The main difference
is that it enforces limits to make sure we never produce an extremely long
string or take too much time.
Args:
value: Python object to pr... | python | {
"resource": ""
} |
q34725 | OpenAndRead | train | def OpenAndRead(relative_path='debugger-blacklist.yaml'):
"""Attempts to find the yaml configuration file, then read it.
Args:
relative_path: Optional relative path override.
Returns:
A Config object if the open and read were successful, None if the file
does not exist (which is not considered an er... | python | {
"resource": ""
} |
q34726 | Read | train | def Read(f):
"""Reads and returns Config data from a yaml file.
Args:
f: Yaml file to parse.
Returns:
Config object as defined in this file.
Raises:
Error (some subclass): If there is a problem loading or parsing the file.
"""
try:
yaml_data = yaml.load(f)
except yaml.YAMLError as e:
... | python | {
"resource": ""
} |
q34727 | _CheckData | train | def _CheckData(yaml_data):
"""Checks data for illegal keys and formatting."""
legal_keys = set(('blacklist', 'whitelist'))
unknown_keys = set(yaml_data) - legal_keys
if unknown_keys:
raise UnknownConfigKeyError(
'Unknown keys in configuration: %s' % unknown_keys)
for key, data in six.iteritems(ya... | python | {
"resource": ""
} |
q34728 | _AssertDataIsList | train | def _AssertDataIsList(key, lst):
"""Assert that lst contains list data and is not structured."""
# list and tuple are supported. Not supported are direct strings
# and dictionary; these indicate too much or two little structure.
if not isinstance(lst, list) and not isinstance(lst, tuple):
raise NotAListEr... | python | {
"resource": ""
} |
q34729 | _StripCommonPathPrefix | train | def _StripCommonPathPrefix(paths):
"""Removes path common prefix from a list of path strings."""
# Find the longest common prefix in terms of characters.
common_prefix = os.path.commonprefix(paths)
# Truncate at last segment boundary. E.g. '/aa/bb1/x.py' and '/a/bb2/x.py'
# have '/aa/bb' as the common prefix,... | python | {
"resource": ""
} |
q34730 | _MultipleModulesFoundError | train | def _MultipleModulesFoundError(path, candidates):
"""Generates an error message to be used when multiple matches are found.
Args:
path: The breakpoint location path that the user provided.
candidates: List of paths that match the user provided path. Must
contain at least 2 entries (throws Assertion... | python | {
"resource": ""
} |
q34731 | _NormalizePath | train | def _NormalizePath(path):
"""Removes surrounding whitespace, leading separator and normalize."""
# TODO(emrekultursay): Calling os.path.normpath "may change the meaning of a
# path that contains symbolic links" (e.g., "A/foo/../B" != "A/B" if foo is a
# symlink). This might cause trouble when matching against l... | python | {
"resource": ""
} |
q34732 | PythonBreakpoint.Clear | train | def Clear(self):
"""Clears the breakpoint and releases all breakpoint resources.
This function is assumed to be called by BreakpointsManager. Therefore we
don't call CompleteBreakpoint from here.
"""
self._RemoveImportHook()
if self._cookie is not None:
native.LogInfo('Clearing breakpoint... | python | {
"resource": ""
} |
q34733 | PythonBreakpoint.GetExpirationTime | train | def GetExpirationTime(self):
"""Computes the timestamp at which this breakpoint will expire."""
# TODO(emrekultursay): Move this to a common method.
if '.' not in self.definition['createTime']:
fmt = '%Y-%m-%dT%H:%M:%S%Z'
else:
fmt = '%Y-%m-%dT%H:%M:%S.%f%Z'
create_datetime = datetime.s... | python | {
"resource": ""
} |
q34734 | PythonBreakpoint.ExpireBreakpoint | train | def ExpireBreakpoint(self):
"""Expires this breakpoint."""
# Let only one thread capture the data and complete the breakpoint.
if not self._SetCompleted():
return
if self.definition.get('action') == 'LOG':
message = ERROR_AGE_LOGPOINT_EXPIRED_0
else:
message = ERROR_AGE_SNAPSHOT_E... | python | {
"resource": ""
} |
q34735 | PythonBreakpoint._ActivateBreakpoint | train | def _ActivateBreakpoint(self, module):
"""Sets the breakpoint in the loaded module, or complete with error."""
# First remove the import hook (if installed).
self._RemoveImportHook()
line = self.definition['location']['line']
# Find the code object in which the breakpoint is being set.
status... | python | {
"resource": ""
} |
q34736 | PythonBreakpoint._CompleteBreakpoint | train | def _CompleteBreakpoint(self, data, is_incremental=True):
"""Sends breakpoint update and deactivates the breakpoint."""
if is_incremental:
data = dict(self.definition, **data)
data['isFinalState'] = True
self._hub_client.EnqueueBreakpointUpdate(data)
self._breakpoints_manager.CompleteBreakpoi... | python | {
"resource": ""
} |
q34737 | PythonBreakpoint._SetCompleted | train | def _SetCompleted(self):
"""Atomically marks the breakpoint as completed.
Returns:
True if the breakpoint wasn't marked already completed or False if the
breakpoint was already completed.
"""
with self._lock:
if self._completed:
return False
self._completed = True
... | python | {
"resource": ""
} |
q34738 | PythonBreakpoint._BreakpointEvent | train | def _BreakpointEvent(self, event, frame):
"""Callback invoked by cdbg_native when breakpoint hits.
Args:
event: breakpoint event (see kIntegerConstants in native_module.cc).
frame: Python stack frame of breakpoint hit or None for other events.
"""
error_status = None
if event != native... | python | {
"resource": ""
} |
q34739 | Search | train | def Search(path):
"""Search sys.path to find a source file that matches path.
The provided input path may have an unknown number of irrelevant outer
directories (e.g., /garbage1/garbage2/real1/real2/x.py'). This function
does multiple search iterations until an actual Python module file that
matches the inp... | python | {
"resource": ""
} |
q34740 | _StartDebugger | train | def _StartDebugger():
"""Configures and starts the debugger."""
global _hub_client
global _breakpoints_manager
cdbg_native.InitializeModule(_flags)
_hub_client = gcp_hub_client.GcpHubClient()
visibility_policy = _GetVisibilityPolicy()
_breakpoints_manager = breakpoints_manager.BreakpointsManager(
... | python | {
"resource": ""
} |
q34741 | _GetVisibilityPolicy | train | def _GetVisibilityPolicy():
"""If a debugger configuration is found, create a visibility policy."""
try:
visibility_config = yaml_data_visibility_config_reader.OpenAndRead()
except yaml_data_visibility_config_reader.Error as err:
return error_data_visibility_policy.ErrorDataVisibilityPolicy(
'Coul... | python | {
"resource": ""
} |
q34742 | _DebuggerMain | train | def _DebuggerMain():
"""Starts the debugger and runs the application with debugger attached."""
global _flags
# The first argument is cdbg module, which we don't care.
del sys.argv[0]
# Parse debugger flags until we encounter '--'.
_flags = {}
while sys.argv[0]:
arg = sys.argv[0]
del sys.argv[0]... | python | {
"resource": ""
} |
q34743 | _Matches | train | def _Matches(path, pattern_list):
"""Returns true if path matches any patten found in pattern_list.
Args:
path: A dot separated path to a package, class, method or variable
pattern_list: A list of wildcard patterns
Returns:
True if path matches any wildcard found in pattern_list.
"""
# Note: Thi... | python | {
"resource": ""
} |
q34744 | BreakpointsManager.SetActiveBreakpoints | train | def SetActiveBreakpoints(self, breakpoints_data):
"""Adds new breakpoints and removes missing ones.
Args:
breakpoints_data: updated list of active breakpoints.
"""
with self._lock:
ids = set([x['id'] for x in breakpoints_data])
# Clear breakpoints that no longer show up in active bre... | python | {
"resource": ""
} |
q34745 | BreakpointsManager.CompleteBreakpoint | train | def CompleteBreakpoint(self, breakpoint_id):
"""Marks the specified breaking as completed.
Appends the ID to set of completed breakpoints and clears it.
Args:
breakpoint_id: breakpoint ID to complete.
"""
with self._lock:
self._completed.add(breakpoint_id)
if breakpoint_id in sel... | python | {
"resource": ""
} |
q34746 | BreakpointsManager.CheckBreakpointsExpiration | train | def CheckBreakpointsExpiration(self):
"""Completes all breakpoints that have been active for too long."""
with self._lock:
current_time = BreakpointsManager.GetCurrentTime()
if self._next_expiration > current_time:
return
expired_breakpoints = []
self._next_expiration = datetime... | python | {
"resource": ""
} |
q34747 | PrettyPrinter | train | def PrettyPrinter(obj):
"""Pretty printers for AppEngine objects."""
if ndb and isinstance(obj, ndb.Model):
return six.iteritems(obj.to_dict()), 'ndb.Model(%s)' % type(obj).__name__
if messages and isinstance(obj, messages.Enum):
return [('name', obj.name), ('number', obj.number)], type(obj).__name__
... | python | {
"resource": ""
} |
q34748 | IsPathSuffix | train | def IsPathSuffix(mod_path, path):
"""Checks whether path is a full path suffix of mod_path.
Args:
mod_path: Must be an absolute path to a source file. Must not have
file extension.
path: A relative path. Must not have file extension.
Returns:
True if path is a full path suffix of mod_p... | python | {
"resource": ""
} |
q34749 | GetLoadedModuleBySuffix | train | def GetLoadedModuleBySuffix(path):
"""Searches sys.modules to find a module with the given file path.
Args:
path: Path to the source file. It can be relative or absolute, as suffix
match can handle both. If absolute, it must have already been
sanitized.
Algorithm:
The given path must... | python | {
"resource": ""
} |
q34750 | GetCodeObjectAtLine | train | def GetCodeObjectAtLine(module, line):
"""Searches for a code object at the specified line in the specified module.
Args:
module: module to explore.
line: 1-based line number of the statement.
Returns:
(True, Code object) on success or (False, (prev_line, next_line)) on
failure, where prev_line ... | python | {
"resource": ""
} |
q34751 | _GetLineNumbers | train | def _GetLineNumbers(code_object):
"""Generator for getting the line numbers of a code object.
Args:
code_object: the code object.
Yields:
The next line number in the code object.
"""
# Get the line number deltas, which are the odd number entries, from the
# lnotab. See
# https://svn.python.org/p... | python | {
"resource": ""
} |
q34752 | _GetModuleCodeObjects | train | def _GetModuleCodeObjects(module):
"""Gets all code objects defined in the specified module.
There are two BFS traversals involved. One in this function and the other in
_FindCodeObjectsReferents. Only the BFS in _FindCodeObjectsReferents has
a depth limit. This function does not. The motivation is that this f... | python | {
"resource": ""
} |
q34753 | _FindCodeObjectsReferents | train | def _FindCodeObjectsReferents(module, start_objects, visit_recorder):
"""Looks for all the code objects referenced by objects in start_objects.
The traversal implemented by this function is a shallow one. In other words
if the reference chain is a -> b -> co1 -> c -> co2, this function will
return [co1] only.
... | python | {
"resource": ""
} |
q34754 | _VisitRecorder.Record | train | def Record(self, obj):
"""Records the object as visited.
Args:
obj: visited object.
Returns:
True if the object hasn't been previously visited or False if it has
already been recorded or the quota has been exhausted.
"""
if len(self._visit_recorder_objects) >= _MAX_VISIT_OBJECTS:... | python | {
"resource": ""
} |
q34755 | Backoff.Failed | train | def Failed(self):
"""Indicates that a request has failed.
Returns:
Time interval to wait before retrying (in seconds).
"""
interval = self._current_interval_sec
self._current_interval_sec = min(
self.max_interval_sec, self._current_interval_sec * self.multiplier)
return interval | python | {
"resource": ""
} |
q34756 | ComputeApplicationUniquifier | train | def ComputeApplicationUniquifier(hash_obj):
"""Computes hash of application files.
Application files can be anywhere on the disk. The application is free to
import a Python module from an arbitrary path ok the disk. It is also
impossible to distinguish application files from third party libraries.
Third part... | python | {
"resource": ""
} |
q34757 | AddImportCallbackBySuffix | train | def AddImportCallbackBySuffix(path, callback):
"""Register import hook.
This function overrides the default import process. Then whenever a module
whose suffix matches path is imported, the callback will be invoked.
A module may be imported multiple times. Import event only means that the
Python code contai... | python | {
"resource": ""
} |
q34758 | _InstallImportHookBySuffix | train | def _InstallImportHookBySuffix():
"""Lazily installs import hook."""
global _real_import
if _real_import:
return # Import hook already installed
_real_import = getattr(builtins, '__import__')
assert _real_import
builtins.__import__ = _ImportHookBySuffix
if six.PY3:
# In Python 2, importlib.imp... | python | {
"resource": ""
} |
q34759 | _IncrementNestLevel | train | def _IncrementNestLevel():
"""Increments the per thread nest level of imports."""
# This is the top call to import (no nesting), init the per-thread nest level
# and names set.
if getattr(_import_local, 'nest_level', None) is None:
_import_local.nest_level = 0
if _import_local.nest_level == 0:
# Re-i... | python | {
"resource": ""
} |
q34760 | _ProcessImportBySuffix | train | def _ProcessImportBySuffix(name, fromlist, globals):
"""Processes an import.
Calculates the possible names generated from an import and invokes
registered callbacks if needed.
Args:
name: Argument as passed to the importer.
fromlist: Argument as passed to the importer.
globals: Argument as passed ... | python | {
"resource": ""
} |
q34761 | _ImportHookBySuffix | train | def _ImportHookBySuffix(
name, globals=None, locals=None, fromlist=None, level=None):
"""Callback when an import statement is executed by the Python interpreter.
Argument names have to exactly match those of __import__. Otherwise calls
to __import__ that use keyword syntax will fail: __import('a', fromlist=[... | python | {
"resource": ""
} |
q34762 | _ResolveRelativeImport | train | def _ResolveRelativeImport(name, package):
"""Resolves a relative import into an absolute path.
This is mostly an adapted version of the logic found in the backported
version of import_module in Python 2.7.
https://github.com/python/cpython/blob/2.7/Lib/importlib/__init__.py
Args:
name: relative name im... | python | {
"resource": ""
} |
q34763 | _ImportModuleHookBySuffix | train | def _ImportModuleHookBySuffix(name, package=None):
"""Callback when a module is imported through importlib.import_module."""
_IncrementNestLevel()
try:
# Really import modules.
module = _real_import_module(name, package)
finally:
if name.startswith('.'):
if package:
name = _ResolveRel... | python | {
"resource": ""
} |
q34764 | _GenerateNames | train | def _GenerateNames(name, fromlist, globals):
"""Generates the names of modules that might be loaded via this import.
Args:
name: Argument as passed to the importer.
fromlist: Argument as passed to the importer.
globals: Argument as passed to the importer.
Returns:
A set that contains the names o... | python | {
"resource": ""
} |
q34765 | _InvokeImportCallbackBySuffix | train | def _InvokeImportCallbackBySuffix(names):
"""Invokes import callbacks for newly loaded modules.
Uses a path suffix match to identify whether a loaded module matches the
file path provided by the user.
Args:
names: A set of names for modules that are loaded by the current import.
The set may con... | python | {
"resource": ""
} |
q34766 | init | train | def init(driverName=None, debug=False):
'''
Constructs a new TTS engine instance or reuses the existing instance for
the driver name.
@param driverName: Name of the platform specific driver to use. If
None, selects the default driver for the operating system.
@type: str
@param debug: De... | python | {
"resource": ""
} |
q34767 | DummyDriver.startLoop | train | def startLoop(self):
'''
Starts a blocking run loop in which driver callbacks are properly
invoked.
@precondition: There was no previous successful call to L{startLoop}
without an intervening call to L{stopLoop}.
'''
first = True
self._looping = True
... | python | {
"resource": ""
} |
q34768 | Engine._notify | train | def _notify(self, topic, **kwargs):
"""
Invokes callbacks for an event topic.
@param topic: String event name
@type topic: str
@param kwargs: Values associated with the event
@type kwargs: dict
"""
for cb in self._connects.get(topic, []):
try:... | python | {
"resource": ""
} |
q34769 | Engine.disconnect | train | def disconnect(self, token):
"""
Unregisters a callback for an event topic.
@param token: Token of the callback to unregister
@type token: dict
"""
topic = token['topic']
try:
arr = self._connects[topic]
except KeyError:
return
... | python | {
"resource": ""
} |
q34770 | Engine.save_to_file | train | def save_to_file(self, text, filename, name=None):
'''
Adds an utterance to speak to the event queue.
@param text: Text to sepak
@type text: unicode
@param filename: the name of file to save.
@param name: Name to associate with this utterance. Included in
not... | python | {
"resource": ""
} |
q34771 | Engine.runAndWait | train | def runAndWait(self):
"""
Runs an event loop until all commands queued up until this method call
complete. Blocks during the event loop and returns when the queue is
cleared.
@raise RuntimeError: When the loop is already running
"""
if self._inLoop:
r... | python | {
"resource": ""
} |
q34772 | Engine.startLoop | train | def startLoop(self, useDriverLoop=True):
"""
Starts an event loop to process queued commands and callbacks.
@param useDriverLoop: If True, uses the run loop provided by the driver
(the default). If False, assumes the caller will enter its own
run loop which will pump any... | python | {
"resource": ""
} |
q34773 | Engine.endLoop | train | def endLoop(self):
"""
Stops a running event loop.
@raise RuntimeError: When the loop is not running
"""
if not self._inLoop:
raise RuntimeError('run loop not started')
self.proxy.endLoop(self._driverLoop)
self._inLoop = False | python | {
"resource": ""
} |
q34774 | Engine.iterate | train | def iterate(self):
"""
Must be called regularly when using an external event loop.
"""
if not self._inLoop:
raise RuntimeError('run loop not started')
elif self._driverLoop:
raise RuntimeError('iterate not valid in driver run loop')
self.proxy.iter... | python | {
"resource": ""
} |
q34775 | DriverProxy._push | train | def _push(self, mtd, args, name=None):
'''
Adds a command to the queue.
@param mtd: Method to invoke to process the command
@type mtd: method
@param args: Arguments to apply when invoking the method
@type args: tuple
@param name: Name associated with the command
... | python | {
"resource": ""
} |
q34776 | DriverProxy._pump | train | def _pump(self):
'''
Attempts to process the next command in the queue if one exists and the
driver is not currently busy.
'''
while (not self._busy) and len(self._queue):
cmd = self._queue.pop(0)
self._name = cmd[2]
try:
cmd[0]... | python | {
"resource": ""
} |
q34777 | DriverProxy.notify | train | def notify(self, topic, **kwargs):
'''
Sends a notification to the engine from the driver.
@param topic: Notification topic
@type topic: str
@param kwargs: Arbitrary keyword arguments
@type kwargs: dict
'''
kwargs['name'] = self._name
self._engine... | python | {
"resource": ""
} |
q34778 | DriverProxy.setBusy | train | def setBusy(self, busy):
'''
Called by the driver to indicate it is busy.
@param busy: True when busy, false when idle
@type busy: bool
'''
self._busy = busy
if not self._busy:
self._pump() | python | {
"resource": ""
} |
q34779 | DriverProxy.stop | train | def stop(self):
'''
Called by the engine to stop the current utterance and clear the queue
of commands.
'''
# clear queue up to first end loop command
while(True):
try:
mtd, args, name = self._queue[0]
except IndexError:
... | python | {
"resource": ""
} |
q34780 | DriverProxy.setProperty | train | def setProperty(self, name, value):
'''
Called by the engine to set a driver property value.
@param name: Name of the property
@type name: str
@param value: Property value
@type value: object
'''
self._push(self._driver.setProperty, (name, value)) | python | {
"resource": ""
} |
q34781 | DriverProxy.runAndWait | train | def runAndWait(self):
'''
Called by the engine to start an event loop, process all commands in
the queue at the start of the loop, and then exit the loop.
'''
self._push(self._engine.endLoop, tuple())
self._driver.startLoop() | python | {
"resource": ""
} |
q34782 | DriverProxy.startLoop | train | def startLoop(self, useDriverLoop):
'''
Called by the engine to start an event loop.
'''
if useDriverLoop:
self._driver.startLoop()
else:
self._iterator = self._driver.iterate() | python | {
"resource": ""
} |
q34783 | DriverProxy.endLoop | train | def endLoop(self, useDriverLoop):
'''
Called by the engine to stop an event loop.
'''
self._queue = []
self._driver.stop()
if useDriverLoop:
self._driver.endLoop()
else:
self._iterator = None
self.setBusy(True) | python | {
"resource": ""
} |
q34784 | post_slack | train | def post_slack():
"""Post slack message."""
try:
token = os.environ['SLACK_TOKEN']
slack = Slacker(token)
obj = slack.chat.post_message('#general', 'Hello fellow slackers!')
print(obj.successful, obj.__dict__['body']['channel'], obj.__dict__[
'body']['ts'])
excep... | python | {
"resource": ""
} |
q34785 | list_slack | train | def list_slack():
"""List channels & users in slack."""
try:
token = os.environ['SLACK_TOKEN']
slack = Slacker(token)
# Get channel list
response = slack.channels.list()
channels = response.body['channels']
for channel in channels:
print(channel['id']... | python | {
"resource": ""
} |
q34786 | DeviceManager.run | train | def run(self):
"""
Starts the main loop that is necessary to receive Bluetooth events from the Bluetooth adapter.
This call blocks until you call `stop()` to stop the main loop.
"""
if self._main_loop:
return
self._interface_added_signal = self._bus.add_sig... | python | {
"resource": ""
} |
q34787 | DeviceManager.start_discovery | train | def start_discovery(self, service_uuids=[]):
"""Starts a discovery for BLE devices with given service UUIDs.
:param service_uuids: Filters the search to only return devices with given UUIDs.
"""
discovery_filter = {'Transport': 'le'}
if service_uuids: # D-Bus doesn't like empt... | python | {
"resource": ""
} |
q34788 | DeviceManager.stop_discovery | train | def stop_discovery(self):
"""
Stops the discovery started with `start_discovery`
"""
try:
self._adapter.StopDiscovery()
except dbus.exceptions.DBusException as e:
if (e.get_dbus_name() == 'org.bluez.Error.Failed') and (e.get_dbus_message() == 'No discovery... | python | {
"resource": ""
} |
q34789 | Device.properties_changed | train | def properties_changed(self, sender, changed_properties, invalidated_properties):
"""
Called when a device property has changed or got invalidated.
"""
if 'Connected' in changed_properties:
if changed_properties['Connected']:
self.connect_succeeded()
... | python | {
"resource": ""
} |
q34790 | Device.services_resolved | train | def services_resolved(self):
"""
Called when all device's services and characteristics got resolved.
"""
self._disconnect_service_signals()
services_regex = re.compile(self._device_path + '/service[0-9abcdef]{4}$')
managed_services = [
service for service in ... | python | {
"resource": ""
} |
q34791 | Service.characteristics_resolved | train | def characteristics_resolved(self):
"""
Called when all service's characteristics got resolved.
"""
self._disconnect_characteristic_signals()
characteristics_regex = re.compile(self._path + '/char[0-9abcdef]{4}$')
managed_characteristics = [
char for char in ... | python | {
"resource": ""
} |
q34792 | Descriptor.read_value | train | def read_value(self, offset=0):
"""
Reads the value of this descriptor.
When successful, the value will be returned, otherwise `descriptor_read_value_failed()` of the related
device is invoked.
"""
try:
val = self._object.ReadValue(
{'offset':... | python | {
"resource": ""
} |
q34793 | Characteristic.properties_changed | train | def properties_changed(self, properties, changed_properties, invalidated_properties):
value = changed_properties.get('Value')
"""
Called when a Characteristic property has changed.
"""
if value is not None:
self.service.device.characteristic_value_updated(characterist... | python | {
"resource": ""
} |
q34794 | Characteristic.write_value | train | def write_value(self, value, offset=0):
"""
Attempts to write a value to the characteristic.
Success or failure will be notified by calls to `write_value_succeeded` or `write_value_failed` respectively.
:param value: array of bytes to be written
:param offset: offset from where... | python | {
"resource": ""
} |
q34795 | Characteristic._write_value_failed | train | def _write_value_failed(self, dbus_error):
"""
Called when the write request has failed.
"""
error = _error_from_dbus_error(dbus_error)
self.service.device.characteristic_write_value_failed(characteristic=self, error=error) | python | {
"resource": ""
} |
q34796 | Characteristic.enable_notifications | train | def enable_notifications(self, enabled=True):
"""
Enables or disables value change notifications.
Success or failure will be notified by calls to `characteristic_enable_notifications_succeeded`
or `enable_notifications_failed` respectively.
Each time when the device notifies a ... | python | {
"resource": ""
} |
q34797 | Characteristic._enable_notifications_failed | train | def _enable_notifications_failed(self, dbus_error):
"""
Called when notification enabling has failed.
"""
if ((dbus_error.get_dbus_name() == 'org.bluez.Error.Failed') and
((dbus_error.get_dbus_message() == "Already notifying") or
(dbus_error.get_dbus_message() ==... | python | {
"resource": ""
} |
q34798 | _split | train | def _split(string, splitters):
"""Splits a string into parts at multiple characters"""
part = ''
for character in string:
if character in splitters:
yield part
part = ''
else:
part += character
yield part | python | {
"resource": ""
} |
q34799 | _hash | train | def _hash(number, alphabet):
"""Hashes `number` using the given `alphabet` sequence."""
hashed = ''
len_alphabet = len(alphabet)
while True:
hashed = alphabet[number % len_alphabet] + hashed
number //= len_alphabet
if not number:
return hashed | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.