_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q239000
convert_to_BuildError
train
def convert_to_BuildError(status, exc_info=None): """ Convert any return code a BuildError Exception. :Parameters: - `status`: can either be a return code or an Exception. The buildError.status we set here will normally be used as the exit status of the "scons" process. """ if not e...
python
{ "resource": "" }
q239001
format_config
train
def format_config(sensor_graph): """Extract the config variables from this sensor graph in ASCII format. Args: sensor_graph (SensorGraph): the sensor graph that we want to format Returns: str: The ascii output lines concatenated as a single string """ cmdfile = CommandFile("Config...
python
{ "resource": "" }
q239002
generate
train
def generate(env): """ Add Builders and construction variables for the Visual Age FORTRAN compiler to an Environment. """ path, _f77, _shf77, version = get_xlf77(env) if path: _f77 = os.path.join(path, _f77) _shf77 = os.path.join(path, _shf77) f77.generate(env) env['F77...
python
{ "resource": "" }
q239003
DirScanner
train
def DirScanner(**kw): """Return a prototype Scanner instance for scanning directories for on-disk files""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = only_dirs return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw)
python
{ "resource": "" }
q239004
DirEntryScanner
train
def DirEntryScanner(**kw): """Return a prototype Scanner instance for "scanning" directory Nodes for their in-memory entries""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = None return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw)
python
{ "resource": "" }
q239005
scan_on_disk
train
def scan_on_disk(node, env, path=()): """ Scans a directory for on-disk files and directories therein. Looking up the entries will add these to the in-memory Node tree representation of the file system, so all we have to do is just that and then call the in-memory scanning function. """ try...
python
{ "resource": "" }
q239006
scan_in_memory
train
def scan_in_memory(node, env, path=()): """ "Scans" a Node.FS.Dir for its in-memory entries. """ try: entries = node.entries except AttributeError: # It's not a Node.FS.Dir (or doesn't look enough like one for # our purposes), which can happen if a target list containing ...
python
{ "resource": "" }
q239007
GenericResponse.set_result
train
def set_result(self, result): """Finish this response and set the result.""" if self.is_finished(): raise InternalError("set_result called on finished AsynchronousResponse", result=self._result, exception=self._exception) self._result = result ...
python
{ "resource": "" }
q239008
GenericResponse.set_exception
train
def set_exception(self, exc_class, exc_info, exc_stack): """Set an exception as the result of this operation. Args: exc_class (object): The exception type """ if self.is_finished(): raise InternalError("set_exception called on finished AsynchronousResponse", ...
python
{ "resource": "" }
q239009
get_released_versions
train
def get_released_versions(component): """Get all released versions of the given component ordered newest to oldest """ releases = get_tags() releases = sorted([(x[0], [int(y) for y in x[1].split('.')]) for x in releases], key=lambda x: x[1])[::-1] return [(x[0], ".".join(map(str, x[1]))) for x in ...
python
{ "resource": "" }
q239010
load_dependencies
train
def load_dependencies(orig_tile, build_env): """Load all tile dependencies and filter only the products from each that we use build_env must define the architecture that we are targeting so that we get the correct dependency list and products per dependency since that may change when building for diffe...
python
{ "resource": "" }
q239011
find_dependency_wheels
train
def find_dependency_wheels(tile): """Return a list of all python wheel objects created by dependencies of this tile Args: tile (IOTile): Tile that we should scan for dependencies Returns: list: A list of paths to dependency wheels """ return [os.path.join(x.folder, 'python', x.sup...
python
{ "resource": "" }
q239012
SemanticVersionRange._check_ver_range
train
def _check_ver_range(self, version, ver_range): """Check if version is included in ver_range """ lower, upper, lower_inc, upper_inc = ver_range #If the range extends over everything, we automatically match if lower is None and upper is None: return True if ...
python
{ "resource": "" }
q239013
SemanticVersionRange._check_insersection
train
def _check_insersection(self, version, ranges): """Check that a version is inside all of a list of ranges""" for ver_range in ranges: if not self._check_ver_range(version, ver_range): return False return True
python
{ "resource": "" }
q239014
SemanticVersionRange.check
train
def check(self, version): """Check that a version is inside this SemanticVersionRange Args: version (SemanticVersion): The version to check Returns: bool: True if the version is included in the range, False if not """ for disjunct in self._disjuncts: ...
python
{ "resource": "" }
q239015
SemanticVersionRange.filter
train
def filter(self, versions, key=lambda x: x): """Filter all of the versions in an iterable that match this version range Args: versions (iterable): An iterable of SemanticVersion objects Returns: list: A list of the SemanticVersion objects that matched this range ...
python
{ "resource": "" }
q239016
SemanticVersionRange.FromString
train
def FromString(cls, range_string): """Parse a version range string into a SemanticVersionRange Currently, the only possible range strings are: ^X.Y.Z - matches all versions with the same leading nonzero digit greater than or equal the given range. * - matches everything ...
python
{ "resource": "" }
q239017
SemihostedRPCExecutor._call_rpc
train
def _call_rpc(self, address, rpc_id, payload): """Call an RPC with the given information and return its response. Must raise a hardware error of the appropriate kind if the RPC can not be executed correctly. Otherwise it should return the binary response payload received from the RPC. ...
python
{ "resource": "" }
q239018
IndividualReadingReport.FromReadings
train
def FromReadings(cls, uuid, readings): """Generate an instance of the report format from a list of readings and a uuid """ if len(readings) != 1: raise ArgumentError("IndividualReading reports must be created with exactly one reading", num_readings=le...
python
{ "resource": "" }
q239019
IndividualReadingReport.decode
train
def decode(self): """Decode this report into a single reading """ fmt, _, stream, uuid, sent_timestamp, reading_timestamp, reading_value = unpack("<BBHLLLL", self.raw_report) assert fmt == 0 # Estimate the UTC time when this device was turned on time_base = self.receive...
python
{ "resource": "" }
q239020
IndividualReadingReport.encode
train
def encode(self): """Turn this report into a serialized bytearray that could be decoded with a call to decode""" reading = self.visible_readings[0] data = struct.pack("<BBHLLLL", 0, 0, reading.stream, self.origin, self.sent_timestamp, reading.raw_time, reading.value) ...
python
{ "resource": "" }
q239021
is_LaTeX
train
def is_LaTeX(flist,env,abspath): """Scan a file list to decide if it's TeX- or LaTeX-flavored.""" # We need to scan files that are included in case the # \documentclass command is in them. # get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS'] savedpath = modify_env_var(env, 'TEXIN...
python
{ "resource": "" }
q239022
TeXLaTeXStrFunction
train
def TeXLaTeXStrFunction(target = None, source= None, env=None): """A strfunction for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then returns the appropriate command string.""" if env.GetOption("no_exec"): # find these paths for use in is_LaTeX to search fo...
python
{ "resource": "" }
q239023
tex_eps_emitter
train
def tex_eps_emitter(target, source, env): """An emitter for TeX and LaTeX sources when executing tex or latex. It will accept .ps and .eps graphics files """ (target, source) = tex_emitter_core(target, source, env, TexGraphics) return (target, source)
python
{ "resource": "" }
q239024
tex_pdf_emitter
train
def tex_pdf_emitter(target, source, env): """An emitter for TeX and LaTeX sources when executing pdftex or pdflatex. It will accept graphics files of types .pdf, .jpg, .png, .gif, and .tif """ (target, source) = tex_emitter_core(target, source, env, LatexGraphics) return (target, source)
python
{ "resource": "" }
q239025
generate
train
def generate(env): """Add Builders and construction variables for TeX to an Environment.""" global TeXLaTeXAction if TeXLaTeXAction is None: TeXLaTeXAction = SCons.Action.Action(TeXLaTeXFunction, strfunction=TeXLaTeXStrFunction) env.AppendUnique(LATEXSUFFIXES=SCon...
python
{ "resource": "" }
q239026
is_win64
train
def is_win64(): """Return true if running on windows 64 bits. Works whether python itself runs in 64 bits or 32 bits.""" # Unfortunately, python does not provide a useful way to determine # if the underlying Windows OS is 32-bit or 64-bit. Worse, whether # the Python itself is 32-bit or 64-bit aff...
python
{ "resource": "" }
q239027
has_reg
train
def has_reg(value): """Return True if the given key exists in HKEY_LOCAL_MACHINE, False otherwise.""" try: SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, value) ret = True except SCons.Util.WinError: ret = False return ret
python
{ "resource": "" }
q239028
normalize_env
train
def normalize_env(env, keys, force=False): """Given a dictionary representing a shell environment, add the variables from os.environ needed for the processing of .bat files; the keys are controlled by the keys argument. It also makes sure the environment values are correctly encoded. If force=True...
python
{ "resource": "" }
q239029
get_output
train
def get_output(vcbat, args = None, env = None): """Parse the output of given bat file, with given args.""" if env is None: # Create a blank environment, for use in launching the tools env = SCons.Environment.Environment(tools=[]) # TODO: This is a hard-coded list of the variables that (ma...
python
{ "resource": "" }
q239030
generate
train
def generate(env): """Add default tools.""" for t in SCons.Tool.tool_list(env['PLATFORM'], env): SCons.Tool.Tool(t)(env)
python
{ "resource": "" }
q239031
_PathList.subst_path
train
def subst_path(self, env, target, source): """ Performs construction variable substitution on a pre-digested PathList for a specific target and source. """ result = [] for type, value in self.pathlist: if type == TYPE_STRING_SUBST: value = env....
python
{ "resource": "" }
q239032
PathListCache._PathList_key
train
def _PathList_key(self, pathlist): """ Returns the key for memoization of PathLists. Note that we want this to be pretty quick, so we don't completely canonicalize all forms of the same list. For example, 'dir1:$ROOT/dir2' and ['$ROOT/dir1', 'dir'] may logically represe...
python
{ "resource": "" }
q239033
PathListCache.PathList
train
def PathList(self, pathlist): """ Returns the cached _PathList object for the specified pathlist, creating and caching a new object as necessary. """ pathlist = self._PathList_key(pathlist) try: memo_dict = self._memo['PathList'] except KeyError: ...
python
{ "resource": "" }
q239034
DefaultEnvironment
train
def DefaultEnvironment(*args, **kw): """ Initial public entry point for creating the default construction Environment. After creating the environment, we overwrite our name (DefaultEnvironment) with the _fetch_DefaultEnvironment() function, which more efficiently returns the initialized default...
python
{ "resource": "" }
q239035
_concat
train
def _concat(prefix, list, suffix, env, f=lambda x: x, target=None, source=None): """ Creates a new list from 'list' by first interpolating each element in the list using the 'env' dictionary and then calling f on the list, and finally calling _concat_ixes to concatenate 'prefix' and 'suffix' onto ea...
python
{ "resource": "" }
q239036
_concat_ixes
train
def _concat_ixes(prefix, list, suffix, env): """ Creates a new list from 'list' by concatenating the 'prefix' and 'suffix' arguments onto each element of the list. A trailing space on 'prefix' or leading space on 'suffix' will cause them to be put into separate list elements rather than being conca...
python
{ "resource": "" }
q239037
processDefines
train
def processDefines(defs): """process defines, resolving strings, lists, dictionaries, into a list of strings """ if SCons.Util.is_List(defs): l = [] for d in defs: if d is None: continue elif SCons.Util.is_List(d) or isinstance(d, tuple): ...
python
{ "resource": "" }
q239038
_defines
train
def _defines(prefix, defs, suffix, env, c=_concat_ixes): """A wrapper around _concat_ixes that turns a list or string into a list of C preprocessor command-line definitions. """ return c(prefix, env.subst_path(processDefines(defs)), suffix, env)
python
{ "resource": "" }
q239039
Scanner
train
def Scanner(function, *args, **kw): """ Public interface factory function for creating different types of Scanners based on the different types of "functions" that may be supplied. TODO: Deprecate this some day. We've moved the functionality inside the Base class and really don't need this fa...
python
{ "resource": "" }
q239040
BroadcastReport.ReportLength
train
def ReportLength(cls, header): """Given a header of HeaderLength bytes, calculate the size of this report. Returns: int: The total length of the report including the header that we are passed. """ parsed_header = cls._parse_header(header) auth_size = cls._AUTH_BLOC...
python
{ "resource": "" }
q239041
BroadcastReport.FromReadings
train
def FromReadings(cls, uuid, readings, sent_timestamp=0): """Generate a broadcast report from a list of readings and a uuid.""" header = struct.pack("<BBHLLL", cls.ReportType, 0, len(readings)*16, uuid, sent_timestamp, 0) packed_readings = bytearray() for reading in readings: ...
python
{ "resource": "" }
q239042
BroadcastReport.decode
train
def decode(self): """Decode this report into a list of visible readings.""" parsed_header = self._parse_header(self.raw_report[:self._HEADER_LENGTH]) auth_size = self._AUTH_BLOCK_LENGTHS.get(parsed_header.auth_type) assert auth_size is not None assert parsed_header.reading_leng...
python
{ "resource": "" }
q239043
NativeBLEVirtualInterface.start
train
def start(self, device): """Start serving access to this VirtualIOTileDevice Args: device (VirtualIOTileDevice): The device we will be providing access to """ super(NativeBLEVirtualInterface, self).start(device) self.set_advertising(True)
python
{ "resource": "" }
q239044
NativeBLEVirtualInterface.register_gatt_table
train
def register_gatt_table(self): """Register the GATT table into baBLE.""" services = [BLEService, TileBusService] characteristics = [ NameChar, AppearanceChar, ReceiveHeaderChar, ReceivePayloadChar, SendHeaderChar, SendPaylo...
python
{ "resource": "" }
q239045
NativeBLEVirtualInterface.set_advertising
train
def set_advertising(self, enabled): """Toggle advertising.""" if enabled: self.bable.set_advertising( enabled=True, uuids=[TileBusService.uuid], name="V_IOTile ", company_id=ArchManuID, advertising_data=self._adv...
python
{ "resource": "" }
q239046
NativeBLEVirtualInterface._advertisement
train
def _advertisement(self): """Create advertisement data.""" # Flags are # bit 0: whether we have pending data # bit 1: whether we are in a low voltage state # bit 2: whether another user is connected # bit 3: whether we support robust reports # bit 4: whether we al...
python
{ "resource": "" }
q239047
NativeBLEVirtualInterface._scan_response
train
def _scan_response(self): """Create scan response data.""" voltage = struct.pack("<H", int(self.voltage*256)) reading = struct.pack("<HLLL", 0xFFFF, 0, 0, 0) response = voltage + reading return response
python
{ "resource": "" }
q239048
NativeBLEVirtualInterface.stop_sync
train
def stop_sync(self): """Safely stop this BLED112 instance without leaving it in a weird state.""" # Disconnect connected device if self.connected: self.disconnect_sync(self._connection_handle) # Disable advertising self.set_advertising(False) # Stop the baBL...
python
{ "resource": "" }
q239049
NativeBLEVirtualInterface.disconnect_sync
train
def disconnect_sync(self, connection_handle): """Synchronously disconnect from whoever has connected to us Args: connection_handle (int): The handle of the connection we wish to disconnect. """ self.bable.disconnect(connection_handle=connection_handle, sync=True)
python
{ "resource": "" }
q239050
NativeBLEVirtualInterface._stream_data
train
def _stream_data(self, chunk=None): """Stream reports to the ble client in 20 byte chunks Args: chunk (bytearray): A chunk that should be sent instead of requesting a new chunk from the pending reports. """ # If we failed to transmit a chunk, we will be requ...
python
{ "resource": "" }
q239051
NativeBLEVirtualInterface._send_trace
train
def _send_trace(self, chunk=None): """Stream tracing data to the ble client in 20 byte chunks Args: chunk (bytearray): A chunk that should be sent instead of requesting a new chunk from the pending reports. """ self._trace_sm_running = True # If we f...
python
{ "resource": "" }
q239052
NativeBLEVirtualInterface.process
train
def process(self): """Periodic nonblocking processes""" super(NativeBLEVirtualInterface, self).process() if (not self._stream_sm_running) and (not self.reports.empty()): self._stream_data() if (not self._trace_sm_running) and (not self.traces.empty()): self._se...
python
{ "resource": "" }
q239053
AsyncSupervisorClient._populate_name_map
train
async def _populate_name_map(self): """Populate the name map of services as reported by the supervisor""" services = await self.sync_services() with self._state_lock: self.services = services for i, name in enumerate(self.services.keys()): self._name_ma...
python
{ "resource": "" }
q239054
AsyncSupervisorClient.local_service
train
def local_service(self, name_or_id): """Get the locally synced information for a service. This method is safe to call outside of the background event loop without any race condition. Internally it uses a thread-safe mutex to protect the local copies of supervisor data and ensure that i...
python
{ "resource": "" }
q239055
AsyncSupervisorClient.local_services
train
def local_services(self): """Get a list of id, name pairs for all of the known synced services. This method is safe to call outside of the background event loop without any race condition. Internally it uses a thread-safe mutex to protect the local copies of supervisor data and ensure ...
python
{ "resource": "" }
q239056
AsyncSupervisorClient.sync_services
train
async def sync_services(self): """Poll the current state of all services. Returns: dict: A dictionary mapping service name to service status """ services = {} servs = await self.list_services() for i, serv in enumerate(servs): info = await self....
python
{ "resource": "" }
q239057
AsyncSupervisorClient.post_state
train
def post_state(self, name, state): """Asynchronously try to update the state for a service. If the update fails, nothing is reported because we don't wait for a response from the server. This function will return immmediately and not block. Args: name (string): The...
python
{ "resource": "" }
q239058
AsyncSupervisorClient.post_error
train
def post_error(self, name, message): """Asynchronously post a user facing error message about a service. Args: name (string): The name of the service message (string): The user facing error message that will be stored for the service and can be queried later. ...
python
{ "resource": "" }
q239059
AsyncSupervisorClient.post_warning
train
def post_warning(self, name, message): """Asynchronously post a user facing warning message about a service. Args: name (string): The name of the service message (string): The user facing warning message that will be stored for the service and can be queried late...
python
{ "resource": "" }
q239060
AsyncSupervisorClient.post_info
train
def post_info(self, name, message): """Asynchronously post a user facing info message about a service. Args: name (string): The name of the service message (string): The user facing info message that will be stored for the service and can be queried later. ...
python
{ "resource": "" }
q239061
AsyncSupervisorClient._on_status_change
train
async def _on_status_change(self, update): """Update a service that has its status updated.""" info = update['payload'] new_number = info['new_status'] name = update['service'] if name not in self.services: return with self._state_lock: is_chang...
python
{ "resource": "" }
q239062
AsyncSupervisorClient._on_heartbeat
train
async def _on_heartbeat(self, update): """Receive a new heartbeat for a service.""" name = update['service'] if name not in self.services: return with self._state_lock: self.services[name].heartbeat()
python
{ "resource": "" }
q239063
AsyncSupervisorClient._on_message
train
async def _on_message(self, update): """Receive a message from a service.""" name = update['service'] message_obj = update['payload'] if name not in self.services: return with self._state_lock: self.services[name].post_message(message_obj['level'], mess...
python
{ "resource": "" }
q239064
AsyncSupervisorClient._on_headline
train
async def _on_headline(self, update): """Receive a headline from a service.""" name = update['service'] message_obj = update['payload'] new_headline = False if name not in self.services: return with self._state_lock: self.services[name].set_head...
python
{ "resource": "" }
q239065
AsyncSupervisorClient._on_rpc_command
train
async def _on_rpc_command(self, event): """Received an RPC command that we should execute.""" payload = event['payload'] rpc_id = payload['rpc_id'] tag = payload['response_uuid'] args = payload['payload'] result = 'success' response = b'' if self._rpc_d...
python
{ "resource": "" }
q239066
_decode_datetime
train
def _decode_datetime(obj): """Decode a msgpack'ed datetime.""" if '__datetime__' in obj: obj = datetime.datetime.strptime(obj['as_str'].decode(), "%Y%m%dT%H:%M:%S.%f") return obj
python
{ "resource": "" }
q239067
_encode_datetime
train
def _encode_datetime(obj): """Encode a msgpck'ed datetime.""" if isinstance(obj, datetime.datetime): obj = {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f").encode()} return obj
python
{ "resource": "" }
q239068
_versioned_lib_suffix
train
def _versioned_lib_suffix(env, suffix, version): """Generate versioned shared library suffix from a unversioned one. If suffix='.dll', and version='0.1.2', then it returns '-0-1-2.dll'""" Verbose = False if Verbose: print("_versioned_lib_suffix: suffix= ", suffix) print("_versioned_li...
python
{ "resource": "" }
q239069
generate
train
def generate(env): """Add Builders and construction variables for cyglink to an Environment.""" gnulink.generate(env) env['LINKFLAGS'] = SCons.Util.CLVar('-Wl,-no-undefined') env['SHLINKCOM'] = shlib_action env['LDMODULECOM'] = ldmod_action env.Append(SHLIBEMITTER = [shlib_emitter]) env....
python
{ "resource": "" }
q239070
ValidatingDispatcher.dispatch
train
def dispatch(self, message): """Dispatch a message to a callback based on its schema. Args: message (dict): The message to dispatch """ for validator, callback in self.validators: if not validator.matches(message): continue callback(...
python
{ "resource": "" }
q239071
main
train
def main(raw_args=None): """Run the iotile-emulate script. Args: raw_args (list): Optional list of commmand line arguments. If not passed these are pulled from sys.argv. """ if raw_args is None: raw_args = sys.argv[1:] parser = build_parser() args = parser.parse_a...
python
{ "resource": "" }
q239072
_detect
train
def _detect(env): """Not really safe, but fast method to detect the QT library""" QTDIR = None if not QTDIR: QTDIR = env.get('QTDIR',None) if not QTDIR: QTDIR = os.environ.get('QTDIR',None) if not QTDIR: moc = env.WhereIs('moc') if moc: QTDIR = os.path.dir...
python
{ "resource": "" }
q239073
generate
train
def generate(env): """Add Builders and construction variables for qt to an Environment.""" CLVar = SCons.Util.CLVar Action = SCons.Action.Action Builder = SCons.Builder.Builder env.SetDefault(QTDIR = _detect(env), QT_BINPATH = os.path.join('$QTDIR', 'bin'), QT...
python
{ "resource": "" }
q239074
CPP_to_Python
train
def CPP_to_Python(s): """ Converts a C pre-processor expression into an equivalent Python expression that can be evaluated. """ s = CPP_to_Python_Ops_Expression.sub(CPP_to_Python_Ops_Sub, s) for expr, repl in CPP_to_Python_Eval_List: s = expr.sub(repl, s) return s
python
{ "resource": "" }
q239075
PreProcessor.tupleize
train
def tupleize(self, contents): """ Turns the contents of a file into a list of easily-processed tuples describing the CPP lines in the file. The first element of each tuple is the line's preprocessor directive (#if, #include, #define, etc., minus the initial '#'). The rem...
python
{ "resource": "" }
q239076
PreProcessor.process_contents
train
def process_contents(self, contents, fname=None): """ Pre-processes a file contents. This is the main internal entry point. """ self.stack = [] self.dispatch_table = self.default_table.copy() self.current_file = fname self.tuples = self.tupleize(contents)...
python
{ "resource": "" }
q239077
PreProcessor.save
train
def save(self): """ Pushes the current dispatch table on the stack and re-initializes the current dispatch table to the default. """ self.stack.append(self.dispatch_table) self.dispatch_table = self.default_table.copy()
python
{ "resource": "" }
q239078
PreProcessor.eval_expression
train
def eval_expression(self, t): """ Evaluates a C preprocessor expression. This is done by converting it to a Python equivalent and eval()ing it in the C preprocessor namespace we use to track #define values. """ t = CPP_to_Python(' '.join(t[1:])) try: retu...
python
{ "resource": "" }
q239079
emit_rmic_classes
train
def emit_rmic_classes(target, source, env): """Create and return lists of Java RMI stub and skeleton class files to be created from a set of class files. """ class_suffix = env.get('JAVACLASSSUFFIX', '.class') classdir = env.get('JAVACLASSDIR') if not classdir: try: s = sour...
python
{ "resource": "" }
q239080
generate
train
def generate(env): """Add Builders and construction variables for rmic to an Environment.""" env['BUILDERS']['RMIC'] = RMICBuilder env['RMIC'] = 'rmic' env['RMICFLAGS'] = SCons.Util.CLVar('') env['RMICCOM'] = '$RMIC $RMICFLAGS -d ${TARGET.attributes.java_lookupdir} -classpa...
python
{ "resource": "" }
q239081
BLED112CommandProcessor._set_scan_parameters
train
def _set_scan_parameters(self, interval=2100, window=2100, active=False): """ Set the scan interval and window in units of ms and set whether active scanning is performed """ active_num = 0 if bool(active): active_num = 1 interval_num = int(interval*1000/625...
python
{ "resource": "" }
q239082
BLED112CommandProcessor._query_systemstate
train
def _query_systemstate(self): """Query the maximum number of connections supported by this adapter """ def status_filter_func(event): if event.command_class == 3 and event.command == 0: return True return False try: response = self._...
python
{ "resource": "" }
q239083
BLED112CommandProcessor._start_scan
train
def _start_scan(self, active): """Begin scanning forever """ success, retval = self._set_scan_parameters(active=active) if not success: return success, retval try: response = self._send_command(6, 2, [2]) if response.payload[0] != 0: ...
python
{ "resource": "" }
q239084
BLED112CommandProcessor._stop_scan
train
def _stop_scan(self): """Stop scanning for BLE devices """ try: response = self._send_command(6, 4, []) if response.payload[0] != 0: # Error code 129 means we just were not currently scanning if response.payload[0] != 129: ...
python
{ "resource": "" }
q239085
BLED112CommandProcessor._probe_services
train
def _probe_services(self, handle): """Probe for all primary services and characteristics in those services Args: handle (int): the connection handle to probe """ code = 0x2800 def event_filter_func(event): if (event.command_class == 4 and event.command ...
python
{ "resource": "" }
q239086
BLED112CommandProcessor._probe_characteristics
train
def _probe_characteristics(self, conn, services, timeout=5.0): """Probe gatt services for all associated characteristics in a BLE device Args: conn (int): the connection handle to probe services (dict): a dictionary of services produced by probe_services() timeout (f...
python
{ "resource": "" }
q239087
BLED112CommandProcessor._enable_rpcs
train
def _enable_rpcs(self, conn, services, timeout=1.0): """Prepare this device to receive RPCs """ #FIXME: Check for characteristic existence in a try/catch and return failure if not found success, result = self._set_notification(conn, services[TileBusService]['characteristics'][TileBusRe...
python
{ "resource": "" }
q239088
BLED112CommandProcessor._disable_rpcs
train
def _disable_rpcs(self, conn, services, timeout=1.0): """Prevent this device from receiving more RPCs """ success, result = self._set_notification(conn, services[TileBusService]['characteristics'][TileBusReceiveHeaderCharacteristic], False, timeout) if not success: return su...
python
{ "resource": "" }
q239089
BLED112CommandProcessor._write_handle
train
def _write_handle(self, conn, handle, ack, value, timeout=1.0): """Write to a BLE device characteristic by its handle Args: conn (int): The connection handle for the device we should read from handle (int): The characteristics handle we should read ack (bool): Should...
python
{ "resource": "" }
q239090
BLED112CommandProcessor._set_advertising_data
train
def _set_advertising_data(self, packet_type, data): """Set the advertising data for advertisements sent out by this bled112 Args: packet_type (int): 0 for advertisement, 1 for scan response data (bytearray): the data to set """ payload = struct.pack("<BB%ss" % (...
python
{ "resource": "" }
q239091
BLED112CommandProcessor._set_mode
train
def _set_mode(self, discover_mode, connect_mode): """Set the mode of the BLED112, used to enable and disable advertising To enable advertising, use 4, 2. To disable advertising use 0, 0. Args: discover_mode (int): The discoverability mode, 0 for off, 4 for on (user data) ...
python
{ "resource": "" }
q239092
BLED112CommandProcessor._send_notification
train
def _send_notification(self, handle, value): """Send a notification to all connected clients on a characteristic Args: handle (int): The handle we wish to notify on value (bytearray): The value we wish to send """ value_len = len(value) value = bytes(val...
python
{ "resource": "" }
q239093
BLED112CommandProcessor._disconnect
train
def _disconnect(self, handle): """Disconnect from a device that we have previously connected to """ payload = struct.pack('<B', handle) response = self._send_command(3, 0, payload) conn_handle, result = unpack("<BH", response.payload) if result != 0: self._l...
python
{ "resource": "" }
q239094
BLED112CommandProcessor._send_command
train
def _send_command(self, cmd_class, command, payload, timeout=3.0): """ Send a BGAPI packet to the dongle and return the response """ if len(payload) > 60: return ValueError("Attempting to send a BGAPI packet with length > 60 is not allowed", actual_length=len(payload), comma...
python
{ "resource": "" }
q239095
BLED112CommandProcessor._receive_packet
train
def _receive_packet(self, timeout=3.0): """ Receive a response packet to a command """ while True: response_data = self._stream.read_packet(timeout=timeout) response = BGAPIPacket(is_event=(response_data[0] == 0x80), command_class=response_data[2], command=respon...
python
{ "resource": "" }
q239096
BLED112CommandProcessor._wait_process_events
train
def _wait_process_events(self, total_time, return_filter, end_filter): """Synchronously process events until a specific event is found or we timeout Args: total_time (float): The aproximate maximum number of seconds we should wait for the end event return_filter (callable): A fu...
python
{ "resource": "" }
q239097
OrderedAWSIOTClient.connect
train
def connect(self, client_id): """Connect to AWS IOT with the given client_id Args: client_id (string): The client ID passed to the MQTT message broker """ if self.client is not None: raise InternalError("Connect called on an alreaded connected MQTT client") ...
python
{ "resource": "" }
q239098
OrderedAWSIOTClient.disconnect
train
def disconnect(self): """Disconnect from AWS IOT message broker """ if self.client is None: return try: self.client.disconnect() except operationError as exc: raise InternalError("Could not disconnect from AWS IOT", message=exc.message)
python
{ "resource": "" }
q239099
OrderedAWSIOTClient.publish
train
def publish(self, topic, message): """Publish a json message to a topic with a type and a sequence number The actual message will be published as a JSON object: { "sequence": <incrementing id>, "message": message } Args: topic (string): The M...
python
{ "resource": "" }