id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
23,700 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py | generate_guids | def generate_guids(root):
""" generates globally unique identifiers for parts of the xml which need
them.
Component tags have a special requirement. Their UUID is only allowed to
change if the list of their contained resources has changed. This allows
for clean removal and proper updates.
To handle this requirement, the uuid is generated with an md5 hashing the
whole subtree of a xml node.
"""
from hashlib import md5
# specify which tags need a guid and in which attribute this should be stored.
needs_id = { 'Product' : 'Id',
'Package' : 'Id',
'Component' : 'Guid',
}
# find all XMl nodes matching the key, retrieve their attribute, hash their
# subtree, convert hash to string and add as a attribute to the xml node.
for (key,value) in needs_id.items():
node_list = root.getElementsByTagName(key)
attribute = value
for node in node_list:
hash = md5(node.toxml()).hexdigest()
hash_str = '%s-%s-%s-%s-%s' % ( hash[:8], hash[8:12], hash[12:16], hash[16:20], hash[20:] )
node.attributes[attribute] = hash_str | python | def generate_guids(root):
from hashlib import md5
# specify which tags need a guid and in which attribute this should be stored.
needs_id = { 'Product' : 'Id',
'Package' : 'Id',
'Component' : 'Guid',
}
# find all XMl nodes matching the key, retrieve their attribute, hash their
# subtree, convert hash to string and add as a attribute to the xml node.
for (key,value) in needs_id.items():
node_list = root.getElementsByTagName(key)
attribute = value
for node in node_list:
hash = md5(node.toxml()).hexdigest()
hash_str = '%s-%s-%s-%s-%s' % ( hash[:8], hash[8:12], hash[12:16], hash[16:20], hash[20:] )
node.attributes[attribute] = hash_str | [
"def",
"generate_guids",
"(",
"root",
")",
":",
"from",
"hashlib",
"import",
"md5",
"# specify which tags need a guid and in which attribute this should be stored.",
"needs_id",
"=",
"{",
"'Product'",
":",
"'Id'",
",",
"'Package'",
":",
"'Id'",
",",
"'Component'",
":",
... | generates globally unique identifiers for parts of the xml which need
them.
Component tags have a special requirement. Their UUID is only allowed to
change if the list of their contained resources has changed. This allows
for clean removal and proper updates.
To handle this requirement, the uuid is generated with an md5 hashing the
whole subtree of a xml node. | [
"generates",
"globally",
"unique",
"identifiers",
"for",
"parts",
"of",
"the",
"xml",
"which",
"need",
"them",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py#L154-L181 |
23,701 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py | create_default_directory_layout | def create_default_directory_layout(root, NAME, VERSION, VENDOR, filename_set):
""" Create the wix default target directory layout and return the innermost
directory.
We assume that the XML tree delivered in the root argument already contains
the Product tag.
Everything is put under the PFiles directory property defined by WiX.
After that a directory with the 'VENDOR' tag is placed and then a
directory with the name of the project and its VERSION. This leads to the
following TARGET Directory Layout:
C:\<PFiles>\<Vendor>\<Projectname-Version>\
Example: C:\Programme\Company\Product-1.2\
"""
doc = Document()
d1 = doc.createElement( 'Directory' )
d1.attributes['Id'] = 'TARGETDIR'
d1.attributes['Name'] = 'SourceDir'
d2 = doc.createElement( 'Directory' )
d2.attributes['Id'] = 'ProgramFilesFolder'
d2.attributes['Name'] = 'PFiles'
d3 = doc.createElement( 'Directory' )
d3.attributes['Id'] = 'VENDOR_folder'
d3.attributes['Name'] = escape( gen_dos_short_file_name( VENDOR, filename_set ) )
d3.attributes['LongName'] = escape( VENDOR )
d4 = doc.createElement( 'Directory' )
project_folder = "%s-%s" % ( NAME, VERSION )
d4.attributes['Id'] = 'MY_DEFAULT_FOLDER'
d4.attributes['Name'] = escape( gen_dos_short_file_name( project_folder, filename_set ) )
d4.attributes['LongName'] = escape( project_folder )
d1.childNodes.append( d2 )
d2.childNodes.append( d3 )
d3.childNodes.append( d4 )
root.getElementsByTagName('Product')[0].childNodes.append( d1 )
return d4 | python | def create_default_directory_layout(root, NAME, VERSION, VENDOR, filename_set):
doc = Document()
d1 = doc.createElement( 'Directory' )
d1.attributes['Id'] = 'TARGETDIR'
d1.attributes['Name'] = 'SourceDir'
d2 = doc.createElement( 'Directory' )
d2.attributes['Id'] = 'ProgramFilesFolder'
d2.attributes['Name'] = 'PFiles'
d3 = doc.createElement( 'Directory' )
d3.attributes['Id'] = 'VENDOR_folder'
d3.attributes['Name'] = escape( gen_dos_short_file_name( VENDOR, filename_set ) )
d3.attributes['LongName'] = escape( VENDOR )
d4 = doc.createElement( 'Directory' )
project_folder = "%s-%s" % ( NAME, VERSION )
d4.attributes['Id'] = 'MY_DEFAULT_FOLDER'
d4.attributes['Name'] = escape( gen_dos_short_file_name( project_folder, filename_set ) )
d4.attributes['LongName'] = escape( project_folder )
d1.childNodes.append( d2 )
d2.childNodes.append( d3 )
d3.childNodes.append( d4 )
root.getElementsByTagName('Product')[0].childNodes.append( d1 )
return d4 | [
"def",
"create_default_directory_layout",
"(",
"root",
",",
"NAME",
",",
"VERSION",
",",
"VENDOR",
",",
"filename_set",
")",
":",
"doc",
"=",
"Document",
"(",
")",
"d1",
"=",
"doc",
".",
"createElement",
"(",
"'Directory'",
")",
"d1",
".",
"attributes",
"[... | Create the wix default target directory layout and return the innermost
directory.
We assume that the XML tree delivered in the root argument already contains
the Product tag.
Everything is put under the PFiles directory property defined by WiX.
After that a directory with the 'VENDOR' tag is placed and then a
directory with the name of the project and its VERSION. This leads to the
following TARGET Directory Layout:
C:\<PFiles>\<Vendor>\<Projectname-Version>\
Example: C:\Programme\Company\Product-1.2\ | [
"Create",
"the",
"wix",
"default",
"target",
"directory",
"layout",
"and",
"return",
"the",
"innermost",
"directory",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py#L225-L265 |
23,702 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py | build_wxsfile_file_section | def build_wxsfile_file_section(root, files, NAME, VERSION, VENDOR, filename_set, id_set):
""" Builds the Component sections of the wxs file with their included files.
Files need to be specified in 8.3 format and in the long name format, long
filenames will be converted automatically.
Features are specficied with the 'X_MSI_FEATURE' or 'DOC' FileTag.
"""
root = create_default_directory_layout( root, NAME, VERSION, VENDOR, filename_set )
components = create_feature_dict( files )
factory = Document()
def get_directory( node, dir ):
""" Returns the node under the given node representing the directory.
Returns the component node if dir is None or empty.
"""
if dir == '' or not dir:
return node
Directory = node
dir_parts = dir.split(os.path.sep)
# to make sure that our directory ids are unique, the parent folders are
# consecutively added to upper_dir
upper_dir = ''
# walk down the xml tree finding parts of the directory
dir_parts = [d for d in dir_parts if d != '']
for d in dir_parts[:]:
already_created = [c for c in Directory.childNodes
if c.nodeName == 'Directory'
and c.attributes['LongName'].value == escape(d)]
if already_created != []:
Directory = already_created[0]
dir_parts.remove(d)
upper_dir += d
else:
break
for d in dir_parts:
nDirectory = factory.createElement( 'Directory' )
nDirectory.attributes['LongName'] = escape( d )
nDirectory.attributes['Name'] = escape( gen_dos_short_file_name( d, filename_set ) )
upper_dir += d
nDirectory.attributes['Id'] = convert_to_id( upper_dir, id_set )
Directory.childNodes.append( nDirectory )
Directory = nDirectory
return Directory
for file in files:
drive, path = os.path.splitdrive( file.PACKAGING_INSTALL_LOCATION )
filename = os.path.basename( path )
dirname = os.path.dirname( path )
h = {
# tagname : default value
'PACKAGING_X_MSI_VITAL' : 'yes',
'PACKAGING_X_MSI_FILEID' : convert_to_id(filename, id_set),
'PACKAGING_X_MSI_LONGNAME' : filename,
'PACKAGING_X_MSI_SHORTNAME' : gen_dos_short_file_name(filename, filename_set),
'PACKAGING_X_MSI_SOURCE' : file.get_path(),
}
# fill in the default tags given above.
for k,v in [ (k, v) for (k,v) in h.items() if not hasattr(file, k) ]:
setattr( file, k, v )
File = factory.createElement( 'File' )
File.attributes['LongName'] = escape( file.PACKAGING_X_MSI_LONGNAME )
File.attributes['Name'] = escape( file.PACKAGING_X_MSI_SHORTNAME )
File.attributes['Source'] = escape( file.PACKAGING_X_MSI_SOURCE )
File.attributes['Id'] = escape( file.PACKAGING_X_MSI_FILEID )
File.attributes['Vital'] = escape( file.PACKAGING_X_MSI_VITAL )
# create the <Component> Tag under which this file should appear
Component = factory.createElement('Component')
Component.attributes['DiskId'] = '1'
Component.attributes['Id'] = convert_to_id( filename, id_set )
# hang the component node under the root node and the file node
# under the component node.
Directory = get_directory( root, dirname )
Directory.childNodes.append( Component )
Component.childNodes.append( File ) | python | def build_wxsfile_file_section(root, files, NAME, VERSION, VENDOR, filename_set, id_set):
root = create_default_directory_layout( root, NAME, VERSION, VENDOR, filename_set )
components = create_feature_dict( files )
factory = Document()
def get_directory( node, dir ):
""" Returns the node under the given node representing the directory.
Returns the component node if dir is None or empty.
"""
if dir == '' or not dir:
return node
Directory = node
dir_parts = dir.split(os.path.sep)
# to make sure that our directory ids are unique, the parent folders are
# consecutively added to upper_dir
upper_dir = ''
# walk down the xml tree finding parts of the directory
dir_parts = [d for d in dir_parts if d != '']
for d in dir_parts[:]:
already_created = [c for c in Directory.childNodes
if c.nodeName == 'Directory'
and c.attributes['LongName'].value == escape(d)]
if already_created != []:
Directory = already_created[0]
dir_parts.remove(d)
upper_dir += d
else:
break
for d in dir_parts:
nDirectory = factory.createElement( 'Directory' )
nDirectory.attributes['LongName'] = escape( d )
nDirectory.attributes['Name'] = escape( gen_dos_short_file_name( d, filename_set ) )
upper_dir += d
nDirectory.attributes['Id'] = convert_to_id( upper_dir, id_set )
Directory.childNodes.append( nDirectory )
Directory = nDirectory
return Directory
for file in files:
drive, path = os.path.splitdrive( file.PACKAGING_INSTALL_LOCATION )
filename = os.path.basename( path )
dirname = os.path.dirname( path )
h = {
# tagname : default value
'PACKAGING_X_MSI_VITAL' : 'yes',
'PACKAGING_X_MSI_FILEID' : convert_to_id(filename, id_set),
'PACKAGING_X_MSI_LONGNAME' : filename,
'PACKAGING_X_MSI_SHORTNAME' : gen_dos_short_file_name(filename, filename_set),
'PACKAGING_X_MSI_SOURCE' : file.get_path(),
}
# fill in the default tags given above.
for k,v in [ (k, v) for (k,v) in h.items() if not hasattr(file, k) ]:
setattr( file, k, v )
File = factory.createElement( 'File' )
File.attributes['LongName'] = escape( file.PACKAGING_X_MSI_LONGNAME )
File.attributes['Name'] = escape( file.PACKAGING_X_MSI_SHORTNAME )
File.attributes['Source'] = escape( file.PACKAGING_X_MSI_SOURCE )
File.attributes['Id'] = escape( file.PACKAGING_X_MSI_FILEID )
File.attributes['Vital'] = escape( file.PACKAGING_X_MSI_VITAL )
# create the <Component> Tag under which this file should appear
Component = factory.createElement('Component')
Component.attributes['DiskId'] = '1'
Component.attributes['Id'] = convert_to_id( filename, id_set )
# hang the component node under the root node and the file node
# under the component node.
Directory = get_directory( root, dirname )
Directory.childNodes.append( Component )
Component.childNodes.append( File ) | [
"def",
"build_wxsfile_file_section",
"(",
"root",
",",
"files",
",",
"NAME",
",",
"VERSION",
",",
"VENDOR",
",",
"filename_set",
",",
"id_set",
")",
":",
"root",
"=",
"create_default_directory_layout",
"(",
"root",
",",
"NAME",
",",
"VERSION",
",",
"VENDOR",
... | Builds the Component sections of the wxs file with their included files.
Files need to be specified in 8.3 format and in the long name format, long
filenames will be converted automatically.
Features are specficied with the 'X_MSI_FEATURE' or 'DOC' FileTag. | [
"Builds",
"the",
"Component",
"sections",
"of",
"the",
"wxs",
"file",
"with",
"their",
"included",
"files",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py#L270-L357 |
23,703 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py | build_wxsfile_default_gui | def build_wxsfile_default_gui(root):
""" This function adds a default GUI to the wxs file
"""
factory = Document()
Product = root.getElementsByTagName('Product')[0]
UIRef = factory.createElement('UIRef')
UIRef.attributes['Id'] = 'WixUI_Mondo'
Product.childNodes.append(UIRef)
UIRef = factory.createElement('UIRef')
UIRef.attributes['Id'] = 'WixUI_ErrorProgressText'
Product.childNodes.append(UIRef) | python | def build_wxsfile_default_gui(root):
factory = Document()
Product = root.getElementsByTagName('Product')[0]
UIRef = factory.createElement('UIRef')
UIRef.attributes['Id'] = 'WixUI_Mondo'
Product.childNodes.append(UIRef)
UIRef = factory.createElement('UIRef')
UIRef.attributes['Id'] = 'WixUI_ErrorProgressText'
Product.childNodes.append(UIRef) | [
"def",
"build_wxsfile_default_gui",
"(",
"root",
")",
":",
"factory",
"=",
"Document",
"(",
")",
"Product",
"=",
"root",
".",
"getElementsByTagName",
"(",
"'Product'",
")",
"[",
"0",
"]",
"UIRef",
"=",
"factory",
".",
"createElement",
"(",
"'UIRef'",
")",
... | This function adds a default GUI to the wxs file | [
"This",
"function",
"adds",
"a",
"default",
"GUI",
"to",
"the",
"wxs",
"file"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py#L417-L429 |
23,704 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py | build_license_file | def build_license_file(directory, spec):
""" Creates a License.rtf file with the content of "X_MSI_LICENSE_TEXT"
in the given directory
"""
name, text = '', ''
try:
name = spec['LICENSE']
text = spec['X_MSI_LICENSE_TEXT']
except KeyError:
pass # ignore this as X_MSI_LICENSE_TEXT is optional
if name!='' or text!='':
file = open( os.path.join(directory.get_path(), 'License.rtf'), 'w' )
file.write('{\\rtf')
if text!='':
file.write(text.replace('\n', '\\par '))
else:
file.write(name+'\\par\\par')
file.write('}')
file.close() | python | def build_license_file(directory, spec):
name, text = '', ''
try:
name = spec['LICENSE']
text = spec['X_MSI_LICENSE_TEXT']
except KeyError:
pass # ignore this as X_MSI_LICENSE_TEXT is optional
if name!='' or text!='':
file = open( os.path.join(directory.get_path(), 'License.rtf'), 'w' )
file.write('{\\rtf')
if text!='':
file.write(text.replace('\n', '\\par '))
else:
file.write(name+'\\par\\par')
file.write('}')
file.close() | [
"def",
"build_license_file",
"(",
"directory",
",",
"spec",
")",
":",
"name",
",",
"text",
"=",
"''",
",",
"''",
"try",
":",
"name",
"=",
"spec",
"[",
"'LICENSE'",
"]",
"text",
"=",
"spec",
"[",
"'X_MSI_LICENSE_TEXT'",
"]",
"except",
"KeyError",
":",
"... | Creates a License.rtf file with the content of "X_MSI_LICENSE_TEXT"
in the given directory | [
"Creates",
"a",
"License",
".",
"rtf",
"file",
"with",
"the",
"content",
"of",
"X_MSI_LICENSE_TEXT",
"in",
"the",
"given",
"directory"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py#L431-L451 |
23,705 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py | build_wxsfile_header_section | def build_wxsfile_header_section(root, spec):
""" Adds the xml file node which define the package meta-data.
"""
# Create the needed DOM nodes and add them at the correct position in the tree.
factory = Document()
Product = factory.createElement( 'Product' )
Package = factory.createElement( 'Package' )
root.childNodes.append( Product )
Product.childNodes.append( Package )
# set "mandatory" default values
if 'X_MSI_LANGUAGE' not in spec:
spec['X_MSI_LANGUAGE'] = '1033' # select english
# mandatory sections, will throw a KeyError if the tag is not available
Product.attributes['Name'] = escape( spec['NAME'] )
Product.attributes['Version'] = escape( spec['VERSION'] )
Product.attributes['Manufacturer'] = escape( spec['VENDOR'] )
Product.attributes['Language'] = escape( spec['X_MSI_LANGUAGE'] )
Package.attributes['Description'] = escape( spec['SUMMARY'] )
# now the optional tags, for which we avoid the KeyErrror exception
if 'DESCRIPTION' in spec:
Package.attributes['Comments'] = escape( spec['DESCRIPTION'] )
if 'X_MSI_UPGRADE_CODE' in spec:
Package.attributes['X_MSI_UPGRADE_CODE'] = escape( spec['X_MSI_UPGRADE_CODE'] )
# We hardcode the media tag as our current model cannot handle it.
Media = factory.createElement('Media')
Media.attributes['Id'] = '1'
Media.attributes['Cabinet'] = 'default.cab'
Media.attributes['EmbedCab'] = 'yes'
root.getElementsByTagName('Product')[0].childNodes.append(Media) | python | def build_wxsfile_header_section(root, spec):
# Create the needed DOM nodes and add them at the correct position in the tree.
factory = Document()
Product = factory.createElement( 'Product' )
Package = factory.createElement( 'Package' )
root.childNodes.append( Product )
Product.childNodes.append( Package )
# set "mandatory" default values
if 'X_MSI_LANGUAGE' not in spec:
spec['X_MSI_LANGUAGE'] = '1033' # select english
# mandatory sections, will throw a KeyError if the tag is not available
Product.attributes['Name'] = escape( spec['NAME'] )
Product.attributes['Version'] = escape( spec['VERSION'] )
Product.attributes['Manufacturer'] = escape( spec['VENDOR'] )
Product.attributes['Language'] = escape( spec['X_MSI_LANGUAGE'] )
Package.attributes['Description'] = escape( spec['SUMMARY'] )
# now the optional tags, for which we avoid the KeyErrror exception
if 'DESCRIPTION' in spec:
Package.attributes['Comments'] = escape( spec['DESCRIPTION'] )
if 'X_MSI_UPGRADE_CODE' in spec:
Package.attributes['X_MSI_UPGRADE_CODE'] = escape( spec['X_MSI_UPGRADE_CODE'] )
# We hardcode the media tag as our current model cannot handle it.
Media = factory.createElement('Media')
Media.attributes['Id'] = '1'
Media.attributes['Cabinet'] = 'default.cab'
Media.attributes['EmbedCab'] = 'yes'
root.getElementsByTagName('Product')[0].childNodes.append(Media) | [
"def",
"build_wxsfile_header_section",
"(",
"root",
",",
"spec",
")",
":",
"# Create the needed DOM nodes and add them at the correct position in the tree.",
"factory",
"=",
"Document",
"(",
")",
"Product",
"=",
"factory",
".",
"createElement",
"(",
"'Product'",
")",
"Pac... | Adds the xml file node which define the package meta-data. | [
"Adds",
"the",
"xml",
"file",
"node",
"which",
"define",
"the",
"package",
"meta",
"-",
"data",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py#L456-L490 |
23,706 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/suncxx.py | generate | def generate(env):
"""Add Builders and construction variables for SunPRO C++."""
path, cxx, shcxx, version = get_cppc(env)
if path:
cxx = os.path.join(path, cxx)
shcxx = os.path.join(path, shcxx)
cplusplus.generate(env)
env['CXX'] = cxx
env['SHCXX'] = shcxx
env['CXXVERSION'] = version
env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS -KPIC')
env['SHOBJPREFIX'] = 'so_'
env['SHOBJSUFFIX'] = '.o' | python | def generate(env):
path, cxx, shcxx, version = get_cppc(env)
if path:
cxx = os.path.join(path, cxx)
shcxx = os.path.join(path, shcxx)
cplusplus.generate(env)
env['CXX'] = cxx
env['SHCXX'] = shcxx
env['CXXVERSION'] = version
env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS -KPIC')
env['SHOBJPREFIX'] = 'so_'
env['SHOBJSUFFIX'] = '.o' | [
"def",
"generate",
"(",
"env",
")",
":",
"path",
",",
"cxx",
",",
"shcxx",
",",
"version",
"=",
"get_cppc",
"(",
"env",
")",
"if",
"path",
":",
"cxx",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"cxx",
")",
"shcxx",
"=",
"os",
".",
... | Add Builders and construction variables for SunPRO C++. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"SunPRO",
"C",
"++",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/suncxx.py#L116-L130 |
23,707 | iotile/coretools | iotilecore/iotile/core/hw/reports/flexible_dictionary.py | FlexibleDictionaryReport.FromReadings | def FromReadings(cls, uuid, readings, events, report_id=IOTileReading.InvalidReadingID,
selector=0xFFFF, streamer=0x100, sent_timestamp=0, received_time=None):
"""Create a flexible dictionary report from a list of readings and events.
Args:
uuid (int): The uuid of the device that this report came from
readings (list of IOTileReading): A list of IOTileReading objects containing the data in the report
events (list of IOTileEvent): A list of the events contained in the report.
report_id (int): The id of the report. If not provided it defaults to IOTileReading.InvalidReadingID.
Note that you can specify anything you want for the report id but for actual IOTile devices
the report id will always be greater than the id of all of the readings contained in the report
since devices generate ids sequentially.
selector (int): The streamer selector of this report. This can be anything but if the report came from
a device, it would correspond with the query the device used to pick readings to go into the report.
streamer (int): The streamer id that this reading was sent from.
sent_timestamp (int): The device's uptime that sent this report.
received_time(datetime): The UTC time when this report was received from an IOTile device. If it is being
created now, received_time defaults to datetime.utcnow().
Returns:
FlexibleDictionaryReport: A report containing the readings and events passed in.
"""
lowest_id = IOTileReading.InvalidReadingID
highest_id = IOTileReading.InvalidReadingID
for item in itertools.chain(iter(readings), iter(events)):
if item.reading_id == IOTileReading.InvalidReadingID:
continue
if lowest_id == IOTileReading.InvalidReadingID or item.reading_id < lowest_id:
lowest_id = item.reading_id
if highest_id == IOTileReading.InvalidReadingID or item.reading_id > highest_id:
highest_id = item.reading_id
reading_list = [x.asdict() for x in readings]
event_list = [x.asdict() for x in events]
report_dict = {
"format": cls.FORMAT_TAG,
"device": uuid,
"streamer_index": streamer,
"streamer_selector": selector,
"incremental_id": report_id,
"lowest_id": lowest_id,
"highest_id": highest_id,
"device_sent_timestamp": sent_timestamp,
"events": event_list,
"data": reading_list
}
encoded = msgpack.packb(report_dict, default=_encode_datetime, use_bin_type=True)
return FlexibleDictionaryReport(encoded, signed=False, encrypted=False, received_time=received_time) | python | def FromReadings(cls, uuid, readings, events, report_id=IOTileReading.InvalidReadingID,
selector=0xFFFF, streamer=0x100, sent_timestamp=0, received_time=None):
lowest_id = IOTileReading.InvalidReadingID
highest_id = IOTileReading.InvalidReadingID
for item in itertools.chain(iter(readings), iter(events)):
if item.reading_id == IOTileReading.InvalidReadingID:
continue
if lowest_id == IOTileReading.InvalidReadingID or item.reading_id < lowest_id:
lowest_id = item.reading_id
if highest_id == IOTileReading.InvalidReadingID or item.reading_id > highest_id:
highest_id = item.reading_id
reading_list = [x.asdict() for x in readings]
event_list = [x.asdict() for x in events]
report_dict = {
"format": cls.FORMAT_TAG,
"device": uuid,
"streamer_index": streamer,
"streamer_selector": selector,
"incremental_id": report_id,
"lowest_id": lowest_id,
"highest_id": highest_id,
"device_sent_timestamp": sent_timestamp,
"events": event_list,
"data": reading_list
}
encoded = msgpack.packb(report_dict, default=_encode_datetime, use_bin_type=True)
return FlexibleDictionaryReport(encoded, signed=False, encrypted=False, received_time=received_time) | [
"def",
"FromReadings",
"(",
"cls",
",",
"uuid",
",",
"readings",
",",
"events",
",",
"report_id",
"=",
"IOTileReading",
".",
"InvalidReadingID",
",",
"selector",
"=",
"0xFFFF",
",",
"streamer",
"=",
"0x100",
",",
"sent_timestamp",
"=",
"0",
",",
"received_ti... | Create a flexible dictionary report from a list of readings and events.
Args:
uuid (int): The uuid of the device that this report came from
readings (list of IOTileReading): A list of IOTileReading objects containing the data in the report
events (list of IOTileEvent): A list of the events contained in the report.
report_id (int): The id of the report. If not provided it defaults to IOTileReading.InvalidReadingID.
Note that you can specify anything you want for the report id but for actual IOTile devices
the report id will always be greater than the id of all of the readings contained in the report
since devices generate ids sequentially.
selector (int): The streamer selector of this report. This can be anything but if the report came from
a device, it would correspond with the query the device used to pick readings to go into the report.
streamer (int): The streamer id that this reading was sent from.
sent_timestamp (int): The device's uptime that sent this report.
received_time(datetime): The UTC time when this report was received from an IOTile device. If it is being
created now, received_time defaults to datetime.utcnow().
Returns:
FlexibleDictionaryReport: A report containing the readings and events passed in. | [
"Create",
"a",
"flexible",
"dictionary",
"report",
"from",
"a",
"list",
"of",
"readings",
"and",
"events",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/flexible_dictionary.py#L28-L80 |
23,708 | iotile/coretools | iotilecore/iotile/core/hw/reports/flexible_dictionary.py | FlexibleDictionaryReport.decode | def decode(self):
"""Decode this report from a msgpack encoded binary blob."""
report_dict = msgpack.unpackb(self.raw_report, raw=False)
events = [IOTileEvent.FromDict(x) for x in report_dict.get('events', [])]
readings = [IOTileReading.FromDict(x) for x in report_dict.get('data', [])]
if 'device' not in report_dict:
raise DataError("Invalid encoded FlexibleDictionaryReport that did not "
"have a device key set with the device uuid")
self.origin = report_dict['device']
self.report_id = report_dict.get("incremental_id", IOTileReading.InvalidReadingID)
self.sent_timestamp = report_dict.get("device_sent_timestamp", 0)
self.origin_streamer = report_dict.get("streamer_index")
self.streamer_selector = report_dict.get("streamer_selector")
self.lowest_id = report_dict.get('lowest_id')
self.highest_id = report_dict.get('highest_id')
return readings, events | python | def decode(self):
report_dict = msgpack.unpackb(self.raw_report, raw=False)
events = [IOTileEvent.FromDict(x) for x in report_dict.get('events', [])]
readings = [IOTileReading.FromDict(x) for x in report_dict.get('data', [])]
if 'device' not in report_dict:
raise DataError("Invalid encoded FlexibleDictionaryReport that did not "
"have a device key set with the device uuid")
self.origin = report_dict['device']
self.report_id = report_dict.get("incremental_id", IOTileReading.InvalidReadingID)
self.sent_timestamp = report_dict.get("device_sent_timestamp", 0)
self.origin_streamer = report_dict.get("streamer_index")
self.streamer_selector = report_dict.get("streamer_selector")
self.lowest_id = report_dict.get('lowest_id')
self.highest_id = report_dict.get('highest_id')
return readings, events | [
"def",
"decode",
"(",
"self",
")",
":",
"report_dict",
"=",
"msgpack",
".",
"unpackb",
"(",
"self",
".",
"raw_report",
",",
"raw",
"=",
"False",
")",
"events",
"=",
"[",
"IOTileEvent",
".",
"FromDict",
"(",
"x",
")",
"for",
"x",
"in",
"report_dict",
... | Decode this report from a msgpack encoded binary blob. | [
"Decode",
"this",
"report",
"from",
"a",
"msgpack",
"encoded",
"binary",
"blob",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/flexible_dictionary.py#L82-L102 |
23,709 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py | _callable_contents | def _callable_contents(obj):
"""Return the signature contents of a callable Python object.
"""
try:
# Test if obj is a method.
return _function_contents(obj.__func__)
except AttributeError:
try:
# Test if obj is a callable object.
return _function_contents(obj.__call__.__func__)
except AttributeError:
try:
# Test if obj is a code object.
return _code_contents(obj)
except AttributeError:
# Test if obj is a function object.
return _function_contents(obj) | python | def _callable_contents(obj):
try:
# Test if obj is a method.
return _function_contents(obj.__func__)
except AttributeError:
try:
# Test if obj is a callable object.
return _function_contents(obj.__call__.__func__)
except AttributeError:
try:
# Test if obj is a code object.
return _code_contents(obj)
except AttributeError:
# Test if obj is a function object.
return _function_contents(obj) | [
"def",
"_callable_contents",
"(",
"obj",
")",
":",
"try",
":",
"# Test if obj is a method.",
"return",
"_function_contents",
"(",
"obj",
".",
"__func__",
")",
"except",
"AttributeError",
":",
"try",
":",
"# Test if obj is a callable object.",
"return",
"_function_conten... | Return the signature contents of a callable Python object. | [
"Return",
"the",
"signature",
"contents",
"of",
"a",
"callable",
"Python",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py#L150-L169 |
23,710 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py | _object_contents | def _object_contents(obj):
"""Return the signature contents of any Python object.
We have to handle the case where object contains a code object
since it can be pickled directly.
"""
try:
# Test if obj is a method.
return _function_contents(obj.__func__)
except AttributeError:
try:
# Test if obj is a callable object.
return _function_contents(obj.__call__.__func__)
except AttributeError:
try:
# Test if obj is a code object.
return _code_contents(obj)
except AttributeError:
try:
# Test if obj is a function object.
return _function_contents(obj)
except AttributeError as ae:
# Should be a pickle-able Python object.
try:
return _object_instance_content(obj)
# pickling an Action instance or object doesn't yield a stable
# content as instance property may be dumped in different orders
# return pickle.dumps(obj, ACTION_SIGNATURE_PICKLE_PROTOCOL)
except (pickle.PicklingError, TypeError, AttributeError) as ex:
# This is weird, but it seems that nested classes
# are unpickable. The Python docs say it should
# always be a PicklingError, but some Python
# versions seem to return TypeError. Just do
# the best we can.
return bytearray(repr(obj), 'utf-8') | python | def _object_contents(obj):
try:
# Test if obj is a method.
return _function_contents(obj.__func__)
except AttributeError:
try:
# Test if obj is a callable object.
return _function_contents(obj.__call__.__func__)
except AttributeError:
try:
# Test if obj is a code object.
return _code_contents(obj)
except AttributeError:
try:
# Test if obj is a function object.
return _function_contents(obj)
except AttributeError as ae:
# Should be a pickle-able Python object.
try:
return _object_instance_content(obj)
# pickling an Action instance or object doesn't yield a stable
# content as instance property may be dumped in different orders
# return pickle.dumps(obj, ACTION_SIGNATURE_PICKLE_PROTOCOL)
except (pickle.PicklingError, TypeError, AttributeError) as ex:
# This is weird, but it seems that nested classes
# are unpickable. The Python docs say it should
# always be a PicklingError, but some Python
# versions seem to return TypeError. Just do
# the best we can.
return bytearray(repr(obj), 'utf-8') | [
"def",
"_object_contents",
"(",
"obj",
")",
":",
"try",
":",
"# Test if obj is a method.",
"return",
"_function_contents",
"(",
"obj",
".",
"__func__",
")",
"except",
"AttributeError",
":",
"try",
":",
"# Test if obj is a callable object.",
"return",
"_function_contents... | Return the signature contents of any Python object.
We have to handle the case where object contains a code object
since it can be pickled directly. | [
"Return",
"the",
"signature",
"contents",
"of",
"any",
"Python",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py#L172-L210 |
23,711 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py | _code_contents | def _code_contents(code, docstring=None):
"""Return the signature contents of a code object.
By providing direct access to the code object of the
function, Python makes this extremely easy. Hooray!
Unfortunately, older versions of Python include line
number indications in the compiled byte code. Boo!
So we remove the line number byte codes to prevent
recompilations from moving a Python function.
See:
- https://docs.python.org/2/library/inspect.html
- http://python-reference.readthedocs.io/en/latest/docs/code/index.html
For info on what each co\_ variable provides
The signature is as follows (should be byte/chars):
co_argcount, len(co_varnames), len(co_cellvars), len(co_freevars),
( comma separated signature for each object in co_consts ),
( comma separated signature for each object in co_names ),
( The bytecode with line number bytecodes removed from co_code )
co_argcount - Returns the number of positional arguments (including arguments with default values).
co_varnames - Returns a tuple containing the names of the local variables (starting with the argument names).
co_cellvars - Returns a tuple containing the names of local variables that are referenced by nested functions.
co_freevars - Returns a tuple containing the names of free variables. (?)
co_consts - Returns a tuple containing the literals used by the bytecode.
co_names - Returns a tuple containing the names used by the bytecode.
co_code - Returns a string representing the sequence of bytecode instructions.
"""
# contents = []
# The code contents depends on the number of local variables
# but not their actual names.
contents = bytearray("{}, {}".format(code.co_argcount, len(code.co_varnames)), 'utf-8')
contents.extend(b", ")
contents.extend(bytearray(str(len(code.co_cellvars)), 'utf-8'))
contents.extend(b", ")
contents.extend(bytearray(str(len(code.co_freevars)), 'utf-8'))
# The code contents depends on any constants accessed by the
# function. Note that we have to call _object_contents on each
# constants because the code object of nested functions can
# show-up among the constants.
z = [_object_contents(cc) for cc in code.co_consts[1:]]
contents.extend(b',(')
contents.extend(bytearray(',', 'utf-8').join(z))
contents.extend(b')')
# The code contents depends on the variable names used to
# accessed global variable, as changing the variable name changes
# the variable actually accessed and therefore changes the
# function result.
z= [bytearray(_object_contents(cc)) for cc in code.co_names]
contents.extend(b',(')
contents.extend(bytearray(',','utf-8').join(z))
contents.extend(b')')
# The code contents depends on its actual code!!!
contents.extend(b',(')
contents.extend(code.co_code)
contents.extend(b')')
return contents | python | def _code_contents(code, docstring=None):
# contents = []
# The code contents depends on the number of local variables
# but not their actual names.
contents = bytearray("{}, {}".format(code.co_argcount, len(code.co_varnames)), 'utf-8')
contents.extend(b", ")
contents.extend(bytearray(str(len(code.co_cellvars)), 'utf-8'))
contents.extend(b", ")
contents.extend(bytearray(str(len(code.co_freevars)), 'utf-8'))
# The code contents depends on any constants accessed by the
# function. Note that we have to call _object_contents on each
# constants because the code object of nested functions can
# show-up among the constants.
z = [_object_contents(cc) for cc in code.co_consts[1:]]
contents.extend(b',(')
contents.extend(bytearray(',', 'utf-8').join(z))
contents.extend(b')')
# The code contents depends on the variable names used to
# accessed global variable, as changing the variable name changes
# the variable actually accessed and therefore changes the
# function result.
z= [bytearray(_object_contents(cc)) for cc in code.co_names]
contents.extend(b',(')
contents.extend(bytearray(',','utf-8').join(z))
contents.extend(b')')
# The code contents depends on its actual code!!!
contents.extend(b',(')
contents.extend(code.co_code)
contents.extend(b')')
return contents | [
"def",
"_code_contents",
"(",
"code",
",",
"docstring",
"=",
"None",
")",
":",
"# contents = []",
"# The code contents depends on the number of local variables",
"# but not their actual names.",
"contents",
"=",
"bytearray",
"(",
"\"{}, {}\"",
".",
"format",
"(",
"code",
... | Return the signature contents of a code object.
By providing direct access to the code object of the
function, Python makes this extremely easy. Hooray!
Unfortunately, older versions of Python include line
number indications in the compiled byte code. Boo!
So we remove the line number byte codes to prevent
recompilations from moving a Python function.
See:
- https://docs.python.org/2/library/inspect.html
- http://python-reference.readthedocs.io/en/latest/docs/code/index.html
For info on what each co\_ variable provides
The signature is as follows (should be byte/chars):
co_argcount, len(co_varnames), len(co_cellvars), len(co_freevars),
( comma separated signature for each object in co_consts ),
( comma separated signature for each object in co_names ),
( The bytecode with line number bytecodes removed from co_code )
co_argcount - Returns the number of positional arguments (including arguments with default values).
co_varnames - Returns a tuple containing the names of the local variables (starting with the argument names).
co_cellvars - Returns a tuple containing the names of local variables that are referenced by nested functions.
co_freevars - Returns a tuple containing the names of free variables. (?)
co_consts - Returns a tuple containing the literals used by the bytecode.
co_names - Returns a tuple containing the names used by the bytecode.
co_code - Returns a string representing the sequence of bytecode instructions. | [
"Return",
"the",
"signature",
"contents",
"of",
"a",
"code",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py#L213-L281 |
23,712 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py | _object_instance_content | def _object_instance_content(obj):
"""
Returns consistant content for a action class or an instance thereof
:Parameters:
- `obj` Should be either and action class or an instance thereof
:Returns:
bytearray or bytes representing the obj suitable for generating a signature from.
"""
retval = bytearray()
if obj is None:
return b'N.'
if isinstance(obj, SCons.Util.BaseStringTypes):
return SCons.Util.to_bytes(obj)
inst_class = obj.__class__
inst_class_name = bytearray(obj.__class__.__name__,'utf-8')
inst_class_module = bytearray(obj.__class__.__module__,'utf-8')
inst_class_hierarchy = bytearray(repr(inspect.getclasstree([obj.__class__,])),'utf-8')
# print("ICH:%s : %s"%(inst_class_hierarchy, repr(obj)))
properties = [(p, getattr(obj, p, "None")) for p in dir(obj) if not (p[:2] == '__' or inspect.ismethod(getattr(obj, p)) or inspect.isbuiltin(getattr(obj,p))) ]
properties.sort()
properties_str = ','.join(["%s=%s"%(p[0],p[1]) for p in properties])
properties_bytes = bytearray(properties_str,'utf-8')
methods = [p for p in dir(obj) if inspect.ismethod(getattr(obj, p))]
methods.sort()
method_contents = []
for m in methods:
# print("Method:%s"%m)
v = _function_contents(getattr(obj, m))
# print("[%s->]V:%s [%s]"%(m,v,type(v)))
method_contents.append(v)
retval = bytearray(b'{')
retval.extend(inst_class_name)
retval.extend(b":")
retval.extend(inst_class_module)
retval.extend(b'}[[')
retval.extend(inst_class_hierarchy)
retval.extend(b']]{{')
retval.extend(bytearray(b",").join(method_contents))
retval.extend(b"}}{{{")
retval.extend(properties_bytes)
retval.extend(b'}}}')
return retval | python | def _object_instance_content(obj):
retval = bytearray()
if obj is None:
return b'N.'
if isinstance(obj, SCons.Util.BaseStringTypes):
return SCons.Util.to_bytes(obj)
inst_class = obj.__class__
inst_class_name = bytearray(obj.__class__.__name__,'utf-8')
inst_class_module = bytearray(obj.__class__.__module__,'utf-8')
inst_class_hierarchy = bytearray(repr(inspect.getclasstree([obj.__class__,])),'utf-8')
# print("ICH:%s : %s"%(inst_class_hierarchy, repr(obj)))
properties = [(p, getattr(obj, p, "None")) for p in dir(obj) if not (p[:2] == '__' or inspect.ismethod(getattr(obj, p)) or inspect.isbuiltin(getattr(obj,p))) ]
properties.sort()
properties_str = ','.join(["%s=%s"%(p[0],p[1]) for p in properties])
properties_bytes = bytearray(properties_str,'utf-8')
methods = [p for p in dir(obj) if inspect.ismethod(getattr(obj, p))]
methods.sort()
method_contents = []
for m in methods:
# print("Method:%s"%m)
v = _function_contents(getattr(obj, m))
# print("[%s->]V:%s [%s]"%(m,v,type(v)))
method_contents.append(v)
retval = bytearray(b'{')
retval.extend(inst_class_name)
retval.extend(b":")
retval.extend(inst_class_module)
retval.extend(b'}[[')
retval.extend(inst_class_hierarchy)
retval.extend(b']]{{')
retval.extend(bytearray(b",").join(method_contents))
retval.extend(b"}}{{{")
retval.extend(properties_bytes)
retval.extend(b'}}}')
return retval | [
"def",
"_object_instance_content",
"(",
"obj",
")",
":",
"retval",
"=",
"bytearray",
"(",
")",
"if",
"obj",
"is",
"None",
":",
"return",
"b'N.'",
"if",
"isinstance",
"(",
"obj",
",",
"SCons",
".",
"Util",
".",
"BaseStringTypes",
")",
":",
"return",
"SCon... | Returns consistant content for a action class or an instance thereof
:Parameters:
- `obj` Should be either and action class or an instance thereof
:Returns:
bytearray or bytes representing the obj suitable for generating a signature from. | [
"Returns",
"consistant",
"content",
"for",
"a",
"action",
"class",
"or",
"an",
"instance",
"thereof"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py#L332-L382 |
23,713 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py | _do_create_keywords | def _do_create_keywords(args, kw):
"""This converts any arguments after the action argument into
their equivalent keywords and adds them to the kw argument.
"""
v = kw.get('varlist', ())
# prevent varlist="FOO" from being interpreted as ['F', 'O', 'O']
if is_String(v): v = (v,)
kw['varlist'] = tuple(v)
if args:
# turn positional args into equivalent keywords
cmdstrfunc = args[0]
if cmdstrfunc is None or is_String(cmdstrfunc):
kw['cmdstr'] = cmdstrfunc
elif callable(cmdstrfunc):
kw['strfunction'] = cmdstrfunc
else:
raise SCons.Errors.UserError(
'Invalid command display variable type. '
'You must either pass a string or a callback which '
'accepts (target, source, env) as parameters.')
if len(args) > 1:
kw['varlist'] = tuple(SCons.Util.flatten(args[1:])) + kw['varlist']
if kw.get('strfunction', _null) is not _null \
and kw.get('cmdstr', _null) is not _null:
raise SCons.Errors.UserError(
'Cannot have both strfunction and cmdstr args to Action()') | python | def _do_create_keywords(args, kw):
v = kw.get('varlist', ())
# prevent varlist="FOO" from being interpreted as ['F', 'O', 'O']
if is_String(v): v = (v,)
kw['varlist'] = tuple(v)
if args:
# turn positional args into equivalent keywords
cmdstrfunc = args[0]
if cmdstrfunc is None or is_String(cmdstrfunc):
kw['cmdstr'] = cmdstrfunc
elif callable(cmdstrfunc):
kw['strfunction'] = cmdstrfunc
else:
raise SCons.Errors.UserError(
'Invalid command display variable type. '
'You must either pass a string or a callback which '
'accepts (target, source, env) as parameters.')
if len(args) > 1:
kw['varlist'] = tuple(SCons.Util.flatten(args[1:])) + kw['varlist']
if kw.get('strfunction', _null) is not _null \
and kw.get('cmdstr', _null) is not _null:
raise SCons.Errors.UserError(
'Cannot have both strfunction and cmdstr args to Action()') | [
"def",
"_do_create_keywords",
"(",
"args",
",",
"kw",
")",
":",
"v",
"=",
"kw",
".",
"get",
"(",
"'varlist'",
",",
"(",
")",
")",
"# prevent varlist=\"FOO\" from being interpreted as ['F', 'O', 'O']",
"if",
"is_String",
"(",
"v",
")",
":",
"v",
"=",
"(",
"v"... | This converts any arguments after the action argument into
their equivalent keywords and adds them to the kw argument. | [
"This",
"converts",
"any",
"arguments",
"after",
"the",
"action",
"argument",
"into",
"their",
"equivalent",
"keywords",
"and",
"adds",
"them",
"to",
"the",
"kw",
"argument",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py#L413-L438 |
23,714 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py | _do_create_list_action | def _do_create_list_action(act, kw):
"""A factory for list actions. Convert the input list into Actions
and then wrap them in a ListAction."""
acts = []
for a in act:
aa = _do_create_action(a, kw)
if aa is not None: acts.append(aa)
if not acts:
return ListAction([])
elif len(acts) == 1:
return acts[0]
else:
return ListAction(acts) | python | def _do_create_list_action(act, kw):
acts = []
for a in act:
aa = _do_create_action(a, kw)
if aa is not None: acts.append(aa)
if not acts:
return ListAction([])
elif len(acts) == 1:
return acts[0]
else:
return ListAction(acts) | [
"def",
"_do_create_list_action",
"(",
"act",
",",
"kw",
")",
":",
"acts",
"=",
"[",
"]",
"for",
"a",
"in",
"act",
":",
"aa",
"=",
"_do_create_action",
"(",
"a",
",",
"kw",
")",
"if",
"aa",
"is",
"not",
"None",
":",
"acts",
".",
"append",
"(",
"aa... | A factory for list actions. Convert the input list into Actions
and then wrap them in a ListAction. | [
"A",
"factory",
"for",
"list",
"actions",
".",
"Convert",
"the",
"input",
"list",
"into",
"Actions",
"and",
"then",
"wrap",
"them",
"in",
"a",
"ListAction",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py#L494-L506 |
23,715 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py | Action | def Action(act, *args, **kw):
"""A factory for action objects."""
# Really simple: the _do_create_* routines do the heavy lifting.
_do_create_keywords(args, kw)
if is_List(act):
return _do_create_list_action(act, kw)
return _do_create_action(act, kw) | python | def Action(act, *args, **kw):
# Really simple: the _do_create_* routines do the heavy lifting.
_do_create_keywords(args, kw)
if is_List(act):
return _do_create_list_action(act, kw)
return _do_create_action(act, kw) | [
"def",
"Action",
"(",
"act",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Really simple: the _do_create_* routines do the heavy lifting.",
"_do_create_keywords",
"(",
"args",
",",
"kw",
")",
"if",
"is_List",
"(",
"act",
")",
":",
"return",
"_do_create_lis... | A factory for action objects. | [
"A",
"factory",
"for",
"action",
"objects",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py#L509-L515 |
23,716 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py | _string_from_cmd_list | def _string_from_cmd_list(cmd_list):
"""Takes a list of command line arguments and returns a pretty
representation for printing."""
cl = []
for arg in map(str, cmd_list):
if ' ' in arg or '\t' in arg:
arg = '"' + arg + '"'
cl.append(arg)
return ' '.join(cl) | python | def _string_from_cmd_list(cmd_list):
cl = []
for arg in map(str, cmd_list):
if ' ' in arg or '\t' in arg:
arg = '"' + arg + '"'
cl.append(arg)
return ' '.join(cl) | [
"def",
"_string_from_cmd_list",
"(",
"cmd_list",
")",
":",
"cl",
"=",
"[",
"]",
"for",
"arg",
"in",
"map",
"(",
"str",
",",
"cmd_list",
")",
":",
"if",
"' '",
"in",
"arg",
"or",
"'\\t'",
"in",
"arg",
":",
"arg",
"=",
"'\"'",
"+",
"arg",
"+",
"'\"... | Takes a list of command line arguments and returns a pretty
representation for printing. | [
"Takes",
"a",
"list",
"of",
"command",
"line",
"arguments",
"and",
"returns",
"a",
"pretty",
"representation",
"for",
"printing",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py#L727-L735 |
23,717 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py | get_default_ENV | def get_default_ENV(env):
"""
A fiddlin' little function that has an 'import SCons.Environment' which
can't be moved to the top level without creating an import loop. Since
this import creates a local variable named 'SCons', it blocks access to
the global variable, so we move it here to prevent complaints about local
variables being used uninitialized.
"""
global default_ENV
try:
return env['ENV']
except KeyError:
if not default_ENV:
import SCons.Environment
# This is a hideously expensive way to get a default shell
# environment. What it really should do is run the platform
# setup to get the default ENV. Fortunately, it's incredibly
# rare for an Environment not to have a shell environment, so
# we're not going to worry about it overmuch.
default_ENV = SCons.Environment.Environment()['ENV']
return default_ENV | python | def get_default_ENV(env):
global default_ENV
try:
return env['ENV']
except KeyError:
if not default_ENV:
import SCons.Environment
# This is a hideously expensive way to get a default shell
# environment. What it really should do is run the platform
# setup to get the default ENV. Fortunately, it's incredibly
# rare for an Environment not to have a shell environment, so
# we're not going to worry about it overmuch.
default_ENV = SCons.Environment.Environment()['ENV']
return default_ENV | [
"def",
"get_default_ENV",
"(",
"env",
")",
":",
"global",
"default_ENV",
"try",
":",
"return",
"env",
"[",
"'ENV'",
"]",
"except",
"KeyError",
":",
"if",
"not",
"default_ENV",
":",
"import",
"SCons",
".",
"Environment",
"# This is a hideously expensive way to get ... | A fiddlin' little function that has an 'import SCons.Environment' which
can't be moved to the top level without creating an import loop. Since
this import creates a local variable named 'SCons', it blocks access to
the global variable, so we move it here to prevent complaints about local
variables being used uninitialized. | [
"A",
"fiddlin",
"little",
"function",
"that",
"has",
"an",
"import",
"SCons",
".",
"Environment",
"which",
"can",
"t",
"be",
"moved",
"to",
"the",
"top",
"level",
"without",
"creating",
"an",
"import",
"loop",
".",
"Since",
"this",
"import",
"creates",
"a"... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py#L740-L760 |
23,718 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py | CommandAction.execute | def execute(self, target, source, env, executor=None):
"""Execute a command action.
This will handle lists of commands as well as individual commands,
because construction variable substitution may turn a single
"command" into a list. This means that this class can actually
handle lists of commands, even though that's not how we use it
externally.
"""
escape_list = SCons.Subst.escape_list
flatten_sequence = SCons.Util.flatten_sequence
try:
shell = env['SHELL']
except KeyError:
raise SCons.Errors.UserError('Missing SHELL construction variable.')
try:
spawn = env['SPAWN']
except KeyError:
raise SCons.Errors.UserError('Missing SPAWN construction variable.')
else:
if is_String(spawn):
spawn = env.subst(spawn, raw=1, conv=lambda x: x)
escape = env.get('ESCAPE', lambda x: x)
ENV = get_default_ENV(env)
# Ensure that the ENV values are all strings:
for key, value in ENV.items():
if not is_String(value):
if is_List(value):
# If the value is a list, then we assume it is a
# path list, because that's a pretty common list-like
# value to stick in an environment variable:
value = flatten_sequence(value)
ENV[key] = os.pathsep.join(map(str, value))
else:
# If it isn't a string or a list, then we just coerce
# it to a string, which is the proper way to handle
# Dir and File instances and will produce something
# reasonable for just about everything else:
ENV[key] = str(value)
if executor:
target = executor.get_all_targets()
source = executor.get_all_sources()
cmd_list, ignore, silent = self.process(target, list(map(rfile, source)), env, executor)
# Use len() to filter out any "command" that's zero-length.
for cmd_line in filter(len, cmd_list):
# Escape the command line for the interpreter we are using.
cmd_line = escape_list(cmd_line, escape)
result = spawn(shell, escape, cmd_line[0], cmd_line, ENV)
if not ignore and result:
msg = "Error %s" % result
return SCons.Errors.BuildError(errstr=msg,
status=result,
action=self,
command=cmd_line)
return 0 | python | def execute(self, target, source, env, executor=None):
escape_list = SCons.Subst.escape_list
flatten_sequence = SCons.Util.flatten_sequence
try:
shell = env['SHELL']
except KeyError:
raise SCons.Errors.UserError('Missing SHELL construction variable.')
try:
spawn = env['SPAWN']
except KeyError:
raise SCons.Errors.UserError('Missing SPAWN construction variable.')
else:
if is_String(spawn):
spawn = env.subst(spawn, raw=1, conv=lambda x: x)
escape = env.get('ESCAPE', lambda x: x)
ENV = get_default_ENV(env)
# Ensure that the ENV values are all strings:
for key, value in ENV.items():
if not is_String(value):
if is_List(value):
# If the value is a list, then we assume it is a
# path list, because that's a pretty common list-like
# value to stick in an environment variable:
value = flatten_sequence(value)
ENV[key] = os.pathsep.join(map(str, value))
else:
# If it isn't a string or a list, then we just coerce
# it to a string, which is the proper way to handle
# Dir and File instances and will produce something
# reasonable for just about everything else:
ENV[key] = str(value)
if executor:
target = executor.get_all_targets()
source = executor.get_all_sources()
cmd_list, ignore, silent = self.process(target, list(map(rfile, source)), env, executor)
# Use len() to filter out any "command" that's zero-length.
for cmd_line in filter(len, cmd_list):
# Escape the command line for the interpreter we are using.
cmd_line = escape_list(cmd_line, escape)
result = spawn(shell, escape, cmd_line[0], cmd_line, ENV)
if not ignore and result:
msg = "Error %s" % result
return SCons.Errors.BuildError(errstr=msg,
status=result,
action=self,
command=cmd_line)
return 0 | [
"def",
"execute",
"(",
"self",
",",
"target",
",",
"source",
",",
"env",
",",
"executor",
"=",
"None",
")",
":",
"escape_list",
"=",
"SCons",
".",
"Subst",
".",
"escape_list",
"flatten_sequence",
"=",
"SCons",
".",
"Util",
".",
"flatten_sequence",
"try",
... | Execute a command action.
This will handle lists of commands as well as individual commands,
because construction variable substitution may turn a single
"command" into a list. This means that this class can actually
handle lists of commands, even though that's not how we use it
externally. | [
"Execute",
"a",
"command",
"action",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py#L886-L947 |
23,719 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py | FunctionAction.get_presig | def get_presig(self, target, source, env):
"""Return the signature contents of this callable action."""
try:
return self.gc(target, source, env)
except AttributeError:
return self.funccontents | python | def get_presig(self, target, source, env):
try:
return self.gc(target, source, env)
except AttributeError:
return self.funccontents | [
"def",
"get_presig",
"(",
"self",
",",
"target",
",",
"source",
",",
"env",
")",
":",
"try",
":",
"return",
"self",
".",
"gc",
"(",
"target",
",",
"source",
",",
"env",
")",
"except",
"AttributeError",
":",
"return",
"self",
".",
"funccontents"
] | Return the signature contents of this callable action. | [
"Return",
"the",
"signature",
"contents",
"of",
"this",
"callable",
"action",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py#L1232-L1237 |
23,720 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py | ListAction.get_presig | def get_presig(self, target, source, env):
"""Return the signature contents of this action list.
Simple concatenation of the signatures of the elements.
"""
return b"".join([bytes(x.get_contents(target, source, env)) for x in self.list]) | python | def get_presig(self, target, source, env):
return b"".join([bytes(x.get_contents(target, source, env)) for x in self.list]) | [
"def",
"get_presig",
"(",
"self",
",",
"target",
",",
"source",
",",
"env",
")",
":",
"return",
"b\"\"",
".",
"join",
"(",
"[",
"bytes",
"(",
"x",
".",
"get_contents",
"(",
"target",
",",
"source",
",",
"env",
")",
")",
"for",
"x",
"in",
"self",
... | Return the signature contents of this action list.
Simple concatenation of the signatures of the elements. | [
"Return",
"the",
"signature",
"contents",
"of",
"this",
"action",
"list",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py#L1266-L1271 |
23,721 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager._notify_update | async def _notify_update(self, name, change_type, change_info=None, directed_client=None):
"""Notify updates on a service to anyone who cares."""
for monitor in self._monitors:
try:
result = monitor(name, change_type, change_info, directed_client=directed_client)
if inspect.isawaitable(result):
await result
except Exception:
# We can't allow any exceptions in a monitor routine to break the server.
self._logger.warning("Error calling monitor with update %s", name, exc_info=True) | python | async def _notify_update(self, name, change_type, change_info=None, directed_client=None):
for monitor in self._monitors:
try:
result = monitor(name, change_type, change_info, directed_client=directed_client)
if inspect.isawaitable(result):
await result
except Exception:
# We can't allow any exceptions in a monitor routine to break the server.
self._logger.warning("Error calling monitor with update %s", name, exc_info=True) | [
"async",
"def",
"_notify_update",
"(",
"self",
",",
"name",
",",
"change_type",
",",
"change_info",
"=",
"None",
",",
"directed_client",
"=",
"None",
")",
":",
"for",
"monitor",
"in",
"self",
".",
"_monitors",
":",
"try",
":",
"result",
"=",
"monitor",
"... | Notify updates on a service to anyone who cares. | [
"Notify",
"updates",
"on",
"a",
"service",
"to",
"anyone",
"who",
"cares",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L61-L71 |
23,722 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.update_state | async def update_state(self, short_name, state):
"""Set the current state of a service.
If the state is unchanged from a previous attempt, this routine does
nothing.
Args:
short_name (string): The short name of the service
state (int): The new stae of the service
"""
if short_name not in self.services:
raise ArgumentError("Service name is unknown", short_name=short_name)
if state not in states.KNOWN_STATES:
raise ArgumentError("Invalid service state", state=state)
serv = self.services[short_name]['state']
if serv.state == state:
return
update = {}
update['old_status'] = serv.state
update['new_status'] = state
update['new_status_string'] = states.KNOWN_STATES[state]
serv.state = state
await self._notify_update(short_name, 'state_change', update) | python | async def update_state(self, short_name, state):
if short_name not in self.services:
raise ArgumentError("Service name is unknown", short_name=short_name)
if state not in states.KNOWN_STATES:
raise ArgumentError("Invalid service state", state=state)
serv = self.services[short_name]['state']
if serv.state == state:
return
update = {}
update['old_status'] = serv.state
update['new_status'] = state
update['new_status_string'] = states.KNOWN_STATES[state]
serv.state = state
await self._notify_update(short_name, 'state_change', update) | [
"async",
"def",
"update_state",
"(",
"self",
",",
"short_name",
",",
"state",
")",
":",
"if",
"short_name",
"not",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Service name is unknown\"",
",",
"short_name",
"=",
"short_name",
")",
"if"... | Set the current state of a service.
If the state is unchanged from a previous attempt, this routine does
nothing.
Args:
short_name (string): The short name of the service
state (int): The new stae of the service | [
"Set",
"the",
"current",
"state",
"of",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L73-L101 |
23,723 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.add_service | def add_service(self, name, long_name, preregistered=False, notify=True):
"""Add a service to the list of tracked services.
Args:
name (string): A unique short service name for the service
long_name (string): A longer, user friendly name for the service
preregistered (bool): Whether this service is an expected preregistered
service.
notify (bool): Send notifications about this service to all clients
Returns:
awaitable: If notify is True, an awaitable for the notifications.
Otherwise None.
"""
if name in self.services:
raise ArgumentError("Could not add service because the long_name is taken", long_name=long_name)
serv_state = states.ServiceState(name, long_name, preregistered)
service = {
'state': serv_state,
'heartbeat_threshold': 600
}
self.services[name] = service
if notify:
return self._notify_update(name, 'new_service', self.service_info(name))
return None | python | def add_service(self, name, long_name, preregistered=False, notify=True):
if name in self.services:
raise ArgumentError("Could not add service because the long_name is taken", long_name=long_name)
serv_state = states.ServiceState(name, long_name, preregistered)
service = {
'state': serv_state,
'heartbeat_threshold': 600
}
self.services[name] = service
if notify:
return self._notify_update(name, 'new_service', self.service_info(name))
return None | [
"def",
"add_service",
"(",
"self",
",",
"name",
",",
"long_name",
",",
"preregistered",
"=",
"False",
",",
"notify",
"=",
"True",
")",
":",
"if",
"name",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Could not add service because the lo... | Add a service to the list of tracked services.
Args:
name (string): A unique short service name for the service
long_name (string): A longer, user friendly name for the service
preregistered (bool): Whether this service is an expected preregistered
service.
notify (bool): Send notifications about this service to all clients
Returns:
awaitable: If notify is True, an awaitable for the notifications.
Otherwise None. | [
"Add",
"a",
"service",
"to",
"the",
"list",
"of",
"tracked",
"services",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L103-L134 |
23,724 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.service_info | def service_info(self, short_name):
"""Get static information about a service.
Args:
short_name (string): The short name of the service to query
Returns:
dict: A dictionary with the long_name and preregistered info
on this service.
"""
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
info = {}
info['short_name'] = short_name
info['long_name'] = self.services[short_name]['state'].long_name
info['preregistered'] = self.services[short_name]['state'].preregistered
return info | python | def service_info(self, short_name):
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
info = {}
info['short_name'] = short_name
info['long_name'] = self.services[short_name]['state'].long_name
info['preregistered'] = self.services[short_name]['state'].preregistered
return info | [
"def",
"service_info",
"(",
"self",
",",
"short_name",
")",
":",
"if",
"short_name",
"not",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown service name\"",
",",
"short_name",
"=",
"short_name",
")",
"info",
"=",
"{",
"}",
"info... | Get static information about a service.
Args:
short_name (string): The short name of the service to query
Returns:
dict: A dictionary with the long_name and preregistered info
on this service. | [
"Get",
"static",
"information",
"about",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L136-L155 |
23,725 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.service_messages | def service_messages(self, short_name):
"""Get the messages stored for a service.
Args:
short_name (string): The short name of the service to get messages for
Returns:
list(ServiceMessage): A list of the ServiceMessages stored for this service
"""
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
return list(self.services[short_name]['state'].messages) | python | def service_messages(self, short_name):
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
return list(self.services[short_name]['state'].messages) | [
"def",
"service_messages",
"(",
"self",
",",
"short_name",
")",
":",
"if",
"short_name",
"not",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown service name\"",
",",
"short_name",
"=",
"short_name",
")",
"return",
"list",
"(",
"se... | Get the messages stored for a service.
Args:
short_name (string): The short name of the service to get messages for
Returns:
list(ServiceMessage): A list of the ServiceMessages stored for this service | [
"Get",
"the",
"messages",
"stored",
"for",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L157-L170 |
23,726 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.service_headline | def service_headline(self, short_name):
"""Get the headline stored for a service.
Args:
short_name (string): The short name of the service to get messages for
Returns:
ServiceMessage: the headline or None if there is no headline
"""
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
return self.services[short_name]['state'].headline | python | def service_headline(self, short_name):
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
return self.services[short_name]['state'].headline | [
"def",
"service_headline",
"(",
"self",
",",
"short_name",
")",
":",
"if",
"short_name",
"not",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown service name\"",
",",
"short_name",
"=",
"short_name",
")",
"return",
"self",
".",
"se... | Get the headline stored for a service.
Args:
short_name (string): The short name of the service to get messages for
Returns:
ServiceMessage: the headline or None if there is no headline | [
"Get",
"the",
"headline",
"stored",
"for",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L172-L185 |
23,727 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.service_status | def service_status(self, short_name):
"""Get the current status of a service.
Returns information about the service such as the length since the last
heartbeat, any status messages that have been posted about the service
and whether the heartbeat should be considered out of the ordinary.
Args:
short_name (string): The short name of the service to query
Returns:
dict: A dictionary with the status of the service
"""
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
info = {}
service = self.services[short_name]['state']
info['heartbeat_age'] = monotonic() - service.last_heartbeat
info['numeric_status'] = service.state
info['string_status'] = service.string_state
return info | python | def service_status(self, short_name):
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
info = {}
service = self.services[short_name]['state']
info['heartbeat_age'] = monotonic() - service.last_heartbeat
info['numeric_status'] = service.state
info['string_status'] = service.string_state
return info | [
"def",
"service_status",
"(",
"self",
",",
"short_name",
")",
":",
"if",
"short_name",
"not",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown service name\"",
",",
"short_name",
"=",
"short_name",
")",
"info",
"=",
"{",
"}",
"se... | Get the current status of a service.
Returns information about the service such as the length since the last
heartbeat, any status messages that have been posted about the service
and whether the heartbeat should be considered out of the ordinary.
Args:
short_name (string): The short name of the service to query
Returns:
dict: A dictionary with the status of the service | [
"Get",
"the",
"current",
"status",
"of",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L187-L212 |
23,728 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.send_message | async def send_message(self, name, level, message):
"""Post a message for a service.
Args:
name (string): The short name of the service to query
level (int): The level of the message (info, warning, error)
message (string): The message contents
"""
if name not in self.services:
raise ArgumentError("Unknown service name", short_name=name)
msg = self.services[name]['state'].post_message(level, message)
await self._notify_update(name, 'new_message', msg.to_dict()) | python | async def send_message(self, name, level, message):
if name not in self.services:
raise ArgumentError("Unknown service name", short_name=name)
msg = self.services[name]['state'].post_message(level, message)
await self._notify_update(name, 'new_message', msg.to_dict()) | [
"async",
"def",
"send_message",
"(",
"self",
",",
"name",
",",
"level",
",",
"message",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown service name\"",
",",
"short_name",
"=",
"name",
")",
"msg"... | Post a message for a service.
Args:
name (string): The short name of the service to query
level (int): The level of the message (info, warning, error)
message (string): The message contents | [
"Post",
"a",
"message",
"for",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L214-L227 |
23,729 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.set_headline | async def set_headline(self, name, level, message):
"""Set the sticky headline for a service.
Args:
name (string): The short name of the service to query
level (int): The level of the message (info, warning, error)
message (string): The message contents
"""
if name not in self.services:
raise ArgumentError("Unknown service name", short_name=name)
self.services[name]['state'].set_headline(level, message)
headline = self.services[name]['state'].headline.to_dict()
await self._notify_update(name, 'new_headline', headline) | python | async def set_headline(self, name, level, message):
if name not in self.services:
raise ArgumentError("Unknown service name", short_name=name)
self.services[name]['state'].set_headline(level, message)
headline = self.services[name]['state'].headline.to_dict()
await self._notify_update(name, 'new_headline', headline) | [
"async",
"def",
"set_headline",
"(",
"self",
",",
"name",
",",
"level",
",",
"message",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown service name\"",
",",
"short_name",
"=",
"name",
")",
"self... | Set the sticky headline for a service.
Args:
name (string): The short name of the service to query
level (int): The level of the message (info, warning, error)
message (string): The message contents | [
"Set",
"the",
"sticky",
"headline",
"for",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L229-L244 |
23,730 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.send_heartbeat | async def send_heartbeat(self, short_name):
"""Post a heartbeat for a service.
Args:
short_name (string): The short name of the service to query
"""
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
self.services[short_name]['state'].heartbeat()
await self._notify_update(short_name, 'heartbeat') | python | async def send_heartbeat(self, short_name):
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
self.services[short_name]['state'].heartbeat()
await self._notify_update(short_name, 'heartbeat') | [
"async",
"def",
"send_heartbeat",
"(",
"self",
",",
"short_name",
")",
":",
"if",
"short_name",
"not",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown service name\"",
",",
"short_name",
"=",
"short_name",
")",
"self",
".",
"servi... | Post a heartbeat for a service.
Args:
short_name (string): The short name of the service to query | [
"Post",
"a",
"heartbeat",
"for",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L246-L257 |
23,731 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.set_agent | def set_agent(self, short_name, client_id):
"""Register a client id that handlers commands for a service.
Args:
short_name (str): The name of the service to set an agent
for.
client_id (str): A globally unique id for the client that
should receive commands for this service.
"""
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
self.agents[short_name] = client_id | python | def set_agent(self, short_name, client_id):
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
self.agents[short_name] = client_id | [
"def",
"set_agent",
"(",
"self",
",",
"short_name",
",",
"client_id",
")",
":",
"if",
"short_name",
"not",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown service name\"",
",",
"short_name",
"=",
"short_name",
")",
"self",
".",
... | Register a client id that handlers commands for a service.
Args:
short_name (str): The name of the service to set an agent
for.
client_id (str): A globally unique id for the client that
should receive commands for this service. | [
"Register",
"a",
"client",
"id",
"that",
"handlers",
"commands",
"for",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L268-L281 |
23,732 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.clear_agent | def clear_agent(self, short_name, client_id):
"""Remove a client id from being the command handler for a service.
Args:
short_name (str): The name of the service to set an agent
for.
client_id (str): A globally unique id for the client that
should no longer receive commands for this service.
"""
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
if short_name not in self.agents:
raise ArgumentError("No agent registered for service", short_name=short_name)
if client_id != self.agents[short_name]:
raise ArgumentError("Client was not registered for service", short_name=short_name,
client_id=client_id, current_client=self.agents[short_name])
del self.agents[short_name] | python | def clear_agent(self, short_name, client_id):
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
if short_name not in self.agents:
raise ArgumentError("No agent registered for service", short_name=short_name)
if client_id != self.agents[short_name]:
raise ArgumentError("Client was not registered for service", short_name=short_name,
client_id=client_id, current_client=self.agents[short_name])
del self.agents[short_name] | [
"def",
"clear_agent",
"(",
"self",
",",
"short_name",
",",
"client_id",
")",
":",
"if",
"short_name",
"not",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown service name\"",
",",
"short_name",
"=",
"short_name",
")",
"if",
"short_... | Remove a client id from being the command handler for a service.
Args:
short_name (str): The name of the service to set an agent
for.
client_id (str): A globally unique id for the client that
should no longer receive commands for this service. | [
"Remove",
"a",
"client",
"id",
"from",
"being",
"the",
"command",
"handler",
"for",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L283-L303 |
23,733 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.send_rpc_command | async def send_rpc_command(self, short_name, rpc_id, payload, sender_client, timeout=1.0):
"""Send an RPC to a service using its registered agent.
Args:
short_name (str): The name of the service we would like to send
and RPC to
rpc_id (int): The rpc id that we would like to call
payload (bytes): The raw bytes that we would like to send as an
argument
sender_client (str): The uuid of the sending client
timeout (float): The maximum number of seconds before we signal a timeout
of the RPC
Returns:
str: A unique id that can used to identify the notified response of this
RPC.
"""
rpc_tag = str(uuid.uuid4())
self.rpc_results.declare(rpc_tag)
if short_name in self.services and short_name in self.agents:
agent_tag = self.agents[short_name]
rpc_message = {
'rpc_id': rpc_id,
'payload': payload,
'response_uuid': rpc_tag
}
self.in_flight_rpcs[rpc_tag] = InFlightRPC(sender_client, short_name,
monotonic(), timeout)
await self._notify_update(short_name, 'rpc_command', rpc_message, directed_client=agent_tag)
else:
response = dict(result='service_not_found', response=b'')
self.rpc_results.set(rpc_tag, response)
return rpc_tag | python | async def send_rpc_command(self, short_name, rpc_id, payload, sender_client, timeout=1.0):
rpc_tag = str(uuid.uuid4())
self.rpc_results.declare(rpc_tag)
if short_name in self.services and short_name in self.agents:
agent_tag = self.agents[short_name]
rpc_message = {
'rpc_id': rpc_id,
'payload': payload,
'response_uuid': rpc_tag
}
self.in_flight_rpcs[rpc_tag] = InFlightRPC(sender_client, short_name,
monotonic(), timeout)
await self._notify_update(short_name, 'rpc_command', rpc_message, directed_client=agent_tag)
else:
response = dict(result='service_not_found', response=b'')
self.rpc_results.set(rpc_tag, response)
return rpc_tag | [
"async",
"def",
"send_rpc_command",
"(",
"self",
",",
"short_name",
",",
"rpc_id",
",",
"payload",
",",
"sender_client",
",",
"timeout",
"=",
"1.0",
")",
":",
"rpc_tag",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"self",
".",
"rpc_results",
... | Send an RPC to a service using its registered agent.
Args:
short_name (str): The name of the service we would like to send
and RPC to
rpc_id (int): The rpc id that we would like to call
payload (bytes): The raw bytes that we would like to send as an
argument
sender_client (str): The uuid of the sending client
timeout (float): The maximum number of seconds before we signal a timeout
of the RPC
Returns:
str: A unique id that can used to identify the notified response of this
RPC. | [
"Send",
"an",
"RPC",
"to",
"a",
"service",
"using",
"its",
"registered",
"agent",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L305-L343 |
23,734 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.send_rpc_response | def send_rpc_response(self, rpc_tag, result, response):
"""Send a response to an RPC.
Args:
rpc_tag (str): The exact string given in a previous call to send_rpc_command
result (str): The result of the operation. The possible values of response are:
service_not_found, rpc_not_found, timeout, success, invalid_response,
invalid_arguments, execution_exception
response (bytes): The raw bytes that we should send back as a response.
"""
if rpc_tag not in self.in_flight_rpcs:
raise ArgumentError("In flight RPC could not be found, it may have timed out", rpc_tag=rpc_tag)
del self.in_flight_rpcs[rpc_tag]
response_message = {
'response': response,
'result': result
}
try:
self.rpc_results.set(rpc_tag, response_message)
except KeyError:
self._logger.warning("RPC response came but no one was waiting: response=%s", response) | python | def send_rpc_response(self, rpc_tag, result, response):
if rpc_tag not in self.in_flight_rpcs:
raise ArgumentError("In flight RPC could not be found, it may have timed out", rpc_tag=rpc_tag)
del self.in_flight_rpcs[rpc_tag]
response_message = {
'response': response,
'result': result
}
try:
self.rpc_results.set(rpc_tag, response_message)
except KeyError:
self._logger.warning("RPC response came but no one was waiting: response=%s", response) | [
"def",
"send_rpc_response",
"(",
"self",
",",
"rpc_tag",
",",
"result",
",",
"response",
")",
":",
"if",
"rpc_tag",
"not",
"in",
"self",
".",
"in_flight_rpcs",
":",
"raise",
"ArgumentError",
"(",
"\"In flight RPC could not be found, it may have timed out\"",
",",
"r... | Send a response to an RPC.
Args:
rpc_tag (str): The exact string given in a previous call to send_rpc_command
result (str): The result of the operation. The possible values of response are:
service_not_found, rpc_not_found, timeout, success, invalid_response,
invalid_arguments, execution_exception
response (bytes): The raw bytes that we should send back as a response. | [
"Send",
"a",
"response",
"to",
"an",
"RPC",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L345-L369 |
23,735 | iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | ServiceManager.periodic_service_rpcs | def periodic_service_rpcs(self):
"""Check if any RPC has expired and remove it from the in flight list.
This function should be called periodically to expire any RPCs that never complete.
"""
to_remove = []
now = monotonic()
for rpc_tag, rpc in self.in_flight_rpcs.items():
expiry = rpc.sent_timestamp + rpc.timeout
if now > expiry:
to_remove.append(rpc_tag)
for tag in to_remove:
del self.in_flight_rpcs[tag] | python | def periodic_service_rpcs(self):
to_remove = []
now = monotonic()
for rpc_tag, rpc in self.in_flight_rpcs.items():
expiry = rpc.sent_timestamp + rpc.timeout
if now > expiry:
to_remove.append(rpc_tag)
for tag in to_remove:
del self.in_flight_rpcs[tag] | [
"def",
"periodic_service_rpcs",
"(",
"self",
")",
":",
"to_remove",
"=",
"[",
"]",
"now",
"=",
"monotonic",
"(",
")",
"for",
"rpc_tag",
",",
"rpc",
"in",
"self",
".",
"in_flight_rpcs",
".",
"items",
"(",
")",
":",
"expiry",
"=",
"rpc",
".",
"sent_times... | Check if any RPC has expired and remove it from the in flight list.
This function should be called periodically to expire any RPCs that never complete. | [
"Check",
"if",
"any",
"RPC",
"has",
"expired",
"and",
"remove",
"it",
"from",
"the",
"in",
"flight",
"list",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L371-L386 |
23,736 | iotile/coretools | iotilecore/iotile/core/utilities/paths.py | settings_directory | def settings_directory():
"""Find a per user settings directory that is appropriate for each
type of system that we are installed on.
"""
system = platform.system()
basedir = None
if system == 'Windows':
if 'APPDATA' in os.environ:
basedir = os.environ['APPDATA']
# If we're not on Windows assume we're on some
# kind of posix system or Mac, where the appropriate place would be
# ~/.config
if basedir is None:
basedir = os.path.expanduser('~')
basedir = os.path.join(basedir, '.config')
settings_dir = os.path.abspath(os.path.join(basedir, 'IOTile-Core'))
return settings_dir | python | def settings_directory():
system = platform.system()
basedir = None
if system == 'Windows':
if 'APPDATA' in os.environ:
basedir = os.environ['APPDATA']
# If we're not on Windows assume we're on some
# kind of posix system or Mac, where the appropriate place would be
# ~/.config
if basedir is None:
basedir = os.path.expanduser('~')
basedir = os.path.join(basedir, '.config')
settings_dir = os.path.abspath(os.path.join(basedir, 'IOTile-Core'))
return settings_dir | [
"def",
"settings_directory",
"(",
")",
":",
"system",
"=",
"platform",
".",
"system",
"(",
")",
"basedir",
"=",
"None",
"if",
"system",
"==",
"'Windows'",
":",
"if",
"'APPDATA'",
"in",
"os",
".",
"environ",
":",
"basedir",
"=",
"os",
".",
"environ",
"[... | Find a per user settings directory that is appropriate for each
type of system that we are installed on. | [
"Find",
"a",
"per",
"user",
"settings",
"directory",
"that",
"is",
"appropriate",
"for",
"each",
"type",
"of",
"system",
"that",
"we",
"are",
"installed",
"on",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/paths.py#L14-L35 |
23,737 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/gs.py | generate | def generate(env):
"""Add Builders and construction variables for Ghostscript to an
Environment."""
global GhostscriptAction
# The following try-except block enables us to use the Tool
# in standalone mode (without the accompanying pdf.py),
# whenever we need an explicit call of gs via the Gs()
# Builder ...
try:
if GhostscriptAction is None:
GhostscriptAction = SCons.Action.Action('$GSCOM', '$GSCOMSTR')
from SCons.Tool import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
bld.add_action('.ps', GhostscriptAction)
except ImportError as e:
pass
gsbuilder = SCons.Builder.Builder(action = SCons.Action.Action('$GSCOM', '$GSCOMSTR'))
env['BUILDERS']['Gs'] = gsbuilder
env['GS'] = gs
env['GSFLAGS'] = SCons.Util.CLVar('-dNOPAUSE -dBATCH -sDEVICE=pdfwrite')
env['GSCOM'] = '$GS $GSFLAGS -sOutputFile=$TARGET $SOURCES' | python | def generate(env):
global GhostscriptAction
# The following try-except block enables us to use the Tool
# in standalone mode (without the accompanying pdf.py),
# whenever we need an explicit call of gs via the Gs()
# Builder ...
try:
if GhostscriptAction is None:
GhostscriptAction = SCons.Action.Action('$GSCOM', '$GSCOMSTR')
from SCons.Tool import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
bld.add_action('.ps', GhostscriptAction)
except ImportError as e:
pass
gsbuilder = SCons.Builder.Builder(action = SCons.Action.Action('$GSCOM', '$GSCOMSTR'))
env['BUILDERS']['Gs'] = gsbuilder
env['GS'] = gs
env['GSFLAGS'] = SCons.Util.CLVar('-dNOPAUSE -dBATCH -sDEVICE=pdfwrite')
env['GSCOM'] = '$GS $GSFLAGS -sOutputFile=$TARGET $SOURCES' | [
"def",
"generate",
"(",
"env",
")",
":",
"global",
"GhostscriptAction",
"# The following try-except block enables us to use the Tool",
"# in standalone mode (without the accompanying pdf.py),",
"# whenever we need an explicit call of gs via the Gs()",
"# Builder ...",
"try",
":",
"if",
... | Add Builders and construction variables for Ghostscript to an
Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"Ghostscript",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/gs.py#L53-L78 |
23,738 | iotile/coretools | iotilebuild/iotile/build/utilities/bundled_data.py | resource_path | def resource_path(relative_path=None, expect=None):
"""Return the absolute path to a resource in iotile-build.
This method finds the path to the `config` folder inside
iotile-build, appends `relative_path` to it and then
checks to make sure the desired file or directory exists.
You can specify expect=(None, 'file', or 'folder') for
what you expect to find at the given path.
Args:
relative_path (str): The relative_path from the config
folder to the resource in question. This path can
be specified using / characters on all operating
systems since it will be normalized before usage.
If None is passed, the based config folder will
be returned.
expect (str): What the path should resolve to, which is
checked before returning, raising a DataError if
the check fails. You can pass None for no checking,
file for checking `os.path.isfile`, or folder for
checking `os.path.isdir`. Default: None
Returns:
str: The normalized absolute path to the resource.
"""
if expect not in (None, 'file', 'folder'):
raise ArgumentError("Invalid expect parameter, must be None, 'file' or 'folder'",
expect=expect)
this_dir = os.path.dirname(__file__)
_resource_path = os.path.join(this_dir, '..', 'config')
if relative_path is not None:
path = os.path.normpath(relative_path)
_resource_path = os.path.join(_resource_path, path)
if expect == 'file' and not os.path.isfile(_resource_path):
raise DataError("Expected resource %s to be a file and it wasn't" % _resource_path)
elif expect == 'folder' and not os.path.isdir(_resource_path):
raise DataError("Expected resource %s to be a folder and it wasn't" % _resource_path)
return os.path.abspath(_resource_path) | python | def resource_path(relative_path=None, expect=None):
if expect not in (None, 'file', 'folder'):
raise ArgumentError("Invalid expect parameter, must be None, 'file' or 'folder'",
expect=expect)
this_dir = os.path.dirname(__file__)
_resource_path = os.path.join(this_dir, '..', 'config')
if relative_path is not None:
path = os.path.normpath(relative_path)
_resource_path = os.path.join(_resource_path, path)
if expect == 'file' and not os.path.isfile(_resource_path):
raise DataError("Expected resource %s to be a file and it wasn't" % _resource_path)
elif expect == 'folder' and not os.path.isdir(_resource_path):
raise DataError("Expected resource %s to be a folder and it wasn't" % _resource_path)
return os.path.abspath(_resource_path) | [
"def",
"resource_path",
"(",
"relative_path",
"=",
"None",
",",
"expect",
"=",
"None",
")",
":",
"if",
"expect",
"not",
"in",
"(",
"None",
",",
"'file'",
",",
"'folder'",
")",
":",
"raise",
"ArgumentError",
"(",
"\"Invalid expect parameter, must be None, 'file' ... | Return the absolute path to a resource in iotile-build.
This method finds the path to the `config` folder inside
iotile-build, appends `relative_path` to it and then
checks to make sure the desired file or directory exists.
You can specify expect=(None, 'file', or 'folder') for
what you expect to find at the given path.
Args:
relative_path (str): The relative_path from the config
folder to the resource in question. This path can
be specified using / characters on all operating
systems since it will be normalized before usage.
If None is passed, the based config folder will
be returned.
expect (str): What the path should resolve to, which is
checked before returning, raising a DataError if
the check fails. You can pass None for no checking,
file for checking `os.path.isfile`, or folder for
checking `os.path.isdir`. Default: None
Returns:
str: The normalized absolute path to the resource. | [
"Return",
"the",
"absolute",
"path",
"to",
"a",
"resource",
"in",
"iotile",
"-",
"build",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/utilities/bundled_data.py#L22-L65 |
23,739 | iotile/coretools | iotilecore/iotile/core/utilities/packed.py | unpack | def unpack(fmt, arg):
"""A shim around struct.unpack to allow it to work on python 2.7.3."""
if isinstance(arg, bytearray) and not (sys.version_info >= (2, 7, 5)):
return struct.unpack(fmt, str(arg))
return struct.unpack(fmt, arg) | python | def unpack(fmt, arg):
if isinstance(arg, bytearray) and not (sys.version_info >= (2, 7, 5)):
return struct.unpack(fmt, str(arg))
return struct.unpack(fmt, arg) | [
"def",
"unpack",
"(",
"fmt",
",",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"bytearray",
")",
"and",
"not",
"(",
"sys",
".",
"version_info",
">=",
"(",
"2",
",",
"7",
",",
"5",
")",
")",
":",
"return",
"struct",
".",
"unpack",
"(",
... | A shim around struct.unpack to allow it to work on python 2.7.3. | [
"A",
"shim",
"around",
"struct",
".",
"unpack",
"to",
"allow",
"it",
"to",
"work",
"on",
"python",
"2",
".",
"7",
".",
"3",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/packed.py#L5-L11 |
23,740 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/controller_system.py | ControllerSubsystemBase.initialize | async def initialize(self, timeout=2.0):
"""Launch any background tasks associated with this subsystem.
This method will synchronously await self.initialized() which makes
sure that the background tasks start up correctly.
"""
if self.initialized.is_set():
raise InternalError("initialize called when already initialized")
self._emulator.add_task(8, self._reset_vector())
await asyncio.wait_for(self.initialized.wait(), timeout=timeout) | python | async def initialize(self, timeout=2.0):
if self.initialized.is_set():
raise InternalError("initialize called when already initialized")
self._emulator.add_task(8, self._reset_vector())
await asyncio.wait_for(self.initialized.wait(), timeout=timeout) | [
"async",
"def",
"initialize",
"(",
"self",
",",
"timeout",
"=",
"2.0",
")",
":",
"if",
"self",
".",
"initialized",
".",
"is_set",
"(",
")",
":",
"raise",
"InternalError",
"(",
"\"initialize called when already initialized\"",
")",
"self",
".",
"_emulator",
"."... | Launch any background tasks associated with this subsystem.
This method will synchronously await self.initialized() which makes
sure that the background tasks start up correctly. | [
"Launch",
"any",
"background",
"tasks",
"associated",
"with",
"this",
"subsystem",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/controller_system.py#L45-L57 |
23,741 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | _check_registry_type | def _check_registry_type(folder=None):
"""Check if the user has placed a registry_type.txt file to choose the registry type
If a default registry type file is found, the DefaultBackingType and DefaultBackingFile
class parameters in ComponentRegistry are updated accordingly.
Args:
folder (string): The folder that we should check for a default registry type
"""
folder = _registry_folder(folder)
default_file = os.path.join(folder, 'registry_type.txt')
try:
with open(default_file, "r") as infile:
data = infile.read()
data = data.strip()
ComponentRegistry.SetBackingStore(data)
except IOError:
pass | python | def _check_registry_type(folder=None):
folder = _registry_folder(folder)
default_file = os.path.join(folder, 'registry_type.txt')
try:
with open(default_file, "r") as infile:
data = infile.read()
data = data.strip()
ComponentRegistry.SetBackingStore(data)
except IOError:
pass | [
"def",
"_check_registry_type",
"(",
"folder",
"=",
"None",
")",
":",
"folder",
"=",
"_registry_folder",
"(",
"folder",
")",
"default_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"'registry_type.txt'",
")",
"try",
":",
"with",
"open",
"("... | Check if the user has placed a registry_type.txt file to choose the registry type
If a default registry type file is found, the DefaultBackingType and DefaultBackingFile
class parameters in ComponentRegistry are updated accordingly.
Args:
folder (string): The folder that we should check for a default registry type | [
"Check",
"if",
"the",
"user",
"has",
"placed",
"a",
"registry_type",
".",
"txt",
"file",
"to",
"choose",
"the",
"registry",
"type"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L582-L603 |
23,742 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | _ensure_package_loaded | def _ensure_package_loaded(path, component):
"""Ensure that the given module is loaded as a submodule.
Returns:
str: The name that the module should be imported as.
"""
logger = logging.getLogger(__name__)
packages = component.find_products('support_package')
if len(packages) == 0:
return None
elif len(packages) > 1:
raise ExternalError("Component had multiple products declared as 'support_package", products=packages)
if len(path) > 2 and ':' in path[2:]: # Don't flag windows C: type paths
path, _, _ = path.rpartition(":")
package_base = packages[0]
relative_path = os.path.normpath(os.path.relpath(path, start=package_base))
if relative_path.startswith('..'):
raise ExternalError("Component had python product output of support_package",
package=package_base, product=path, relative_path=relative_path)
if not relative_path.endswith('.py'):
raise ExternalError("Python product did not end with .py", path=path)
relative_path = relative_path[:-3]
if os.pathsep in relative_path:
raise ExternalError("Python support wheels with multiple subpackages not yet supported",
relative_path=relative_path)
support_distro = component.support_distribution
if support_distro not in sys.modules:
logger.debug("Creating dynamic support wheel package: %s", support_distro)
file, path, desc = imp.find_module(os.path.basename(package_base), [os.path.dirname(package_base)])
imp.load_module(support_distro, file, path, desc)
return "{}.{}".format(support_distro, relative_path) | python | def _ensure_package_loaded(path, component):
logger = logging.getLogger(__name__)
packages = component.find_products('support_package')
if len(packages) == 0:
return None
elif len(packages) > 1:
raise ExternalError("Component had multiple products declared as 'support_package", products=packages)
if len(path) > 2 and ':' in path[2:]: # Don't flag windows C: type paths
path, _, _ = path.rpartition(":")
package_base = packages[0]
relative_path = os.path.normpath(os.path.relpath(path, start=package_base))
if relative_path.startswith('..'):
raise ExternalError("Component had python product output of support_package",
package=package_base, product=path, relative_path=relative_path)
if not relative_path.endswith('.py'):
raise ExternalError("Python product did not end with .py", path=path)
relative_path = relative_path[:-3]
if os.pathsep in relative_path:
raise ExternalError("Python support wheels with multiple subpackages not yet supported",
relative_path=relative_path)
support_distro = component.support_distribution
if support_distro not in sys.modules:
logger.debug("Creating dynamic support wheel package: %s", support_distro)
file, path, desc = imp.find_module(os.path.basename(package_base), [os.path.dirname(package_base)])
imp.load_module(support_distro, file, path, desc)
return "{}.{}".format(support_distro, relative_path) | [
"def",
"_ensure_package_loaded",
"(",
"path",
",",
"component",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"packages",
"=",
"component",
".",
"find_products",
"(",
"'support_package'",
")",
"if",
"len",
"(",
"packages",
")",
... | Ensure that the given module is loaded as a submodule.
Returns:
str: The name that the module should be imported as. | [
"Ensure",
"that",
"the",
"given",
"module",
"is",
"loaded",
"as",
"a",
"submodule",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L606-L644 |
23,743 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | _try_load_module | def _try_load_module(path, import_name=None):
"""Try to programmatically load a python module by path.
Path should point to a python file (optionally without the .py) at the
end. If it ends in a :<name> then name must point to an object defined in
the module, which is returned instead of the module itself.
Args:
path (str): The path of the module to load
import_name (str): The explicity name that the module should be given.
If not specified, this defaults to being the basename() of
path. However, if the module is inside of a support package,
you should pass the correct name so that relative imports
proceed correctly.
Returns:
str, object: The basename of the module loaded and the requested object.
"""
logger = logging.getLogger(__name__)
obj_name = None
if len(path) > 2 and ':' in path[2:]: # Don't flag windows C: type paths
path, _, obj_name = path.rpartition(":")
folder, basename = os.path.split(path)
if folder == '':
folder = './'
if basename == '' or not os.path.exists(path):
raise ArgumentError("Could not find python module to load extension", path=path)
basename, ext = os.path.splitext(basename)
if ext not in (".py", ".pyc", ""):
raise ArgumentError("Attempted to load module is not a python package or module (.py or .pyc)", path=path)
if import_name is None:
import_name = basename
else:
logger.debug("Importing module as subpackage: %s", import_name)
try:
fileobj = None
fileobj, pathname, description = imp.find_module(basename, [folder])
# Don't load modules twice
if basename in sys.modules:
mod = sys.modules[basename]
else:
mod = imp.load_module(import_name, fileobj, pathname, description)
if obj_name is not None:
if obj_name not in mod.__dict__:
raise ArgumentError("Cannot find named object '%s' inside module '%s'" % (obj_name, basename), path=path)
mod = mod.__dict__[obj_name]
return basename, mod
finally:
if fileobj is not None:
fileobj.close() | python | def _try_load_module(path, import_name=None):
logger = logging.getLogger(__name__)
obj_name = None
if len(path) > 2 and ':' in path[2:]: # Don't flag windows C: type paths
path, _, obj_name = path.rpartition(":")
folder, basename = os.path.split(path)
if folder == '':
folder = './'
if basename == '' or not os.path.exists(path):
raise ArgumentError("Could not find python module to load extension", path=path)
basename, ext = os.path.splitext(basename)
if ext not in (".py", ".pyc", ""):
raise ArgumentError("Attempted to load module is not a python package or module (.py or .pyc)", path=path)
if import_name is None:
import_name = basename
else:
logger.debug("Importing module as subpackage: %s", import_name)
try:
fileobj = None
fileobj, pathname, description = imp.find_module(basename, [folder])
# Don't load modules twice
if basename in sys.modules:
mod = sys.modules[basename]
else:
mod = imp.load_module(import_name, fileobj, pathname, description)
if obj_name is not None:
if obj_name not in mod.__dict__:
raise ArgumentError("Cannot find named object '%s' inside module '%s'" % (obj_name, basename), path=path)
mod = mod.__dict__[obj_name]
return basename, mod
finally:
if fileobj is not None:
fileobj.close() | [
"def",
"_try_load_module",
"(",
"path",
",",
"import_name",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"obj_name",
"=",
"None",
"if",
"len",
"(",
"path",
")",
">",
"2",
"and",
"':'",
"in",
"path",
"[",
"2... | Try to programmatically load a python module by path.
Path should point to a python file (optionally without the .py) at the
end. If it ends in a :<name> then name must point to an object defined in
the module, which is returned instead of the module itself.
Args:
path (str): The path of the module to load
import_name (str): The explicity name that the module should be given.
If not specified, this defaults to being the basename() of
path. However, if the module is inside of a support package,
you should pass the correct name so that relative imports
proceed correctly.
Returns:
str, object: The basename of the module loaded and the requested object. | [
"Try",
"to",
"programmatically",
"load",
"a",
"python",
"module",
"by",
"path",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L647-L707 |
23,744 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.frozen | def frozen(self):
"""Return whether we have a cached list of all installed entry_points."""
frozen_path = os.path.join(_registry_folder(), 'frozen_extensions.json')
return os.path.isfile(frozen_path) | python | def frozen(self):
frozen_path = os.path.join(_registry_folder(), 'frozen_extensions.json')
return os.path.isfile(frozen_path) | [
"def",
"frozen",
"(",
"self",
")",
":",
"frozen_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_registry_folder",
"(",
")",
",",
"'frozen_extensions.json'",
")",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"frozen_path",
")"
] | Return whether we have a cached list of all installed entry_points. | [
"Return",
"whether",
"we",
"have",
"a",
"cached",
"list",
"of",
"all",
"installed",
"entry_points",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L45-L49 |
23,745 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.kvstore | def kvstore(self):
"""Lazily load the underlying key-value store backing this registry."""
if self._kvstore is None:
self._kvstore = self.BackingType(self.BackingFileName, respect_venv=True)
return self._kvstore | python | def kvstore(self):
if self._kvstore is None:
self._kvstore = self.BackingType(self.BackingFileName, respect_venv=True)
return self._kvstore | [
"def",
"kvstore",
"(",
"self",
")",
":",
"if",
"self",
".",
"_kvstore",
"is",
"None",
":",
"self",
".",
"_kvstore",
"=",
"self",
".",
"BackingType",
"(",
"self",
".",
"BackingFileName",
",",
"respect_venv",
"=",
"True",
")",
"return",
"self",
".",
"_kv... | Lazily load the underlying key-value store backing this registry. | [
"Lazily",
"load",
"the",
"underlying",
"key",
"-",
"value",
"store",
"backing",
"this",
"registry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L52-L58 |
23,746 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.plugins | def plugins(self):
"""Lazily load iotile plugins only on demand.
This is a slow operation on computers with a slow FS and is rarely
accessed information, so only compute it when it is actually asked
for.
"""
if self._plugins is None:
self._plugins = {}
for _, plugin in self.load_extensions('iotile.plugin'):
links = plugin()
for name, value in links:
self._plugins[name] = value
return self._plugins | python | def plugins(self):
if self._plugins is None:
self._plugins = {}
for _, plugin in self.load_extensions('iotile.plugin'):
links = plugin()
for name, value in links:
self._plugins[name] = value
return self._plugins | [
"def",
"plugins",
"(",
"self",
")",
":",
"if",
"self",
".",
"_plugins",
"is",
"None",
":",
"self",
".",
"_plugins",
"=",
"{",
"}",
"for",
"_",
",",
"plugin",
"in",
"self",
".",
"load_extensions",
"(",
"'iotile.plugin'",
")",
":",
"links",
"=",
"plugi... | Lazily load iotile plugins only on demand.
This is a slow operation on computers with a slow FS and is rarely
accessed information, so only compute it when it is actually asked
for. | [
"Lazily",
"load",
"iotile",
"plugins",
"only",
"on",
"demand",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L61-L77 |
23,747 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.load_extensions | def load_extensions(self, group, name_filter=None, comp_filter=None, class_filter=None, product_name=None, unique=False):
"""Dynamically load and return extension objects of a given type.
This is the centralized way for all parts of CoreTools to allow plugin
behavior. Whenever a plugin is needed, this method should be called
to load it. Examples of plugins are proxy modules, emulated tiles,
iotile-build autobuilders, etc.
Each kind of plugin will typically be a subclass of a certain base class
and can be provided one of three ways:
1. It can be registered as an entry point in a pip installed package.
The entry point group must map the group passed to load_extensions.
2. It can be listed as a product of an IOTile component that is stored
in this ComponentRegistry. The relevant python file inside the
component will be imported dynamically as needed.
3. It can be programmatically registered by calling ``register_extension()``
on this class with a string name and an object. This is equivalent to
exposing that same object as an entry point with the given name.
There is special behavior of this function if class_filter is passed
and the object returned by one of the above three methods is a python
module. The module will be search for object definitions that match
the defined class.
The order of the returned objects list is only partially defined.
Locally installed components are searched before pip installed
packages with entry points. The order of results within each group is
not specified.
Args:
group (str): The extension type that you wish to enumerate. This
will be used as the entry_point group for searching pip
installed packages.
name_filter (str): Only return objects with the given name
comp_filter (str): When searching through installed components
(not entry_points), only search through components with the
given name.
class_filter (type or tuple of types): An object that will be passed to
instanceof() to verify that all extension objects have the correct
types. If not passed, no checking will be done.
product_name (str): If this extension can be provided by a registered
local component, the name of the product that should be loaded.
unique (bool): If True (default is False), there must be exactly one object
found inside this extension that matches all of the other criteria.
Returns:
list of (str, object): A list of the found and loaded extension objects.
The string returned with each extension is the name of the
entry_point or the base name of the file in the component or the
value provided by the call to register_extension depending on how
the extension was found.
If unique is True, then the list only contains a single entry and that
entry will be directly returned.
"""
found_extensions = []
if product_name is not None:
for comp in self.iter_components():
if comp_filter is not None and comp.name != comp_filter:
continue
products = comp.find_products(product_name)
for product in products:
try:
entries = self.load_extension(product, name_filter=name_filter, class_filter=class_filter,
component=comp)
if len(entries) == 0 and name_filter is None:
# Don't warn if we're filtering by name since most extensions won't match
self._logger.warn("Found no valid extensions in product %s of component %s",
product, comp.path)
continue
found_extensions.extend(entries)
except: # pylint:disable=bare-except;We don't want a broken extension to take down the whole system
self._logger.exception("Unable to load extension %s from local component %s at path %s",
product_name, comp, product)
for entry in self._iter_entrypoint_group(group):
name = entry.name
if name_filter is not None and name != name_filter:
continue
try:
ext = entry.load()
except: # pylint:disable=bare-except;
self._logger.warn("Unable to load %s from %s", entry.name, entry.distro, exc_info=True)
continue
found_extensions.extend((name, x) for x in self._filter_subclasses(ext, class_filter))
for (name, ext) in self._registered_extensions.get(group, []):
if name_filter is not None and name != name_filter:
continue
found_extensions.extend((name, x) for x in self._filter_subclasses(ext, class_filter))
found_extensions = [(name, x) for name, x in found_extensions if self._filter_nonextensions(x)]
if unique is True:
if len(found_extensions) > 1:
raise ArgumentError("Extension %s should have had exactly one instance of class %s, found %d" % (group, class_filter.__name__, len(found_extensions)), classes=found_extensions)
elif len(found_extensions) == 0:
raise ArgumentError("Extension %s had no instances of class %s" % (group, class_filter.__name__))
return found_extensions[0]
return found_extensions | python | def load_extensions(self, group, name_filter=None, comp_filter=None, class_filter=None, product_name=None, unique=False):
found_extensions = []
if product_name is not None:
for comp in self.iter_components():
if comp_filter is not None and comp.name != comp_filter:
continue
products = comp.find_products(product_name)
for product in products:
try:
entries = self.load_extension(product, name_filter=name_filter, class_filter=class_filter,
component=comp)
if len(entries) == 0 and name_filter is None:
# Don't warn if we're filtering by name since most extensions won't match
self._logger.warn("Found no valid extensions in product %s of component %s",
product, comp.path)
continue
found_extensions.extend(entries)
except: # pylint:disable=bare-except;We don't want a broken extension to take down the whole system
self._logger.exception("Unable to load extension %s from local component %s at path %s",
product_name, comp, product)
for entry in self._iter_entrypoint_group(group):
name = entry.name
if name_filter is not None and name != name_filter:
continue
try:
ext = entry.load()
except: # pylint:disable=bare-except;
self._logger.warn("Unable to load %s from %s", entry.name, entry.distro, exc_info=True)
continue
found_extensions.extend((name, x) for x in self._filter_subclasses(ext, class_filter))
for (name, ext) in self._registered_extensions.get(group, []):
if name_filter is not None and name != name_filter:
continue
found_extensions.extend((name, x) for x in self._filter_subclasses(ext, class_filter))
found_extensions = [(name, x) for name, x in found_extensions if self._filter_nonextensions(x)]
if unique is True:
if len(found_extensions) > 1:
raise ArgumentError("Extension %s should have had exactly one instance of class %s, found %d" % (group, class_filter.__name__, len(found_extensions)), classes=found_extensions)
elif len(found_extensions) == 0:
raise ArgumentError("Extension %s had no instances of class %s" % (group, class_filter.__name__))
return found_extensions[0]
return found_extensions | [
"def",
"load_extensions",
"(",
"self",
",",
"group",
",",
"name_filter",
"=",
"None",
",",
"comp_filter",
"=",
"None",
",",
"class_filter",
"=",
"None",
",",
"product_name",
"=",
"None",
",",
"unique",
"=",
"False",
")",
":",
"found_extensions",
"=",
"[",
... | Dynamically load and return extension objects of a given type.
This is the centralized way for all parts of CoreTools to allow plugin
behavior. Whenever a plugin is needed, this method should be called
to load it. Examples of plugins are proxy modules, emulated tiles,
iotile-build autobuilders, etc.
Each kind of plugin will typically be a subclass of a certain base class
and can be provided one of three ways:
1. It can be registered as an entry point in a pip installed package.
The entry point group must map the group passed to load_extensions.
2. It can be listed as a product of an IOTile component that is stored
in this ComponentRegistry. The relevant python file inside the
component will be imported dynamically as needed.
3. It can be programmatically registered by calling ``register_extension()``
on this class with a string name and an object. This is equivalent to
exposing that same object as an entry point with the given name.
There is special behavior of this function if class_filter is passed
and the object returned by one of the above three methods is a python
module. The module will be search for object definitions that match
the defined class.
The order of the returned objects list is only partially defined.
Locally installed components are searched before pip installed
packages with entry points. The order of results within each group is
not specified.
Args:
group (str): The extension type that you wish to enumerate. This
will be used as the entry_point group for searching pip
installed packages.
name_filter (str): Only return objects with the given name
comp_filter (str): When searching through installed components
(not entry_points), only search through components with the
given name.
class_filter (type or tuple of types): An object that will be passed to
instanceof() to verify that all extension objects have the correct
types. If not passed, no checking will be done.
product_name (str): If this extension can be provided by a registered
local component, the name of the product that should be loaded.
unique (bool): If True (default is False), there must be exactly one object
found inside this extension that matches all of the other criteria.
Returns:
list of (str, object): A list of the found and loaded extension objects.
The string returned with each extension is the name of the
entry_point or the base name of the file in the component or the
value provided by the call to register_extension depending on how
the extension was found.
If unique is True, then the list only contains a single entry and that
entry will be directly returned. | [
"Dynamically",
"load",
"and",
"return",
"extension",
"objects",
"of",
"a",
"given",
"type",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L79-L190 |
23,748 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.register_extension | def register_extension(self, group, name, extension):
"""Register an extension.
Args:
group (str): The type of the extension
name (str): A name for the extension
extension (str or class): If this is a string, then it will be
interpreted as a path to import and load. Otherwise it
will be treated as the extension object itself.
"""
if isinstance(extension, str):
name, extension = self.load_extension(extension)[0]
if group not in self._registered_extensions:
self._registered_extensions[group] = []
self._registered_extensions[group].append((name, extension)) | python | def register_extension(self, group, name, extension):
if isinstance(extension, str):
name, extension = self.load_extension(extension)[0]
if group not in self._registered_extensions:
self._registered_extensions[group] = []
self._registered_extensions[group].append((name, extension)) | [
"def",
"register_extension",
"(",
"self",
",",
"group",
",",
"name",
",",
"extension",
")",
":",
"if",
"isinstance",
"(",
"extension",
",",
"str",
")",
":",
"name",
",",
"extension",
"=",
"self",
".",
"load_extension",
"(",
"extension",
")",
"[",
"0",
... | Register an extension.
Args:
group (str): The type of the extension
name (str): A name for the extension
extension (str or class): If this is a string, then it will be
interpreted as a path to import and load. Otherwise it
will be treated as the extension object itself. | [
"Register",
"an",
"extension",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L192-L209 |
23,749 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.clear_extensions | def clear_extensions(self, group=None):
"""Clear all previously registered extensions."""
if group is None:
ComponentRegistry._registered_extensions = {}
return
if group in self._registered_extensions:
self._registered_extensions[group] = [] | python | def clear_extensions(self, group=None):
if group is None:
ComponentRegistry._registered_extensions = {}
return
if group in self._registered_extensions:
self._registered_extensions[group] = [] | [
"def",
"clear_extensions",
"(",
"self",
",",
"group",
"=",
"None",
")",
":",
"if",
"group",
"is",
"None",
":",
"ComponentRegistry",
".",
"_registered_extensions",
"=",
"{",
"}",
"return",
"if",
"group",
"in",
"self",
".",
"_registered_extensions",
":",
"self... | Clear all previously registered extensions. | [
"Clear",
"all",
"previously",
"registered",
"extensions",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L211-L219 |
23,750 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.freeze_extensions | def freeze_extensions(self):
"""Freeze the set of extensions into a single file.
Freezing extensions can speed up the extension loading process on
machines with slow file systems since it requires only a single file
to store all of the extensions.
Calling this method will save a file into the current virtual
environment that stores a list of all currently found extensions that
have been installed as entry_points. Future calls to
`load_extensions` will only search the one single file containing
frozen extensions rather than enumerating all installed distributions.
"""
output_path = os.path.join(_registry_folder(), 'frozen_extensions.json')
with open(output_path, "w") as outfile:
json.dump(self._dump_extensions(), outfile) | python | def freeze_extensions(self):
output_path = os.path.join(_registry_folder(), 'frozen_extensions.json')
with open(output_path, "w") as outfile:
json.dump(self._dump_extensions(), outfile) | [
"def",
"freeze_extensions",
"(",
"self",
")",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_registry_folder",
"(",
")",
",",
"'frozen_extensions.json'",
")",
"with",
"open",
"(",
"output_path",
",",
"\"w\"",
")",
"as",
"outfile",
":",
"js... | Freeze the set of extensions into a single file.
Freezing extensions can speed up the extension loading process on
machines with slow file systems since it requires only a single file
to store all of the extensions.
Calling this method will save a file into the current virtual
environment that stores a list of all currently found extensions that
have been installed as entry_points. Future calls to
`load_extensions` will only search the one single file containing
frozen extensions rather than enumerating all installed distributions. | [
"Freeze",
"the",
"set",
"of",
"extensions",
"into",
"a",
"single",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L221-L238 |
23,751 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.unfreeze_extensions | def unfreeze_extensions(self):
"""Remove a previously frozen list of extensions."""
output_path = os.path.join(_registry_folder(), 'frozen_extensions.json')
if not os.path.isfile(output_path):
raise ExternalError("There is no frozen extension list")
os.remove(output_path)
ComponentRegistry._frozen_extensions = None | python | def unfreeze_extensions(self):
output_path = os.path.join(_registry_folder(), 'frozen_extensions.json')
if not os.path.isfile(output_path):
raise ExternalError("There is no frozen extension list")
os.remove(output_path)
ComponentRegistry._frozen_extensions = None | [
"def",
"unfreeze_extensions",
"(",
"self",
")",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_registry_folder",
"(",
")",
",",
"'frozen_extensions.json'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"output_path",
")",
":",
... | Remove a previously frozen list of extensions. | [
"Remove",
"a",
"previously",
"frozen",
"list",
"of",
"extensions",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L240-L248 |
23,752 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.load_extension | def load_extension(self, path, name_filter=None, class_filter=None, unique=False, component=None):
"""Load a single python module extension.
This function is similar to using the imp module directly to load a
module and potentially inspecting the objects it declares to filter
them by class.
Args:
path (str): The path to the python file to load
name_filter (str): If passed, the basename of the module must match
name or nothing is returned.
class_filter (type): If passed, only instance of this class are returned.
unique (bool): If True (default is False), there must be exactly one object
found inside this extension that matches all of the other criteria.
component (IOTile): The component that this extension comes from if it is
loaded from an installed component. This is used to properly import
the extension as a submodule of the component's support package.
Returns:
list of (name, type): A list of the objects found at the extension path.
If unique is True, then the list only contains a single entry and that
entry will be directly returned.
"""
import_name = None
if component is not None:
import_name = _ensure_package_loaded(path, component)
name, ext = _try_load_module(path, import_name=import_name)
if name_filter is not None and name != name_filter:
return []
found = [(name, x) for x in self._filter_subclasses(ext, class_filter)]
found = [(name, x) for name, x in found if self._filter_nonextensions(x)]
if not unique:
return found
if len(found) > 1:
raise ArgumentError("Extension %s should have had exactly one instance of class %s, found %d"
% (path, class_filter.__name__, len(found)), classes=found)
elif len(found) == 0:
raise ArgumentError("Extension %s had no instances of class %s" % (path, class_filter.__name__))
return found[0] | python | def load_extension(self, path, name_filter=None, class_filter=None, unique=False, component=None):
import_name = None
if component is not None:
import_name = _ensure_package_loaded(path, component)
name, ext = _try_load_module(path, import_name=import_name)
if name_filter is not None and name != name_filter:
return []
found = [(name, x) for x in self._filter_subclasses(ext, class_filter)]
found = [(name, x) for name, x in found if self._filter_nonextensions(x)]
if not unique:
return found
if len(found) > 1:
raise ArgumentError("Extension %s should have had exactly one instance of class %s, found %d"
% (path, class_filter.__name__, len(found)), classes=found)
elif len(found) == 0:
raise ArgumentError("Extension %s had no instances of class %s" % (path, class_filter.__name__))
return found[0] | [
"def",
"load_extension",
"(",
"self",
",",
"path",
",",
"name_filter",
"=",
"None",
",",
"class_filter",
"=",
"None",
",",
"unique",
"=",
"False",
",",
"component",
"=",
"None",
")",
":",
"import_name",
"=",
"None",
"if",
"component",
"is",
"not",
"None"... | Load a single python module extension.
This function is similar to using the imp module directly to load a
module and potentially inspecting the objects it declares to filter
them by class.
Args:
path (str): The path to the python file to load
name_filter (str): If passed, the basename of the module must match
name or nothing is returned.
class_filter (type): If passed, only instance of this class are returned.
unique (bool): If True (default is False), there must be exactly one object
found inside this extension that matches all of the other criteria.
component (IOTile): The component that this extension comes from if it is
loaded from an installed component. This is used to properly import
the extension as a submodule of the component's support package.
Returns:
list of (name, type): A list of the objects found at the extension path.
If unique is True, then the list only contains a single entry and that
entry will be directly returned. | [
"Load",
"a",
"single",
"python",
"module",
"extension",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L250-L296 |
23,753 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry._filter_nonextensions | def _filter_nonextensions(cls, obj):
"""Remove all classes marked as not extensions.
This allows us to have a deeper hierarchy of classes than just
one base class that is filtered by _filter_subclasses. Any
class can define a class propery named:
__NO_EXTENSION__ = True
That class will never be returned as an extension. This is useful
for masking out base classes for extensions that are declared in
CoreTools and would be present in module imports but should not
create a second entry point.
"""
# Not all objects have __dict__ attributes. For example, tuples don't.
# and tuples are used in iotile.build for some entry points.
if hasattr(obj, '__dict__') and obj.__dict__.get('__NO_EXTENSION__', False) is True:
return False
return True | python | def _filter_nonextensions(cls, obj):
# Not all objects have __dict__ attributes. For example, tuples don't.
# and tuples are used in iotile.build for some entry points.
if hasattr(obj, '__dict__') and obj.__dict__.get('__NO_EXTENSION__', False) is True:
return False
return True | [
"def",
"_filter_nonextensions",
"(",
"cls",
",",
"obj",
")",
":",
"# Not all objects have __dict__ attributes. For example, tuples don't.",
"# and tuples are used in iotile.build for some entry points.",
"if",
"hasattr",
"(",
"obj",
",",
"'__dict__'",
")",
"and",
"obj",
".",
... | Remove all classes marked as not extensions.
This allows us to have a deeper hierarchy of classes than just
one base class that is filtered by _filter_subclasses. Any
class can define a class propery named:
__NO_EXTENSION__ = True
That class will never be returned as an extension. This is useful
for masking out base classes for extensions that are declared in
CoreTools and would be present in module imports but should not
create a second entry point. | [
"Remove",
"all",
"classes",
"marked",
"as",
"not",
"extensions",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L331-L351 |
23,754 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.SetBackingStore | def SetBackingStore(cls, backing):
"""Set the global backing type used by the ComponentRegistry from this point forward
This function must be called before any operations that use the registry are initiated
otherwise they will work from different registries that will likely contain different data
"""
if backing not in ['json', 'sqlite', 'memory']:
raise ArgumentError("Unknown backing store type that is not json or sqlite", backing=backing)
if backing == 'json':
cls.BackingType = JSONKVStore
cls.BackingFileName = 'component_registry.json'
elif backing == 'memory':
cls.BackingType = InMemoryKVStore
cls.BackingFileName = None
else:
cls.BackingType = SQLiteKVStore
cls.BackingFileName = 'component_registry.db' | python | def SetBackingStore(cls, backing):
if backing not in ['json', 'sqlite', 'memory']:
raise ArgumentError("Unknown backing store type that is not json or sqlite", backing=backing)
if backing == 'json':
cls.BackingType = JSONKVStore
cls.BackingFileName = 'component_registry.json'
elif backing == 'memory':
cls.BackingType = InMemoryKVStore
cls.BackingFileName = None
else:
cls.BackingType = SQLiteKVStore
cls.BackingFileName = 'component_registry.db' | [
"def",
"SetBackingStore",
"(",
"cls",
",",
"backing",
")",
":",
"if",
"backing",
"not",
"in",
"[",
"'json'",
",",
"'sqlite'",
",",
"'memory'",
"]",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown backing store type that is not json or sqlite\"",
",",
"backing",
"="... | Set the global backing type used by the ComponentRegistry from this point forward
This function must be called before any operations that use the registry are initiated
otherwise they will work from different registries that will likely contain different data | [
"Set",
"the",
"global",
"backing",
"type",
"used",
"by",
"the",
"ComponentRegistry",
"from",
"this",
"point",
"forward"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L390-L408 |
23,755 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.add_component | def add_component(self, component, temporary=False):
"""Register a component with ComponentRegistry.
Component must be a buildable object with a module_settings.json file
that describes its name and the domain that it is part of. By
default, this component is saved in the permanent registry associated
with this environment and will remain registered for future CoreTools
invocations.
If you only want this component to be temporarily registered during
this program's session, you can pass temporary=True and the component
will be stored in RAM only, not persisted to the underlying key-value
store.
Args:
component (str): The path to a component that should be registered.
temporary (bool): Optional flag to only temporarily register the
component for the duration of this program invocation.
"""
tile = IOTile(component)
value = os.path.normpath(os.path.abspath(component))
if temporary is True:
self._component_overlays[tile.name] = value
else:
self.kvstore.set(tile.name, value) | python | def add_component(self, component, temporary=False):
tile = IOTile(component)
value = os.path.normpath(os.path.abspath(component))
if temporary is True:
self._component_overlays[tile.name] = value
else:
self.kvstore.set(tile.name, value) | [
"def",
"add_component",
"(",
"self",
",",
"component",
",",
"temporary",
"=",
"False",
")",
":",
"tile",
"=",
"IOTile",
"(",
"component",
")",
"value",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"component",
... | Register a component with ComponentRegistry.
Component must be a buildable object with a module_settings.json file
that describes its name and the domain that it is part of. By
default, this component is saved in the permanent registry associated
with this environment and will remain registered for future CoreTools
invocations.
If you only want this component to be temporarily registered during
this program's session, you can pass temporary=True and the component
will be stored in RAM only, not persisted to the underlying key-value
store.
Args:
component (str): The path to a component that should be registered.
temporary (bool): Optional flag to only temporarily register the
component for the duration of this program invocation. | [
"Register",
"a",
"component",
"with",
"ComponentRegistry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L410-L436 |
23,756 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.list_plugins | def list_plugins(self):
"""
List all of the plugins that have been registerd for the iotile program on this computer
"""
vals = self.plugins.items()
return {x: y for x, y in vals} | python | def list_plugins(self):
vals = self.plugins.items()
return {x: y for x, y in vals} | [
"def",
"list_plugins",
"(",
"self",
")",
":",
"vals",
"=",
"self",
".",
"plugins",
".",
"items",
"(",
")",
"return",
"{",
"x",
":",
"y",
"for",
"x",
",",
"y",
"in",
"vals",
"}"
] | List all of the plugins that have been registerd for the iotile program on this computer | [
"List",
"all",
"of",
"the",
"plugins",
"that",
"have",
"been",
"registerd",
"for",
"the",
"iotile",
"program",
"on",
"this",
"computer"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L449-L456 |
23,757 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.clear_components | def clear_components(self):
"""Clear all of the registered components
"""
ComponentRegistry._component_overlays = {}
for key in self.list_components():
self.remove_component(key) | python | def clear_components(self):
ComponentRegistry._component_overlays = {}
for key in self.list_components():
self.remove_component(key) | [
"def",
"clear_components",
"(",
"self",
")",
":",
"ComponentRegistry",
".",
"_component_overlays",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"list_components",
"(",
")",
":",
"self",
".",
"remove_component",
"(",
"key",
")"
] | Clear all of the registered components | [
"Clear",
"all",
"of",
"the",
"registered",
"components"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L473-L480 |
23,758 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.list_components | def list_components(self):
"""List all of the registered component names.
This list will include all of the permanently stored components as
well as any temporary components that were added with a temporary=True
flag in this session.
Returns:
list of str: The list of component names.
Any of these names can be passed to get_component as is to get the
corresponding IOTile object.
"""
overlays = list(self._component_overlays)
items = self.kvstore.get_all()
return overlays + [x[0] for x in items if not x[0].startswith('config:')] | python | def list_components(self):
overlays = list(self._component_overlays)
items = self.kvstore.get_all()
return overlays + [x[0] for x in items if not x[0].startswith('config:')] | [
"def",
"list_components",
"(",
"self",
")",
":",
"overlays",
"=",
"list",
"(",
"self",
".",
"_component_overlays",
")",
"items",
"=",
"self",
".",
"kvstore",
".",
"get_all",
"(",
")",
"return",
"overlays",
"+",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"i... | List all of the registered component names.
This list will include all of the permanently stored components as
well as any temporary components that were added with a temporary=True
flag in this session.
Returns:
list of str: The list of component names.
Any of these names can be passed to get_component as is to get the
corresponding IOTile object. | [
"List",
"all",
"of",
"the",
"registered",
"component",
"names",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L488-L505 |
23,759 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.iter_components | def iter_components(self):
"""Iterate over all defined components yielding IOTile objects."""
names = self.list_components()
for name in names:
yield self.get_component(name) | python | def iter_components(self):
names = self.list_components()
for name in names:
yield self.get_component(name) | [
"def",
"iter_components",
"(",
"self",
")",
":",
"names",
"=",
"self",
".",
"list_components",
"(",
")",
"for",
"name",
"in",
"names",
":",
"yield",
"self",
".",
"get_component",
"(",
"name",
")"
] | Iterate over all defined components yielding IOTile objects. | [
"Iterate",
"over",
"all",
"defined",
"components",
"yielding",
"IOTile",
"objects",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L507-L513 |
23,760 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.list_config | def list_config(self):
"""List all of the configuration variables
"""
items = self.kvstore.get_all()
return ["{0}={1}".format(x[0][len('config:'):], x[1])
for x in items if x[0].startswith('config:')] | python | def list_config(self):
items = self.kvstore.get_all()
return ["{0}={1}".format(x[0][len('config:'):], x[1])
for x in items if x[0].startswith('config:')] | [
"def",
"list_config",
"(",
"self",
")",
":",
"items",
"=",
"self",
".",
"kvstore",
".",
"get_all",
"(",
")",
"return",
"[",
"\"{0}={1}\"",
".",
"format",
"(",
"x",
"[",
"0",
"]",
"[",
"len",
"(",
"'config:'",
")",
":",
"]",
",",
"x",
"[",
"1",
... | List all of the configuration variables | [
"List",
"all",
"of",
"the",
"configuration",
"variables"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L515-L520 |
23,761 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.set_config | def set_config(self, key, value):
"""Set a persistent config key to a value, stored in the registry
Args:
key (string): The key name
value (string): The key value
"""
keyname = "config:" + key
self.kvstore.set(keyname, value) | python | def set_config(self, key, value):
keyname = "config:" + key
self.kvstore.set(keyname, value) | [
"def",
"set_config",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"keyname",
"=",
"\"config:\"",
"+",
"key",
"self",
".",
"kvstore",
".",
"set",
"(",
"keyname",
",",
"value",
")"
] | Set a persistent config key to a value, stored in the registry
Args:
key (string): The key name
value (string): The key value | [
"Set",
"a",
"persistent",
"config",
"key",
"to",
"a",
"value",
"stored",
"in",
"the",
"registry"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L522-L532 |
23,762 | iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.get_config | def get_config(self, key, default=MISSING):
"""Get the value of a persistent config key from the registry
If no default is specified and the key is not found ArgumentError is raised.
Args:
key (string): The key name to fetch
default (string): an optional value to be returned if key cannot be found
Returns:
string: the key's value
"""
keyname = "config:" + key
try:
return self.kvstore.get(keyname)
except KeyError:
if default is MISSING:
raise ArgumentError("No config value found for key", key=key)
return default | python | def get_config(self, key, default=MISSING):
keyname = "config:" + key
try:
return self.kvstore.get(keyname)
except KeyError:
if default is MISSING:
raise ArgumentError("No config value found for key", key=key)
return default | [
"def",
"get_config",
"(",
"self",
",",
"key",
",",
"default",
"=",
"MISSING",
")",
":",
"keyname",
"=",
"\"config:\"",
"+",
"key",
"try",
":",
"return",
"self",
".",
"kvstore",
".",
"get",
"(",
"keyname",
")",
"except",
"KeyError",
":",
"if",
"default"... | Get the value of a persistent config key from the registry
If no default is specified and the key is not found ArgumentError is raised.
Args:
key (string): The key name to fetch
default (string): an optional value to be returned if key cannot be found
Returns:
string: the key's value | [
"Get",
"the",
"value",
"of",
"a",
"persistent",
"config",
"key",
"from",
"the",
"registry"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L534-L555 |
23,763 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | execute_action_list | def execute_action_list(obj, target, kw):
"""Actually execute the action list."""
env = obj.get_build_env()
kw = obj.get_kw(kw)
status = 0
for act in obj.get_action_list():
args = ([], [], env)
status = act(*args, **kw)
if isinstance(status, SCons.Errors.BuildError):
status.executor = obj
raise status
elif status:
msg = "Error %s" % status
raise SCons.Errors.BuildError(
errstr=msg,
node=obj.batches[0].targets,
executor=obj,
action=act)
return status | python | def execute_action_list(obj, target, kw):
env = obj.get_build_env()
kw = obj.get_kw(kw)
status = 0
for act in obj.get_action_list():
args = ([], [], env)
status = act(*args, **kw)
if isinstance(status, SCons.Errors.BuildError):
status.executor = obj
raise status
elif status:
msg = "Error %s" % status
raise SCons.Errors.BuildError(
errstr=msg,
node=obj.batches[0].targets,
executor=obj,
action=act)
return status | [
"def",
"execute_action_list",
"(",
"obj",
",",
"target",
",",
"kw",
")",
":",
"env",
"=",
"obj",
".",
"get_build_env",
"(",
")",
"kw",
"=",
"obj",
".",
"get_kw",
"(",
"kw",
")",
"status",
"=",
"0",
"for",
"act",
"in",
"obj",
".",
"get_action_list",
... | Actually execute the action list. | [
"Actually",
"execute",
"the",
"action",
"list",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L119-L137 |
23,764 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_all_targets | def get_all_targets(self):
"""Returns all targets for all batches of this Executor."""
result = []
for batch in self.batches:
result.extend(batch.targets)
return result | python | def get_all_targets(self):
result = []
for batch in self.batches:
result.extend(batch.targets)
return result | [
"def",
"get_all_targets",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"batch",
"in",
"self",
".",
"batches",
":",
"result",
".",
"extend",
"(",
"batch",
".",
"targets",
")",
"return",
"result"
] | Returns all targets for all batches of this Executor. | [
"Returns",
"all",
"targets",
"for",
"all",
"batches",
"of",
"this",
"Executor",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L295-L300 |
23,765 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_all_sources | def get_all_sources(self):
"""Returns all sources for all batches of this Executor."""
result = []
for batch in self.batches:
result.extend(batch.sources)
return result | python | def get_all_sources(self):
result = []
for batch in self.batches:
result.extend(batch.sources)
return result | [
"def",
"get_all_sources",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"batch",
"in",
"self",
".",
"batches",
":",
"result",
".",
"extend",
"(",
"batch",
".",
"sources",
")",
"return",
"result"
] | Returns all sources for all batches of this Executor. | [
"Returns",
"all",
"sources",
"for",
"all",
"batches",
"of",
"this",
"Executor",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L302-L307 |
23,766 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_action_side_effects | def get_action_side_effects(self):
"""Returns all side effects for all batches of this
Executor used by the underlying Action.
"""
result = SCons.Util.UniqueList([])
for target in self.get_action_targets():
result.extend(target.side_effects)
return result | python | def get_action_side_effects(self):
result = SCons.Util.UniqueList([])
for target in self.get_action_targets():
result.extend(target.side_effects)
return result | [
"def",
"get_action_side_effects",
"(",
"self",
")",
":",
"result",
"=",
"SCons",
".",
"Util",
".",
"UniqueList",
"(",
"[",
"]",
")",
"for",
"target",
"in",
"self",
".",
"get_action_targets",
"(",
")",
":",
"result",
".",
"extend",
"(",
"target",
".",
"... | Returns all side effects for all batches of this
Executor used by the underlying Action. | [
"Returns",
"all",
"side",
"effects",
"for",
"all",
"batches",
"of",
"this",
"Executor",
"used",
"by",
"the",
"underlying",
"Action",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L335-L343 |
23,767 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_build_env | def get_build_env(self):
"""Fetch or create the appropriate build Environment
for this Executor.
"""
try:
return self._memo['get_build_env']
except KeyError:
pass
# Create the build environment instance with appropriate
# overrides. These get evaluated against the current
# environment's construction variables so that users can
# add to existing values by referencing the variable in
# the expansion.
overrides = {}
for odict in self.overridelist:
overrides.update(odict)
import SCons.Defaults
env = self.env or SCons.Defaults.DefaultEnvironment()
build_env = env.Override(overrides)
self._memo['get_build_env'] = build_env
return build_env | python | def get_build_env(self):
try:
return self._memo['get_build_env']
except KeyError:
pass
# Create the build environment instance with appropriate
# overrides. These get evaluated against the current
# environment's construction variables so that users can
# add to existing values by referencing the variable in
# the expansion.
overrides = {}
for odict in self.overridelist:
overrides.update(odict)
import SCons.Defaults
env = self.env or SCons.Defaults.DefaultEnvironment()
build_env = env.Override(overrides)
self._memo['get_build_env'] = build_env
return build_env | [
"def",
"get_build_env",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_memo",
"[",
"'get_build_env'",
"]",
"except",
"KeyError",
":",
"pass",
"# Create the build environment instance with appropriate",
"# overrides. These get evaluated against the current",
"#... | Fetch or create the appropriate build Environment
for this Executor. | [
"Fetch",
"or",
"create",
"the",
"appropriate",
"build",
"Environment",
"for",
"this",
"Executor",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L346-L370 |
23,768 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_build_scanner_path | def get_build_scanner_path(self, scanner):
"""Fetch the scanner path for this executor's targets and sources.
"""
env = self.get_build_env()
try:
cwd = self.batches[0].targets[0].cwd
except (IndexError, AttributeError):
cwd = None
return scanner.path(env, cwd,
self.get_all_targets(),
self.get_all_sources()) | python | def get_build_scanner_path(self, scanner):
env = self.get_build_env()
try:
cwd = self.batches[0].targets[0].cwd
except (IndexError, AttributeError):
cwd = None
return scanner.path(env, cwd,
self.get_all_targets(),
self.get_all_sources()) | [
"def",
"get_build_scanner_path",
"(",
"self",
",",
"scanner",
")",
":",
"env",
"=",
"self",
".",
"get_build_env",
"(",
")",
"try",
":",
"cwd",
"=",
"self",
".",
"batches",
"[",
"0",
"]",
".",
"targets",
"[",
"0",
"]",
".",
"cwd",
"except",
"(",
"In... | Fetch the scanner path for this executor's targets and sources. | [
"Fetch",
"the",
"scanner",
"path",
"for",
"this",
"executor",
"s",
"targets",
"and",
"sources",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L372-L382 |
23,769 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.add_sources | def add_sources(self, sources):
"""Add source files to this Executor's list. This is necessary
for "multi" Builders that can be called repeatedly to build up
a source file list for a given target."""
# TODO(batch): extend to multiple batches
assert (len(self.batches) == 1)
# TODO(batch): remove duplicates?
sources = [x for x in sources if x not in self.batches[0].sources]
self.batches[0].sources.extend(sources) | python | def add_sources(self, sources):
# TODO(batch): extend to multiple batches
assert (len(self.batches) == 1)
# TODO(batch): remove duplicates?
sources = [x for x in sources if x not in self.batches[0].sources]
self.batches[0].sources.extend(sources) | [
"def",
"add_sources",
"(",
"self",
",",
"sources",
")",
":",
"# TODO(batch): extend to multiple batches",
"assert",
"(",
"len",
"(",
"self",
".",
"batches",
")",
"==",
"1",
")",
"# TODO(batch): remove duplicates?",
"sources",
"=",
"[",
"x",
"for",
"x",
"in",
... | Add source files to this Executor's list. This is necessary
for "multi" Builders that can be called repeatedly to build up
a source file list for a given target. | [
"Add",
"source",
"files",
"to",
"this",
"Executor",
"s",
"list",
".",
"This",
"is",
"necessary",
"for",
"multi",
"Builders",
"that",
"can",
"be",
"called",
"repeatedly",
"to",
"build",
"up",
"a",
"source",
"file",
"list",
"for",
"a",
"given",
"target",
"... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L400-L408 |
23,770 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.add_batch | def add_batch(self, targets, sources):
"""Add pair of associated target and source to this Executor's list.
This is necessary for "batch" Builders that can be called repeatedly
to build up a list of matching target and source files that will be
used in order to update multiple target files at once from multiple
corresponding source files, for tools like MSVC that support it."""
self.batches.append(Batch(targets, sources)) | python | def add_batch(self, targets, sources):
self.batches.append(Batch(targets, sources)) | [
"def",
"add_batch",
"(",
"self",
",",
"targets",
",",
"sources",
")",
":",
"self",
".",
"batches",
".",
"append",
"(",
"Batch",
"(",
"targets",
",",
"sources",
")",
")"
] | Add pair of associated target and source to this Executor's list.
This is necessary for "batch" Builders that can be called repeatedly
to build up a list of matching target and source files that will be
used in order to update multiple target files at once from multiple
corresponding source files, for tools like MSVC that support it. | [
"Add",
"pair",
"of",
"associated",
"target",
"and",
"source",
"to",
"this",
"Executor",
"s",
"list",
".",
"This",
"is",
"necessary",
"for",
"batch",
"Builders",
"that",
"can",
"be",
"called",
"repeatedly",
"to",
"build",
"up",
"a",
"list",
"of",
"matching"... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L413-L419 |
23,771 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_contents | def get_contents(self):
"""Fetch the signature contents. This is the main reason this
class exists, so we can compute this once and cache it regardless
of how many target or source Nodes there are.
"""
try:
return self._memo['get_contents']
except KeyError:
pass
env = self.get_build_env()
action_list = self.get_action_list()
all_targets = self.get_all_targets()
all_sources = self.get_all_sources()
result = bytearray("",'utf-8').join([action.get_contents(all_targets,
all_sources,
env)
for action in action_list])
self._memo['get_contents'] = result
return result | python | def get_contents(self):
try:
return self._memo['get_contents']
except KeyError:
pass
env = self.get_build_env()
action_list = self.get_action_list()
all_targets = self.get_all_targets()
all_sources = self.get_all_sources()
result = bytearray("",'utf-8').join([action.get_contents(all_targets,
all_sources,
env)
for action in action_list])
self._memo['get_contents'] = result
return result | [
"def",
"get_contents",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_memo",
"[",
"'get_contents'",
"]",
"except",
"KeyError",
":",
"pass",
"env",
"=",
"self",
".",
"get_build_env",
"(",
")",
"action_list",
"=",
"self",
".",
"get_action_list",... | Fetch the signature contents. This is the main reason this
class exists, so we can compute this once and cache it regardless
of how many target or source Nodes there are. | [
"Fetch",
"the",
"signature",
"contents",
".",
"This",
"is",
"the",
"main",
"reason",
"this",
"class",
"exists",
"so",
"we",
"can",
"compute",
"this",
"once",
"and",
"cache",
"it",
"regardless",
"of",
"how",
"many",
"target",
"or",
"source",
"Nodes",
"there... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L448-L469 |
23,772 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_implicit_deps | def get_implicit_deps(self):
"""Return the executor's implicit dependencies, i.e. the nodes of
the commands to be executed."""
result = []
build_env = self.get_build_env()
for act in self.get_action_list():
deps = act.get_implicit_deps(self.get_all_targets(),
self.get_all_sources(),
build_env)
result.extend(deps)
return result | python | def get_implicit_deps(self):
result = []
build_env = self.get_build_env()
for act in self.get_action_list():
deps = act.get_implicit_deps(self.get_all_targets(),
self.get_all_sources(),
build_env)
result.extend(deps)
return result | [
"def",
"get_implicit_deps",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"build_env",
"=",
"self",
".",
"get_build_env",
"(",
")",
"for",
"act",
"in",
"self",
".",
"get_action_list",
"(",
")",
":",
"deps",
"=",
"act",
".",
"get_implicit_deps",
"(",
... | Return the executor's implicit dependencies, i.e. the nodes of
the commands to be executed. | [
"Return",
"the",
"executor",
"s",
"implicit",
"dependencies",
"i",
".",
"e",
".",
"the",
"nodes",
"of",
"the",
"commands",
"to",
"be",
"executed",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L546-L556 |
23,773 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Null._morph | def _morph(self):
"""Morph this Null executor to a real Executor object."""
batches = self.batches
self.__class__ = Executor
self.__init__([])
self.batches = batches | python | def _morph(self):
batches = self.batches
self.__class__ = Executor
self.__init__([])
self.batches = batches | [
"def",
"_morph",
"(",
"self",
")",
":",
"batches",
"=",
"self",
".",
"batches",
"self",
".",
"__class__",
"=",
"Executor",
"self",
".",
"__init__",
"(",
"[",
"]",
")",
"self",
".",
"batches",
"=",
"batches"
] | Morph this Null executor to a real Executor object. | [
"Morph",
"this",
"Null",
"executor",
"to",
"a",
"real",
"Executor",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L645-L650 |
23,774 | iotile/coretools | iotilecore/iotile/core/hw/update/record.py | UpdateRecord.LoadPlugins | def LoadPlugins(cls):
"""Load all registered iotile.update_record plugins."""
if cls.PLUGINS_LOADED:
return
reg = ComponentRegistry()
for _, record in reg.load_extensions('iotile.update_record'):
cls.RegisterRecordType(record)
cls.PLUGINS_LOADED = True | python | def LoadPlugins(cls):
if cls.PLUGINS_LOADED:
return
reg = ComponentRegistry()
for _, record in reg.load_extensions('iotile.update_record'):
cls.RegisterRecordType(record)
cls.PLUGINS_LOADED = True | [
"def",
"LoadPlugins",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"PLUGINS_LOADED",
":",
"return",
"reg",
"=",
"ComponentRegistry",
"(",
")",
"for",
"_",
",",
"record",
"in",
"reg",
".",
"load_extensions",
"(",
"'iotile.update_record'",
")",
":",
"cls",
".",
... | Load all registered iotile.update_record plugins. | [
"Load",
"all",
"registered",
"iotile",
".",
"update_record",
"plugins",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/update/record.py#L82-L92 |
23,775 | iotile/coretools | iotilecore/iotile/core/hw/update/record.py | UpdateRecord.RegisterRecordType | def RegisterRecordType(cls, record_class):
"""Register a known record type in KNOWN_CLASSES.
Args:
record_class (UpdateRecord): An update record subclass.
"""
record_type = record_class.MatchType()
if record_type not in UpdateRecord.KNOWN_CLASSES:
UpdateRecord.KNOWN_CLASSES[record_type] = []
UpdateRecord.KNOWN_CLASSES[record_type].append(record_class) | python | def RegisterRecordType(cls, record_class):
record_type = record_class.MatchType()
if record_type not in UpdateRecord.KNOWN_CLASSES:
UpdateRecord.KNOWN_CLASSES[record_type] = []
UpdateRecord.KNOWN_CLASSES[record_type].append(record_class) | [
"def",
"RegisterRecordType",
"(",
"cls",
",",
"record_class",
")",
":",
"record_type",
"=",
"record_class",
".",
"MatchType",
"(",
")",
"if",
"record_type",
"not",
"in",
"UpdateRecord",
".",
"KNOWN_CLASSES",
":",
"UpdateRecord",
".",
"KNOWN_CLASSES",
"[",
"recor... | Register a known record type in KNOWN_CLASSES.
Args:
record_class (UpdateRecord): An update record subclass. | [
"Register",
"a",
"known",
"record",
"type",
"in",
"KNOWN_CLASSES",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/update/record.py#L131-L142 |
23,776 | iotile/coretools | iotilesensorgraph/iotile/sg/parser/scopes/root_scope.py | RootScope._setup | def _setup(self):
"""Prepare for code generation by setting up root clock nodes.
These nodes are subsequently used as the basis for all clock operations.
"""
# Create a root system ticks and user configurable ticks
systick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
fasttick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
user1tick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
user2tick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(system_tick, systick))
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(fast_tick, fasttick))
self.sensor_graph.add_config(SlotIdentifier.FromString('controller'), config_fast_tick_secs, 'uint32_t', 1)
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(tick_1, user1tick))
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(tick_2, user2tick))
self.system_tick = systick
self.fast_tick = fasttick
self.user1_tick = user1tick
self.user2_tick = user2tick | python | def _setup(self):
# Create a root system ticks and user configurable ticks
systick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
fasttick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
user1tick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
user2tick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(system_tick, systick))
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(fast_tick, fasttick))
self.sensor_graph.add_config(SlotIdentifier.FromString('controller'), config_fast_tick_secs, 'uint32_t', 1)
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(tick_1, user1tick))
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(tick_2, user2tick))
self.system_tick = systick
self.fast_tick = fasttick
self.user1_tick = user1tick
self.user2_tick = user2tick | [
"def",
"_setup",
"(",
"self",
")",
":",
"# Create a root system ticks and user configurable ticks",
"systick",
"=",
"self",
".",
"allocator",
".",
"allocate_stream",
"(",
"DataStream",
".",
"CounterType",
",",
"attach",
"=",
"True",
")",
"fasttick",
"=",
"self",
"... | Prepare for code generation by setting up root clock nodes.
These nodes are subsequently used as the basis for all clock operations. | [
"Prepare",
"for",
"code",
"generation",
"by",
"setting",
"up",
"root",
"clock",
"nodes",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/scopes/root_scope.py#L30-L51 |
23,777 | iotile/coretools | iotilecore/iotile/core/hw/proxy/external_proxy.py | find_proxy_plugin | def find_proxy_plugin(component, plugin_name):
""" Attempt to find a proxy plugin provided by a specific component
Args:
component (string): The name of the component that provides the plugin
plugin_name (string): The name of the plugin to load
Returns:
TileBuxProxyPlugin: The plugin, if found, otherwise raises DataError
"""
reg = ComponentRegistry()
plugins = reg.load_extensions('iotile.proxy_plugin', comp_filter=component, class_filter=TileBusProxyPlugin,
product_name='proxy_plugin')
for _name, plugin in plugins:
if plugin.__name__ == plugin_name:
return plugin
raise DataError("Could not find proxy plugin module in registered components or installed distributions",
component=component, name=plugin_name) | python | def find_proxy_plugin(component, plugin_name):
reg = ComponentRegistry()
plugins = reg.load_extensions('iotile.proxy_plugin', comp_filter=component, class_filter=TileBusProxyPlugin,
product_name='proxy_plugin')
for _name, plugin in plugins:
if plugin.__name__ == plugin_name:
return plugin
raise DataError("Could not find proxy plugin module in registered components or installed distributions",
component=component, name=plugin_name) | [
"def",
"find_proxy_plugin",
"(",
"component",
",",
"plugin_name",
")",
":",
"reg",
"=",
"ComponentRegistry",
"(",
")",
"plugins",
"=",
"reg",
".",
"load_extensions",
"(",
"'iotile.proxy_plugin'",
",",
"comp_filter",
"=",
"component",
",",
"class_filter",
"=",
"T... | Attempt to find a proxy plugin provided by a specific component
Args:
component (string): The name of the component that provides the plugin
plugin_name (string): The name of the plugin to load
Returns:
TileBuxProxyPlugin: The plugin, if found, otherwise raises DataError | [
"Attempt",
"to",
"find",
"a",
"proxy",
"plugin",
"provided",
"by",
"a",
"specific",
"component"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/proxy/external_proxy.py#L12-L33 |
23,778 | iotile/coretools | iotilesensorgraph/iotile/sg/parser/statements/on_block.py | OnBlock._convert_trigger | def _convert_trigger(self, trigger_def, parent):
"""Convert a TriggerDefinition into a stream, trigger pair."""
if trigger_def.explicit_stream is None:
stream = parent.resolve_identifier(trigger_def.named_event, DataStream)
trigger = TrueTrigger()
else:
stream = trigger_def.explicit_stream
trigger = trigger_def.explicit_trigger
return (stream, trigger) | python | def _convert_trigger(self, trigger_def, parent):
if trigger_def.explicit_stream is None:
stream = parent.resolve_identifier(trigger_def.named_event, DataStream)
trigger = TrueTrigger()
else:
stream = trigger_def.explicit_stream
trigger = trigger_def.explicit_trigger
return (stream, trigger) | [
"def",
"_convert_trigger",
"(",
"self",
",",
"trigger_def",
",",
"parent",
")",
":",
"if",
"trigger_def",
".",
"explicit_stream",
"is",
"None",
":",
"stream",
"=",
"parent",
".",
"resolve_identifier",
"(",
"trigger_def",
".",
"named_event",
",",
"DataStream",
... | Convert a TriggerDefinition into a stream, trigger pair. | [
"Convert",
"a",
"TriggerDefinition",
"into",
"a",
"stream",
"trigger",
"pair",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/statements/on_block.py#L46-L56 |
23,779 | iotile/coretools | iotilesensorgraph/iotile/sg/parser/statements/on_block.py | OnBlock._parse_trigger | def _parse_trigger(self, trigger_clause):
"""Parse a named event or explicit stream trigger into a TriggerDefinition."""
cond = trigger_clause[0]
named_event = None
explicit_stream = None
explicit_trigger = None
# Identifier parse tree is Group(Identifier)
if cond.getName() == 'identifier':
named_event = cond[0]
elif cond.getName() == 'stream_trigger':
trigger_type = cond[0]
stream = cond[1]
oper = cond[2]
ref = cond[3]
trigger = InputTrigger(trigger_type, oper, ref)
explicit_stream = stream
explicit_trigger = trigger
elif cond.getName() == 'stream_always':
stream = cond[0]
trigger = TrueTrigger()
explicit_stream = stream
explicit_trigger = trigger
else:
raise ArgumentError("OnBlock created from an invalid ParseResults object", parse_results=trigger_clause)
return TriggerDefinition(named_event, explicit_stream, explicit_trigger) | python | def _parse_trigger(self, trigger_clause):
cond = trigger_clause[0]
named_event = None
explicit_stream = None
explicit_trigger = None
# Identifier parse tree is Group(Identifier)
if cond.getName() == 'identifier':
named_event = cond[0]
elif cond.getName() == 'stream_trigger':
trigger_type = cond[0]
stream = cond[1]
oper = cond[2]
ref = cond[3]
trigger = InputTrigger(trigger_type, oper, ref)
explicit_stream = stream
explicit_trigger = trigger
elif cond.getName() == 'stream_always':
stream = cond[0]
trigger = TrueTrigger()
explicit_stream = stream
explicit_trigger = trigger
else:
raise ArgumentError("OnBlock created from an invalid ParseResults object", parse_results=trigger_clause)
return TriggerDefinition(named_event, explicit_stream, explicit_trigger) | [
"def",
"_parse_trigger",
"(",
"self",
",",
"trigger_clause",
")",
":",
"cond",
"=",
"trigger_clause",
"[",
"0",
"]",
"named_event",
"=",
"None",
"explicit_stream",
"=",
"None",
"explicit_trigger",
"=",
"None",
"# Identifier parse tree is Group(Identifier)",
"if",
"c... | Parse a named event or explicit stream trigger into a TriggerDefinition. | [
"Parse",
"a",
"named",
"event",
"or",
"explicit",
"stream",
"trigger",
"into",
"a",
"TriggerDefinition",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/statements/on_block.py#L58-L87 |
23,780 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py | platform_default | def platform_default():
"""Return the platform string for our execution environment.
The returned value should map to one of the SCons/Platform/*.py
files. Since we're architecture independent, though, we don't
care about the machine architecture.
"""
osname = os.name
if osname == 'java':
osname = os._osType
if osname == 'posix':
if sys.platform == 'cygwin':
return 'cygwin'
elif sys.platform.find('irix') != -1:
return 'irix'
elif sys.platform.find('sunos') != -1:
return 'sunos'
elif sys.platform.find('hp-ux') != -1:
return 'hpux'
elif sys.platform.find('aix') != -1:
return 'aix'
elif sys.platform.find('darwin') != -1:
return 'darwin'
else:
return 'posix'
elif os.name == 'os2':
return 'os2'
else:
return sys.platform | python | def platform_default():
osname = os.name
if osname == 'java':
osname = os._osType
if osname == 'posix':
if sys.platform == 'cygwin':
return 'cygwin'
elif sys.platform.find('irix') != -1:
return 'irix'
elif sys.platform.find('sunos') != -1:
return 'sunos'
elif sys.platform.find('hp-ux') != -1:
return 'hpux'
elif sys.platform.find('aix') != -1:
return 'aix'
elif sys.platform.find('darwin') != -1:
return 'darwin'
else:
return 'posix'
elif os.name == 'os2':
return 'os2'
else:
return sys.platform | [
"def",
"platform_default",
"(",
")",
":",
"osname",
"=",
"os",
".",
"name",
"if",
"osname",
"==",
"'java'",
":",
"osname",
"=",
"os",
".",
"_osType",
"if",
"osname",
"==",
"'posix'",
":",
"if",
"sys",
".",
"platform",
"==",
"'cygwin'",
":",
"return",
... | Return the platform string for our execution environment.
The returned value should map to one of the SCons/Platform/*.py
files. Since we're architecture independent, though, we don't
care about the machine architecture. | [
"Return",
"the",
"platform",
"string",
"for",
"our",
"execution",
"environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py#L59-L87 |
23,781 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py | platform_module | def platform_module(name = platform_default()):
"""Return the imported module for the platform.
This looks for a module name that matches the specified argument.
If the name is unspecified, we fetch the appropriate default for
our execution environment.
"""
full_name = 'SCons.Platform.' + name
if full_name not in sys.modules:
if os.name == 'java':
eval(full_name)
else:
try:
file, path, desc = imp.find_module(name,
sys.modules['SCons.Platform'].__path__)
try:
mod = imp.load_module(full_name, file, path, desc)
finally:
if file:
file.close()
except ImportError:
try:
import zipimport
importer = zipimport.zipimporter( sys.modules['SCons.Platform'].__path__[0] )
mod = importer.load_module(full_name)
except ImportError:
raise SCons.Errors.UserError("No platform named '%s'" % name)
setattr(SCons.Platform, name, mod)
return sys.modules[full_name] | python | def platform_module(name = platform_default()):
full_name = 'SCons.Platform.' + name
if full_name not in sys.modules:
if os.name == 'java':
eval(full_name)
else:
try:
file, path, desc = imp.find_module(name,
sys.modules['SCons.Platform'].__path__)
try:
mod = imp.load_module(full_name, file, path, desc)
finally:
if file:
file.close()
except ImportError:
try:
import zipimport
importer = zipimport.zipimporter( sys.modules['SCons.Platform'].__path__[0] )
mod = importer.load_module(full_name)
except ImportError:
raise SCons.Errors.UserError("No platform named '%s'" % name)
setattr(SCons.Platform, name, mod)
return sys.modules[full_name] | [
"def",
"platform_module",
"(",
"name",
"=",
"platform_default",
"(",
")",
")",
":",
"full_name",
"=",
"'SCons.Platform.'",
"+",
"name",
"if",
"full_name",
"not",
"in",
"sys",
".",
"modules",
":",
"if",
"os",
".",
"name",
"==",
"'java'",
":",
"eval",
"(",... | Return the imported module for the platform.
This looks for a module name that matches the specified argument.
If the name is unspecified, we fetch the appropriate default for
our execution environment. | [
"Return",
"the",
"imported",
"module",
"for",
"the",
"platform",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py#L89-L117 |
23,782 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py | Platform | def Platform(name = platform_default()):
"""Select a canned Platform specification.
"""
module = platform_module(name)
spec = PlatformSpec(name, module.generate)
return spec | python | def Platform(name = platform_default()):
module = platform_module(name)
spec = PlatformSpec(name, module.generate)
return spec | [
"def",
"Platform",
"(",
"name",
"=",
"platform_default",
"(",
")",
")",
":",
"module",
"=",
"platform_module",
"(",
"name",
")",
"spec",
"=",
"PlatformSpec",
"(",
"name",
",",
"module",
".",
"generate",
")",
"return",
"spec"
] | Select a canned Platform specification. | [
"Select",
"a",
"canned",
"Platform",
"specification",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py#L255-L260 |
23,783 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py | jarSources | def jarSources(target, source, env, for_signature):
"""Only include sources that are not a manifest file."""
try:
env['JARCHDIR']
except KeyError:
jarchdir_set = False
else:
jarchdir_set = True
jarchdir = env.subst('$JARCHDIR', target=target, source=source)
if jarchdir:
jarchdir = env.fs.Dir(jarchdir)
result = []
for src in source:
contents = src.get_text_contents()
if contents[:16] != "Manifest-Version":
if jarchdir_set:
_chdir = jarchdir
else:
try:
_chdir = src.attributes.java_classdir
except AttributeError:
_chdir = None
if _chdir:
# If we are changing the dir with -C, then sources should
# be relative to that directory.
src = SCons.Subst.Literal(src.get_path(_chdir))
result.append('-C')
result.append(_chdir)
result.append(src)
return result | python | def jarSources(target, source, env, for_signature):
try:
env['JARCHDIR']
except KeyError:
jarchdir_set = False
else:
jarchdir_set = True
jarchdir = env.subst('$JARCHDIR', target=target, source=source)
if jarchdir:
jarchdir = env.fs.Dir(jarchdir)
result = []
for src in source:
contents = src.get_text_contents()
if contents[:16] != "Manifest-Version":
if jarchdir_set:
_chdir = jarchdir
else:
try:
_chdir = src.attributes.java_classdir
except AttributeError:
_chdir = None
if _chdir:
# If we are changing the dir with -C, then sources should
# be relative to that directory.
src = SCons.Subst.Literal(src.get_path(_chdir))
result.append('-C')
result.append(_chdir)
result.append(src)
return result | [
"def",
"jarSources",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
")",
":",
"try",
":",
"env",
"[",
"'JARCHDIR'",
"]",
"except",
"KeyError",
":",
"jarchdir_set",
"=",
"False",
"else",
":",
"jarchdir_set",
"=",
"True",
"jarchdir",
"=",
... | Only include sources that are not a manifest file. | [
"Only",
"include",
"sources",
"that",
"are",
"not",
"a",
"manifest",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py#L41-L70 |
23,784 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py | jarManifest | def jarManifest(target, source, env, for_signature):
"""Look in sources for a manifest file, if any."""
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
return src
return '' | python | def jarManifest(target, source, env, for_signature):
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
return src
return '' | [
"def",
"jarManifest",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
")",
":",
"for",
"src",
"in",
"source",
":",
"contents",
"=",
"src",
".",
"get_text_contents",
"(",
")",
"if",
"contents",
"[",
":",
"16",
"]",
"==",
"\"Manifest-Versio... | Look in sources for a manifest file, if any. | [
"Look",
"in",
"sources",
"for",
"a",
"manifest",
"file",
"if",
"any",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py#L72-L78 |
23,785 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py | jarFlags | def jarFlags(target, source, env, for_signature):
"""If we have a manifest, make sure that the 'm'
flag is specified."""
jarflags = env.subst('$JARFLAGS', target=target, source=source)
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
if not 'm' in jarflags:
return jarflags + 'm'
break
return jarflags | python | def jarFlags(target, source, env, for_signature):
jarflags = env.subst('$JARFLAGS', target=target, source=source)
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
if not 'm' in jarflags:
return jarflags + 'm'
break
return jarflags | [
"def",
"jarFlags",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
")",
":",
"jarflags",
"=",
"env",
".",
"subst",
"(",
"'$JARFLAGS'",
",",
"target",
"=",
"target",
",",
"source",
"=",
"source",
")",
"for",
"src",
"in",
"source",
":",
... | If we have a manifest, make sure that the 'm'
flag is specified. | [
"If",
"we",
"have",
"a",
"manifest",
"make",
"sure",
"that",
"the",
"m",
"flag",
"is",
"specified",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py#L80-L90 |
23,786 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py | generate | def generate(env):
"""Add Builders and construction variables for jar to an Environment."""
SCons.Tool.CreateJarBuilder(env)
SCons.Tool.CreateJavaFileBuilder(env)
SCons.Tool.CreateJavaClassFileBuilder(env)
SCons.Tool.CreateJavaClassDirBuilder(env)
env.AddMethod(Jar)
env['JAR'] = 'jar'
env['JARFLAGS'] = SCons.Util.CLVar('cf')
env['_JARFLAGS'] = jarFlags
env['_JARMANIFEST'] = jarManifest
env['_JARSOURCES'] = jarSources
env['_JARCOM'] = '$JAR $_JARFLAGS $TARGET $_JARMANIFEST $_JARSOURCES'
env['JARCOM'] = "${TEMPFILE('$_JARCOM','$JARCOMSTR')}"
env['JARSUFFIX'] = '.jar' | python | def generate(env):
SCons.Tool.CreateJarBuilder(env)
SCons.Tool.CreateJavaFileBuilder(env)
SCons.Tool.CreateJavaClassFileBuilder(env)
SCons.Tool.CreateJavaClassDirBuilder(env)
env.AddMethod(Jar)
env['JAR'] = 'jar'
env['JARFLAGS'] = SCons.Util.CLVar('cf')
env['_JARFLAGS'] = jarFlags
env['_JARMANIFEST'] = jarManifest
env['_JARSOURCES'] = jarSources
env['_JARCOM'] = '$JAR $_JARFLAGS $TARGET $_JARMANIFEST $_JARSOURCES'
env['JARCOM'] = "${TEMPFILE('$_JARCOM','$JARCOMSTR')}"
env['JARSUFFIX'] = '.jar' | [
"def",
"generate",
"(",
"env",
")",
":",
"SCons",
".",
"Tool",
".",
"CreateJarBuilder",
"(",
"env",
")",
"SCons",
".",
"Tool",
".",
"CreateJavaFileBuilder",
"(",
"env",
")",
"SCons",
".",
"Tool",
".",
"CreateJavaClassFileBuilder",
"(",
"env",
")",
"SCons",... | Add Builders and construction variables for jar to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"jar",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py#L199-L216 |
23,787 | iotile/coretools | iotilesensorgraph/iotile/sg/sim/executor.py | RPCExecutor.mock | def mock(self, slot, rpc_id, value):
"""Store a mock return value for an RPC
Args:
slot (SlotIdentifier): The slot we are mocking
rpc_id (int): The rpc we are mocking
value (int): The value that should be returned
when the RPC is called.
"""
address = slot.address
if address not in self.mock_rpcs:
self.mock_rpcs[address] = {}
self.mock_rpcs[address][rpc_id] = value | python | def mock(self, slot, rpc_id, value):
address = slot.address
if address not in self.mock_rpcs:
self.mock_rpcs[address] = {}
self.mock_rpcs[address][rpc_id] = value | [
"def",
"mock",
"(",
"self",
",",
"slot",
",",
"rpc_id",
",",
"value",
")",
":",
"address",
"=",
"slot",
".",
"address",
"if",
"address",
"not",
"in",
"self",
".",
"mock_rpcs",
":",
"self",
".",
"mock_rpcs",
"[",
"address",
"]",
"=",
"{",
"}",
"self... | Store a mock return value for an RPC
Args:
slot (SlotIdentifier): The slot we are mocking
rpc_id (int): The rpc we are mocking
value (int): The value that should be returned
when the RPC is called. | [
"Store",
"a",
"mock",
"return",
"value",
"for",
"an",
"RPC"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/executor.py#L21-L36 |
23,788 | iotile/coretools | iotilesensorgraph/iotile/sg/sim/executor.py | RPCExecutor.rpc | def rpc(self, address, rpc_id):
"""Call an RPC and receive the result as an integer.
If the RPC does not properly return a 32 bit integer, raise a warning
unless it cannot be converted into an integer at all, in which case
a HardwareError is thrown.
Args:
address (int): The address of the tile we want to call the RPC
on
rpc_id (int): The id of the RPC that we want to call
Returns:
int: The result of the RPC call. If the rpc did not succeed
an error is thrown instead.
"""
# Always allow mocking an RPC to override whatever the defaul behavior is
if address in self.mock_rpcs and rpc_id in self.mock_rpcs[address]:
value = self.mock_rpcs[address][rpc_id]
return value
result = self._call_rpc(address, rpc_id, bytes())
if len(result) != 4:
self.warn(u"RPC 0x%X on address %d: response had invalid length %d not equal to 4" % (rpc_id, address, len(result)))
if len(result) < 4:
raise HardwareError("Response from RPC was not long enough to parse as an integer", rpc_id=rpc_id, address=address, response_length=len(result))
if len(result) > 4:
result = result[:4]
res, = struct.unpack("<L", result)
return res | python | def rpc(self, address, rpc_id):
# Always allow mocking an RPC to override whatever the defaul behavior is
if address in self.mock_rpcs and rpc_id in self.mock_rpcs[address]:
value = self.mock_rpcs[address][rpc_id]
return value
result = self._call_rpc(address, rpc_id, bytes())
if len(result) != 4:
self.warn(u"RPC 0x%X on address %d: response had invalid length %d not equal to 4" % (rpc_id, address, len(result)))
if len(result) < 4:
raise HardwareError("Response from RPC was not long enough to parse as an integer", rpc_id=rpc_id, address=address, response_length=len(result))
if len(result) > 4:
result = result[:4]
res, = struct.unpack("<L", result)
return res | [
"def",
"rpc",
"(",
"self",
",",
"address",
",",
"rpc_id",
")",
":",
"# Always allow mocking an RPC to override whatever the defaul behavior is",
"if",
"address",
"in",
"self",
".",
"mock_rpcs",
"and",
"rpc_id",
"in",
"self",
".",
"mock_rpcs",
"[",
"address",
"]",
... | Call an RPC and receive the result as an integer.
If the RPC does not properly return a 32 bit integer, raise a warning
unless it cannot be converted into an integer at all, in which case
a HardwareError is thrown.
Args:
address (int): The address of the tile we want to call the RPC
on
rpc_id (int): The id of the RPC that we want to call
Returns:
int: The result of the RPC call. If the rpc did not succeed
an error is thrown instead. | [
"Call",
"an",
"RPC",
"and",
"receive",
"the",
"result",
"as",
"an",
"integer",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/executor.py#L49-L83 |
23,789 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/swig.py | _get_swig_version | def _get_swig_version(env, swig):
"""Run the SWIG command line tool to get and return the version number"""
swig = env.subst(swig)
pipe = SCons.Action._subproc(env, SCons.Util.CLVar(swig) + ['-version'],
stdin = 'devnull',
stderr = 'devnull',
stdout = subprocess.PIPE)
if pipe.wait() != 0: return
# MAYBE: out = SCons.Util.to_str (pipe.stdout.read())
out = SCons.Util.to_str(pipe.stdout.read())
match = re.search('SWIG Version\s+(\S+).*', out, re.MULTILINE)
if match:
if verbose: print("Version is:%s"%match.group(1))
return match.group(1)
else:
if verbose: print("Unable to detect version: [%s]"%out) | python | def _get_swig_version(env, swig):
swig = env.subst(swig)
pipe = SCons.Action._subproc(env, SCons.Util.CLVar(swig) + ['-version'],
stdin = 'devnull',
stderr = 'devnull',
stdout = subprocess.PIPE)
if pipe.wait() != 0: return
# MAYBE: out = SCons.Util.to_str (pipe.stdout.read())
out = SCons.Util.to_str(pipe.stdout.read())
match = re.search('SWIG Version\s+(\S+).*', out, re.MULTILINE)
if match:
if verbose: print("Version is:%s"%match.group(1))
return match.group(1)
else:
if verbose: print("Unable to detect version: [%s]"%out) | [
"def",
"_get_swig_version",
"(",
"env",
",",
"swig",
")",
":",
"swig",
"=",
"env",
".",
"subst",
"(",
"swig",
")",
"pipe",
"=",
"SCons",
".",
"Action",
".",
"_subproc",
"(",
"env",
",",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"swig",
")",
"+",
"... | Run the SWIG command line tool to get and return the version number | [
"Run",
"the",
"SWIG",
"command",
"line",
"tool",
"to",
"get",
"and",
"return",
"the",
"version",
"number"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/swig.py#L134-L150 |
23,790 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/swig.py | generate | def generate(env):
"""Add Builders and construction variables for swig to an Environment."""
c_file, cxx_file = SCons.Tool.createCFileBuilders(env)
c_file.suffix['.i'] = swigSuffixEmitter
cxx_file.suffix['.i'] = swigSuffixEmitter
c_file.add_action('.i', SwigAction)
c_file.add_emitter('.i', _swigEmitter)
cxx_file.add_action('.i', SwigAction)
cxx_file.add_emitter('.i', _swigEmitter)
java_file = SCons.Tool.CreateJavaFileBuilder(env)
java_file.suffix['.i'] = swigSuffixEmitter
java_file.add_action('.i', SwigAction)
java_file.add_emitter('.i', _swigEmitter)
if 'SWIG' not in env:
env['SWIG'] = env.Detect(swigs) or swigs[0]
env['SWIGVERSION'] = _get_swig_version(env, env['SWIG'])
env['SWIGFLAGS'] = SCons.Util.CLVar('')
env['SWIGDIRECTORSUFFIX'] = '_wrap.h'
env['SWIGCFILESUFFIX'] = '_wrap$CFILESUFFIX'
env['SWIGCXXFILESUFFIX'] = '_wrap$CXXFILESUFFIX'
env['_SWIGOUTDIR'] = r'${"-outdir \"%s\"" % SWIGOUTDIR}'
env['SWIGPATH'] = []
env['SWIGINCPREFIX'] = '-I'
env['SWIGINCSUFFIX'] = ''
env['_SWIGINCFLAGS'] = '$( ${_concat(SWIGINCPREFIX, SWIGPATH, SWIGINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
env['SWIGCOM'] = '$SWIG -o $TARGET ${_SWIGOUTDIR} ${_SWIGINCFLAGS} $SWIGFLAGS $SOURCES' | python | def generate(env):
c_file, cxx_file = SCons.Tool.createCFileBuilders(env)
c_file.suffix['.i'] = swigSuffixEmitter
cxx_file.suffix['.i'] = swigSuffixEmitter
c_file.add_action('.i', SwigAction)
c_file.add_emitter('.i', _swigEmitter)
cxx_file.add_action('.i', SwigAction)
cxx_file.add_emitter('.i', _swigEmitter)
java_file = SCons.Tool.CreateJavaFileBuilder(env)
java_file.suffix['.i'] = swigSuffixEmitter
java_file.add_action('.i', SwigAction)
java_file.add_emitter('.i', _swigEmitter)
if 'SWIG' not in env:
env['SWIG'] = env.Detect(swigs) or swigs[0]
env['SWIGVERSION'] = _get_swig_version(env, env['SWIG'])
env['SWIGFLAGS'] = SCons.Util.CLVar('')
env['SWIGDIRECTORSUFFIX'] = '_wrap.h'
env['SWIGCFILESUFFIX'] = '_wrap$CFILESUFFIX'
env['SWIGCXXFILESUFFIX'] = '_wrap$CXXFILESUFFIX'
env['_SWIGOUTDIR'] = r'${"-outdir \"%s\"" % SWIGOUTDIR}'
env['SWIGPATH'] = []
env['SWIGINCPREFIX'] = '-I'
env['SWIGINCSUFFIX'] = ''
env['_SWIGINCFLAGS'] = '$( ${_concat(SWIGINCPREFIX, SWIGPATH, SWIGINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
env['SWIGCOM'] = '$SWIG -o $TARGET ${_SWIGOUTDIR} ${_SWIGINCFLAGS} $SWIGFLAGS $SOURCES' | [
"def",
"generate",
"(",
"env",
")",
":",
"c_file",
",",
"cxx_file",
"=",
"SCons",
".",
"Tool",
".",
"createCFileBuilders",
"(",
"env",
")",
"c_file",
".",
"suffix",
"[",
"'.i'",
"]",
"=",
"swigSuffixEmitter",
"cxx_file",
".",
"suffix",
"[",
"'.i'",
"]",
... | Add Builders and construction variables for swig to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"swig",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/swig.py#L152-L183 |
23,791 | iotile/coretools | transport_plugins/jlink/iotile_transport_jlink/multiplexers.py | _select_ftdi_channel | def _select_ftdi_channel(channel):
"""Select multiplexer channel. Currently uses a FTDI chip via pylibftdi"""
if channel < 0 or channel > 8:
raise ArgumentError("FTDI-selected multiplexer only has channels 0-7 valid, "
"make sure you specify channel with -c channel=number", channel=channel)
from pylibftdi import BitBangDevice
bb = BitBangDevice(auto_detach=False)
bb.direction = 0b111
bb.port = channel | python | def _select_ftdi_channel(channel):
if channel < 0 or channel > 8:
raise ArgumentError("FTDI-selected multiplexer only has channels 0-7 valid, "
"make sure you specify channel with -c channel=number", channel=channel)
from pylibftdi import BitBangDevice
bb = BitBangDevice(auto_detach=False)
bb.direction = 0b111
bb.port = channel | [
"def",
"_select_ftdi_channel",
"(",
"channel",
")",
":",
"if",
"channel",
"<",
"0",
"or",
"channel",
">",
"8",
":",
"raise",
"ArgumentError",
"(",
"\"FTDI-selected multiplexer only has channels 0-7 valid, \"",
"\"make sure you specify channel with -c channel=number\"",
",",
... | Select multiplexer channel. Currently uses a FTDI chip via pylibftdi | [
"Select",
"multiplexer",
"channel",
".",
"Currently",
"uses",
"a",
"FTDI",
"chip",
"via",
"pylibftdi"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/multiplexers.py#L5-L13 |
23,792 | iotile/coretools | iotilesensorgraph/iotile/sg/streamer_descriptor.py | parse_binary_descriptor | def parse_binary_descriptor(bindata, sensor_log=None):
"""Convert a binary streamer descriptor into a string descriptor.
Binary streamer descriptors are 20-byte binary structures that encode all
information needed to create a streamer. They are used to communicate
that information to an embedded device in an efficent format. This
function exists to turn such a compressed streamer description back into
an understandable string.
Args:
bindata (bytes): The binary streamer descriptor that we want to
understand.
sensor_log (SensorLog): Optional sensor_log to add this streamer to
a an underlying data store.
Returns:
DataStreamer: A DataStreamer object representing the streamer.
You can get a useful human readable string by calling str() on the
return value.
"""
if len(bindata) != 14:
raise ArgumentError("Invalid length of binary data in streamer descriptor", length=len(bindata), expected=14, data=bindata)
dest_tile, stream_id, trigger, format_code, type_code = struct.unpack("<8sHBBBx", bindata)
dest_id = SlotIdentifier.FromEncoded(dest_tile)
selector = DataStreamSelector.FromEncoded(stream_id)
format_name = DataStreamer.KnownFormatCodes.get(format_code)
type_name = DataStreamer.KnownTypeCodes.get(type_code)
if format_name is None:
raise ArgumentError("Unknown format code", code=format_code, known_code=DataStreamer.KnownFormatCodes)
if type_name is None:
raise ArgumentError("Unknown type code", code=type_code, known_codes=DataStreamer.KnownTypeCodes)
with_other = None
if trigger & (1 << 7):
auto = False
with_other = trigger & ((1 << 7) - 1)
elif trigger == 0:
auto = False
elif trigger == 1:
auto = True
else:
raise ArgumentError("Unknown trigger type for streamer", trigger_code=trigger)
return DataStreamer(selector, dest_id, format_name, auto, type_name, with_other=with_other, sensor_log=sensor_log) | python | def parse_binary_descriptor(bindata, sensor_log=None):
if len(bindata) != 14:
raise ArgumentError("Invalid length of binary data in streamer descriptor", length=len(bindata), expected=14, data=bindata)
dest_tile, stream_id, trigger, format_code, type_code = struct.unpack("<8sHBBBx", bindata)
dest_id = SlotIdentifier.FromEncoded(dest_tile)
selector = DataStreamSelector.FromEncoded(stream_id)
format_name = DataStreamer.KnownFormatCodes.get(format_code)
type_name = DataStreamer.KnownTypeCodes.get(type_code)
if format_name is None:
raise ArgumentError("Unknown format code", code=format_code, known_code=DataStreamer.KnownFormatCodes)
if type_name is None:
raise ArgumentError("Unknown type code", code=type_code, known_codes=DataStreamer.KnownTypeCodes)
with_other = None
if trigger & (1 << 7):
auto = False
with_other = trigger & ((1 << 7) - 1)
elif trigger == 0:
auto = False
elif trigger == 1:
auto = True
else:
raise ArgumentError("Unknown trigger type for streamer", trigger_code=trigger)
return DataStreamer(selector, dest_id, format_name, auto, type_name, with_other=with_other, sensor_log=sensor_log) | [
"def",
"parse_binary_descriptor",
"(",
"bindata",
",",
"sensor_log",
"=",
"None",
")",
":",
"if",
"len",
"(",
"bindata",
")",
"!=",
"14",
":",
"raise",
"ArgumentError",
"(",
"\"Invalid length of binary data in streamer descriptor\"",
",",
"length",
"=",
"len",
"("... | Convert a binary streamer descriptor into a string descriptor.
Binary streamer descriptors are 20-byte binary structures that encode all
information needed to create a streamer. They are used to communicate
that information to an embedded device in an efficent format. This
function exists to turn such a compressed streamer description back into
an understandable string.
Args:
bindata (bytes): The binary streamer descriptor that we want to
understand.
sensor_log (SensorLog): Optional sensor_log to add this streamer to
a an underlying data store.
Returns:
DataStreamer: A DataStreamer object representing the streamer.
You can get a useful human readable string by calling str() on the
return value. | [
"Convert",
"a",
"binary",
"streamer",
"descriptor",
"into",
"a",
"string",
"descriptor",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/streamer_descriptor.py#L16-L65 |
23,793 | iotile/coretools | iotilesensorgraph/iotile/sg/streamer_descriptor.py | create_binary_descriptor | def create_binary_descriptor(streamer):
"""Create a packed binary descriptor of a DataStreamer object.
Args:
streamer (DataStreamer): The streamer to create a packed descriptor for
Returns:
bytes: A packed 14-byte streamer descriptor.
"""
trigger = 0
if streamer.automatic:
trigger = 1
elif streamer.with_other is not None:
trigger = (1 << 7) | streamer.with_other
return struct.pack("<8sHBBBx", streamer.dest.encode(), streamer.selector.encode(), trigger, streamer.KnownFormats[streamer.format], streamer.KnownTypes[streamer.report_type]) | python | def create_binary_descriptor(streamer):
trigger = 0
if streamer.automatic:
trigger = 1
elif streamer.with_other is not None:
trigger = (1 << 7) | streamer.with_other
return struct.pack("<8sHBBBx", streamer.dest.encode(), streamer.selector.encode(), trigger, streamer.KnownFormats[streamer.format], streamer.KnownTypes[streamer.report_type]) | [
"def",
"create_binary_descriptor",
"(",
"streamer",
")",
":",
"trigger",
"=",
"0",
"if",
"streamer",
".",
"automatic",
":",
"trigger",
"=",
"1",
"elif",
"streamer",
".",
"with_other",
"is",
"not",
"None",
":",
"trigger",
"=",
"(",
"1",
"<<",
"7",
")",
... | Create a packed binary descriptor of a DataStreamer object.
Args:
streamer (DataStreamer): The streamer to create a packed descriptor for
Returns:
bytes: A packed 14-byte streamer descriptor. | [
"Create",
"a",
"packed",
"binary",
"descriptor",
"of",
"a",
"DataStreamer",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/streamer_descriptor.py#L68-L84 |
23,794 | iotile/coretools | iotilesensorgraph/iotile/sg/streamer_descriptor.py | parse_string_descriptor | def parse_string_descriptor(string_desc):
"""Parse a string descriptor of a streamer into a DataStreamer object.
Args:
string_desc (str): The string descriptor that we wish to parse.
Returns:
DataStreamer: A DataStreamer object representing the streamer.
"""
if not isinstance(string_desc, str):
string_desc = str(string_desc)
if not string_desc.endswith(';'):
string_desc += ';'
parsed = get_streamer_parser().parseString(string_desc)[0]
realtime = 'realtime' in parsed
broadcast = 'broadcast' in parsed
encrypted = 'security' in parsed and parsed['security'] == 'encrypted'
signed = 'security' in parsed and parsed['security'] == 'signed'
auto = 'manual' not in parsed
with_other = None
if 'with_other' in parsed:
with_other = parsed['with_other']
auto = False
dest = SlotIdentifier.FromString('controller')
if 'explicit_tile' in parsed:
dest = parsed['explicit_tile']
selector = parsed['selector']
# Make sure all of the combination are valid
if realtime and (encrypted or signed):
raise SensorGraphSemanticError("Realtime streamers cannot be either signed or encrypted")
if broadcast and (encrypted or signed):
raise SensorGraphSemanticError("Broadcast streamers cannot be either signed or encrypted")
report_type = 'broadcast' if broadcast else 'telegram'
dest = dest
selector = selector
if realtime or broadcast:
report_format = u'individual'
elif signed:
report_format = u'signedlist_userkey'
elif encrypted:
raise SensorGraphSemanticError("Encrypted streamers are not yet supported")
else:
report_format = u'hashedlist'
return DataStreamer(selector, dest, report_format, auto, report_type=report_type, with_other=with_other) | python | def parse_string_descriptor(string_desc):
if not isinstance(string_desc, str):
string_desc = str(string_desc)
if not string_desc.endswith(';'):
string_desc += ';'
parsed = get_streamer_parser().parseString(string_desc)[0]
realtime = 'realtime' in parsed
broadcast = 'broadcast' in parsed
encrypted = 'security' in parsed and parsed['security'] == 'encrypted'
signed = 'security' in parsed and parsed['security'] == 'signed'
auto = 'manual' not in parsed
with_other = None
if 'with_other' in parsed:
with_other = parsed['with_other']
auto = False
dest = SlotIdentifier.FromString('controller')
if 'explicit_tile' in parsed:
dest = parsed['explicit_tile']
selector = parsed['selector']
# Make sure all of the combination are valid
if realtime and (encrypted or signed):
raise SensorGraphSemanticError("Realtime streamers cannot be either signed or encrypted")
if broadcast and (encrypted or signed):
raise SensorGraphSemanticError("Broadcast streamers cannot be either signed or encrypted")
report_type = 'broadcast' if broadcast else 'telegram'
dest = dest
selector = selector
if realtime or broadcast:
report_format = u'individual'
elif signed:
report_format = u'signedlist_userkey'
elif encrypted:
raise SensorGraphSemanticError("Encrypted streamers are not yet supported")
else:
report_format = u'hashedlist'
return DataStreamer(selector, dest, report_format, auto, report_type=report_type, with_other=with_other) | [
"def",
"parse_string_descriptor",
"(",
"string_desc",
")",
":",
"if",
"not",
"isinstance",
"(",
"string_desc",
",",
"str",
")",
":",
"string_desc",
"=",
"str",
"(",
"string_desc",
")",
"if",
"not",
"string_desc",
".",
"endswith",
"(",
"';'",
")",
":",
"str... | Parse a string descriptor of a streamer into a DataStreamer object.
Args:
string_desc (str): The string descriptor that we wish to parse.
Returns:
DataStreamer: A DataStreamer object representing the streamer. | [
"Parse",
"a",
"string",
"descriptor",
"of",
"a",
"streamer",
"into",
"a",
"DataStreamer",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/streamer_descriptor.py#L87-L142 |
23,795 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/applelink.py | generate | def generate(env):
"""Add Builders and construction variables for applelink to an
Environment."""
link.generate(env)
env['FRAMEWORKPATHPREFIX'] = '-F'
env['_FRAMEWORKPATH'] = '${_concat(FRAMEWORKPATHPREFIX, FRAMEWORKPATH, "", __env__)}'
env['_FRAMEWORKS'] = '${_concat("-framework ", FRAMEWORKS, "", __env__)}'
env['LINKCOM'] = env['LINKCOM'] + ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -dynamiclib')
env['SHLINKCOM'] = env['SHLINKCOM'] + ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'
# TODO: Work needed to generate versioned shared libraries
# Leaving this commented out, and also going to disable versioned library checking for now
# see: http://docstore.mik.ua/orelly/unix3/mac/ch05_04.htm for proper naming
#link._setup_versioned_lib_variables(env, tool = 'applelink')#, use_soname = use_soname)
#env['LINKCALLBACKS'] = link._versioned_lib_callbacks()
# override the default for loadable modules, which are different
# on OS X than dynamic shared libs. echoing what XCode does for
# pre/suffixes:
env['LDMODULEPREFIX'] = ''
env['LDMODULESUFFIX'] = ''
env['LDMODULEFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -bundle')
env['LDMODULECOM'] = '$LDMODULE -o ${TARGET} $LDMODULEFLAGS $SOURCES $_LIBDIRFLAGS $_LIBFLAGS $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS' | python | def generate(env):
link.generate(env)
env['FRAMEWORKPATHPREFIX'] = '-F'
env['_FRAMEWORKPATH'] = '${_concat(FRAMEWORKPATHPREFIX, FRAMEWORKPATH, "", __env__)}'
env['_FRAMEWORKS'] = '${_concat("-framework ", FRAMEWORKS, "", __env__)}'
env['LINKCOM'] = env['LINKCOM'] + ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -dynamiclib')
env['SHLINKCOM'] = env['SHLINKCOM'] + ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'
# TODO: Work needed to generate versioned shared libraries
# Leaving this commented out, and also going to disable versioned library checking for now
# see: http://docstore.mik.ua/orelly/unix3/mac/ch05_04.htm for proper naming
#link._setup_versioned_lib_variables(env, tool = 'applelink')#, use_soname = use_soname)
#env['LINKCALLBACKS'] = link._versioned_lib_callbacks()
# override the default for loadable modules, which are different
# on OS X than dynamic shared libs. echoing what XCode does for
# pre/suffixes:
env['LDMODULEPREFIX'] = ''
env['LDMODULESUFFIX'] = ''
env['LDMODULEFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -bundle')
env['LDMODULECOM'] = '$LDMODULE -o ${TARGET} $LDMODULEFLAGS $SOURCES $_LIBDIRFLAGS $_LIBFLAGS $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS' | [
"def",
"generate",
"(",
"env",
")",
":",
"link",
".",
"generate",
"(",
"env",
")",
"env",
"[",
"'FRAMEWORKPATHPREFIX'",
"]",
"=",
"'-F'",
"env",
"[",
"'_FRAMEWORKPATH'",
"]",
"=",
"'${_concat(FRAMEWORKPATHPREFIX, FRAMEWORKPATH, \"\", __env__)}'",
"env",
"[",
"'_FR... | Add Builders and construction variables for applelink to an
Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"applelink",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/applelink.py#L42-L68 |
23,796 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py | _generateGUID | def _generateGUID(slnfile, name):
"""This generates a dummy GUID for the sln file to use. It is
based on the MD5 signatures of the sln filename plus the name of
the project. It basically just needs to be unique, and not
change with each invocation."""
m = hashlib.md5()
# Normalize the slnfile path to a Windows path (\ separators) so
# the generated file has a consistent GUID even if we generate
# it on a non-Windows platform.
m.update(bytearray(ntpath.normpath(str(slnfile)) + str(name),'utf-8'))
solution = m.hexdigest().upper()
# convert most of the signature to GUID form (discard the rest)
solution = "{" + solution[:8] + "-" + solution[8:12] + "-" + solution[12:16] + "-" + solution[16:20] + "-" + solution[20:32] + "}"
return solution | python | def _generateGUID(slnfile, name):
m = hashlib.md5()
# Normalize the slnfile path to a Windows path (\ separators) so
# the generated file has a consistent GUID even if we generate
# it on a non-Windows platform.
m.update(bytearray(ntpath.normpath(str(slnfile)) + str(name),'utf-8'))
solution = m.hexdigest().upper()
# convert most of the signature to GUID form (discard the rest)
solution = "{" + solution[:8] + "-" + solution[8:12] + "-" + solution[12:16] + "-" + solution[16:20] + "-" + solution[20:32] + "}"
return solution | [
"def",
"_generateGUID",
"(",
"slnfile",
",",
"name",
")",
":",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"# Normalize the slnfile path to a Windows path (\\ separators) so",
"# the generated file has a consistent GUID even if we generate",
"# it on a non-Windows platform.",
"m",... | This generates a dummy GUID for the sln file to use. It is
based on the MD5 signatures of the sln filename plus the name of
the project. It basically just needs to be unique, and not
change with each invocation. | [
"This",
"generates",
"a",
"dummy",
"GUID",
"for",
"the",
"sln",
"file",
"to",
"use",
".",
"It",
"is",
"based",
"on",
"the",
"MD5",
"signatures",
"of",
"the",
"sln",
"filename",
"plus",
"the",
"name",
"of",
"the",
"project",
".",
"It",
"basically",
"jus... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py#L80-L93 |
23,797 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py | makeHierarchy | def makeHierarchy(sources):
'''Break a list of files into a hierarchy; for each value, if it is a string,
then it is a file. If it is a dictionary, it is a folder. The string is
the original path of the file.'''
hierarchy = {}
for file in sources:
path = splitFully(file)
if len(path):
dict = hierarchy
for part in path[:-1]:
if part not in dict:
dict[part] = {}
dict = dict[part]
dict[path[-1]] = file
#else:
# print 'Warning: failed to decompose path for '+str(file)
return hierarchy | python | def makeHierarchy(sources):
'''Break a list of files into a hierarchy; for each value, if it is a string,
then it is a file. If it is a dictionary, it is a folder. The string is
the original path of the file.'''
hierarchy = {}
for file in sources:
path = splitFully(file)
if len(path):
dict = hierarchy
for part in path[:-1]:
if part not in dict:
dict[part] = {}
dict = dict[part]
dict[path[-1]] = file
#else:
# print 'Warning: failed to decompose path for '+str(file)
return hierarchy | [
"def",
"makeHierarchy",
"(",
"sources",
")",
":",
"hierarchy",
"=",
"{",
"}",
"for",
"file",
"in",
"sources",
":",
"path",
"=",
"splitFully",
"(",
"file",
")",
"if",
"len",
"(",
"path",
")",
":",
"dict",
"=",
"hierarchy",
"for",
"part",
"in",
"path",... | Break a list of files into a hierarchy; for each value, if it is a string,
then it is a file. If it is a dictionary, it is a folder. The string is
the original path of the file. | [
"Break",
"a",
"list",
"of",
"files",
"into",
"a",
"hierarchy",
";",
"for",
"each",
"value",
"if",
"it",
"is",
"a",
"string",
"then",
"it",
"is",
"a",
"file",
".",
"If",
"it",
"is",
"a",
"dictionary",
"it",
"is",
"a",
"folder",
".",
"The",
"string",... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py#L150-L167 |
23,798 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py | GenerateDSP | def GenerateDSP(dspfile, source, env):
"""Generates a Project file based on the version of MSVS that is being used"""
version_num = 6.0
if 'MSVS_VERSION' in env:
version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
if version_num >= 10.0:
g = _GenerateV10DSP(dspfile, source, env)
g.Build()
elif version_num >= 7.0:
g = _GenerateV7DSP(dspfile, source, env)
g.Build()
else:
g = _GenerateV6DSP(dspfile, source, env)
g.Build() | python | def GenerateDSP(dspfile, source, env):
version_num = 6.0
if 'MSVS_VERSION' in env:
version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
if version_num >= 10.0:
g = _GenerateV10DSP(dspfile, source, env)
g.Build()
elif version_num >= 7.0:
g = _GenerateV7DSP(dspfile, source, env)
g.Build()
else:
g = _GenerateV6DSP(dspfile, source, env)
g.Build() | [
"def",
"GenerateDSP",
"(",
"dspfile",
",",
"source",
",",
"env",
")",
":",
"version_num",
"=",
"6.0",
"if",
"'MSVS_VERSION'",
"in",
"env",
":",
"version_num",
",",
"suite",
"=",
"msvs_parse_version",
"(",
"env",
"[",
"'MSVS_VERSION'",
"]",
")",
"if",
"vers... | Generates a Project file based on the version of MSVS that is being used | [
"Generates",
"a",
"Project",
"file",
"based",
"on",
"the",
"version",
"of",
"MSVS",
"that",
"is",
"being",
"used"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py#L1675-L1689 |
23,799 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py | solutionEmitter | def solutionEmitter(target, source, env):
"""Sets up the DSW dependencies."""
# todo: Not sure what sets source to what user has passed as target,
# but this is what happens. When that is fixed, we also won't have
# to make the user always append env['MSVSSOLUTIONSUFFIX'] to target.
if source[0] == target[0]:
source = []
# make sure the suffix is correct for the version of MSVS we're running.
(base, suff) = SCons.Util.splitext(str(target[0]))
suff = env.subst('$MSVSSOLUTIONSUFFIX')
target[0] = base + suff
if not source:
source = 'sln_inputs:'
if 'name' in env:
if SCons.Util.is_String(env['name']):
source = source + ' "%s"' % env['name']
else:
raise SCons.Errors.InternalError("name must be a string")
if 'variant' in env:
if SCons.Util.is_String(env['variant']):
source = source + ' "%s"' % env['variant']
elif SCons.Util.is_List(env['variant']):
for variant in env['variant']:
if SCons.Util.is_String(variant):
source = source + ' "%s"' % variant
else:
raise SCons.Errors.InternalError("name must be a string or a list of strings")
else:
raise SCons.Errors.InternalError("variant must be a string or a list of strings")
else:
raise SCons.Errors.InternalError("variant must be specified")
if 'slnguid' in env:
if SCons.Util.is_String(env['slnguid']):
source = source + ' "%s"' % env['slnguid']
else:
raise SCons.Errors.InternalError("slnguid must be a string")
if 'projects' in env:
if SCons.Util.is_String(env['projects']):
source = source + ' "%s"' % env['projects']
elif SCons.Util.is_List(env['projects']):
for t in env['projects']:
if SCons.Util.is_String(t):
source = source + ' "%s"' % t
source = source + ' "%s"' % str(target[0])
source = [SCons.Node.Python.Value(source)]
return ([target[0]], source) | python | def solutionEmitter(target, source, env):
# todo: Not sure what sets source to what user has passed as target,
# but this is what happens. When that is fixed, we also won't have
# to make the user always append env['MSVSSOLUTIONSUFFIX'] to target.
if source[0] == target[0]:
source = []
# make sure the suffix is correct for the version of MSVS we're running.
(base, suff) = SCons.Util.splitext(str(target[0]))
suff = env.subst('$MSVSSOLUTIONSUFFIX')
target[0] = base + suff
if not source:
source = 'sln_inputs:'
if 'name' in env:
if SCons.Util.is_String(env['name']):
source = source + ' "%s"' % env['name']
else:
raise SCons.Errors.InternalError("name must be a string")
if 'variant' in env:
if SCons.Util.is_String(env['variant']):
source = source + ' "%s"' % env['variant']
elif SCons.Util.is_List(env['variant']):
for variant in env['variant']:
if SCons.Util.is_String(variant):
source = source + ' "%s"' % variant
else:
raise SCons.Errors.InternalError("name must be a string or a list of strings")
else:
raise SCons.Errors.InternalError("variant must be a string or a list of strings")
else:
raise SCons.Errors.InternalError("variant must be specified")
if 'slnguid' in env:
if SCons.Util.is_String(env['slnguid']):
source = source + ' "%s"' % env['slnguid']
else:
raise SCons.Errors.InternalError("slnguid must be a string")
if 'projects' in env:
if SCons.Util.is_String(env['projects']):
source = source + ' "%s"' % env['projects']
elif SCons.Util.is_List(env['projects']):
for t in env['projects']:
if SCons.Util.is_String(t):
source = source + ' "%s"' % t
source = source + ' "%s"' % str(target[0])
source = [SCons.Node.Python.Value(source)]
return ([target[0]], source) | [
"def",
"solutionEmitter",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"# todo: Not sure what sets source to what user has passed as target,",
"# but this is what happens. When that is fixed, we also won't have",
"# to make the user always append env['MSVSSOLUTIONSUFFIX'] to target.",... | Sets up the DSW dependencies. | [
"Sets",
"up",
"the",
"DSW",
"dependencies",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py#L1858-L1912 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.