示例#1
0
class PaletteEntry(Object):

    __fields__ = {"primary": List(int), "secondary": List(int)}

    @args(void, [List(int), List(int)])
    def __init__(self, primary, secondary):

        Object.__init__(self)
        self.primary = primary
        self.secondary = secondary
示例#2
0
class CacheItem(Object):

    __fields__ = {"time": long, "forecasts": List(Forecast)}

    @args(void, [long, List(Forecast)])
    def __init__(self, time, forecasts):

        Object.__init__(self)

        self.time = time
        self.forecasts = forecasts
示例#3
0
class SpriteFileListAdapter(FileListAdapter):
    @args(void, [File, List(String)])
    def __init__(self, directory, suffixes):

        FileListAdapter.__init__(self, directory, suffixes)

    def getView(self, position, convertView, parent):

        view = FileListAdapter.getView(self, position, convertView, parent)
        CAST(view, TextView).setTextSize(TypedValue.COMPLEX_UNIT_SP, float(20))
        return view

    """We define a method to obtain a new list of file names and report whether
    the list has changed."""

    @args(bool, [])
    def update(self):

        items = self.items
        self.items = []

        for suffix in self.suffixes:
            self.addFiles(suffix)

        for item1, item2 in zip(items, self.items):
            if item1 != item2:
                return True

        return False
示例#4
0
    def __init__(self, func=None, env=None):
        self.arrows = HashMap()
        self.cls = None
        self.defaultTypes = List()

        self.selfType = None
        self.func = None
        from pysonarsq.java.Analyzer import Analyzer

        super(FunType, self).__init__()
        self.env = None
        if isinstance(func, FunctionDef):
            self.func = func
            self.env = env
        elif isinstance(func, Type):
            from_, to = func, env
            self.addMapping(from_, to)
            self.getTable().addSuper(
                Analyzer.self.builtins.BaseFunction.getTable())
            self.getTable().setPath(
                Analyzer.self.builtins.BaseFunction.getTable().getPath())
class QueryGridDataSetResult(object):
    """ generated source for class QueryGridDataSetResult """
    gridDataSetMetas = List()
    totalCount = long()
    isAllSuccess = bool()
    nextToken = []

    def getGridDataSetMetas(self):
        """ generated source for method getGridDataSetMetas """
        return self.gridDataSetMetas

    def setGridDataSetMetas(self, gridDataSetMetas):
        """ generated source for method setGridDataSetMetas """
        self.gridDataSetMetas = gridDataSetMetas

    def getTotalCount(self):
        """ generated source for method getTotalCount """
        return self.totalCount

    def setTotalCount(self, totalCount):
        """ generated source for method setTotalCount """
        self.totalCount = totalCount

    def isAllSuccess(self):
        """ generated source for method isAllSuccess """
        return self.isAllSuccess

    def setAllSuccess(self, allSuccess):
        """ generated source for method setAllSuccess """
        self.isAllSuccess = allSuccess

    def getNextToken(self):
        """ generated source for method getNextToken """
        return self.nextToken

    def setNextToken(self, nextToken):
        """ generated source for method setNextToken """
        self.nextToken = nextToken
示例#6
0
    def __init__(self, parent=None, type_=None):
        #  stays null for most scopes (mem opt)
        #  all are non-null except global table
        #  link to the closest non-class scope, for lifting functions out
        # ....

        if not hasattr(self, 'scopeType'):
            self.scopeType = None

        self.supers = List()
        self.globalNames = Set()
        self.type_ = None
        self.path = ""
        self.parent = parent
        self.setScopeType(type_)
        self.forwarding = None
        self.table = Map()

        if isinstance(parent, Scope) and type_ is None:
            s = parent  # case of creating a new scope from an existing one
            if s.table is not None:
                self.table = HashMap()
                self.table.update(s.table)
                self.parent = s.parent
                self.setScopeType(s.scopeType)
                self.forwarding = s.forwarding
                self.supers = s.supers
                self.globalNames = s.globalNames
            self.type_ = s.type_
            self.path = s.path
        elif parent is not None:
            self.parent = parent
            self.setScopeType(type_)
            if type_ == self.ScopeType.CLASS:
                self.forwarding = (None if parent is None else
                                   parent.getForwarding())
            else:
                self.forwarding = self
示例#7
0
class Palette(Object):

    __fields__ = {"entries": List(PaletteEntry)}

    def __init__(self):

        Object.__init__(self)
        self.entries = []

    @args(void, [PaletteEntry])
    def add(self, entry):
        self.entries.add(entry)

    @args(PaletteEntry, [int])
    def getEntry(self, index):
        return self.entries[index]

    @args(bool, [])
    def hasEntries(self):
        return len(self.entries) != 0

    @args(int, [])
    def size(self):
        return len(self.entries)
示例#8
0
class SpriteAdapter(BaseAdapter):

    __interfaces__ = [Runnable]

    __fields__ = {
        "spritefile": Spritefile,
        "items": List(String),
        "cache": Map(int, CacheEntry),
        "name_cache": Map(int, String),
        "positions": Queue(int),
        "pending": Queue(WorkItem)
    }

    preview_size = 128
    cache_size = 20

    def __init__(self):

        BaseAdapter.__init__(self)

        self.handler = Handler()

        self.spritefile = None
        self.items = []

        self.cache = {}
        self.positions = []
        self.pending = []

    def getCount(self):
        return len(self.items)

    def getItem(self, position):
        return None

    def getItemId(self, position):
        return long(0)

    """We implement the `getView` method to provide a `LinearLayout` view for
    each item, containing an `ImageView` and a `TextView`. For sprites in the
    cache, we obtain a `Bitmap` and include it in the layout. Sprites that
    need to be rendered are represented by a placeholder `Bitmap` and a
    background task is started to render the sprite. When rendering is
    complete, the `SpriteRenderer` object that performs the task will update
    the `ImageView` with a new `Bitmap`."""

    def getView(self, position, convertView, parent):

        context = parent.getContext()

        layout = LinearLayout(context)
        layout.setOrientation(LinearLayout.VERTICAL)

        imageView = ImageView(context)

        if self.cache.containsKey(position):
            entry = self.cache[position]
            name = entry.name
            bitmap = entry.bitmap
            imageView.setImageBitmap(bitmap)

            if len(self.positions) > self.cache_size:
                self.cache.remove(self.positions.remove())

        else:
            # Create a placeholder bitmap to put into the view.
            bitmap = SpriteRenderer.emptyBitmap(self.preview_size,
                                                self.preview_size, False)
            imageView.setImageBitmap(bitmap)

            # Schedule the rendering process.
            name = self.items[position]
            self.scheduleRender(WorkItem(position, imageView))

        textView = TextView(context)
        textView.setText(name)
        textView.setGravity(0x01)  # center_horizontal

        layout.addView(imageView)
        layout.addView(textView)

        return layout

    """This method is used to tell the adapter which file to examine. We create
    a `Spritefile` object for the given file and read the names of the sprites
    it contains. We also clear the structures used to hold cache information."""

    @args(void, [File])
    def setFile(self, file):

        try:
            self.spritefile = Spritefile(file)
            self.items = LinkedList(self.spritefile.sprites.keySet())
            Collections.sort(self.items)
        except:
            self.items = []

        self.cache = {}
        self.positions = []

    @args(String, [int])
    def getSpriteName(self, position):

        return self.items[position]

    """This method is used to obtain a `Bitmap` for a sprite at a given
    position in the list of items held by the adapter."""

    @args(Bitmap, [int])
    def getSpriteBitmap(self, position):

        name = self.items[position]
        return SpriteRenderer.getSpriteBitmap(self.spritefile, name)

    """The following method schedules a sprite render, either performing it
    immediately or, if too many sprites are already being rendered, schedules
    it for later."""

    @args(void, [WorkItem])
    def scheduleRender(self, work):

        name = self.items[work.position]
        renderer = SpriteRenderer(self.spritefile, name, work.view, self.cache,
                                  self.positions)
        try:
            # Create a list then convert it to an array. The initial list
            # creation causes the items to be wrapped in Integer objects.
            renderer.execute(
                array([self.preview_size, self.preview_size, work.position]))
        except:
            # The sprite couldn't be rendered immediately. Add this item of
            # work to a queue and schedule an event for later. This will cause
            # the run method to be called.
            self.pending.add(work)
            self.handler.postDelayed(self, long(250))  # 0.25s

    """This method is called when a sprite render scheduled for later needs to
    be performed. We simply check that there is at least one sprite in the
    queue and try to schedule it again."""

    def run(self):

        if not self.pending.isEmpty():
            work = self.pending.remove()
            self.scheduleRender(work)
示例#9
0
class WeatherForecastActivity(Activity):

    __interfaces__ = [LocationListener]

    __fields__ = {"cache": Map(String, CacheItem)}

    def __init__(self):

        Activity.__init__(self)
        self.state = "entry"
        self.cache = {}

    def onCreate(self, bundle):

        Activity.onCreate(self, bundle)

        self.entryWidget = LocationWidget(self, self)
        self.forecastWidget = ForecastWidget(self)
        self.setContentView(self.entryWidget)
        self.parser = ForecastParser(self.getResources())

    def onPause(self):

        Activity.onPause(self)
        self.entryWidget.writeLocations()

    def locationEntered(self, location):

        if self.state == "fetching":
            return

        self.current_time = System.currentTimeMillis()
        self.place = location

        try:
            item = self.cache[location]
            if self.current_time - item.time < 600000:  # 10 minutes
                self.showForecasts(item.forecasts)
                return

        except KeyError:
            pass

        self.state = "fetching"

        self.task = Task(self)
        self.task.execute(array([location]))
        #self.parseForecasts(self.getSampleStream())

    @args(void, [InputStream])
    def parseForecasts(self, stream):

        if stream == None:
            self.showError()
            self.state = "entry"
            return

        forecasts = self.parser.parse(stream)
        stream.close()

        self.showForecasts(forecasts)

    @args(void, [List(Forecast)])
    def showForecasts(self, forecasts):

        self.cache[self.place] = CacheItem(self.current_time, forecasts)

        try:
            self.forecastWidget.addForecasts(forecasts)

            self.state = "forecast"
            self.setContentView(self.forecastWidget)

        except:
            self.state = "entry"
            self.showError()

    def showError(self):

        Toast.makeText(self, "Failed to read weather forecast,",
                       Toast.LENGTH_SHORT).show()

    @args(InputStream, [])
    def getSampleStream(self):

        resources = self.getResources()
        return resources.openRawResource(R.raw.sample)

    def onBackPressed(self):

        if self.state == "forecast":
            # Return to the entry widget.
            self.state = "entry"
            self.setContentView(self.entryWidget)

        elif self.state == "entry":
            # If already showing the entry widget then exit.
            Activity.onBackPressed(self)
class ForecastParser(Object):
    @args(void, [Resources])
    def __init__(self, resources):

        Object.__init__(self)

        # Obtain the keys and values to be used to create the symbols
        # dictionary from the application's resources.
        symbols = resources.getStringArray(R.array.symbols)
        resourceIDs = resources.getIntArray(R.array.resourceIDs)

        self.symbols = dict(symbols, resourceIDs)

    @args(List(Forecast), [InputStream])
    def parse(self, stream):

        factory = XmlPullParserFactory.newInstance()
        parser = factory.newPullParser()
        parser.setInput(stream, None)

        eventType = parser.getEventType()
        section = ""
        sections = {"location", "credit", "tabular"}

        dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"))
        sunrise = Date()
        sunset = Date()

        place = ""
        credit = ""
        forecasts = []
        forecast = Forecast()

        while eventType != XmlPullParser.END_DOCUMENT:

            eventType = parser.next()

            if eventType == XmlPullParser.START_TAG:

                name = parser.getName()

                if name in sections:
                    section = name

                elif section != "":

                    if name == "name":
                        while eventType != XmlPullParser.TEXT:
                            eventType = parser.next()

                        place = parser.getText()

                    elif name == "link":
                        credit = parser.getAttributeValue(None, "text")

                    elif name == "time":

                        forecast = Forecast()
                        forecast.place = place
                        forecast.credit = credit

                        from_ = parser.getAttributeValue(None, "from")
                        to_ = parser.getAttributeValue(None, "to")

                        forecast.from_ = dateFormat.parse(
                            from_, ParsePosition(0))
                        forecast.to_ = dateFormat.parse(to_, ParsePosition(0))

                    elif name == "symbol":

                        forecast.description = parser.getAttributeValue(
                            None, "name")
                        symbol = parser.getAttributeValue(None, "numberEx")

                        forecast.midDate = Date(forecast.from_.getTime()/2 + \
                                                forecast.to_.getTime()/2)
                        try:
                            forecast.symbol = self.symbols[symbol]
                            continue
                        except KeyError:
                            pass

                        if self.isDayTime(forecast.midDate, sunrise, sunset):
                            symbol += "d"
                        else:
                            symbol += "n"

                        try:
                            forecast.symbol = self.symbols[symbol]
                        except KeyError:
                            forecast.symbol = -1

                    elif name == "windSpeed":
                        forecast.windSpeed = parser.getAttributeValue(
                            None, "name")

                    elif name == "temperature":
                        forecast.temperature = parser.getAttributeValue(
                            None, "value")
                        forecast.temperatureUnit = parser.getAttributeValue(
                            None, "unit")

                elif name == "sun":
                    rise = parser.getAttributeValue(None, "rise")
                    sset = parser.getAttributeValue(None, "set")
                    sunrise = dateFormat.parse(rise, ParsePosition(0))
                    sunset = dateFormat.parse(sset, ParsePosition(0))

            elif eventType == XmlPullParser.END_TAG:

                name = parser.getName()

                if name == section and name in sections:
                    section = ""

                elif section == "tabular" and name == "time":
                    forecasts.add(forecast)

        return forecasts

    @args(bool, [Date, Date, Date])
    def isDayTime(self, forecastDate, sunrise, sunset):

        # Only check the time, not the date, of the forecast against the
        # sunrise and sunset times.

        cal = GregorianCalendar(TimeZone.getTimeZone("UTC"))
        cal.setTime(forecastDate)

        riseCal = GregorianCalendar(TimeZone.getTimeZone("UTC"))
        riseCal.setTime(sunrise)
        riseCal.set(cal.get(cal.YEAR), cal.get(cal.MONTH), cal.get(cal.DATE))

        setCal = GregorianCalendar(TimeZone.getTimeZone("UTC"))
        setCal.setTime(sunset)
        setCal.set(cal.get(cal.YEAR), cal.get(cal.MONTH), cal.get(cal.DATE))

        if cal.compareTo(riseCal) == -1:
            return False
        elif cal.compareTo(setCal) == 1:
            return False

        return True
示例#11
0
class Player(Object):

    SAMPLE_RATE = 44100
    SAMPLES_PER_BIT = 36

    def __init__(self):

        Object.__init__(self)

        # Define low and high tone waveforms.
        self.low_tone = []
        self.high_tone = []
        self.gap = []

        i = 0
        dx = 2 * Math.PI / self.SAMPLES_PER_BIT
        while i < self.SAMPLES_PER_BIT:

            low = Math.sin(i * dx)
            if low >= 0:
                self.low_tone.add(short(16384))
            else:
                self.low_tone.add(short(-16384))

            high = Math.sin(2 * i * dx)
            if high >= 0:
                self.high_tone.add(short(16384))
            else:
                self.high_tone.add(short(-16384))

            self.gap.add(short(0))

            i += 1

        # Define a track with a capacity large enough to fit five bytes of
        # encoded data.
        #         data (bits)                  bytes per short
        capacity = 60 * self.SAMPLES_PER_BIT * 2

        self.track = AudioTrack(AudioManager.STREAM_MUSIC, self.SAMPLE_RATE,
                                AudioFormat.CHANNEL_OUT_MONO,
                                AudioFormat.ENCODING_PCM_16BIT, capacity,
                                AudioTrack.MODE_STREAM)

        self.track.play()

    @args(int, [ShortBuffer, int, List(short)])
    def writeTone(self, buf, i, tone):

        j = 0
        while j < self.SAMPLES_PER_BIT:
            buf.put(i, tone[j])
            i += 1
            j += 1

        return i

    @args(ShortBuffer, [[byte]])
    def generateData(self, data):

        # Each byte in the block is expanded to ten bits. Each bit is
        # represented as one low frequency cycle or two high frequency cycles.
        bytes = len(data)
        bits = bytes * 10

        # Include samples for 1 channel
        samples = bits * self.SAMPLES_PER_BIT
        buf = ShortBuffer.allocate(samples)

        j = 0

        i = 0
        while i < bytes:

            j = self.writeTone(buf, j, self.low_tone)

            b = Byte(data[i]).intValue()
            k = 0
            while k < 8:
                if b & 1 == 0:
                    j = self.writeTone(buf, j, self.low_tone)
                else:
                    j = self.writeTone(buf, j, self.high_tone)

                b = b >> 1
                k += 1

            j = self.writeTone(buf, j, self.high_tone)
            i += 1

        return buf

    @args(void, [[byte]])
    def playData(self, data):

        buf = self.generateData(data)
        shorts = buf.capacity()
        bytes = shorts * 2

        self.track.write(buf.array(), 0, shorts)

    @args(void, [int])
    def playHighTone(self, bits):

        # Include samples for 1 channel
        samples = bits * self.SAMPLES_PER_BIT
        buf = ShortBuffer.allocate(samples)

        i = 0
        j = 0
        while i < bits:

            j = self.writeTone(buf, j, self.high_tone)
            i += 1

        shorts = buf.capacity()
        bytes = shorts * 2

        self.track.write(buf.array(), 0, shorts)

    @args(void, [InputStream])
    def sendCode(self, stream):

        self.playHighTone(60)

        a = array(byte, 6)

        while True:

            code = stream.read(a, 0, 6)
            if code == -1:
                break

            self.playData(a)

        stream.close()
class GridDataSetMeta(object):
    """ generated source for class GridDataSetMeta """
    gridDataSetId = str()
    dataType = DataType()
    variables = List()
    tSize = int()
    zSize = int()
    xSize = int()
    ySize = int()
    storeOptions = StoreOptions()
    attributes = Map()

    def __init__(self, gridDataSetId, dataType, variables, tSize, zSize, xSize,
                 ySize, storeOptions):
        """ generated source for method __init__ """
        assert gridDataSetId != None
        assert variables != None
        assert storeOptions != None
        self.gridDataSetId = gridDataSetId
        self.dataType = dataType
        self.variables = variables
        self.tSize = tSize
        self.zSize = zSize
        self.xSize = xSize
        self.ySize = ySize
        self.storeOptions = storeOptions

    def getGridDataSetId(self):
        """ generated source for method getGridDataSetId """
        return self.gridDataSetId

    def setGridDataSetId(self, gridDataSetId):
        """ generated source for method setGridDataSetId """
        self.gridDataSetId = gridDataSetId

    def getVariables(self):
        """ generated source for method getVariables """
        return self.variables

    def setVariables(self, variables):
        """ generated source for method setVariables """
        self.variables = variables

    def gettSize(self):
        """ generated source for method gettSize """
        return self.tSize

    def settSize(self, tSize):
        """ generated source for method settSize """
        self.tSize = tSize

    def getzSize(self):
        """ generated source for method getzSize """
        return self.zSize

    def setzSize(self, zSize):
        """ generated source for method setzSize """
        self.zSize = zSize

    def getxSize(self):
        """ generated source for method getxSize """
        return self.xSize

    def setxSize(self, xSize):
        """ generated source for method setxSize """
        self.xSize = xSize

    def getySize(self):
        """ generated source for method getySize """
        return self.ySize

    def setySize(self, ySize):
        """ generated source for method setySize """
        self.ySize = ySize

    def getAttributes(self):
        """ generated source for method getAttributes """
        return self.attributes

    def setAttributes(self, attributes):
        """ generated source for method setAttributes """
        assert attributes != None
        for key in attributes.keySet():
            if key.startsWith("_"):
                raise IllegalArgumentException(
                    "attribute key can't start with \"_\"")
        self.attributes = attributes

    def addAttribute(self, key, value):
        """ generated source for method addAttribute """
        if key.startsWith("_"):
            raise IllegalArgumentException(
                "attribute key can't start with \"_\"")
        if self.attributes == None:
            self.attributes = ConcurrentHashMap()
        self.attributes.put(key, value)

    def getStoreOptions(self):
        """ generated source for method getStoreOptions """
        return self.storeOptions

    def getDataType(self):
        """ generated source for method getDataType """
        return self.dataType
示例#13
0
class GetDataParam(object):
    """ generated source for class GetDataParam """
    dataTableName = str()
    dataSetId = str()
    variable = str()
    t = int()
    z = int()
    columnsToGet = List()

    def __init__(self, dataTableName, dataSetId, variable, t, z, columnsToGet):
        """ generated source for method __init__ """
        self.dataTableName = dataTableName
        self.dataSetId = dataSetId
        self.variable = variable
        self.t = t
        self.z = z
        self.columnsToGet = columnsToGet

    def getDataTableName(self):
        """ generated source for method getDataTableName """
        return self.dataTableName

    def setDataTableName(self, dataTableName):
        """ generated source for method setDataTableName """
        self.dataTableName = dataTableName

    def getDataSetId(self):
        """ generated source for method getDataSetId """
        return self.dataSetId

    def setDataSetId(self, dataSetId):
        """ generated source for method setDataSetId """
        self.dataSetId = dataSetId

    def getVariable(self):
        """ generated source for method getVariable """
        return self.variable

    def setVariable(self, variable):
        """ generated source for method setVariable """
        self.variable = variable

    def getT(self):
        """ generated source for method getT """
        return self.t

    def setT(self, t):
        """ generated source for method setT """
        self.t = t

    def getZ(self):
        """ generated source for method getZ """
        return self.z

    def setZ(self, z):
        """ generated source for method setZ """
        self.z = z

    def getColumnsToGet(self):
        """ generated source for method getColumnsToGet """
        return self.columnsToGet

    def setColumnsToGet(self, columnsToGet):
        """ generated source for method setColumnsToGet """
        self.columnsToGet = columnsToGet